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
psychopy/psychopy
01b674094f38d0e0bd51c45a6f66f671d7041696
psychopy/visual/vlcmoviestim.py
python
VlcMovieStim.getFPS
(self)
return self._frameRate
Movie frames per second. Returns ------- float Nominal number of frames to be displayed per second.
Movie frames per second.
[ "Movie", "frames", "per", "second", "." ]
def getFPS(self): """Movie frames per second. Returns ------- float Nominal number of frames to be displayed per second. """ return self._frameRate
[ "def", "getFPS", "(", "self", ")", ":", "return", "self", ".", "_frameRate" ]
https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/visual/vlcmoviestim.py#L995-L1004
Hood3dRob1n/JSRat-Py
340a69c08c37906d529c4d042051d5f8bddb3945
classes/colors.py
python
red
( msg )
Print RED Colored String
Print RED Colored String
[ "Print", "RED", "Colored", "String" ]
def red( msg ): """ Print RED Colored String """ if os.name == 'nt' or sys.platform.startswith('win'): windows_user_default_color_code = windows_default_colors() set_text_attr(FRED | BBLK | HC | BHC) sys.stdout.write(str(msg)) restore_windows_colors(windows_user_default_color_code) else: return HC + FRED + str(msg) + RS
[ "def", "red", "(", "msg", ")", ":", "if", "os", ".", "name", "==", "'nt'", "or", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "windows_user_default_color_code", "=", "windows_default_colors", "(", ")", "set_text_attr", "(", "FRED", "|...
https://github.com/Hood3dRob1n/JSRat-Py/blob/340a69c08c37906d529c4d042051d5f8bddb3945/classes/colors.py#L315-L323
viewfinderco/viewfinder
453845b5d64ab5b3b826c08b02546d1ca0a07c14
backend/www/photo_store.py
python
PhotoStoreHandler.put
(self, episode_id, photo_id, suffix)
Verifies user credentials. If the user has write access to the photo, and if an 'If-None-Match' is present, sends a HEAD request to the object store to determine asset Etag. If the Etag matches, returns a 304. Otherwise, generates an upload URL and redirects.
Verifies user credentials. If the user has write access to the photo, and if an 'If-None-Match' is present, sends a HEAD request to the object store to determine asset Etag. If the Etag matches, returns a 304. Otherwise, generates an upload URL and redirects.
[ "Verifies", "user", "credentials", ".", "If", "the", "user", "has", "write", "access", "to", "the", "photo", "and", "if", "an", "If", "-", "None", "-", "Match", "is", "present", "sends", "a", "HEAD", "request", "to", "the", "object", "store", "to", "de...
def put(self, episode_id, photo_id, suffix): """Verifies user credentials. If the user has write access to the photo, and if an 'If-None-Match' is present, sends a HEAD request to the object store to determine asset Etag. If the Etag matches, returns a 304. Otherwise, generates an upload URL and redirects. """ def _GetUploadUrl(photo, verified_md5): content_type = photo.content_type or 'image/jpeg' return self._obj_store.GenerateUploadUrl(photo_id + suffix, content_type=content_type, content_md5=verified_md5) # Always expect well-formed Content-MD5 header. This ensures that the image data always matches # what is in the metadata, and also enables the detection of any bit corruption on the wire. if 'Content-MD5' not in self.request.headers: raise web.HTTPError(400, 'Missing Content-MD5 header.') try: request_md5 = self.request.headers['Content-MD5'] actual_md5 = base64.b64decode(request_md5).encode('hex') except: raise web.HTTPError(400, 'Content-MD5 header "%s" is not a valid base-64 value.' % request_md5) # Match against the MD5 value stored in the photo metadata. if suffix not in ['.t', '.m', '.f', '.o']: raise web.HTTPError(404, 'Photo not found; "%s" suffix is invalid.' % suffix) # Ensure that user has permission to PUT the photo. yield PhotoStoreHandler._AuthorizeUser(self._client, episode_id, photo_id, write_access=True) # Get photo metadata, which will be used to create the upload URL. photo = yield gen.Task(Photo.Query, self._client, photo_id, None) # Get name of MD5 attribute in the photo metadata. if suffix == '.o': attr_name = 'orig_md5' elif suffix == '.f': attr_name = 'full_md5' elif suffix == '.m': attr_name = 'med_md5' elif suffix == '.t': attr_name = 'tn_md5' else: raise web.HTTPError(404, 'Photo not found; "%s" suffix is invalid.' % suffix) # Check for the existence of the photo's image data in S3. etag = yield gen.Task(Photo.IsImageUploaded, self._obj_store, photo.photo_id, suffix) expected_md5 = getattr(photo, attr_name) if expected_md5 != actual_md5: if etag is None: # Since there is not yet any photo image data, update the photo metadata to be equal to the # actual MD5 value. setattr(photo, attr_name, actual_md5) yield gen.Task(photo.Update, self._client) # Redirect to the S3 location. self.redirect(_GetUploadUrl(photo, request_md5)) else: # The client often sends mismatched MD5 values due to non-deterministic JPG creation IOS code. # Only log the mismatch if it's an original photo to avoid spamming logs. if suffix == '.o': logging.error('Content-MD5 header "%s" does not match expected MD5 "%s"' % (actual_md5, expected_md5)) self.set_status(400) self.finish() else: # Check for If-None-Match header, which is used by client to check whether photo image data # already exists (and therefore no PUT of the image data is needed). match_etag = self.request.headers.get('If-None-Match', None) if match_etag is not None and etag is not None and (match_etag == '*' or match_etag == etag): # Photo image data exists and is not modified, so no need for client to PUT it again. self.set_status(httplib.NOT_MODIFIED) self.finish() else: # Redirect to the S3 upload location. self.redirect(_GetUploadUrl(photo, request_md5))
[ "def", "put", "(", "self", ",", "episode_id", ",", "photo_id", ",", "suffix", ")", ":", "def", "_GetUploadUrl", "(", "photo", ",", "verified_md5", ")", ":", "content_type", "=", "photo", ".", "content_type", "or", "'image/jpeg'", "return", "self", ".", "_o...
https://github.com/viewfinderco/viewfinder/blob/453845b5d64ab5b3b826c08b02546d1ca0a07c14/backend/www/photo_store.py#L64-L140
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/ext/mutable.py
python
MutableDict.__delitem__
(self, key)
Detect dictionary del events and emit change events.
Detect dictionary del events and emit change events.
[ "Detect", "dictionary", "del", "events", "and", "emit", "change", "events", "." ]
def __delitem__(self, key): """Detect dictionary del events and emit change events.""" dict.__delitem__(self, key) self.changed()
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "dict", ".", "__delitem__", "(", "self", ",", "key", ")", "self", ".", "changed", "(", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/ext/mutable.py#L709-L712
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/phases/coolprop_phase.py
python
CoolPropPhase.H_dep
(self)
return self.AS.hmolar_excess()
[]
def H_dep(self): return self.AS.hmolar_excess()
[ "def", "H_dep", "(", "self", ")", ":", "return", "self", ".", "AS", ".", "hmolar_excess", "(", ")" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/phases/coolprop_phase.py#L403-L404
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/setuptools/msvc.py
python
PlatformInfo.current_dir
(self, hidex86=False, x64=False)
return ( '' if (self.current_cpu == 'x86' and hidex86) else r'\x64' if (self.current_cpu == 'amd64' and x64) else r'\%s' % self.current_cpu )
Current platform specific subfolder. Parameters ---------- hidex86: bool return '' and not '\x86' if architecture is x86. x64: bool return '\x64' and not '\amd64' if architecture is amd64. Return ------ subfolder: str '\target', or '' (see hidex86 parameter)
Current platform specific subfolder.
[ "Current", "platform", "specific", "subfolder", "." ]
def current_dir(self, hidex86=False, x64=False): """ Current platform specific subfolder. Parameters ---------- hidex86: bool return '' and not '\x86' if architecture is x86. x64: bool return '\x64' and not '\amd64' if architecture is amd64. Return ------ subfolder: str '\target', or '' (see hidex86 parameter) """ return ( '' if (self.current_cpu == 'x86' and hidex86) else r'\x64' if (self.current_cpu == 'amd64' and x64) else r'\%s' % self.current_cpu )
[ "def", "current_dir", "(", "self", ",", "hidex86", "=", "False", ",", "x64", "=", "False", ")", ":", "return", "(", "''", "if", "(", "self", ".", "current_cpu", "==", "'x86'", "and", "hidex86", ")", "else", "r'\\x64'", "if", "(", "self", ".", "curren...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/setuptools/msvc.py#L265-L285
LZQthePlane/Online-Realtime-Action-Recognition-based-on-OpenPose
33664be6ae7a26e9875f9771dc43d05a8b071dce
Tracking/generate_dets.py
python
create_box_encoder
(model_filename, input_name="images", output_name="features", batch_size=32)
return encoder
[]
def create_box_encoder(model_filename, input_name="images", output_name="features", batch_size=32): image_encoder = ImageEncoder(model_filename, input_name, output_name) image_shape = image_encoder.image_shape def encoder(image, boxes): image_patches = [] for box in boxes: patch = extract_image_patch(image, box, image_shape[:2]) if patch is None: print("WARNING: Failed to extract image patch: %s." % str(box)) patch = np.random.uniform(0., 255., image_shape).astype(np.uint8) image_patches.append(patch) image_patches = np.asarray(image_patches) return image_encoder(image_patches, batch_size) return encoder
[ "def", "create_box_encoder", "(", "model_filename", ",", "input_name", "=", "\"images\"", ",", "output_name", "=", "\"features\"", ",", "batch_size", "=", "32", ")", ":", "image_encoder", "=", "ImageEncoder", "(", "model_filename", ",", "input_name", ",", "output_...
https://github.com/LZQthePlane/Online-Realtime-Action-Recognition-based-on-OpenPose/blob/33664be6ae7a26e9875f9771dc43d05a8b071dce/Tracking/generate_dets.py#L95-L110
sensepost/Snoopy
57b354e5b41e0aee4eccf58fa91e15b198c304c2
snoopy/server/bin/pytail.py
python
sslstrip
(lines)
[]
def sslstrip(lines): isEntry = False anEntry = {} for aLine in lines: if aLine.startswith('2012-') and aLine.find(' Client:') > -1: if isEntry: processEntry(anEntry) isEntry = False if aLine.find(' POST Data (') > -1: isEntry = True anEntry = {} anEntry['timestamp'] = aLine[:aLine.find(',')] anEntry['secure'] = 0 anEntry['post'] = '' if aLine.find('SECURE POST Data (') > -1: anEntry['secure'] = 1 tStart = aLine.find(' POST Data (') + 12 anEntry['host'] = aLine[tStart:aLine.find(')', tStart)] anEntry['domain']=domain=psl.get_public_suffix(anEntry['host']) tStart = aLine.find(' Client:') + 8 anEntry['src_ip'] = aLine[tStart:aLine.find(' ', tStart)] tStart = aLine.find(' URL(') + 8 anEntry['url'] = aLine[tStart:aLine.find(')URL', tStart)] elif isEntry: anEntry['post'] = '%s%s' % (anEntry['post'], urllib.unquote_plus(aLine.strip())) if isEntry: processEntry(anEntry)
[ "def", "sslstrip", "(", "lines", ")", ":", "isEntry", "=", "False", "anEntry", "=", "{", "}", "for", "aLine", "in", "lines", ":", "if", "aLine", ".", "startswith", "(", "'2012-'", ")", "and", "aLine", ".", "find", "(", "' Client:'", ")", ">", "-", ...
https://github.com/sensepost/Snoopy/blob/57b354e5b41e0aee4eccf58fa91e15b198c304c2/snoopy/server/bin/pytail.py#L52-L83
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/linear_model/_stochastic_gradient.py
python
SGDClassifier.predict_log_proba
(self, X)
return np.log(self.predict_proba(X))
Log of probability estimates. This method is only available for log loss and modified Huber loss. When loss="modified_huber", probability estimates may be hard zeros and ones, so taking the logarithm is not possible. See ``predict_proba`` for details. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data for prediction. Returns ------- T : array-like, shape (n_samples, n_classes) Returns the log-probability of the sample for each class in the model, where classes are ordered as they are in `self.classes_`.
Log of probability estimates.
[ "Log", "of", "probability", "estimates", "." ]
def predict_log_proba(self, X): """Log of probability estimates. This method is only available for log loss and modified Huber loss. When loss="modified_huber", probability estimates may be hard zeros and ones, so taking the logarithm is not possible. See ``predict_proba`` for details. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data for prediction. Returns ------- T : array-like, shape (n_samples, n_classes) Returns the log-probability of the sample for each class in the model, where classes are ordered as they are in `self.classes_`. """ return np.log(self.predict_proba(X))
[ "def", "predict_log_proba", "(", "self", ",", "X", ")", ":", "return", "np", ".", "log", "(", "self", ".", "predict_proba", "(", "X", ")", ")" ]
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/linear_model/_stochastic_gradient.py#L1299-L1321
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/setuptools/pkg_resources/_vendor/pyparsing.py
python
ParseResults.__radd__
(self, other)
[]
def __radd__(self, other): if isinstance(other,int) and other == 0: # useful for merging many ParseResults using sum() builtin return self.copy() else: # this may raise a TypeError - so be it return other + self
[ "def", "__radd__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "int", ")", "and", "other", "==", "0", ":", "# useful for merging many ParseResults using sum() builtin", "return", "self", ".", "copy", "(", ")", "else", ":", "# ...
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/setuptools/pkg_resources/_vendor/pyparsing.py#L679-L685
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/tensorboard-service/app/api/models.py
python
TensorboardResponse.to_dict
(self)
return tb_dict
[]
def to_dict(self): tb_dict = { 'id': self.id, 'status': self.status.value, 'url': self.url } if self.invalid_runs: runs = [] for run in self.invalid_runs: runs.append(run.to_dict()) tb_dict['invalidRuns'] = runs return tb_dict
[ "def", "to_dict", "(", "self", ")", ":", "tb_dict", "=", "{", "'id'", ":", "self", ".", "id", ",", "'status'", ":", "self", ".", "status", ".", "value", ",", "'url'", ":", "self", ".", "url", "}", "if", "self", ".", "invalid_runs", ":", "runs", "...
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/tensorboard-service/app/api/models.py#L47-L61
edwardlib/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
observations/r/pedometer.py
python
pedometer
(path)
return x_train, metadata
Pedometer Daily walking amounts recorded on a personal pedometer from September-December 2011 A dataset with 68 observations on the following 8 variables. `Steps` Total number of steps for the day `Moderate` Number of steps at a moderate walking speed `Min` Number of minutes walking at a moderate speed `kcal` Number of calories burned walking at a moderate speed `Mile` Total number of miles walked `Rain` Type of weather (`rain` or `shine`) `Day` Day of the week (`U`\ =Sunday, `M`\ =Monday, `T`\ =Tuesday, `W`\ =Wednesday, `R`\ =Thursday, `F`\ =Friday, `S`\ =Saturday `DayType` Coded as `Weekday` or `Weekend` Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `pedometer.csv`. Returns: Tuple of np.ndarray `x_train` with 68 rows and 8 columns and dictionary `metadata` of column headers (feature names).
Pedometer
[ "Pedometer" ]
def pedometer(path): """Pedometer Daily walking amounts recorded on a personal pedometer from September-December 2011 A dataset with 68 observations on the following 8 variables. `Steps` Total number of steps for the day `Moderate` Number of steps at a moderate walking speed `Min` Number of minutes walking at a moderate speed `kcal` Number of calories burned walking at a moderate speed `Mile` Total number of miles walked `Rain` Type of weather (`rain` or `shine`) `Day` Day of the week (`U`\ =Sunday, `M`\ =Monday, `T`\ =Tuesday, `W`\ =Wednesday, `R`\ =Thursday, `F`\ =Friday, `S`\ =Saturday `DayType` Coded as `Weekday` or `Weekend` Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `pedometer.csv`. Returns: Tuple of np.ndarray `x_train` with 68 rows and 8 columns and dictionary `metadata` of column headers (feature names). """ import pandas as pd path = os.path.expanduser(path) filename = 'pedometer.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/Stat2Data/Pedometer.csv' maybe_download_and_extract(path, url, save_file_name='pedometer.csv', resume=False) data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True) x_train = data.values metadata = {'columns': data.columns} return x_train, metadata
[ "def", "pedometer", "(", "path", ")", ":", "import", "pandas", "as", "pd", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "filename", "=", "'pedometer.csv'", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path",...
https://github.com/edwardlib/observations/blob/2c8b1ac31025938cb17762e540f2f592e302d5de/observations/r/pedometer.py#L14-L81
SimonShi1994/Princess-connection-farm
c189de660677602167b7245846c2b0e53d5e777e
core/initializer.py
python
Schedule.show_queue
(self)
显示任务队列
显示任务队列
[ "显示任务队列" ]
def show_queue(self): """ 显示任务队列 """ self.pcr.show()
[ "def", "show_queue", "(", "self", ")", ":", "self", ".", "pcr", ".", "show", "(", ")" ]
https://github.com/SimonShi1994/Princess-connection-farm/blob/c189de660677602167b7245846c2b0e53d5e777e/core/initializer.py#L1598-L1602
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/asyncio/futures.py
python
wrap_future
(future, *, loop=None)
return new_future
Wrap concurrent.futures.Future object.
Wrap concurrent.futures.Future object.
[ "Wrap", "concurrent", ".", "futures", ".", "Future", "object", "." ]
def wrap_future(future, *, loop=None): """Wrap concurrent.futures.Future object.""" if isfuture(future): return future assert isinstance(future, concurrent.futures.Future), \ f'concurrent.futures.Future is expected, got {future!r}' if loop is None: loop = events.get_event_loop() new_future = loop.create_future() _chain_future(future, new_future) return new_future
[ "def", "wrap_future", "(", "future", ",", "*", ",", "loop", "=", "None", ")", ":", "if", "isfuture", "(", "future", ")", ":", "return", "future", "assert", "isinstance", "(", "future", ",", "concurrent", ".", "futures", ".", "Future", ")", ",", "f'conc...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/asyncio/futures.py#L380-L390
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/sqlalchemy/dialects/firebird/kinterbasdb.py
python
FBDialect_kinterbasdb._get_server_version_info
(self, connection)
return self._parse_version_info(version)
Get the version of the Firebird server used by a connection. Returns a tuple of (`major`, `minor`, `build`), three integers representing the version of the attached server.
Get the version of the Firebird server used by a connection.
[ "Get", "the", "version", "of", "the", "Firebird", "server", "used", "by", "a", "connection", "." ]
def _get_server_version_info(self, connection): """Get the version of the Firebird server used by a connection. Returns a tuple of (`major`, `minor`, `build`), three integers representing the version of the attached server. """ # This is the simpler approach (the other uses the services api), # that for backward compatibility reasons returns a string like # LI-V6.3.3.12981 Firebird 2.0 # where the first version is a fake one resembling the old # Interbase signature. fbconn = connection.connection version = fbconn.server_version return self._parse_version_info(version)
[ "def", "_get_server_version_info", "(", "self", ",", "connection", ")", ":", "# This is the simpler approach (the other uses the services api),", "# that for backward compatibility reasons returns a string like", "# LI-V6.3.3.12981 Firebird 2.0", "# where the first version is a fake one rese...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/sqlalchemy/dialects/firebird/kinterbasdb.py#L143-L159
ShadowXZT/pytorch_RFCN
0e532444263938aa4d000113dc6aac2e72b4b925
faster_rcnn/pycocotools/coco.py
python
COCO.loadRes
(self, resFile)
return res
Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object
Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object
[ "Load", "result", "file", "and", "return", "a", "result", "api", "object", ".", ":", "param", "resFile", "(", "str", ")", ":", "file", "name", "of", "result", "file", ":", "return", ":", "res", "(", "obj", ")", ":", "result", "api", "object" ]
def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = COCO() res.dataset['images'] = [img for img in self.dataset['images']] # res.dataset['info'] = copy.deepcopy(self.dataset['info']) # res.dataset['licenses'] = copy.deepcopy(self.dataset['licenses']) print 'Loading and preparing results... ' tic = time.time() anns = json.load(open(resFile)) assert type(anns) == list, 'results in not an array of objects' annsImgIds = [ann['image_id'] for ann in anns] assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \ 'Results do not correspond to current coco set' if 'caption' in anns[0]: imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns]) res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds] for id, ann in enumerate(anns): ann['id'] = id+1 elif 'bbox' in anns[0] and not anns[0]['bbox'] == []: res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) for id, ann in enumerate(anns): bb = ann['bbox'] x1, x2, y1, y2 = [bb[0], bb[0]+bb[2], bb[1], bb[1]+bb[3]] if not 'segmentation' in ann: ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]] ann['area'] = bb[2]*bb[3] ann['id'] = id+1 ann['iscrowd'] = 0 elif 'segmentation' in anns[0]: res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) for id, ann in enumerate(anns): # now only support compressed RLE format as segmentation results ann['area'] = mask.area([ann['segmentation']])[0] if not 'bbox' in ann: ann['bbox'] = mask.toBbox([ann['segmentation']])[0] ann['id'] = id+1 ann['iscrowd'] = 0 print 'DONE (t=%0.2fs)'%(time.time()- tic) res.dataset['annotations'] = anns res.createIndex() return res
[ "def", "loadRes", "(", "self", ",", "resFile", ")", ":", "res", "=", "COCO", "(", ")", "res", ".", "dataset", "[", "'images'", "]", "=", "[", "img", "for", "img", "in", "self", ".", "dataset", "[", "'images'", "]", "]", "# res.dataset['info'] = copy.de...
https://github.com/ShadowXZT/pytorch_RFCN/blob/0e532444263938aa4d000113dc6aac2e72b4b925/faster_rcnn/pycocotools/coco.py#L281-L327
FORTH-ICS-INSPIRE/artemis
f0774af8abc25ef5c6b307960c048ff7528d8a9c
backend-services/detection/core/detection.py
python
DetectionDataWorker.detect_prefix_subprefix_hijack
( self, monitor_event: Dict, prefix_node: Dict, prefix_node_conf: Dict, *args, **kwargs )
return "E"
Subprefix or exact prefix hijack detection.
Subprefix or exact prefix hijack detection.
[ "Subprefix", "or", "exact", "prefix", "hijack", "detection", "." ]
def detect_prefix_subprefix_hijack( self, monitor_event: Dict, prefix_node: Dict, prefix_node_conf: Dict, *args, **kwargs ) -> str: """ Subprefix or exact prefix hijack detection. """ mon_prefix = ipaddress.ip_network(monitor_event["prefix"]) if ipaddress.ip_network(prefix_node["prefix"]).prefixlen < mon_prefix.prefixlen: return "S" return "E"
[ "def", "detect_prefix_subprefix_hijack", "(", "self", ",", "monitor_event", ":", "Dict", ",", "prefix_node", ":", "Dict", ",", "prefix_node_conf", ":", "Dict", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "str", ":", "mon_prefix", "=", "ipaddress", ...
https://github.com/FORTH-ICS-INSPIRE/artemis/blob/f0774af8abc25ef5c6b307960c048ff7528d8a9c/backend-services/detection/core/detection.py#L654-L668
fonttools/fonttools
892322aaff6a89bea5927379ec06bc0da3dfb7df
Lib/fontTools/ufoLib/__init__.py
python
UFOWriter.writeGroups
(self, groups, validate=None)
Write groups.plist. This method requires a dict of glyph groups as an argument. ``validate`` will validate the data, by default it is set to the class's validate value, can be overridden.
Write groups.plist. This method requires a dict of glyph groups as an argument.
[ "Write", "groups", ".", "plist", ".", "This", "method", "requires", "a", "dict", "of", "glyph", "groups", "as", "an", "argument", "." ]
def writeGroups(self, groups, validate=None): """ Write groups.plist. This method requires a dict of glyph groups as an argument. ``validate`` will validate the data, by default it is set to the class's validate value, can be overridden. """ if validate is None: validate = self._validate # validate the data structure if validate: valid, message = groupsValidator(groups) if not valid: raise UFOLibError(message) # down convert if ( self._formatVersion < UFOFormatVersion.FORMAT_3_0 and self._downConversionKerningData is not None ): remap = self._downConversionKerningData["groupRenameMap"] remappedGroups = {} # there are some edge cases here that are ignored: # 1. if a group is being renamed to a name that # already exists, the existing group is always # overwritten. (this is why there are two loops # below.) there doesn't seem to be a logical # solution to groups mismatching and overwriting # with the specifiecd group seems like a better # solution than throwing an error. # 2. if side 1 and side 2 groups are being renamed # to the same group name there is no check to # ensure that the contents are identical. that # is left up to the caller. for name, contents in list(groups.items()): if name in remap: continue remappedGroups[name] = contents for name, contents in list(groups.items()): if name not in remap: continue name = remap[name] remappedGroups[name] = contents groups = remappedGroups # pack and write groupsNew = {} for key, value in groups.items(): groupsNew[key] = list(value) if groupsNew: self._writePlist(GROUPS_FILENAME, groupsNew) elif self._havePreviousFile: self.removePath(GROUPS_FILENAME, force=True, removeEmptyParents=False)
[ "def", "writeGroups", "(", "self", ",", "groups", ",", "validate", "=", "None", ")", ":", "if", "validate", "is", "None", ":", "validate", "=", "self", ".", "_validate", "# validate the data structure", "if", "validate", ":", "valid", ",", "message", "=", ...
https://github.com/fonttools/fonttools/blob/892322aaff6a89bea5927379ec06bc0da3dfb7df/Lib/fontTools/ufoLib/__init__.py#L1195-L1246
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/importlib/__init__.py
python
find_loader
(name, path=None)
return spec.loader
Return the loader for the specified module. This is a backward-compatible wrapper around find_spec(). This function is deprecated in favor of importlib.util.find_spec().
Return the loader for the specified module.
[ "Return", "the", "loader", "for", "the", "specified", "module", "." ]
def find_loader(name, path=None): """Return the loader for the specified module. This is a backward-compatible wrapper around find_spec(). This function is deprecated in favor of importlib.util.find_spec(). """ warnings.warn('Use importlib.util.find_spec() instead.', DeprecationWarning, stacklevel=2) try: loader = sys.modules[name].__loader__ if loader is None: raise ValueError('{}.__loader__ is None'.format(name)) else: return loader except KeyError: pass except AttributeError: raise ValueError('{}.__loader__ is not set'.format(name)) from None spec = _bootstrap._find_spec(name, path) # We won't worry about malformed specs (missing attributes). if spec is None: return None if spec.loader is None: if spec.submodule_search_locations is None: raise ImportError('spec for {} missing loader'.format(name), name=name) raise ImportError('namespace packages do not have loaders', name=name) return spec.loader
[ "def", "find_loader", "(", "name", ",", "path", "=", "None", ")", ":", "warnings", ".", "warn", "(", "'Use importlib.util.find_spec() instead.'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "try", ":", "loader", "=", "sys", ".", "modules", "...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/importlib/__init__.py#L74-L105
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/qld_bushfire/geo_location.py
python
QldBushfireLocationEvent.name
(self)
return self._name
Return the name of the entity.
Return the name of the entity.
[ "Return", "the", "name", "of", "the", "entity", "." ]
def name(self) -> str | None: """Return the name of the entity.""" return self._name
[ "def", "name", "(", "self", ")", "->", "str", "|", "None", ":", "return", "self", ".", "_name" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/qld_bushfire/geo_location.py#L220-L222
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
lib-python/3.5.1/numbers.py
python
Real.__divmod__
(self, other)
return (self // other, self % other)
divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations.
divmod(self, other): The pair (self // other, self % other).
[ "divmod", "(", "self", "other", ")", ":", "The", "pair", "(", "self", "//", "other", "self", "%", "other", ")", "." ]
def __divmod__(self, other): """divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. """ return (self // other, self % other)
[ "def", "__divmod__", "(", "self", ",", "other", ")", ":", "return", "(", "self", "//", "other", ",", "self", "%", "other", ")" ]
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/numbers.py#L197-L203
python-openxml/python-docx
36cac78de080d412e9e50d56c2784e33655cad59
docx/section.py
python
Section.different_first_page_header_footer
(self)
return self._sectPr.titlePg_val
True if this section displays a distinct first-page header and footer. Read/write. The definition of the first-page header and footer are accessed using :attr:`.first_page_header` and :attr:`.first_page_footer` respectively.
True if this section displays a distinct first-page header and footer.
[ "True", "if", "this", "section", "displays", "a", "distinct", "first", "-", "page", "header", "and", "footer", "." ]
def different_first_page_header_footer(self): """True if this section displays a distinct first-page header and footer. Read/write. The definition of the first-page header and footer are accessed using :attr:`.first_page_header` and :attr:`.first_page_footer` respectively. """ return self._sectPr.titlePg_val
[ "def", "different_first_page_header_footer", "(", "self", ")", ":", "return", "self", ".", "_sectPr", ".", "titlePg_val" ]
https://github.com/python-openxml/python-docx/blob/36cac78de080d412e9e50d56c2784e33655cad59/docx/section.py#L64-L70
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/app.py
python
add_common_arguments
(parser)
Add command arguments to the ArgumentParser
Add command arguments to the ArgumentParser
[ "Add", "command", "arguments", "to", "the", "ArgumentParser" ]
def add_common_arguments(parser): """Add command arguments to the ArgumentParser""" # We also accept 'git cola version' parser.add_argument( '--version', default=False, action='store_true', help='print version number' ) # Specifies a git repository to open parser.add_argument( '-r', '--repo', metavar='<repo>', default=core.getcwd(), help='open the specified git repository', ) # Specifies that we should prompt for a repository at startup parser.add_argument( '--prompt', action='store_true', default=False, help='prompt for a repository' ) # Specify the icon theme parser.add_argument( '--icon-theme', metavar='<theme>', dest='icon_themes', action='append', default=[], help='specify an icon theme (name or directory)', ) # Resume an X Session Management session parser.add_argument( '-session', metavar='<session>', default=None, help=argparse.SUPPRESS ) # Enable timing information parser.add_argument( '--perf', action='store_true', default=False, help=argparse.SUPPRESS ) # Specify the GUI theme parser.add_argument( '--theme', metavar='<name>', default=None, help='specify an GUI theme name' )
[ "def", "add_common_arguments", "(", "parser", ")", ":", "# We also accept 'git cola version'", "parser", ".", "add_argument", "(", "'--version'", ",", "default", "=", "False", ",", "action", "=", "'store_true'", ",", "help", "=", "'print version number'", ")", "# Sp...
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/app.py#L406-L450
SeuTao/RSNA2019_Intracranial-Hemorrhage-Detection
1db8dbb352484ff7129937d8a4e414ef6900588a
3DNet/models/resnet.py
python
resnet3d_10
(**kwargs)
return model
Constructs a ResNet-18 model.
Constructs a ResNet-18 model.
[ "Constructs", "a", "ResNet", "-", "18", "model", "." ]
def resnet3d_10(**kwargs): """Constructs a ResNet-18 model. """ model = ResNet3D(BasicBlock, [1, 1, 1, 1], **kwargs) return model
[ "def", "resnet3d_10", "(", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet3D", "(", "BasicBlock", ",", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "*", "*", "kwargs", ")", "return", "model" ]
https://github.com/SeuTao/RSNA2019_Intracranial-Hemorrhage-Detection/blob/1db8dbb352484ff7129937d8a4e414ef6900588a/3DNet/models/resnet.py#L187-L191
blacktwin/JBOPS
39fbaa3ade084aec1a2a14303bb6c65f09eb1978
killstream/limiterr.py
python
get_history
(username, start_date=None, section_id=None)
Get the Tautulli history. Parameters ---------- username : str The username to gather history from. Optional ---------- start_date : list ["YYYY-MM-DD", ...] The date in history to search. section_id : int The libraries numeric identifier Returns ------- dict The total number of watches, plays, or total playtime.
Get the Tautulli history.
[ "Get", "the", "Tautulli", "history", "." ]
def get_history(username, start_date=None, section_id=None): """Get the Tautulli history. Parameters ---------- username : str The username to gather history from. Optional ---------- start_date : list ["YYYY-MM-DD", ...] The date in history to search. section_id : int The libraries numeric identifier Returns ------- dict The total number of watches, plays, or total playtime. """ payload = {'apikey': TAUTULLI_APIKEY, 'cmd': 'get_history', 'user': username} if start_date: payload['start_date'] = start_date if section_id: payload['section_id '] = section_id try: req = sess.get(TAUTULLI_URL.rstrip('/') + '/api/v2', params=payload) response = req.json() res_data = response['response']['data'] return res_data except Exception as e: sys.stderr.write("Tautulli API 'get_history' request failed: {0}.".format(e))
[ "def", "get_history", "(", "username", ",", "start_date", "=", "None", ",", "section_id", "=", "None", ")", ":", "payload", "=", "{", "'apikey'", ":", "TAUTULLI_APIKEY", ",", "'cmd'", ":", "'get_history'", ",", "'user'", ":", "username", "}", "if", "start_...
https://github.com/blacktwin/JBOPS/blob/39fbaa3ade084aec1a2a14303bb6c65f09eb1978/killstream/limiterr.py#L167-L205
pytorch/translate
564d011b10b4cef4e110c092c2912277ed64c713
pytorch_translate/train.py
python
setup_training_state
(args, trainer, task, epoch_itr)
return extra_state, epoch_itr, checkpoint_manager
Set up the directory for saving checkpoints. Load pretrained model if specified.
Set up the directory for saving checkpoints. Load pretrained model if specified.
[ "Set", "up", "the", "directory", "for", "saving", "checkpoints", ".", "Load", "pretrained", "model", "if", "specified", "." ]
def setup_training_state(args, trainer, task, epoch_itr): """Set up the directory for saving checkpoints. Load pretrained model if specified.""" PathManager.mkdirs(args.save_dir) # If --restore-file is already present under --save-dir, use that one # instead of --pretrained-checkpoint-file. The idea is that # --pretrained-checkpoint-file allows the user to specify restoring from a # different run's checkpoint (possibly with different training params), # while not polluting the previous run's checkpoint directory # with new checkpoints. However, if training gets interrupted # and the user restarts training, we want to resume from # the checkpoints under --save-dir, instead of # restarting again from the old run's checkpoint at # --pretrained-checkpoint-file. # # Note that if args.restore_file is an absolute path, os.path.join() will # ignore previous directory args and just use the absolute path as is. checkpoint_path = os.path.join(args.save_dir, args.restore_file) restore_state = True if PathManager.isfile(checkpoint_path): print( f"| Using --save-dir={args.save_dir}, --restore-file={args.restore_file}." ) elif args.pretrained_checkpoint_file and PathManager.isfile( args.pretrained_checkpoint_file ): checkpoint_path = args.pretrained_checkpoint_file restore_state = args.load_pretrained_checkpoint_state print( f"| Using --pretrained-checkpoint-file={args.pretrained_checkpoint_file}, " f"--load-pretrained-checkpoint-state={args.load_pretrained_checkpoint_state}." ) extra_state = default_extra_state(args) if not PathManager.isfile(checkpoint_path) and args.multi_model_restore_files: print(f"| Restoring individual models from {args.multi_model_restore_files}") multi_model.import_individual_models(args.multi_model_restore_files, trainer) else: loaded, loaded_extra_state = checkpoint.load_existing_checkpoint( checkpoint_path=checkpoint_path, trainer=trainer, restore_state=restore_state, ) if loaded_extra_state: extra_state.update(loaded_extra_state) # Reset the start time for the current training run. extra_state["start_time"] = time.time() # Skips printing all training progress to prevent log spam. training_progress = extra_state["training_progress"] extra_state["training_progress"] = ( ["...truncated...", training_progress[-1]] if len(training_progress) > 0 else [] ) print(f"| extra_state: {extra_state}") extra_state["training_progress"] = training_progress epoch = extra_state["epoch"] if extra_state["batch_offset"] == 0: epoch -= 1 # this will be incremented when we call epoch_itr.next_epoch_itr() epoch_itr.load_state_dict( {"epoch": epoch, "iterations_in_epoch": extra_state["batch_offset"]} ) checkpoint_manager = None if distributed_utils.is_master(args): checkpoint_manager = checkpoint.CheckpointManager( num_avg_checkpoints=args.num_avg_checkpoints, auto_clear_checkpoints=args.auto_clear_checkpoints, log_verbose=args.log_verbose, checkpoint_files=extra_state["checkpoint_files"], ) return extra_state, epoch_itr, checkpoint_manager
[ "def", "setup_training_state", "(", "args", ",", "trainer", ",", "task", ",", "epoch_itr", ")", ":", "PathManager", ".", "mkdirs", "(", "args", ".", "save_dir", ")", "# If --restore-file is already present under --save-dir, use that one", "# instead of --pretrained-checkpoi...
https://github.com/pytorch/translate/blob/564d011b10b4cef4e110c092c2912277ed64c713/pytorch_translate/train.py#L337-L411
coin-or/rbfopt
3ba5320a23f04ac3729eff7b55527f2f1e6f9fdd
src/rbfopt/rbfopt_aux_problems.py
python
MaximinDistanceObj.__init__
(self, settings, n, k, node_pos)
Constructor.
Constructor.
[ "Constructor", "." ]
def __init__(self, settings, n, k, node_pos): """Constructor. """ assert (isinstance(node_pos, np.ndarray)) assert(len(node_pos) == k) assert(isinstance(settings, RbfoptSettings)) self.settings = settings self.n = n self.k = k self.node_pos = node_pos
[ "def", "__init__", "(", "self", ",", "settings", ",", "n", ",", "k", ",", "node_pos", ")", ":", "assert", "(", "isinstance", "(", "node_pos", ",", "np", ".", "ndarray", ")", ")", "assert", "(", "len", "(", "node_pos", ")", "==", "k", ")", "assert",...
https://github.com/coin-or/rbfopt/blob/3ba5320a23f04ac3729eff7b55527f2f1e6f9fdd/src/rbfopt/rbfopt_aux_problems.py#L1381-L1390
tor2web/Tor2web
63d9e29d1703a06c900b49ada3d9a355225afe7a
tor2web/t2w.py
python
Tor2webObj.__init__
(self)
[]
def __init__(self): # The destination hidden service identifier self.onion = None # The path portion of the URI self.path = None # The full address (hostname + uri) that must be requested self.address = None # The headers to be sent self.headers = None # The requested uri self.uri = None # A boolean that keeps track of client gzip support self.client_supports_gzip = False # A boolean that keeps track of server gzip support self.server_response_is_gzip = False # A variably that keep tracks of special contents to be parsed self.special_content = None
[ "def", "__init__", "(", "self", ")", ":", "# The destination hidden service identifier", "self", ".", "onion", "=", "None", "# The path portion of the URI", "self", ".", "path", "=", "None", "# The full address (hostname + uri) that must be requested", "self", ".", "address...
https://github.com/tor2web/Tor2web/blob/63d9e29d1703a06c900b49ada3d9a355225afe7a/tor2web/t2w.py#L214-L237
flennerhag/mlens
6cbc11354b5f9500a33d9cefb700a1bba9d3199a
mlens/parallel/learner.py
python
BaseNode.gen_predict
(self, X, P=None)
return self._gen_pred('predict', X, P, self.learner)
Generate predicting jobs Parameters ---------- X: array-like of shape [n_samples, n_features] input array y: array-like of shape [n_samples,] targets P: array-like of shape [n_samples, n_prediction_features], optional output array to populate. Must be writeable. Only pass if predictions are desired.
Generate predicting jobs
[ "Generate", "predicting", "jobs" ]
def gen_predict(self, X, P=None): """Generate predicting jobs Parameters ---------- X: array-like of shape [n_samples, n_features] input array y: array-like of shape [n_samples,] targets P: array-like of shape [n_samples, n_prediction_features], optional output array to populate. Must be writeable. Only pass if predictions are desired. """ return self._gen_pred('predict', X, P, self.learner)
[ "def", "gen_predict", "(", "self", ",", "X", ",", "P", "=", "None", ")", ":", "return", "self", ".", "_gen_pred", "(", "'predict'", ",", "X", ",", "P", ",", "self", ".", "learner", ")" ]
https://github.com/flennerhag/mlens/blob/6cbc11354b5f9500a33d9cefb700a1bba9d3199a/mlens/parallel/learner.py#L621-L636
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/ntpath.py
python
expandvars
(path)
return res
Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.
Expand shell variables of the forms $var, ${var} and %var%.
[ "Expand", "shell", "variables", "of", "the", "forms", "$var", "$", "{", "var", "}", "and", "%var%", "." ]
def expandvars(path): """Expand shell variables of the forms $var, ${var} and %var%. Unknown variables are left unchanged.""" path = os.fspath(path) if isinstance(path, bytes): if b'$' not in path and b'%' not in path: return path import string varchars = bytes(string.ascii_letters + string.digits + '_-', 'ascii') quote = b'\'' percent = b'%' brace = b'{' rbrace = b'}' dollar = b'$' environ = getattr(os, 'environb', None) else: if '$' not in path and '%' not in path: return path import string varchars = string.ascii_letters + string.digits + '_-' quote = '\'' percent = '%' brace = '{' rbrace = '}' dollar = '$' environ = os.environ res = path[:0] index = 0 pathlen = len(path) while index < pathlen: c = path[index:index+1] if c == quote: # no expansion within single quotes path = path[index + 1:] pathlen = len(path) try: index = path.index(c) res += c + path[:index + 1] except ValueError: res += c + path index = pathlen - 1 elif c == percent: # variable or '%' if path[index + 1:index + 2] == percent: res += c index += 1 else: path = path[index+1:] pathlen = len(path) try: index = path.index(percent) except ValueError: res += percent + path index = pathlen - 1 else: var = path[:index] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(var)]) else: value = environ[var] except KeyError: value = percent + var + percent res += value elif c == dollar: # variable or '$$' if path[index + 1:index + 2] == dollar: res += c index += 1 elif path[index + 1:index + 2] == brace: path = path[index+2:] pathlen = len(path) try: index = path.index(rbrace) except ValueError: res += dollar + brace + path index = pathlen - 1 else: var = path[:index] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(var)]) else: value = environ[var] except KeyError: value = dollar + brace + var + rbrace res += value else: var = path[:0] index += 1 c = path[index:index + 1] while c and c in varchars: var += c index += 1 c = path[index:index + 1] try: if environ is None: value = os.fsencode(os.environ[os.fsdecode(var)]) else: value = environ[var] except KeyError: value = dollar + var res += value if c: index -= 1 else: res += c index += 1 return res
[ "def", "expandvars", "(", "path", ")", ":", "path", "=", "os", ".", "fspath", "(", "path", ")", "if", "isinstance", "(", "path", ",", "bytes", ")", ":", "if", "b'$'", "not", "in", "path", "and", "b'%'", "not", "in", "path", ":", "return", "path", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/ntpath.py#L358-L464
WikidPad/WikidPad
558109638807bc76b4672922686e416ab2d5f79c
WikidPad/lib/aui/auibook.py
python
AuiNotebookEvent.__init__
(self, command_type=None, win_id=0)
Default class constructor. :param `command_type`: the event kind or an instance of :class:`PyCommandEvent`. :param integer `win_id`: the window identification number.
Default class constructor.
[ "Default", "class", "constructor", "." ]
def __init__(self, command_type=None, win_id=0): """ Default class constructor. :param `command_type`: the event kind or an instance of :class:`PyCommandEvent`. :param integer `win_id`: the window identification number. """ CommandNotebookEvent.__init__(self, command_type, win_id) if type(command_type) == int: self.notify = wx.NotifyEvent(command_type, win_id) else: self.notify = wx.NotifyEvent(command_type.GetEventType(), command_type.GetId())
[ "def", "__init__", "(", "self", ",", "command_type", "=", "None", ",", "win_id", "=", "0", ")", ":", "CommandNotebookEvent", ".", "__init__", "(", "self", ",", "command_type", ",", "win_id", ")", "if", "type", "(", "command_type", ")", "==", "int", ":", ...
https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/aui/auibook.py#L559-L572
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/qark/qark/lib/pubsub/core/topicmgr.py
python
_MasterTopicDefnProvider.getNumProviders
(self)
return len(self.__providers)
Return how many providers added.
Return how many providers added.
[ "Return", "how", "many", "providers", "added", "." ]
def getNumProviders(self): """Return how many providers added.""" return len(self.__providers)
[ "def", "getNumProviders", "(", "self", ")", ":", "return", "len", "(", "self", ".", "__providers", ")" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/qark/qark/lib/pubsub/core/topicmgr.py#L426-L428
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/core/configuration/profile.py
python
ProfileData.__init__
(self)
Create the profile data.
Create the profile data.
[ "Create", "the", "profile", "data", "." ]
def __init__(self): """Create the profile data.""" self.config_path = "" self.profile_id = "" self.base_profile = "" self.os_id = "" self.variant_id = ""
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "config_path", "=", "\"\"", "self", ".", "profile_id", "=", "\"\"", "self", ".", "base_profile", "=", "\"\"", "self", ".", "os_id", "=", "\"\"", "self", ".", "variant_id", "=", "\"\"" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/core/configuration/profile.py#L35-L41
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/resource.py
python
AddressBookHomeResource.makeNewStore
(self)
return self._associatedTransaction.addressbookHomeWithUID(self.name, create=True), False
[]
def makeNewStore(self): return self._associatedTransaction.addressbookHomeWithUID(self.name, create=True), False
[ "def", "makeNewStore", "(", "self", ")", ":", "return", "self", ".", "_associatedTransaction", ".", "addressbookHomeWithUID", "(", "self", ".", "name", ",", "create", "=", "True", ")", ",", "False" ]
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/resource.py#L2781-L2782
jaryee/wechat_sogou_crawl
388887e4c8e5e60bc2558d8359740d108345e61b
wechatsogou/basic.py
python
WechatSogouBasic._get_gzh_article_text
(self, url)
return self._get(url, 'get', host='mp.weixin.qq.com')
获取文章文本 Args: url: 文章链接 Returns: text: 文章文本
获取文章文本
[ "获取文章文本" ]
def _get_gzh_article_text(self, url): """获取文章文本 Args: url: 文章链接 Returns: text: 文章文本 """ return self._get(url, 'get', host='mp.weixin.qq.com')
[ "def", "_get_gzh_article_text", "(", "self", ",", "url", ")", ":", "return", "self", ".", "_get", "(", "url", ",", "'get'", ",", "host", "=", "'mp.weixin.qq.com'", ")" ]
https://github.com/jaryee/wechat_sogou_crawl/blob/388887e4c8e5e60bc2558d8359740d108345e61b/wechatsogou/basic.py#L626-L635
TheAlgorithms/Python
9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c
ciphers/xor_cipher.py
python
XORCipher.decrypt_file
(self, file: str, key: int)
return True
input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1
input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1
[ "input", ":", "filename", "(", "str", ")", "and", "a", "key", "(", "int", ")", "output", ":", "returns", "true", "if", "decrypt", "process", "was", "successful", "otherwise", "false", "if", "key", "not", "passed", "the", "method", "uses", "the", "key", ...
def decrypt_file(self, file: str, key: int) -> bool: """ input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin: with open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True
[ "def", "decrypt_file", "(", "self", ",", "file", ":", "str", ",", "key", ":", "int", ")", "->", "bool", ":", "# precondition", "assert", "isinstance", "(", "file", ",", "str", ")", "and", "isinstance", "(", "key", ",", "int", ")", "try", ":", "with",...
https://github.com/TheAlgorithms/Python/blob/9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c/ciphers/xor_cipher.py#L143-L166
SirFroweey/PyDark
617c2bfda360afa7750c4707ecacd4ec82fa29af
PyDark/engine.py
python
DarkSprite.change_image
(self, index)
return self.ChangeImage(index)
Change the DarkSprites currently displayed image using an index.
Change the DarkSprites currently displayed image using an index.
[ "Change", "the", "DarkSprites", "currently", "displayed", "image", "using", "an", "index", "." ]
def change_image(self, index): """Change the DarkSprites currently displayed image using an index.""" return self.ChangeImage(index)
[ "def", "change_image", "(", "self", ",", "index", ")", ":", "return", "self", ".", "ChangeImage", "(", "index", ")" ]
https://github.com/SirFroweey/PyDark/blob/617c2bfda360afa7750c4707ecacd4ec82fa29af/PyDark/engine.py#L635-L637
Gandi/gandi.cli
5de0605126247e986f8288b467a52710a78e1794
gandi/cli/commands/certificate.py
python
change_dcv
(gandi, resource, dcv_method)
Change the DCV for a running certificate operation. Resource can be a CN or an ID
Change the DCV for a running certificate operation.
[ "Change", "the", "DCV", "for", "a", "running", "certificate", "operation", "." ]
def change_dcv(gandi, resource, dcv_method): """ Change the DCV for a running certificate operation. Resource can be a CN or an ID """ ids = gandi.certificate.usable_ids(resource) if len(ids) > 1: gandi.echo('Will not update, %s is not precise enough.' % resource) gandi.echo(' * cert : ' + '\n * cert : '.join([str(id_) for id_ in ids])) return id_ = ids[0] opers = gandi.oper.list({'cert_id': id_}) if not opers: gandi.echo('Can not find any operation for this certificate.') return oper = opers[0] if (oper['step'] != 'RUN' and oper['params']['inner_step'] != 'comodo_oper_updated'): gandi.echo('This certificate operation is not in the good step to ' 'update the DCV method.') return gandi.certificate.change_dcv(oper['id'], dcv_method) cert = gandi.certificate.info(id_) csr = oper['params']['csr'] package = cert['package'] altnames = oper['params'].get('altnames') gandi.certificate.advice_dcv_method(csr, package, altnames, dcv_method, cert_id=id_)
[ "def", "change_dcv", "(", "gandi", ",", "resource", ",", "dcv_method", ")", ":", "ids", "=", "gandi", ".", "certificate", ".", "usable_ids", "(", "resource", ")", "if", "len", "(", "ids", ")", ">", "1", ":", "gandi", ".", "echo", "(", "'Will not update...
https://github.com/Gandi/gandi.cli/blob/5de0605126247e986f8288b467a52710a78e1794/gandi/cli/commands/certificate.py#L438-L472
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/tornado-4.3b2-py3.3-win-amd64.egg/tornado/web.py
python
authenticated
(method)
return wrapper
Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in.
Decorate methods with this to require that the user be logged in.
[ "Decorate", "methods", "with", "this", "to", "require", "that", "the", "user", "be", "logged", "in", "." ]
def authenticated(method): """Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add a `next` parameter so the login page knows where to send you once you're logged in. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): if not self.current_user: if self.request.method in ("GET", "HEAD"): url = self.get_login_url() if "?" not in url: if urlparse.urlsplit(url).scheme: # if login url is absolute, make next absolute too next_url = self.request.full_url() else: next_url = self.request.uri url += "?" + urlencode(dict(next=next_url)) self.redirect(url) return raise HTTPError(403) return method(self, *args, **kwargs) return wrapper
[ "def", "authenticated", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "current_user", ":", "if", "self", "....
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/tornado-4.3b2-py3.3-win-amd64.egg/tornado/web.py#L2776-L2803
mila-iqia/myia
56774a39579b4ec4123f44843ad4ca688acc859b
myia/grad.py
python
FPropAppRemapper.link_apply
(self, link)
Link generated nodes to their inputs. x = a(b, c) => A:x = (B:a)(B:b, B:c)
Link generated nodes to their inputs.
[ "Link", "generated", "nodes", "to", "their", "inputs", "." ]
def link_apply(self, link): """Link generated nodes to their inputs. x = a(b, c) => A:x = (B:a)(B:b, B:c) """ new_inputs = [ self.remappers["grad_fprop"].get(link.graph, inp) for inp in link.node.inputs ] link.new_node.inputs = new_inputs
[ "def", "link_apply", "(", "self", ",", "link", ")", ":", "new_inputs", "=", "[", "self", ".", "remappers", "[", "\"grad_fprop\"", "]", ".", "get", "(", "link", ".", "graph", ",", "inp", ")", "for", "inp", "in", "link", ".", "node", ".", "inputs", "...
https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia/grad.py#L148-L157
jython/jython3
def4f8ec47cb7a9c799ea4c745f12badf92c5769
ast/asdl.py
python
ASDLParser._advance
(self)
return cur_val
Return the value of the current token and read the next one into self.cur_token.
Return the value of the current token and read the next one into self.cur_token.
[ "Return", "the", "value", "of", "the", "current", "token", "and", "read", "the", "next", "one", "into", "self", ".", "cur_token", "." ]
def _advance(self): """ Return the value of the current token and read the next one into self.cur_token. """ cur_val = None if self.cur_token is None else self.cur_token.value try: self.cur_token = next(self._tokenizer) except StopIteration: self.cur_token = None return cur_val
[ "def", "_advance", "(", "self", ")", ":", "cur_val", "=", "None", "if", "self", ".", "cur_token", "is", "None", "else", "self", ".", "cur_token", ".", "value", "try", ":", "self", ".", "cur_token", "=", "next", "(", "self", ".", "_tokenizer", ")", "e...
https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/ast/asdl.py#L342-L351
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/mac_group.py
python
_format_info
(data)
return { "name": data.gr_name, "gid": data.gr_gid, "passwd": data.gr_passwd, "members": data.gr_mem, }
Return formatted information in a pretty way.
Return formatted information in a pretty way.
[ "Return", "formatted", "information", "in", "a", "pretty", "way", "." ]
def _format_info(data): """ Return formatted information in a pretty way. """ return { "name": data.gr_name, "gid": data.gr_gid, "passwd": data.gr_passwd, "members": data.gr_mem, }
[ "def", "_format_info", "(", "data", ")", ":", "return", "{", "\"name\"", ":", "data", ".", "gr_name", ",", "\"gid\"", ":", "data", ".", "gr_gid", ",", "\"passwd\"", ":", "data", ".", "gr_passwd", ",", "\"members\"", ":", "data", ".", "gr_mem", ",", "}"...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/mac_group.py#L196-L205
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/uuid.py
python
UUID.clock_seq_low
(self)
return (self.int >> 48) & 0xff
[]
def clock_seq_low(self): return (self.int >> 48) & 0xff
[ "def", "clock_seq_low", "(", "self", ")", ":", "return", "(", "self", ".", "int", ">>", "48", ")", "&", "0xff" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/uuid.py#L308-L309
alberanid/imdbpy
88cf37772186e275eff212857f512669086b382c
imdb/utils.py
python
cmpMovies
(m1, m2)
return 0
Compare two movies by year, in reverse order; the imdbIndex is checked for movies with the same year of production and title.
Compare two movies by year, in reverse order; the imdbIndex is checked for movies with the same year of production and title.
[ "Compare", "two", "movies", "by", "year", "in", "reverse", "order", ";", "the", "imdbIndex", "is", "checked", "for", "movies", "with", "the", "same", "year", "of", "production", "and", "title", "." ]
def cmpMovies(m1, m2): """Compare two movies by year, in reverse order; the imdbIndex is checked for movies with the same year of production and title.""" # Sort tv series' episodes. m1e = m1.get('episode of') m2e = m2.get('episode of') if m1e is not None and m2e is not None: cmp_series = cmpMovies(m1e, m2e) if cmp_series != 0: return cmp_series m1s = m1.get('season') m2s = m2.get('season') if m1s is not None and m2s is not None: if m1s < m2s: return 1 elif m1s > m2s: return -1 m1p = m1.get('episode') m2p = m2.get('episode') if m1p < m2p: return 1 elif m1p > m2p: return -1 try: if m1e is None: m1y = int(m1.get('year', 0)) else: m1y = int(m1e.get('year', 0)) except ValueError: m1y = 0 try: if m2e is None: m2y = int(m2.get('year', 0)) else: m2y = int(m2e.get('year', 0)) except ValueError: m2y = 0 if m1y > m2y: return -1 if m1y < m2y: return 1 # Ok, these movies have the same production year... # m1t = m1.get('canonical title', _last) # m2t = m2.get('canonical title', _last) # It should works also with normal dictionaries (returned from searches). # if m1t is _last and m2t is _last: m1t = m1.get('title', _last) m2t = m2.get('title', _last) if m1t < m2t: return -1 if m1t > m2t: return 1 # Ok, these movies have the same title... m1i = m1.get('imdbIndex', _last) m2i = m2.get('imdbIndex', _last) if m1i > m2i: return -1 if m1i < m2i: return 1 m1id = getattr(m1, 'movieID', None) # Introduce this check even for other comparisons functions? # XXX: is it safe to check without knowing the data access system? # probably not a great idea. Check for 'kind', instead? if m1id is not None: m2id = getattr(m2, 'movieID', None) if m1id > m2id: return -1 elif m1id < m2id: return 1 return 0
[ "def", "cmpMovies", "(", "m1", ",", "m2", ")", ":", "# Sort tv series' episodes.", "m1e", "=", "m1", ".", "get", "(", "'episode of'", ")", "m2e", "=", "m2", ".", "get", "(", "'episode of'", ")", "if", "m1e", "is", "not", "None", "and", "m2e", "is", "...
https://github.com/alberanid/imdbpy/blob/88cf37772186e275eff212857f512669086b382c/imdb/utils.py#L643-L712
travisgoodspeed/goodfet
1750cc1e8588af5470385e52fa098ca7364c2863
client/intelhex.py
python
IntelHexError.__str__
(self)
Return the message in this Exception.
Return the message in this Exception.
[ "Return", "the", "message", "in", "this", "Exception", "." ]
def __str__(self): """Return the message in this Exception.""" if self.msg: return self.msg try: return self._fmt % self.__dict__ except (NameError, ValueError, KeyError), e: return 'Unprintable exception %s: %s' \ % (self.__class__.__name__, str(e))
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "msg", ":", "return", "self", ".", "msg", "try", ":", "return", "self", ".", "_fmt", "%", "self", ".", "__dict__", "except", "(", "NameError", ",", "ValueError", ",", "KeyError", ")", ",", ...
https://github.com/travisgoodspeed/goodfet/blob/1750cc1e8588af5470385e52fa098ca7364c2863/client/intelhex.py#L1060-L1068
nschloe/quadpy
c4c076d8ddfa968486a2443a95e2fb3780dcde0f
src/quadpy/c1/_helpers.py
python
_find_shapes
(fx, intervals, x, domain_shape=None, range_shape=None)
return domain_shape, range_shape, interval_set_shape
[]
def _find_shapes(fx, intervals, x, domain_shape=None, range_shape=None): # This following logic is based on the below requirements # # assert intervals.shape == (2,) + domain_shape + interval_set_shape # assert fx.shape == range_shape + interval_set_shape + x.shape # assert len(x.shape) == 1 if intervals.shape[0] != 2: raise ValueError( f"Expected intervals to bbe of shape (2, ...), " f"but got shape {intervals.shape} instead." ) if fx.shape[-1] != x.shape[0]: raise ValueError( f"Expected the function return value to be of shape (..., {x.shape[0]}), " f"but got shape {fx.shape} instead." ) if domain_shape is not None and range_shape is not None: # Only needed for some assertions interval_set_shape = intervals.shape[1 + len(domain_shape) :] elif domain_shape is not None: interval_set_shape = intervals.shape[1 + len(domain_shape) :] range_shape = fx.shape[: -len(interval_set_shape) - 1] elif range_shape is not None: interval_set_shape = fx.shape[len(range_shape) : -1] if len(interval_set_shape) == 0: domain_shape = intervals.shape[1:] else: domain_shape = intervals.shape[1 : -len(interval_set_shape)] else: # Find the common tail of fx.shape[:-1] and intervals.shape. That is the # interval_set_shape unless the tails of domain_shape and range_shape coincide # to some degree. (For this case, one can specify domain_shape, range_shape # explicitly.) interval_set_shape = [] for k in range(min(len(intervals.shape) - 1, len(fx.shape) - 1)): d = intervals.shape[-k - 1] if fx.shape[-k - 2] != d: break interval_set_shape.append(d) interval_set_shape = tuple(reversed(interval_set_shape)) if interval_set_shape == (): domain_shape = intervals.shape[1:] else: domain_shape = intervals.shape[1 : -len(interval_set_shape)] range_shape = fx.shape[: -len(interval_set_shape) - 1] expected_shape_ivals = (2,) + domain_shape + interval_set_shape if intervals.shape != expected_shape_ivals: raise ValueError( f"Expected intervals to be of shape {expected_shape_ivals}, " f"but got shape {intervals.shape} instead." ) expected_shape_fx = range_shape + interval_set_shape + x.shape if fx.shape != expected_shape_fx: raise ValueError( f"Expected the function return value to be of shape {expected_shape_fx}, " f"but got shape {fx.shape} instead." ) return domain_shape, range_shape, interval_set_shape
[ "def", "_find_shapes", "(", "fx", ",", "intervals", ",", "x", ",", "domain_shape", "=", "None", ",", "range_shape", "=", "None", ")", ":", "# This following logic is based on the below requirements", "#", "# assert intervals.shape == (2,) + domain_shape + interval_set_shape",...
https://github.com/nschloe/quadpy/blob/c4c076d8ddfa968486a2443a95e2fb3780dcde0f/src/quadpy/c1/_helpers.py#L6-L69
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
libs/cssutils/css/cssvalue.py
python
CSSVariable._getValue
(self)
Find contained sheet and @variables there
Find contained sheet and
[ "Find", "contained", "sheet", "and" ]
def _getValue(self): "Find contained sheet and @variables there" try: variables = self.parent.parent.parentRule.parentStyleSheet.variables except AttributeError: return None else: try: return variables[self.name] except KeyError: return None
[ "def", "_getValue", "(", "self", ")", ":", "try", ":", "variables", "=", "self", ".", "parent", ".", "parent", ".", "parentRule", ".", "parentStyleSheet", ".", "variables", "except", "AttributeError", ":", "return", "None", "else", ":", "try", ":", "return...
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/libs/cssutils/css/cssvalue.py#L1236-L1246
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
py2manager/gluon/contrib/feedparser.py
python
_BaseHTMLProcessor.output
(self)
return ''.join([str(p) for p in self.pieces])
Return processed HTML as a single string
Return processed HTML as a single string
[ "Return", "processed", "HTML", "as", "a", "single", "string" ]
def output(self): '''Return processed HTML as a single string''' return ''.join([str(p) for p in self.pieces])
[ "def", "output", "(", "self", ")", ":", "return", "''", ".", "join", "(", "[", "str", "(", "p", ")", "for", "p", "in", "self", ".", "pieces", "]", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/contrib/feedparser.py#L2240-L2242
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v9/services/services/geographic_view_service/client.py
python
GeographicViewServiceClient.transport
(self)
return self._transport
Return the transport used by the client instance. Returns: GeographicViewServiceTransport: The transport used by the client instance.
Return the transport used by the client instance.
[ "Return", "the", "transport", "used", "by", "the", "client", "instance", "." ]
def transport(self) -> GeographicViewServiceTransport: """Return the transport used by the client instance. Returns: GeographicViewServiceTransport: The transport used by the client instance. """ return self._transport
[ "def", "transport", "(", "self", ")", "->", "GeographicViewServiceTransport", ":", "return", "self", ".", "_transport" ]
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v9/services/services/geographic_view_service/client.py#L153-L159
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/pip/_vendor/distlib/version.py
python
VersionScheme.is_valid_version
(self, s)
return result
[]
def is_valid_version(self, s): try: self.matcher.version_class(s) result = True except UnsupportedVersionError: result = False return result
[ "def", "is_valid_version", "(", "self", ",", "s", ")", ":", "try", ":", "self", ".", "matcher", ".", "version_class", "(", "s", ")", "result", "=", "True", "except", "UnsupportedVersionError", ":", "result", "=", "False", "return", "result" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/distlib/version.py#L699-L705
stb-tester/stb-tester
5b652bd5018360f2352f9bedc5f80ff92e66b2d1
_stbt/match.py
python
wait_for_match
(image, timeout_secs=10, consecutive_matches=1, match_parameters=None, region=Region.ALL, frames=None)
Search for an image in the device-under-test's video stream. :param image: The image to search for. See `match`. :type timeout_secs: int or float or None :param timeout_secs: A timeout in seconds. This function will raise `MatchTimeout` if no match is found within this time. :param int consecutive_matches: Forces this function to wait for several consecutive frames with a match found at the same x,y position. Increase ``consecutive_matches`` to avoid false positives due to noise, or to wait for a moving selection to stop moving. :param match_parameters: See `match`. :param region: See `match`. :type frames: Iterator[stbt.Frame] :param frames: An iterable of video-frames to analyse. Defaults to ``stbt.frames()``. :returns: `MatchResult` when the image is found. :raises: `MatchTimeout` if no match is found after ``timeout_secs`` seconds.
Search for an image in the device-under-test's video stream.
[ "Search", "for", "an", "image", "in", "the", "device", "-", "under", "-", "test", "s", "video", "stream", "." ]
def wait_for_match(image, timeout_secs=10, consecutive_matches=1, match_parameters=None, region=Region.ALL, frames=None): """Search for an image in the device-under-test's video stream. :param image: The image to search for. See `match`. :type timeout_secs: int or float or None :param timeout_secs: A timeout in seconds. This function will raise `MatchTimeout` if no match is found within this time. :param int consecutive_matches: Forces this function to wait for several consecutive frames with a match found at the same x,y position. Increase ``consecutive_matches`` to avoid false positives due to noise, or to wait for a moving selection to stop moving. :param match_parameters: See `match`. :param region: See `match`. :type frames: Iterator[stbt.Frame] :param frames: An iterable of video-frames to analyse. Defaults to ``stbt.frames()``. :returns: `MatchResult` when the image is found. :raises: `MatchTimeout` if no match is found after ``timeout_secs`` seconds. """ if match_parameters is None: match_parameters = MatchParameters() if frames is None: import stbt_core frames = stbt_core.frames(timeout_secs=timeout_secs) else: frames = limit_time(frames, timeout_secs) match_count = 0 last_pos = Position(0, 0) image = load_image(image) debug("Searching for " + (image.relative_filename or "<Image>")) for frame in frames: res = match(image, match_parameters=match_parameters, region=region, frame=frame) if res.match and (match_count == 0 or res.position == last_pos): match_count += 1 else: match_count = 0 last_pos = res.position if match_count == consecutive_matches: debug("Matched " + (image.relative_filename or "<Image>")) return res raise MatchTimeout(res.frame, image.relative_filename, timeout_secs)
[ "def", "wait_for_match", "(", "image", ",", "timeout_secs", "=", "10", ",", "consecutive_matches", "=", "1", ",", "match_parameters", "=", "None", ",", "region", "=", "Region", ".", "ALL", ",", "frames", "=", "None", ")", ":", "if", "match_parameters", "is...
https://github.com/stb-tester/stb-tester/blob/5b652bd5018360f2352f9bedc5f80ff92e66b2d1/_stbt/match.py#L400-L452
programa-stic/barf-project
9547ef843b8eb021c2c32c140e36173c0b4eafa3
barf/core/reil/builder.py
python
ReilBuilder.gen_ldm
(src, dst)
return ReilBuilder.build(ReilMnemonic.LDM, src, ReilEmptyOperand(), dst)
Return a LDM instruction.
Return a LDM instruction.
[ "Return", "a", "LDM", "instruction", "." ]
def gen_ldm(src, dst): """Return a LDM instruction. """ return ReilBuilder.build(ReilMnemonic.LDM, src, ReilEmptyOperand(), dst)
[ "def", "gen_ldm", "(", "src", ",", "dst", ")", ":", "return", "ReilBuilder", ".", "build", "(", "ReilMnemonic", ".", "LDM", ",", "src", ",", "ReilEmptyOperand", "(", ")", ",", "dst", ")" ]
https://github.com/programa-stic/barf-project/blob/9547ef843b8eb021c2c32c140e36173c0b4eafa3/barf/core/reil/builder.py#L116-L119
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/min/smtpd.py
python
PureProxy.process_message
(self, peer, mailfrom, rcpttos, data)
[]
def process_message(self, peer, mailfrom, rcpttos, data): lines = data.split('\n') # Look for the last header i = 0 for line in lines: if not line: break i += 1 lines.insert(i, 'X-Peer: %s' % peer[0]) data = NEWLINE.join(lines) refused = self._deliver(mailfrom, rcpttos, data) # TBD: what to do with refused addresses? print('we got some refusals:', refused, file=DEBUGSTREAM)
[ "def", "process_message", "(", "self", ",", "peer", ",", "mailfrom", ",", "rcpttos", ",", "data", ")", ":", "lines", "=", "data", ".", "split", "(", "'\\n'", ")", "# Look for the last header", "i", "=", "0", "for", "line", "in", "lines", ":", "if", "no...
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/smtpd.py#L752-L764
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/importlib/util.py
python
_LazyModule.__getattribute__
(self, attr)
return getattr(self, attr)
Trigger the load of the module and return the attribute.
Trigger the load of the module and return the attribute.
[ "Trigger", "the", "load", "of", "the", "module", "and", "return", "the", "attribute", "." ]
def __getattribute__(self, attr): """Trigger the load of the module and return the attribute.""" # All module metadata must be garnered from __spec__ in order to avoid # using mutated values. # Stop triggering this method. self.__class__ = _Module # Get the original name to make sure no object substitution occurred # in sys.modules. original_name = self.__spec__.name # Figure out exactly what attributes were mutated between the creation # of the module and now. attrs_then = self.__spec__.loader_state attrs_now = self.__dict__ attrs_updated = {} for key, value in attrs_now.items(): # Code that set the attribute may have kept a reference to the # assigned object, making identity more important than equality. if key not in attrs_then: attrs_updated[key] = value elif id(attrs_now[key]) != id(attrs_then[key]): attrs_updated[key] = value self.__spec__.loader.exec_module(self) # If exec_module() was used directly there is no guarantee the module # object was put into sys.modules. if original_name in sys.modules: if id(self) != id(sys.modules[original_name]): msg = ('module object for {!r} substituted in sys.modules ' 'during a lazy load') raise ValueError(msg.format(original_name)) # Update after loading since that's what would happen in an eager # loading situation. self.__dict__.update(attrs_updated) return getattr(self, attr)
[ "def", "__getattribute__", "(", "self", ",", "attr", ")", ":", "# All module metadata must be garnered from __spec__ in order to avoid", "# using mutated values.", "# Stop triggering this method.", "self", ".", "__class__", "=", "_Module", "# Get the original name to make sure no obj...
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/importlib/util.py#L216-L248
lspvic/CopyNet
2cc44dd672115fe88a2d76bd59b76fb2d7389bb4
copynet.py
python
CopyNetWrapper.__init__
(self, cell, encoder_states, encoder_input_ids, vocab_size, gen_vocab_size=None, encoder_state_size=None, initial_cell_state=None, name=None)
Args: cell: encoder_states: encoder_input_ids: tgt_vocab_size: gen_vocab_size: encoder_state_size: initial_cell_state:
Args: cell: encoder_states: encoder_input_ids: tgt_vocab_size: gen_vocab_size: encoder_state_size: initial_cell_state:
[ "Args", ":", "cell", ":", "encoder_states", ":", "encoder_input_ids", ":", "tgt_vocab_size", ":", "gen_vocab_size", ":", "encoder_state_size", ":", "initial_cell_state", ":" ]
def __init__(self, cell, encoder_states, encoder_input_ids, vocab_size, gen_vocab_size=None, encoder_state_size=None, initial_cell_state=None, name=None): """ Args: cell: encoder_states: encoder_input_ids: tgt_vocab_size: gen_vocab_size: encoder_state_size: initial_cell_state: """ super(CopyNetWrapper, self).__init__(name=name) self._cell = cell self._vocab_size = vocab_size self._gen_vocab_size = gen_vocab_size or vocab_size self._encoder_input_ids = encoder_input_ids self._encoder_states = encoder_states if encoder_state_size is None: encoder_state_size = self._encoder_states.shape[-1].value if encoder_state_size is None: raise ValueError("encoder_state_size must be set if we can't infer encoder_states last dimension size.") self._encoder_state_size = encoder_state_size self._initial_cell_state = initial_cell_state self._copy_weight = tf.get_variable('CopyWeight', [self._encoder_state_size , self._cell.output_size]) self._projection = tf.layers.Dense(self._gen_vocab_size, use_bias=False, name="OutputProjection")
[ "def", "__init__", "(", "self", ",", "cell", ",", "encoder_states", ",", "encoder_input_ids", ",", "vocab_size", ",", "gen_vocab_size", "=", "None", ",", "encoder_state_size", "=", "None", ",", "initial_cell_state", "=", "None", ",", "name", "=", "None", ")", ...
https://github.com/lspvic/CopyNet/blob/2cc44dd672115fe88a2d76bd59b76fb2d7389bb4/copynet.py#L24-L51
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.iterkeys
(self)
return iter(self)
od.iterkeys() -> an iterator over the keys in od
od.iterkeys() -> an iterator over the keys in od
[ "od", ".", "iterkeys", "()", "-", ">", "an", "iterator", "over", "the", "keys", "in", "od" ]
def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self)
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "self", ")" ]
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pip-7.1.2-py3.3.egg/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py#L128-L130
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/site-geraldo/django/contrib/syndication/feeds.py
python
Feed.get_feed
(self, url=None)
return feed
Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters.
Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters.
[ "Returns", "a", "feedgenerator", ".", "DefaultFeed", "object", "fully", "populated", "for", "this", "feed", ".", "Raises", "FeedDoesNotExist", "for", "invalid", "parameters", "." ]
def get_feed(self, url=None): """ Returns a feedgenerator.DefaultFeed object, fully populated, for this feed. Raises FeedDoesNotExist for invalid parameters. """ if url: bits = url.split('/') else: bits = [] try: obj = self.get_object(bits) except ObjectDoesNotExist: raise FeedDoesNotExist if Site._meta.installed: current_site = Site.objects.get_current() else: current_site = RequestSite(self.request) link = self.__get_dynamic_attr('link', obj) link = add_domain(current_site.domain, link) feed = self.feed_type( title = self.__get_dynamic_attr('title', obj), subtitle = self.__get_dynamic_attr('subtitle', obj), link = link, description = self.__get_dynamic_attr('description', obj), language = settings.LANGUAGE_CODE.decode(), feed_url = add_domain(current_site.domain, self.__get_dynamic_attr('feed_url', obj)), author_name = self.__get_dynamic_attr('author_name', obj), author_link = self.__get_dynamic_attr('author_link', obj), author_email = self.__get_dynamic_attr('author_email', obj), categories = self.__get_dynamic_attr('categories', obj), feed_copyright = self.__get_dynamic_attr('feed_copyright', obj), feed_guid = self.__get_dynamic_attr('feed_guid', obj), ttl = self.__get_dynamic_attr('ttl', obj), **self.feed_extra_kwargs(obj) ) try: title_tmp = loader.get_template(self.title_template_name) except TemplateDoesNotExist: title_tmp = Template('{{ obj }}') try: description_tmp = loader.get_template(self.description_template_name) except TemplateDoesNotExist: description_tmp = Template('{{ obj }}') for item in self.__get_dynamic_attr('items', obj): link = add_domain(current_site.domain, self.__get_dynamic_attr('item_link', item)) enc = None enc_url = self.__get_dynamic_attr('item_enclosure_url', item) if enc_url: enc = feedgenerator.Enclosure( url = smart_unicode(enc_url), length = smart_unicode(self.__get_dynamic_attr('item_enclosure_length', item)), mime_type = smart_unicode(self.__get_dynamic_attr('item_enclosure_mime_type', item)) ) author_name = self.__get_dynamic_attr('item_author_name', item) if author_name is not None: author_email = self.__get_dynamic_attr('item_author_email', item) author_link = self.__get_dynamic_attr('item_author_link', item) else: author_email = author_link = None pubdate = self.__get_dynamic_attr('item_pubdate', item) if pubdate: now = datetime.now() utcnow = datetime.utcnow() # Must always subtract smaller time from larger time here. if utcnow > now: sign = -1 tzDifference = (utcnow - now) else: sign = 1 tzDifference = (now - utcnow) # Round the timezone offset to the nearest half hour. tzOffsetMinutes = sign * ((tzDifference.seconds / 60 + 15) / 30) * 30 tzOffset = timedelta(minutes=tzOffsetMinutes) pubdate = pubdate.replace(tzinfo=FixedOffset(tzOffset)) feed.add_item( title = title_tmp.render(RequestContext(self.request, {'obj': item, 'site': current_site})), link = link, description = description_tmp.render(RequestContext(self.request, {'obj': item, 'site': current_site})), unique_id = self.__get_dynamic_attr('item_guid', item, link), enclosure = enc, pubdate = pubdate, author_name = author_name, author_email = author_email, author_link = author_link, categories = self.__get_dynamic_attr('item_categories', item), item_copyright = self.__get_dynamic_attr('item_copyright', item), **self.item_extra_kwargs(item) ) return feed
[ "def", "get_feed", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", ":", "bits", "=", "url", ".", "split", "(", "'/'", ")", "else", ":", "bits", "=", "[", "]", "try", ":", "obj", "=", "self", ".", "get_object", "(", "bits", ")", "...
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/site-geraldo/django/contrib/syndication/feeds.py#L79-L178
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v7/services/services/google_ads_service/client.py
python
GoogleAdsServiceClient.product_bidding_category_constant_path
( country_code: str, level: str, id: str, )
return "productBiddingCategoryConstants/{country_code}~{level}~{id}".format( country_code=country_code, level=level, id=id, )
Return a fully-qualified product_bidding_category_constant string.
Return a fully-qualified product_bidding_category_constant string.
[ "Return", "a", "fully", "-", "qualified", "product_bidding_category_constant", "string", "." ]
def product_bidding_category_constant_path( country_code: str, level: str, id: str, ) -> str: """Return a fully-qualified product_bidding_category_constant string.""" return "productBiddingCategoryConstants/{country_code}~{level}~{id}".format( country_code=country_code, level=level, id=id, )
[ "def", "product_bidding_category_constant_path", "(", "country_code", ":", "str", ",", "level", ":", "str", ",", "id", ":", "str", ",", ")", "->", "str", ":", "return", "\"productBiddingCategoryConstants/{country_code}~{level}~{id}\"", ".", "format", "(", "country_cod...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v7/services/services/google_ads_service/client.py#L2113-L2119
ni/nidaqmx-python
62fc6b48cbbb330fe1bcc9aedadc86610a1269b6
nidaqmx/_task_modules/channels/ai_channel.py
python
AIChannel.ai_rosette_strain_gage_rosette_meas_type
(self)
return StrainGageRosetteMeasurementType(val.value)
:class:`nidaqmx.constants.StrainGageRosetteMeasurementType`: Specifies the type of rosette measurement.
:class:`nidaqmx.constants.StrainGageRosetteMeasurementType`: Specifies the type of rosette measurement.
[ ":", "class", ":", "nidaqmx", ".", "constants", ".", "StrainGageRosetteMeasurementType", ":", "Specifies", "the", "type", "of", "rosette", "measurement", "." ]
def ai_rosette_strain_gage_rosette_meas_type(self): """ :class:`nidaqmx.constants.StrainGageRosetteMeasurementType`: Specifies the type of rosette measurement. """ val = ctypes.c_int() cfunc = (lib_importer.windll. DAQmxGetAIRosetteStrainGageRosetteMeasType) if cfunc.argtypes is None: with cfunc.arglock: if cfunc.argtypes is None: cfunc.argtypes = [ lib_importer.task_handle, ctypes_byte_str, ctypes.POINTER(ctypes.c_int)] error_code = cfunc( self._handle, self._name, ctypes.byref(val)) check_for_error(error_code) return StrainGageRosetteMeasurementType(val.value)
[ "def", "ai_rosette_strain_gage_rosette_meas_type", "(", "self", ")", ":", "val", "=", "ctypes", ".", "c_int", "(", ")", "cfunc", "=", "(", "lib_importer", ".", "windll", ".", "DAQmxGetAIRosetteStrainGageRosetteMeasType", ")", "if", "cfunc", ".", "argtypes", "is", ...
https://github.com/ni/nidaqmx-python/blob/62fc6b48cbbb330fe1bcc9aedadc86610a1269b6/nidaqmx/_task_modules/channels/ai_channel.py#L6235-L6255
aws/aws-cli
d697e0ed79fca0f853ce53efe1f83ee41a478134
awscli/utils.py
python
_eat_items
(value, iter_parts, part, end_char, replace_char='')
return ','.join(chunks)
Eat items from an iterator, optionally replacing characters with a blank and stopping when the end_char has been reached.
Eat items from an iterator, optionally replacing characters with a blank and stopping when the end_char has been reached.
[ "Eat", "items", "from", "an", "iterator", "optionally", "replacing", "characters", "with", "a", "blank", "and", "stopping", "when", "the", "end_char", "has", "been", "reached", "." ]
def _eat_items(value, iter_parts, part, end_char, replace_char=''): """ Eat items from an iterator, optionally replacing characters with a blank and stopping when the end_char has been reached. """ current = part chunks = [current.replace(replace_char, '')] while True: try: current = six.advance_iterator(iter_parts) except StopIteration: raise ValueError(value) chunks.append(current.replace(replace_char, '')) if current.endswith(end_char): break return ','.join(chunks)
[ "def", "_eat_items", "(", "value", ",", "iter_parts", ",", "part", ",", "end_char", ",", "replace_char", "=", "''", ")", ":", "current", "=", "part", "chunks", "=", "[", "current", ".", "replace", "(", "replace_char", ",", "''", ")", "]", "while", "Tru...
https://github.com/aws/aws-cli/blob/d697e0ed79fca0f853ce53efe1f83ee41a478134/awscli/utils.py#L82-L97
JelteF/PyLaTeX
1a73261b771ae15afbb3ca5f06d4ba61328f1c62
pylatex/tikz.py
python
TikZNode.dumps
(self)
return ' '.join(ret_str)
Return string representation of the node.
Return string representation of the node.
[ "Return", "string", "representation", "of", "the", "node", "." ]
def dumps(self): """Return string representation of the node.""" ret_str = [] ret_str.append(Command('node', options=self.options).dumps()) if self.handle is not None: ret_str.append('({})'.format(self.handle)) if self._node_position is not None: ret_str.append('at {}'.format(str(self._node_position))) if self._node_text is not None: ret_str.append('{{{text}}};'.format(text=self._node_text)) else: ret_str.append('{};') return ' '.join(ret_str)
[ "def", "dumps", "(", "self", ")", ":", "ret_str", "=", "[", "]", "ret_str", ".", "append", "(", "Command", "(", "'node'", ",", "options", "=", "self", ".", "options", ")", ".", "dumps", "(", ")", ")", "if", "self", ".", "handle", "is", "not", "No...
https://github.com/JelteF/PyLaTeX/blob/1a73261b771ae15afbb3ca5f06d4ba61328f1c62/pylatex/tikz.py#L230-L247
tdamdouni/Pythonista
3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad
_2016/mysql-connector-pythonista/protocol.py
python
MySQLProtocol.make_change_user
(self, seed, username=None, password=None, database=None, charset=33, client_flags=0)
return data
Make a MySQL packet with the Change User command
Make a MySQL packet with the Change User command
[ "Make", "a", "MySQL", "packet", "with", "the", "Change", "User", "command" ]
def make_change_user(self, seed, username=None, password=None, database=None, charset=33, client_flags=0): """Make a MySQL packet with the Change User command""" if not seed: raise errors.ProgrammingError('Seed missing') auth = self._prepare_auth(username, password, database, client_flags, seed) data = utils.int1store(ServerCmd.CHANGE_USER) +\ auth[0] + auth[1] + auth[2] + utils.int2store(charset) return data
[ "def", "make_change_user", "(", "self", ",", "seed", ",", "username", "=", "None", ",", "password", "=", "None", ",", "database", "=", "None", ",", "charset", "=", "33", ",", "client_flags", "=", "0", ")", ":", "if", "not", "seed", ":", "raise", "err...
https://github.com/tdamdouni/Pythonista/blob/3e082d53b6b9b501a3c8cf3251a8ad4c8be9c2ad/_2016/mysql-connector-pythonista/protocol.py#L109-L119
i-pan/kaggle-rsna18
2db498fe99615d935aa676f04847d0c562fd8e46
models/DeformableConvNets/faster_rcnn/core/DataParallelExecutorGroup.py
python
_merge_multi_context
(outputs, major_axis)
return rets
Merge outputs that lives on multiple context into one, so that they look like living on one context.
Merge outputs that lives on multiple context into one, so that they look like living on one context.
[ "Merge", "outputs", "that", "lives", "on", "multiple", "context", "into", "one", "so", "that", "they", "look", "like", "living", "on", "one", "context", "." ]
def _merge_multi_context(outputs, major_axis): """Merge outputs that lives on multiple context into one, so that they look like living on one context. """ rets = [] for tensors, axis in zip(outputs, major_axis): if axis >= 0: rets.append(nd.concatenate(tensors, axis=axis, always_copy=False)) else: # negative axis means the there is no batch_size axis, and all the # results should be the same on each device. We simply take the # first one, without checking they are actually the same rets.append(tensors[0]) return rets
[ "def", "_merge_multi_context", "(", "outputs", ",", "major_axis", ")", ":", "rets", "=", "[", "]", "for", "tensors", ",", "axis", "in", "zip", "(", "outputs", ",", "major_axis", ")", ":", "if", "axis", ">=", "0", ":", "rets", ".", "append", "(", "nd"...
https://github.com/i-pan/kaggle-rsna18/blob/2db498fe99615d935aa676f04847d0c562fd8e46/models/DeformableConvNets/faster_rcnn/core/DataParallelExecutorGroup.py#L47-L60
giacomocerquone/UnivaqBot
754519befe24dcc3c4a658160b727de7b14a6b21
libs/utils.py
python
subscribe_user
(telegram_id, section)
Add subscriber to the DB
Add subscriber to the DB
[ "Add", "subscriber", "to", "the", "DB" ]
def subscribe_user(telegram_id, section): """Add subscriber to the DB""" USERS[section].append(telegram_id) DATABASE.users.update_one({"telegramID": telegram_id}, {"$set": {section: telegram_id}})
[ "def", "subscribe_user", "(", "telegram_id", ",", "section", ")", ":", "USERS", "[", "section", "]", ".", "append", "(", "telegram_id", ")", "DATABASE", ".", "users", ".", "update_one", "(", "{", "\"telegramID\"", ":", "telegram_id", "}", ",", "{", "\"$set...
https://github.com/giacomocerquone/UnivaqBot/blob/754519befe24dcc3c4a658160b727de7b14a6b21/libs/utils.py#L58-L62
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/plugins/dbms/firebird/enumeration.py
python
Enumeration.getPasswordHashes
(self)
return {}
[]
def getPasswordHashes(self): warnMsg = "on Firebird it is not possible to enumerate the user password hashes" logger.warn(warnMsg) return {}
[ "def", "getPasswordHashes", "(", "self", ")", ":", "warnMsg", "=", "\"on Firebird it is not possible to enumerate the user password hashes\"", "logger", ".", "warn", "(", "warnMsg", ")", "return", "{", "}" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/plugins/dbms/firebird/enumeration.py#L21-L25
snarfed/granary
ab085de2aef0cff8ac31a99b5e21443a249e8419
granary/mastodon.py
python
Mastodon.upload_media
(self, media)
return ids
Uploads one or more images or videos from web URLs. https://docs.joinmastodon.org/methods/statuses/media/ https://docs.joinmastodon.org/user/posting/#attachments Args: media: sequence of AS image or stream objects, eg: [{'url': 'http://picture', 'displayName': 'a thing'}, ...] Returns: list of string media ids for uploaded files
Uploads one or more images or videos from web URLs.
[ "Uploads", "one", "or", "more", "images", "or", "videos", "from", "web", "URLs", "." ]
def upload_media(self, media): """Uploads one or more images or videos from web URLs. https://docs.joinmastodon.org/methods/statuses/media/ https://docs.joinmastodon.org/user/posting/#attachments Args: media: sequence of AS image or stream objects, eg: [{'url': 'http://picture', 'displayName': 'a thing'}, ...] Returns: list of string media ids for uploaded files """ uploaded = set() # URLs uploaded so far; for de-duping ids = [] for obj in media: url = util.get_url(obj, key='stream') or util.get_url(obj) if not url or url in uploaded: continue data = {} alt = obj.get('displayName') if alt: data['description'] = util.ellipsize(alt, chars=MAX_ALT_LENGTH) # TODO: mime type check? with util.requests_get(url, stream=True) as fetch: fetch.raise_for_status() upload = self._post(API_MEDIA, files={'file': fetch.raw}, data=data) logging.info(f'Got: {upload}') media_id = upload['id'] ids.append(media_id) uploaded.add(url) return ids
[ "def", "upload_media", "(", "self", ",", "media", ")", ":", "uploaded", "=", "set", "(", ")", "# URLs uploaded so far; for de-duping", "ids", "=", "[", "]", "for", "obj", "in", "media", ":", "url", "=", "util", ".", "get_url", "(", "obj", ",", "key", "...
https://github.com/snarfed/granary/blob/ab085de2aef0cff8ac31a99b5e21443a249e8419/granary/mastodon.py#L754-L789
MozillaSecurity/grizzly
1c41478e32f323189a2c322ec041c3e0902a158a
grizzly/reduce/core.py
python
ReduceManager.testcase_size
(self)
return sum(tc.data_size for tc in self.testcases)
Calculate the current testcase size. Returns: int: Current size of the testcase(s).
Calculate the current testcase size.
[ "Calculate", "the", "current", "testcase", "size", "." ]
def testcase_size(self): """Calculate the current testcase size. Returns: int: Current size of the testcase(s). """ return sum(tc.data_size for tc in self.testcases)
[ "def", "testcase_size", "(", "self", ")", ":", "return", "sum", "(", "tc", ".", "data_size", "for", "tc", "in", "self", ".", "testcases", ")" ]
https://github.com/MozillaSecurity/grizzly/blob/1c41478e32f323189a2c322ec041c3e0902a158a/grizzly/reduce/core.py#L418-L424
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/packages/urllib3/util/connection.py
python
_set_socket_options
(sock, options)
[]
def _set_socket_options(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt)
[ "def", "_set_socket_options", "(", "sock", ",", "options", ")", ":", "if", "options", "is", "None", ":", "return", "for", "opt", "in", "options", ":", "sock", ".", "setsockopt", "(", "*", "opt", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/requests/packages/urllib3/util/connection.py#L103-L108
robclewley/pydstool
939e3abc9dd1f180d35152bacbde57e24c85ff26
PyDSTool/Toolbox/optimizers/step/conjugate_gradient_step.py
python
HZConjugateGradientStep
()
return ConjugateGradientStep(function)
The Hager-Zhang conjugate gradient step Has good convergence capabilities (same as the FR-PRP gradient)
The Hager-Zhang conjugate gradient step Has good convergence capabilities (same as the FR-PRP gradient)
[ "The", "Hager", "-", "Zhang", "conjugate", "gradient", "step", "Has", "good", "convergence", "capabilities", "(", "same", "as", "the", "FR", "-", "PRP", "gradient", ")" ]
def HZConjugateGradientStep(): """ The Hager-Zhang conjugate gradient step Has good convergence capabilities (same as the FR-PRP gradient) """ def function(newGradient, oldGradient, oldStep): yk = newGradient - oldGradient beta = numpy.dot((yk - 2*numpy.linalg.norm(yk)/numpy.dot(yk.T, oldStep) * oldStep).T, newGradient) / numpy.dot(yk.T, oldStep) return beta return ConjugateGradientStep(function)
[ "def", "HZConjugateGradientStep", "(", ")", ":", "def", "function", "(", "newGradient", ",", "oldGradient", ",", "oldStep", ")", ":", "yk", "=", "newGradient", "-", "oldGradient", "beta", "=", "numpy", ".", "dot", "(", "(", "yk", "-", "2", "*", "numpy", ...
https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/Toolbox/optimizers/step/conjugate_gradient_step.py#L106-L115
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/models/fields.py
python
BaseSpatialField.__init__
(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs)
The initialization function for base spatial fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns.
The initialization function for base spatial fields. Takes the following as keyword arguments:
[ "The", "initialization", "function", "for", "base", "spatial", "fields", ".", "Takes", "the", "following", "as", "keyword", "arguments", ":" ]
def __init__(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs): """ The initialization function for base spatial fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of 'db_index' for geographic fields since index creation is different for geometry columns. """ # Setting the index flag with the value of the `spatial_index` keyword. self.spatial_index = spatial_index # Setting the SRID and getting the units. Unit information must be # easily available in the field instance for distance queries. self.srid = srid # Setting the verbose_name keyword argument with the positional # first parameter, so this works like normal fields. kwargs['verbose_name'] = verbose_name super(BaseSpatialField, self).__init__(**kwargs)
[ "def", "__init__", "(", "self", ",", "verbose_name", "=", "None", ",", "srid", "=", "4326", ",", "spatial_index", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Setting the index flag with the value of the `spatial_index` keyword.", "self", ".", "spatial_index",...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/models/fields.py#L86-L112
kpreid/shinysdr
25022d36903ff67e036e82a22b6555a12a4d8e8a
shinysdr/i/top.py
python
Top._get_audio_destination_type
(self)
return self.__audio_manager.get_destination_type()
for ContextForReceiver only
for ContextForReceiver only
[ "for", "ContextForReceiver", "only" ]
def _get_audio_destination_type(self): """for ContextForReceiver only""" return self.__audio_manager.get_destination_type()
[ "def", "_get_audio_destination_type", "(", "self", ")", ":", "return", "self", ".", "__audio_manager", ".", "get_destination_type", "(", ")" ]
https://github.com/kpreid/shinysdr/blob/25022d36903ff67e036e82a22b6555a12a4d8e8a/shinysdr/i/top.py#L412-L414
IntelAI/nauta
bbedb114a755cf1f43b834a58fc15fb6e3a4b291
applications/cli/util/k8s/k8s_info.py
python
get_kubectl_host
(replace_https=True, with_port=True)
[]
def get_kubectl_host(replace_https=True, with_port=True) -> str: config.load_kube_config() kubectl_host = configuration.Configuration().host parsed_kubectl_host = urlparse(kubectl_host) scheme = parsed_kubectl_host.scheme hostname = parsed_kubectl_host.hostname port = parsed_kubectl_host.port if not port: if scheme == 'http': port = 80 else: port = 443 if replace_https: if with_port: return f'{hostname}:{port}' else: return f'{hostname}' else: if with_port: return f'{scheme}://{hostname}:{port}' else: return f'{scheme}://{hostname}'
[ "def", "get_kubectl_host", "(", "replace_https", "=", "True", ",", "with_port", "=", "True", ")", "->", "str", ":", "config", ".", "load_kube_config", "(", ")", "kubectl_host", "=", "configuration", ".", "Configuration", "(", ")", ".", "host", "parsed_kubectl_...
https://github.com/IntelAI/nauta/blob/bbedb114a755cf1f43b834a58fc15fb6e3a4b291/applications/cli/util/k8s/k8s_info.py#L56-L78
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/stat.py
python
S_ISPORT
(mode)
return False
Return True if mode is from an event port.
Return True if mode is from an event port.
[ "Return", "True", "if", "mode", "is", "from", "an", "event", "port", "." ]
def S_ISPORT(mode): """Return True if mode is from an event port.""" return False
[ "def", "S_ISPORT", "(", "mode", ")", ":", "return", "False" ]
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/stat.py#L82-L84
armory3d/armory
5a7d41e39710b658029abcc32627435a79b9c02d
blender/arm/node_utils.py
python
get_socket_index
(sockets: Union[NodeInputs, NodeOutputs], socket: NodeSocket)
return -1
Find the socket index in the given node input or output collection, return -1 if not found.
Find the socket index in the given node input or output collection, return -1 if not found.
[ "Find", "the", "socket", "index", "in", "the", "given", "node", "input", "or", "output", "collection", "return", "-", "1", "if", "not", "found", "." ]
def get_socket_index(sockets: Union[NodeInputs, NodeOutputs], socket: NodeSocket) -> int: """Find the socket index in the given node input or output collection, return -1 if not found. """ for i in range(0, len(sockets)): if sockets[i] == socket: return i return -1
[ "def", "get_socket_index", "(", "sockets", ":", "Union", "[", "NodeInputs", ",", "NodeOutputs", "]", ",", "socket", ":", "NodeSocket", ")", "->", "int", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "sockets", ")", ")", ":", "if", "socke...
https://github.com/armory3d/armory/blob/5a7d41e39710b658029abcc32627435a79b9c02d/blender/arm/node_utils.py#L63-L70
hustcc/timeago
7bff6c54d0220df7d958d166f7cfa78bb5230d6f
src/timeago/__init__.py
python
format
(date, now=None, locale='en')
return '%s' in tmp and tmp % diff_seconds or tmp
the entry method
the entry method
[ "the", "entry", "method" ]
def format(date, now=None, locale='en'): ''' the entry method ''' if not isinstance(date, timedelta): if now is None: now = datetime.now() date = parser.parse(date) now = parser.parse(now) if date is None: raise ParameterUnvalid('the parameter `date` should be datetime ' '/ timedelta, or datetime formatted string.') if now is None: raise ParameterUnvalid('the parameter `now` should be datetime, ' 'or datetime formatted string.') date = now - date # the gap sec diff_seconds = int(total_seconds(date)) # is ago or in ago_in = 0 if diff_seconds < 0: ago_in = 1 # date is later then now, is the time in future diff_seconds *= -1 # change to positive tmp = 0 i = 0 while i < SEC_ARRAY_LEN: tmp = SEC_ARRAY[i] if diff_seconds >= tmp: i += 1 diff_seconds /= tmp else: break diff_seconds = int(diff_seconds) i *= 2 if diff_seconds > (i == 0 and 9 or 1): i += 1 if locale is None: locale = DEFAULT_LOCALE tmp = timeago_template(locale, i, ago_in) if hasattr(tmp, '__call__'): tmp = tmp(diff_seconds) return '%s' in tmp and tmp % diff_seconds or tmp
[ "def", "format", "(", "date", ",", "now", "=", "None", ",", "locale", "=", "'en'", ")", ":", "if", "not", "isinstance", "(", "date", ",", "timedelta", ")", ":", "if", "now", "is", "None", ":", "now", "=", "datetime", ".", "now", "(", ")", "date",...
https://github.com/hustcc/timeago/blob/7bff6c54d0220df7d958d166f7cfa78bb5230d6f/src/timeago/__init__.py#L36-L83
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_route.py
python
Utils.check_def_equal
(user_def, result_def, skip_keys=None, debug=False)
return True
Given a user defined definition, compare it with the results given back by our query.
Given a user defined definition, compare it with the results given back by our query.
[ "Given", "a", "user", "defined", "definition", "compare", "it", "with", "the", "results", "given", "back", "by", "our", "query", "." ]
def check_def_equal(user_def, result_def, skip_keys=None, debug=False): ''' Given a user defined definition, compare it with the results given back by our query. ''' # Currently these values are autogenerated and we do not need to check them skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for key, value in result_def.items(): if key in skip: continue # Both are lists if isinstance(value, list): if key not in user_def: if debug: print('User data does not have key [%s]' % key) print('User data: %s' % user_def) return False if not isinstance(user_def[key], list): if debug: print('user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key])) return False if len(user_def[key]) != len(value): if debug: print("List lengths are not equal.") print("key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value))) print("user_def: %s" % user_def[key]) print("value: %s" % value) return False for values in zip(user_def[key], value): if isinstance(values[0], dict) and isinstance(values[1], dict): if debug: print('sending list - list') print(type(values[0])) print(type(values[1])) result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug) if not result: print('list compare returned false') return False elif value != user_def[key]: if debug: print('value should be identical') print(user_def[key]) print(value) return False # recurse on a dictionary elif isinstance(value, dict): if key not in user_def: if debug: print("user_def does not have key [%s]" % key) return False if not isinstance(user_def[key], dict): if debug: print("dict returned false: not instance of dict") return False # before passing ensure keys match api_values = set(value.keys()) - set(skip) user_values = set(user_def[key].keys()) - set(skip) if api_values != user_values: if debug: print("keys are not equal in dict") print(user_values) print(api_values) return False result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug) if not result: if debug: print("dict returned false") print(result) return False # Verify each key, value pair is the same else: if key not in user_def or value != user_def[key]: if debug: print("value not equal; user_def does not have key") print(key) print(value) if key in user_def: print(user_def[key]) return False if debug: print('returning true') return True
[ "def", "check_def_equal", "(", "user_def", ",", "result_def", ",", "skip_keys", "=", "None", ",", "debug", "=", "False", ")", ":", "# Currently these values are autogenerated and we do not need to check them", "skip", "=", "[", "'metadata'", ",", "'status'", "]", "if"...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_route.py#L1384-L1476
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/retry.py
python
Retry._is_read_error
(self, err)
return isinstance(err, (ReadTimeoutError, ProtocolError))
Errors that occur after the request has been started, so we should assume that the server began processing it.
Errors that occur after the request has been started, so we should assume that the server began processing it.
[ "Errors", "that", "occur", "after", "the", "request", "has", "been", "started", "so", "we", "should", "assume", "that", "the", "server", "began", "processing", "it", "." ]
def _is_read_error(self, err): """ Errors that occur after the request has been started, so we should assume that the server began processing it. """ return isinstance(err, (ReadTimeoutError, ProtocolError))
[ "def", "_is_read_error", "(", "self", ",", "err", ")", ":", "return", "isinstance", "(", "err", ",", "(", "ReadTimeoutError", ",", "ProtocolError", ")", ")" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/pip/_vendor/requests/packages/urllib3/util/retry.py#L201-L205
dbrattli/OSlash
c271c7633daf9d72393b419cfc9229e427e6a42a
oslash/list.py
python
Nil.__iter__
(self)
Return iterator for List.
Return iterator for List.
[ "Return", "iterator", "for", "List", "." ]
def __iter__(self) -> Iterator: """Return iterator for List.""" while False: yield
[ "def", "__iter__", "(", "self", ")", "->", "Iterator", ":", "while", "False", ":", "yield" ]
https://github.com/dbrattli/OSlash/blob/c271c7633daf9d72393b419cfc9229e427e6a42a/oslash/list.py#L258-L262
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/req/req_file.py
python
preprocess
(content, options)
return lines_enum
Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options
Split, filter, and join lines, and return a line iterator
[ "Split", "filter", "and", "join", "lines", "and", "return", "a", "line", "iterator" ]
def preprocess(content, options): """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file :param options: cli options """ lines_enum = enumerate(content.splitlines(), start=1) lines_enum = join_lines(lines_enum) lines_enum = ignore_comments(lines_enum) lines_enum = skip_regex(lines_enum, options) return lines_enum
[ "def", "preprocess", "(", "content", ",", "options", ")", ":", "lines_enum", "=", "enumerate", "(", "content", ".", "splitlines", "(", ")", ",", "start", "=", "1", ")", "lines_enum", "=", "join_lines", "(", "lines_enum", ")", "lines_enum", "=", "ignore_com...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/req/req_file.py#L97-L107
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/noarch/dnslib/ranges.py
python
I
(attr)
return range_property(attr,0,4294967295)
Unsigned Long
Unsigned Long
[ "Unsigned", "Long" ]
def I(attr): """ Unsigned Long """ return range_property(attr,0,4294967295)
[ "def", "I", "(", "attr", ")", ":", "return", "range_property", "(", "attr", ",", "0", ",", "4294967295", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/noarch/dnslib/ranges.py#L63-L67
spacetx/starfish
0e879d995d5c49b6f5a842e201e3be04c91afc7e
starfish/data.py
python
MERFISH
(use_test_data: bool = False)
return Experiment.from_json("https://d2nhj9g34unfro.cloudfront.net/browse/formatted/" "MERFISH/20190511/experiment.json")
Loads an experiment with a single field of view of MERFISH data derived from cultured U2-OS cells, published in the following manuscript: `<https://doi.org/10.1073/pnas.1612826113>`_ The data consist of 16 images from 8 rounds, 2 channels, and a single z-plane. Each image is (2048, 2048) (y, x) Parameters ---------- use_test_data: bool If True, returns a cropped Experiment where tiles are (205, 405) (y, x) Returns ------- Experiment
Loads an experiment with a single field of view of MERFISH data derived from cultured U2-OS cells, published in the following manuscript:
[ "Loads", "an", "experiment", "with", "a", "single", "field", "of", "view", "of", "MERFISH", "data", "derived", "from", "cultured", "U2", "-", "OS", "cells", "published", "in", "the", "following", "manuscript", ":" ]
def MERFISH(use_test_data: bool = False) -> Experiment: """ Loads an experiment with a single field of view of MERFISH data derived from cultured U2-OS cells, published in the following manuscript: `<https://doi.org/10.1073/pnas.1612826113>`_ The data consist of 16 images from 8 rounds, 2 channels, and a single z-plane. Each image is (2048, 2048) (y, x) Parameters ---------- use_test_data: bool If True, returns a cropped Experiment where tiles are (205, 405) (y, x) Returns ------- Experiment """ if use_test_data: return Experiment.from_json( "https://d2nhj9g34unfro.cloudfront.net/20181005/MERFISH-TEST/experiment.json") return Experiment.from_json("https://d2nhj9g34unfro.cloudfront.net/browse/formatted/" "MERFISH/20190511/experiment.json")
[ "def", "MERFISH", "(", "use_test_data", ":", "bool", "=", "False", ")", "->", "Experiment", ":", "if", "use_test_data", ":", "return", "Experiment", ".", "from_json", "(", "\"https://d2nhj9g34unfro.cloudfront.net/20181005/MERFISH-TEST/experiment.json\"", ")", "return", ...
https://github.com/spacetx/starfish/blob/0e879d995d5c49b6f5a842e201e3be04c91afc7e/starfish/data.py#L4-L27
poliastro/poliastro
6223a3f127ed730967a7091c4535100176a6c9e4
src/poliastro/plotting/static.py
python
StaticOrbitPlotter.plot
(self, orbit, *, label=None, color=None, trail=False)
return lines
Plots state and osculating orbit in their plane. Parameters ---------- orbit : ~poliastro.twobody.orbit.Orbit Orbit to plot. label : str, optional Label of the orbit. color : str, optional Color of the line and the position. trail : bool, optional Fade the orbit trail, default to False.
Plots state and osculating orbit in their plane.
[ "Plots", "state", "and", "osculating", "orbit", "in", "their", "plane", "." ]
def plot(self, orbit, *, label=None, color=None, trail=False): """Plots state and osculating orbit in their plane. Parameters ---------- orbit : ~poliastro.twobody.orbit.Orbit Orbit to plot. label : str, optional Label of the orbit. color : str, optional Color of the line and the position. trail : bool, optional Fade the orbit trail, default to False. """ if not self._frame: self.set_orbit_frame(orbit) lines = self._plot(orbit, label=label, color=color, trail=trail) lines = lines[0] + [lines[1]] # Set legend using label from last added trajectory self._set_legend(self._trajectories[-1].label, *lines) return lines
[ "def", "plot", "(", "self", ",", "orbit", ",", "*", ",", "label", "=", "None", ",", "color", "=", "None", ",", "trail", "=", "False", ")", ":", "if", "not", "self", ".", "_frame", ":", "self", ".", "set_orbit_frame", "(", "orbit", ")", "lines", "...
https://github.com/poliastro/poliastro/blob/6223a3f127ed730967a7091c4535100176a6c9e4/src/poliastro/plotting/static.py#L249-L273
conda/conda
09cb6bdde68e551852c3844fd2b59c8ba4cafce2
conda/common/serialize.py
python
yaml_round_trip_dump
(object)
return yaml.round_trip_dump( object, block_seq_indent=2, default_flow_style=False, indent=2 )
dump object to string
dump object to string
[ "dump", "object", "to", "string" ]
def yaml_round_trip_dump(object): """dump object to string""" return yaml.round_trip_dump( object, block_seq_indent=2, default_flow_style=False, indent=2 )
[ "def", "yaml_round_trip_dump", "(", "object", ")", ":", "return", "yaml", ".", "round_trip_dump", "(", "object", ",", "block_seq_indent", "=", "2", ",", "default_flow_style", "=", "False", ",", "indent", "=", "2", ")" ]
https://github.com/conda/conda/blob/09cb6bdde68e551852c3844fd2b59c8ba4cafce2/conda/common/serialize.py#L70-L74
respeaker/get_started_with_respeaker
ec859759fcec7e683a5e09328a8ea307046f353d
files/usr/lib/python2.7/site-packages/sockjs/tornado/basehandler.py
python
BaseHandler._log_disconnect
(self)
Decrement connection count
Decrement connection count
[ "Decrement", "connection", "count" ]
def _log_disconnect(self): """Decrement connection count""" if self.logged: self.server.stats.on_conn_closed() self.logged = False
[ "def", "_log_disconnect", "(", "self", ")", ":", "if", "self", ".", "logged", ":", "self", ".", "server", ".", "stats", ".", "on_conn_closed", "(", ")", "self", ".", "logged", "=", "False" ]
https://github.com/respeaker/get_started_with_respeaker/blob/ec859759fcec7e683a5e09328a8ea307046f353d/files/usr/lib/python2.7/site-packages/sockjs/tornado/basehandler.py#L35-L39
compas-dev/compas
0b33f8786481f710115fb1ae5fe79abc2a9a5175
src/compas/datastructures/graph/graph.py
python
Graph.number_of_edges
(self)
return len(list(self.edges()))
Compute the number of edges of the network. Returns ------- int the number of edges.
Compute the number of edges of the network.
[ "Compute", "the", "number", "of", "edges", "of", "the", "network", "." ]
def number_of_edges(self): """Compute the number of edges of the network. Returns ------- int the number of edges. """ return len(list(self.edges()))
[ "def", "number_of_edges", "(", "self", ")", ":", "return", "len", "(", "list", "(", "self", ".", "edges", "(", ")", ")", ")" ]
https://github.com/compas-dev/compas/blob/0b33f8786481f710115fb1ae5fe79abc2a9a5175/src/compas/datastructures/graph/graph.py#L562-L570
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/flaskbb/user/models.py
python
Guest.permissions
(self)
return self.get_permissions()
[]
def permissions(self): return self.get_permissions()
[ "def", "permissions", "(", "self", ")", ":", "return", "self", ".", "get_permissions", "(", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/flaskbb/user/models.py#L474-L475
thombashi/pytablewriter
120392a8723a8ca13a6a519e7e3d11c447e9d9c7
pytablewriter/writer/binary/_excel.py
python
ExcelTableWriter.first_data_row
(self)
return self._first_data_row
:return: Index of the first row of the data (table body). :rtype: int .. note:: |excel_attr|
:return: Index of the first row of the data (table body). :rtype: int
[ ":", "return", ":", "Index", "of", "the", "first", "row", "of", "the", "data", "(", "table", "body", ")", ".", ":", "rtype", ":", "int" ]
def first_data_row(self) -> int: """ :return: Index of the first row of the data (table body). :rtype: int .. note:: |excel_attr| """ return self._first_data_row
[ "def", "first_data_row", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_first_data_row" ]
https://github.com/thombashi/pytablewriter/blob/120392a8723a8ca13a6a519e7e3d11c447e9d9c7/pytablewriter/writer/binary/_excel.py#L77-L85
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/django/views/generic/dates.py
python
WeekMixin._get_current_week
(self, date)
return date - datetime.timedelta(self._get_weekday(date))
Return the start date of the current interval.
Return the start date of the current interval.
[ "Return", "the", "start", "date", "of", "the", "current", "interval", "." ]
def _get_current_week(self, date): """ Return the start date of the current interval. """ return date - datetime.timedelta(self._get_weekday(date))
[ "def", "_get_current_week", "(", "self", ",", "date", ")", ":", "return", "date", "-", "datetime", ".", "timedelta", "(", "self", ".", "_get_weekday", "(", "date", ")", ")" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/django/views/generic/dates.py#L236-L240
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/units/utils.py
python
_get_first_sentence
(s)
return s.replace('\n', ' ')
Get the first sentence from a string and remove any carriage returns.
Get the first sentence from a string and remove any carriage returns.
[ "Get", "the", "first", "sentence", "from", "a", "string", "and", "remove", "any", "carriage", "returns", "." ]
def _get_first_sentence(s): """ Get the first sentence from a string and remove any carriage returns. """ x = re.match(r".*?\S\.\s", s) if x is not None: s = x.group(0) return s.replace('\n', ' ')
[ "def", "_get_first_sentence", "(", "s", ")", ":", "x", "=", "re", ".", "match", "(", "r\".*?\\S\\.\\s\"", ",", "s", ")", "if", "x", "is", "not", "None", ":", "s", "=", "x", ".", "group", "(", "0", ")", "return", "s", ".", "replace", "(", "'\\n'",...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/units/utils.py#L24-L33
angr/angr-management
60ae5fa483e74810fb3a3da8d37b00034d7fefab
angrmanagement/ui/widgets/qxref_viewer.py
python
QXRefAddressModel._access_type
(_r)
return _r.type_string
:param XRef _r: :return:
[]
def _access_type(_r): """ :param XRef _r: :return: """ return _r.type_string
[ "def", "_access_type", "(", "_r", ")", ":", "return", "_r", ".", "type_string" ]
https://github.com/angr/angr-management/blob/60ae5fa483e74810fb3a3da8d37b00034d7fefab/angrmanagement/ui/widgets/qxref_viewer.py#L222-L228
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/frame.py
python
DataFrame.from_csv
(cls, path, header=0, sep=',', index_col=0, parse_dates=True, encoding=None, tupleize_cols=None, infer_datetime_format=False)
return read_csv(path, header=header, sep=sep, parse_dates=parse_dates, index_col=index_col, encoding=encoding, tupleize_cols=tupleize_cols, infer_datetime_format=infer_datetime_format)
Read CSV file. .. deprecated:: 0.21.0 Use :func:`pandas.read_csv` instead. It is preferable to use the more powerful :func:`pandas.read_csv` for most general purposes, but ``from_csv`` makes for an easy roundtrip to and from a file (the exact counterpart of ``to_csv``), especially with a DataFrame of time series data. This method only differs from the preferred :func:`pandas.read_csv` in some defaults: - `index_col` is ``0`` instead of ``None`` (take first column as index by default) - `parse_dates` is ``True`` instead of ``False`` (try parsing the index as datetime by default) So a ``pd.DataFrame.from_csv(path)`` can be replaced by ``pd.read_csv(path, index_col=0, parse_dates=True)``. Parameters ---------- path : string file path or file handle / StringIO header : int, default 0 Row to use as header (skip prior rows) sep : string, default ',' Field delimiter index_col : int or sequence, default 0 Column to use for index. If a sequence is given, a MultiIndex is used. Different default from read_table parse_dates : boolean, default True Parse dates. Different default from read_table tupleize_cols : boolean, default False write multi_index columns as a list of tuples (if True) or new (expanded format) if False) infer_datetime_format : boolean, default False If True and `parse_dates` is True for a column, try to infer the datetime format based on the first datetime string. If the format can be inferred, there often will be a large parsing speed-up. Returns ------- y : DataFrame See Also -------- pandas.read_csv
Read CSV file.
[ "Read", "CSV", "file", "." ]
def from_csv(cls, path, header=0, sep=',', index_col=0, parse_dates=True, encoding=None, tupleize_cols=None, infer_datetime_format=False): """ Read CSV file. .. deprecated:: 0.21.0 Use :func:`pandas.read_csv` instead. It is preferable to use the more powerful :func:`pandas.read_csv` for most general purposes, but ``from_csv`` makes for an easy roundtrip to and from a file (the exact counterpart of ``to_csv``), especially with a DataFrame of time series data. This method only differs from the preferred :func:`pandas.read_csv` in some defaults: - `index_col` is ``0`` instead of ``None`` (take first column as index by default) - `parse_dates` is ``True`` instead of ``False`` (try parsing the index as datetime by default) So a ``pd.DataFrame.from_csv(path)`` can be replaced by ``pd.read_csv(path, index_col=0, parse_dates=True)``. Parameters ---------- path : string file path or file handle / StringIO header : int, default 0 Row to use as header (skip prior rows) sep : string, default ',' Field delimiter index_col : int or sequence, default 0 Column to use for index. If a sequence is given, a MultiIndex is used. Different default from read_table parse_dates : boolean, default True Parse dates. Different default from read_table tupleize_cols : boolean, default False write multi_index columns as a list of tuples (if True) or new (expanded format) if False) infer_datetime_format : boolean, default False If True and `parse_dates` is True for a column, try to infer the datetime format based on the first datetime string. If the format can be inferred, there often will be a large parsing speed-up. Returns ------- y : DataFrame See Also -------- pandas.read_csv """ warnings.warn("from_csv is deprecated. Please use read_csv(...) " "instead. Note that some of the default arguments are " "different, so please refer to the documentation " "for from_csv when changing your function calls", FutureWarning, stacklevel=2) from pandas.io.parsers import read_csv return read_csv(path, header=header, sep=sep, parse_dates=parse_dates, index_col=index_col, encoding=encoding, tupleize_cols=tupleize_cols, infer_datetime_format=infer_datetime_format)
[ "def", "from_csv", "(", "cls", ",", "path", ",", "header", "=", "0", ",", "sep", "=", "','", ",", "index_col", "=", "0", ",", "parse_dates", "=", "True", ",", "encoding", "=", "None", ",", "tupleize_cols", "=", "None", ",", "infer_datetime_format", "="...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/pandas/core/frame.py#L1837-L1901
pyload/pyload
4410827ca7711f1a3cf91a0b11e967b81bbbcaa2
src/pyload/core/managers/file_manager.py
python
FileManager.restart_package
(self, id)
restart package.
restart package.
[ "restart", "package", "." ]
def restart_package(self, id): """ restart package. """ pyfiles = list(self.cache.values()) for pyfile in pyfiles: if pyfile.packageid == id: self.restart_file(pyfile.id) self.pyload.db.restart_package(id) if id in self.package_cache: self.package_cache[id].set_finished = False e = UpdateEvent( "pack", id, "collector" if not self.get_package(id).queue else "queue" ) self.pyload.event_manager.add_event(e)
[ "def", "restart_package", "(", "self", ",", "id", ")", ":", "pyfiles", "=", "list", "(", "self", ".", "cache", ".", "values", "(", ")", ")", "for", "pyfile", "in", "pyfiles", ":", "if", "pyfile", ".", "packageid", "==", "id", ":", "self", ".", "res...
https://github.com/pyload/pyload/blob/4410827ca7711f1a3cf91a0b11e967b81bbbcaa2/src/pyload/core/managers/file_manager.py#L438-L455
deezer/spleeter
48e38088370bdc2997040ea3c57f96495bdf75a5
spleeter/audio/convertor.py
python
to_n_channels
(waveform: tf.Tensor, n_channels: int)
return tf.cond( tf.shape(waveform)[1] >= n_channels, true_fn=lambda: waveform[:, :n_channels], false_fn=lambda: tf.tile(waveform, [1, n_channels])[:, :n_channels], )
Convert a waveform to n_channels by removing or duplicating channels if needed (in tensorflow). Parameters: waveform (tensorflow.Tensor): Waveform to transform. n_channels (int): Number of channel to reshape waveform in. Returns: tensorflow.Tensor: Reshaped waveform.
Convert a waveform to n_channels by removing or duplicating channels if needed (in tensorflow).
[ "Convert", "a", "waveform", "to", "n_channels", "by", "removing", "or", "duplicating", "channels", "if", "needed", "(", "in", "tensorflow", ")", "." ]
def to_n_channels(waveform: tf.Tensor, n_channels: int) -> tf.Tensor: """ Convert a waveform to n_channels by removing or duplicating channels if needed (in tensorflow). Parameters: waveform (tensorflow.Tensor): Waveform to transform. n_channels (int): Number of channel to reshape waveform in. Returns: tensorflow.Tensor: Reshaped waveform. """ return tf.cond( tf.shape(waveform)[1] >= n_channels, true_fn=lambda: waveform[:, :n_channels], false_fn=lambda: tf.tile(waveform, [1, n_channels])[:, :n_channels], )
[ "def", "to_n_channels", "(", "waveform", ":", "tf", ".", "Tensor", ",", "n_channels", ":", "int", ")", "->", "tf", ".", "Tensor", ":", "return", "tf", ".", "cond", "(", "tf", ".", "shape", "(", "waveform", ")", "[", "1", "]", ">=", "n_channels", ",...
https://github.com/deezer/spleeter/blob/48e38088370bdc2997040ea3c57f96495bdf75a5/spleeter/audio/convertor.py#L20-L39
chapmanb/bcbb
dbfb52711f0bfcc1d26c5a5b53c9ff4f50dc0027
nextgen/bcbio/pipeline/qcsummary.py
python
summary_metrics
(run_info, analysis_dir, fc_name, fc_date, fastq_dir)
return lane_info, sample_info, tab_out
Reformat run and analysis statistics into a YAML-ready format.
Reformat run and analysis statistics into a YAML-ready format.
[ "Reformat", "run", "and", "analysis", "statistics", "into", "a", "YAML", "-", "ready", "format", "." ]
def summary_metrics(run_info, analysis_dir, fc_name, fc_date, fastq_dir): """Reformat run and analysis statistics into a YAML-ready format. """ tab_out = [] lane_info = [] sample_info = [] for lane_xs in run_info["details"]: run = lane_xs[0] tab_out.append([run["lane"], run.get("researcher", ""), run.get("name", ""), run.get("description")]) base_info = dict( researcher = run.get("researcher_id", ""), sample = run.get("sample_id", ""), lane = run["lane"], request = run_info["run_id"]) cur_lane_info = copy.deepcopy(base_info) cur_lane_info["metrics"] = _bustard_stats(run["lane"], fastq_dir, fc_date, analysis_dir) lane_info.append(cur_lane_info) for lane_x in lane_xs: cur_name = "%s_%s_%s" % (run["lane"], fc_date, fc_name) if lane_x["barcode_id"]: cur_name = "%s_%s-" % (cur_name, lane_x["barcode_id"]) stats = _metrics_from_stats(_lane_stats(cur_name, analysis_dir)) if stats: cur_run_info = copy.deepcopy(base_info) cur_run_info["metrics"] = stats cur_run_info["barcode_id"] = str(lane_x["barcode_id"]) cur_run_info["barcode_type"] = str(lane_x.get("barcode_type", "")) sample_info.append(cur_run_info) return lane_info, sample_info, tab_out
[ "def", "summary_metrics", "(", "run_info", ",", "analysis_dir", ",", "fc_name", ",", "fc_date", ",", "fastq_dir", ")", ":", "tab_out", "=", "[", "]", "lane_info", "=", "[", "]", "sample_info", "=", "[", "]", "for", "lane_xs", "in", "run_info", "[", "\"de...
https://github.com/chapmanb/bcbb/blob/dbfb52711f0bfcc1d26c5a5b53c9ff4f50dc0027/nextgen/bcbio/pipeline/qcsummary.py#L248-L278
blackye/webdirdig
11eb3df84d228127dde1dd4afcb922f5075903a2
thirdparty_libs/requests/packages/urllib3/exceptions.py
python
MaxRetryError.__init__
(self, pool, url, reason=None)
[]
def __init__(self, pool, url, reason=None): self.reason = reason message = "Max retries exceeded with url: %s" % url if reason: message += " (Caused by %s: %s)" % (type(reason), reason) else: message += " (Caused by redirect)" RequestError.__init__(self, pool, url, message)
[ "def", "__init__", "(", "self", ",", "pool", ",", "url", ",", "reason", "=", "None", ")", ":", "self", ".", "reason", "=", "reason", "message", "=", "\"Max retries exceeded with url: %s\"", "%", "url", "if", "reason", ":", "message", "+=", "\" (Caused by %s:...
https://github.com/blackye/webdirdig/blob/11eb3df84d228127dde1dd4afcb922f5075903a2/thirdparty_libs/requests/packages/urllib3/exceptions.py#L52-L61
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/site-packages/setuptools/msvc.py
python
EnvironmentInfo.FxTools
(self)
return tools
Microsoft .NET Framework Tools
Microsoft .NET Framework Tools
[ "Microsoft", ".", "NET", "Framework", "Tools" ]
def FxTools(self): """ Microsoft .NET Framework Tools """ pi = self.pi si = self.si if self.vc_ver <= 10.0: include32 = True include64 = not pi.target_is_x86() and not pi.current_is_x86() else: include32 = pi.target_is_x86() or pi.current_is_x86() include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64' tools = [] if include32: tools += [os.path.join(si.FrameworkDir32, ver) for ver in si.FrameworkVersion32] if include64: tools += [os.path.join(si.FrameworkDir64, ver) for ver in si.FrameworkVersion64] return tools
[ "def", "FxTools", "(", "self", ")", ":", "pi", "=", "self", ".", "pi", "si", "=", "self", ".", "si", "if", "self", ".", "vc_ver", "<=", "10.0", ":", "include32", "=", "True", "include64", "=", "not", "pi", ".", "target_is_x86", "(", ")", "and", "...
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/site-packages/setuptools/msvc.py#L1071-L1092
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/commandSequencer/CommandSequencer.py
python
CommandSequencer.command_stack_change_indicator
(self)
return self._command_stack_change_counter
Return the current value of a "change indicator" for the command stack as a whole. Any change to the command stack causes this to change, provided it's viewed during one of the command_update* methods in the Command API (see baseCommand for their default defs and docstrings). @see: same-named method in class Assembly.
Return the current value of a "change indicator" for the command stack as a whole. Any change to the command stack causes this to change, provided it's viewed during one of the command_update* methods in the Command API (see baseCommand for their default defs and docstrings).
[ "Return", "the", "current", "value", "of", "a", "change", "indicator", "for", "the", "command", "stack", "as", "a", "whole", ".", "Any", "change", "to", "the", "command", "stack", "causes", "this", "to", "change", "provided", "it", "s", "viewed", "during",...
def command_stack_change_indicator(self): """ Return the current value of a "change indicator" for the command stack as a whole. Any change to the command stack causes this to change, provided it's viewed during one of the command_update* methods in the Command API (see baseCommand for their default defs and docstrings). @see: same-named method in class Assembly. """ return self._command_stack_change_counter pass
[ "def", "command_stack_change_indicator", "(", "self", ")", ":", "return", "self", ".", "_command_stack_change_counter", "pass" ]
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/commandSequencer/CommandSequencer.py#L1236-L1247
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit /tools/sqli/thirdparty/xdot/xdot.py
python
ZoomAction.stop
(self)
[]
def stop(self): self.dot_widget.queue_draw()
[ "def", "stop", "(", "self", ")", ":", "self", ".", "dot_widget", ".", "queue_draw", "(", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit /tools/sqli/thirdparty/xdot/xdot.py#L1340-L1341
nussl/nussl
471e7965c5788bff9fe2e1f7884537cae2d18e6f
nussl/core/migration.py
python
SafeModelLoader._load_eval
(self, eval_dict)
return result
Helper function to load eval dictionary safely.
Helper function to load eval dictionary safely.
[ "Helper", "function", "to", "load", "eval", "dictionary", "safely", "." ]
def _load_eval(self, eval_dict): """Helper function to load eval dictionary safely.""" if self.eval.lower() == 'bssevalv4': keys = BSSEvalV4.keys else: keys = BSSEvalScale.keys stats_keys = ['mean', 'median', 'std'] result = {} for k in keys: if k not in eval_dict: stats = {s: 'UNAVAILABLE' for s in stats_keys} else: stats = {} for s in stats_keys: if s in eval_dict[k]: stats[s] = eval_dict[k][s] else: stats[s] = 'UNAVAILABLE' result[k] = stats return result
[ "def", "_load_eval", "(", "self", ",", "eval_dict", ")", ":", "if", "self", ".", "eval", ".", "lower", "(", ")", "==", "'bssevalv4'", ":", "keys", "=", "BSSEvalV4", ".", "keys", "else", ":", "keys", "=", "BSSEvalScale", ".", "keys", "stats_keys", "=", ...
https://github.com/nussl/nussl/blob/471e7965c5788bff9fe2e1f7884537cae2d18e6f/nussl/core/migration.py#L116-L137
chemlab/chemlab
c8730966316d101e24f39ac3b96b51282aba0abe
chemlab/utils/distances.py
python
distances_within
(coords_a, coords_b, cutoff, periodic=False, method="simple")
return mat[mat.nonzero()]
Calculate distances between the array of coordinates *coord_a* and *coord_b* within a certain cutoff. This function is a wrapper around different routines and data structures for distance searches. It return a np.ndarray containing the distances. **Parameters** coords_a: np.ndarray((N, 3), dtype=float) First coordinate array coords_b: np.ndarray((N, 3), dtype=float) Second coordinate array cutoff: float Maximum distance to search for periodic: False or np.ndarray((3,), dtype=float) If False, don't consider periodic images. Otherwise periodic is an array containing the periodicity in the 3 dimensions. method: "simple" | "cell-lists" The method to use. *simple* is a brute-force distance search, *kdtree* uses scipy ``ckdtree`` module (periodic not available) and *cell-lists* uses the cell linked list method.
Calculate distances between the array of coordinates *coord_a* and *coord_b* within a certain cutoff. This function is a wrapper around different routines and data structures for distance searches. It return a np.ndarray containing the distances. **Parameters**
[ "Calculate", "distances", "between", "the", "array", "of", "coordinates", "*", "coord_a", "*", "and", "*", "coord_b", "*", "within", "a", "certain", "cutoff", ".", "This", "function", "is", "a", "wrapper", "around", "different", "routines", "and", "data", "s...
def distances_within(coords_a, coords_b, cutoff, periodic=False, method="simple"): """Calculate distances between the array of coordinates *coord_a* and *coord_b* within a certain cutoff. This function is a wrapper around different routines and data structures for distance searches. It return a np.ndarray containing the distances. **Parameters** coords_a: np.ndarray((N, 3), dtype=float) First coordinate array coords_b: np.ndarray((N, 3), dtype=float) Second coordinate array cutoff: float Maximum distance to search for periodic: False or np.ndarray((3,), dtype=float) If False, don't consider periodic images. Otherwise periodic is an array containing the periodicity in the 3 dimensions. method: "simple" | "cell-lists" The method to use. *simple* is a brute-force distance search, *kdtree* uses scipy ``ckdtree`` module (periodic not available) and *cell-lists* uses the cell linked list method. """ mat = distance_matrix(coords_a, coords_b, cutoff, periodic, method) return mat[mat.nonzero()]
[ "def", "distances_within", "(", "coords_a", ",", "coords_b", ",", "cutoff", ",", "periodic", "=", "False", ",", "method", "=", "\"simple\"", ")", ":", "mat", "=", "distance_matrix", "(", "coords_a", ",", "coords_b", ",", "cutoff", ",", "periodic", ",", "me...
https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/utils/distances.py#L9-L36