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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
openstack/cinder | 23494a6d6c51451688191e1847a458f1d3cdcaa5 | cinder/db/api.py | python | image_volume_cache_get_all | (context, **filters) | return IMPL.image_volume_cache_get_all(context, **filters) | Query for all image volume cache entry for a host. | Query for all image volume cache entry for a host. | [
"Query",
"for",
"all",
"image",
"volume",
"cache",
"entry",
"for",
"a",
"host",
"."
] | def image_volume_cache_get_all(context, **filters):
"""Query for all image volume cache entry for a host."""
return IMPL.image_volume_cache_get_all(context, **filters) | [
"def",
"image_volume_cache_get_all",
"(",
"context",
",",
"*",
"*",
"filters",
")",
":",
"return",
"IMPL",
".",
"image_volume_cache_get_all",
"(",
"context",
",",
"*",
"*",
"filters",
")"
] | https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/db/api.py#L1685-L1687 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/path.py | python | Path.__init__ | (self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False) | Create a new path with the given vertices and codes.
Parameters
----------
vertices : array_like
The ``(n, 2)`` float array, masked array or sequence of pairs
representing the vertices of the path.
If *vertices* contains masked values, they will be converted
to NaNs which are then handled correctly by the Agg
PathIterator and other consumers of path data, such as
:meth:`iter_segments`.
codes : {None, array_like}, optional
n-length array integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon.
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays. | Create a new path with the given vertices and codes. | [
"Create",
"a",
"new",
"path",
"with",
"the",
"given",
"vertices",
"and",
"codes",
"."
] | def __init__(self, vertices, codes=None, _interpolation_steps=1,
closed=False, readonly=False):
"""
Create a new path with the given vertices and codes.
Parameters
----------
vertices : array_like
The ``(n, 2)`` float array, masked array or sequence of pairs
representing the vertices of the path.
If *vertices* contains masked values, they will be converted
to NaNs which are then handled correctly by the Agg
PathIterator and other consumers of path data, such as
:meth:`iter_segments`.
codes : {None, array_like}, optional
n-length array integers representing the codes of the path.
If not None, codes must be the same length as vertices.
If None, *vertices* will be treated as a series of line segments.
_interpolation_steps : int, optional
Used as a hint to certain projections, such as Polar, that this
path should be linearly interpolated immediately before drawing.
This attribute is primarily an implementation detail and is not
intended for public use.
closed : bool, optional
If *codes* is None and closed is True, vertices will be treated as
line segments of a closed polygon.
readonly : bool, optional
Makes the path behave in an immutable way and sets the vertices
and codes as read-only arrays.
"""
vertices = _to_unmasked_float_array(vertices)
if vertices.ndim != 2 or vertices.shape[1] != 2:
raise ValueError(
"'vertices' must be a 2D list or array with shape Nx2")
if codes is not None:
codes = np.asarray(codes, self.code_type)
if codes.ndim != 1 or len(codes) != len(vertices):
raise ValueError("'codes' must be a 1D list or array with the "
"same length of 'vertices'")
if len(codes) and codes[0] != self.MOVETO:
raise ValueError("The first element of 'code' must be equal "
"to 'MOVETO' ({})".format(self.MOVETO))
elif closed and len(vertices):
codes = np.empty(len(vertices), dtype=self.code_type)
codes[0] = self.MOVETO
codes[1:-1] = self.LINETO
codes[-1] = self.CLOSEPOLY
self._vertices = vertices
self._codes = codes
self._interpolation_steps = _interpolation_steps
self._update_values()
if readonly:
self._vertices.flags.writeable = False
if self._codes is not None:
self._codes.flags.writeable = False
self._readonly = True
else:
self._readonly = False | [
"def",
"__init__",
"(",
"self",
",",
"vertices",
",",
"codes",
"=",
"None",
",",
"_interpolation_steps",
"=",
"1",
",",
"closed",
"=",
"False",
",",
"readonly",
"=",
"False",
")",
":",
"vertices",
"=",
"_to_unmasked_float_array",
"(",
"vertices",
")",
"if"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/path.py#L96-L157 | ||
nltk/nltk | 3f74ac55681667d7ef78b664557487145f51eb02 | nltk/sem/logic.py | python | LambdaExpression._set_type | (self, other_type=ANY_TYPE, signature=None) | :see Expression._set_type() | :see Expression._set_type() | [
":",
"see",
"Expression",
".",
"_set_type",
"()"
] | def _set_type(self, other_type=ANY_TYPE, signature=None):
""":see Expression._set_type()"""
assert isinstance(other_type, Type)
if signature is None:
signature = defaultdict(list)
self.term._set_type(other_type.second, signature)
if not self.type.resolve(other_type):
raise TypeResolutionException(self, other_type) | [
"def",
"_set_type",
"(",
"self",
",",
"other_type",
"=",
"ANY_TYPE",
",",
"signature",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"other_type",
",",
"Type",
")",
"if",
"signature",
"is",
"None",
":",
"signature",
"=",
"defaultdict",
"(",
"list",
... | https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/sem/logic.py#L1692-L1701 | ||
blockcypher/explorer | 3cb07c58ed6573964921e343fce01552accdf958 | transactions/views.py | python | push_tx | (request, coin_symbol) | return {
'coin_symbol': coin_symbol,
'form': form,
'is_input_page': True,
} | Push a raw TX to the bitcoin network | Push a raw TX to the bitcoin network | [
"Push",
"a",
"raw",
"TX",
"to",
"the",
"bitcoin",
"network"
] | def push_tx(request, coin_symbol):
'''
Push a raw TX to the bitcoin network
'''
initial = {'coin_symbol': coin_symbol}
form = RawTXForm(initial=initial)
if request.method == 'POST':
form = RawTXForm(data=request.POST)
if form.is_valid():
# broadcast the transaction
tx_hex = form.cleaned_data['tx_hex']
coin_symbol_to_use = form.cleaned_data['coin_symbol']
result = pushtx(tx_hex=tx_hex, coin_symbol=coin_symbol_to_use, api_key=BLOCKCYPHER_API_KEY)
# import pprint; pprint.pprint(result, width=1)
if result.get('errors'):
for error in result.get('errors'):
messages.error(request, error['error'])
elif result.get('error'):
messages.error(request, result.get('error'))
else:
success_msg = _('Transaction Successfully Broadcast')
messages.success(request, success_msg)
url = reverse('transaction_overview', kwargs={
'coin_symbol': coin_symbol_to_use,
'tx_hash': result['tx']['hash'],
})
return HttpResponseRedirect(url)
elif request.method == 'GET':
# Preseed tx hex if passed through GET string
tx_hex = request.GET.get('t')
if tx_hex:
initial['tx_hex'] = tx_hex
form = RawTXForm(initial=initial)
return {
'coin_symbol': coin_symbol,
'form': form,
'is_input_page': True,
} | [
"def",
"push_tx",
"(",
"request",
",",
"coin_symbol",
")",
":",
"initial",
"=",
"{",
"'coin_symbol'",
":",
"coin_symbol",
"}",
"form",
"=",
"RawTXForm",
"(",
"initial",
"=",
"initial",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"form",
"="... | https://github.com/blockcypher/explorer/blob/3cb07c58ed6573964921e343fce01552accdf958/transactions/views.py#L165-L205 | |
boto/boto | b2a6f08122b2f1b89888d2848e730893595cd001 | boto/fps/connection.py | python | FPSConnection.get_payment_instruction | (self, action, response, **kw) | return self.get_object(action, kw, response) | Gets the payment instruction of a token. | Gets the payment instruction of a token. | [
"Gets",
"the",
"payment",
"instruction",
"of",
"a",
"token",
"."
] | def get_payment_instruction(self, action, response, **kw):
"""
Gets the payment instruction of a token.
"""
return self.get_object(action, kw, response) | [
"def",
"get_payment_instruction",
"(",
"self",
",",
"action",
",",
"response",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"get_object",
"(",
"action",
",",
"kw",
",",
"response",
")"
] | https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/fps/connection.py#L391-L395 | |
aiven/pghoard | 1de0d2e33bf087b7ce3b6af556bbf941acfac3a4 | pghoard/gnutaremu.py | python | GnuTarEmulator._transform_name | (self, name) | return name | [] | def _transform_name(self, name):
for pattern, substitution in self.substitutions.items():
name = pattern.sub(substitution, name)
return name | [
"def",
"_transform_name",
"(",
"self",
",",
"name",
")",
":",
"for",
"pattern",
",",
"substitution",
"in",
"self",
".",
"substitutions",
".",
"items",
"(",
")",
":",
"name",
"=",
"pattern",
".",
"sub",
"(",
"substitution",
",",
"name",
")",
"return",
"... | https://github.com/aiven/pghoard/blob/1de0d2e33bf087b7ce3b6af556bbf941acfac3a4/pghoard/gnutaremu.py#L124-L127 | |||
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/pkg_resources/__init__.py | python | _mkstemp | (*args, **kw) | [] | def _mkstemp(*args, **kw):
old_open = os.open
try:
# temporarily bypass sandboxing
os.open = os_open
return tempfile.mkstemp(*args, **kw)
finally:
# and then put it back
os.open = old_open | [
"def",
"_mkstemp",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"old_open",
"=",
"os",
".",
"open",
"try",
":",
"# temporarily bypass sandboxing",
"os",
".",
"open",
"=",
"os_open",
"return",
"tempfile",
".",
"mkstemp",
"(",
"*",
"args",
",",
"*",
... | 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/pkg_resources/__init__.py#L2984-L2992 | ||||
home-assistant/supervisor | 69c2517d5211b483fdfe968b0a2b36b672ee7ab2 | supervisor/docker/observer.py | python | DockerObserver.image | (self) | return self.sys_plugins.observer.image | Return name of observer image. | Return name of observer image. | [
"Return",
"name",
"of",
"observer",
"image",
"."
] | def image(self):
"""Return name of observer image."""
return self.sys_plugins.observer.image | [
"def",
"image",
"(",
"self",
")",
":",
"return",
"self",
".",
"sys_plugins",
".",
"observer",
".",
"image"
] | https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/docker/observer.py#L18-L20 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/bdf/cards/elements/solid.py | python | CTETRA4.faces | (self) | return faces | Gets the faces of the element
Returns
-------
faces : Dict[int] = [face1, face2, ...]
key = face number
value = a list of nodes (integer pointers) as the values.
.. note:: The order of the nodes are consistent with normals that point outwards
The face numbering is meaningless
Examples
--------
>>> print(element.faces) | Gets the faces of the element | [
"Gets",
"the",
"faces",
"of",
"the",
"element"
] | def faces(self):
"""
Gets the faces of the element
Returns
-------
faces : Dict[int] = [face1, face2, ...]
key = face number
value = a list of nodes (integer pointers) as the values.
.. note:: The order of the nodes are consistent with normals that point outwards
The face numbering is meaningless
Examples
--------
>>> print(element.faces)
"""
nodes = self.node_ids
faces = {
1 : [nodes[0], nodes[1], nodes[3]],
2 : [nodes[0], nodes[3], nodes[2]],
3 : [nodes[1], nodes[2], nodes[3]],
4 : [nodes[0], nodes[2], nodes[1]],
}
return faces | [
"def",
"faces",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"node_ids",
"faces",
"=",
"{",
"1",
":",
"[",
"nodes",
"[",
"0",
"]",
",",
"nodes",
"[",
"1",
"]",
",",
"nodes",
"[",
"3",
"]",
"]",
",",
"2",
":",
"[",
"nodes",
"[",
"0",
... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/cards/elements/solid.py#L2511-L2535 | |
happinesslz/TANet | 2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f | pointpillars_with_TANet/second/data/dataset.py | python | KittiDataset.kitti_infos | (self) | return self._kitti_infos | [] | def kitti_infos(self):
return self._kitti_infos | [
"def",
"kitti_infos",
"(",
"self",
")",
":",
"return",
"self",
".",
"_kitti_infos"
] | https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/pointpillars_with_TANet/second/data/dataset.py#L60-L61 | |||
wbond/asn1crypto | 9ae350f212532dfee7f185f6b3eda24753249cf3 | asn1crypto/util.py | python | extended_datetime.isoformat | (self, sep='T') | return s + _format_offset(self.utcoffset()) | Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions
:param set:
A single character of the separator to place between the date and
time
:return:
The formatted datetime as a unicode string in Python 3 and a byte
string in Python 2 | Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions | [
"Formats",
"the",
"date",
"as",
"%Y",
"-",
"%m",
"-",
"%d",
"%H",
":",
"%M",
":",
"%S",
"with",
"the",
"sep",
"param",
"between",
"the",
"date",
"and",
"time",
"portions"
] | def isoformat(self, sep='T'):
"""
Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions
:param set:
A single character of the separator to place between the date and
time
:return:
The formatted datetime as a unicode string in Python 3 and a byte
string in Python 2
"""
s = '0000-%02d-%02d%c%02d:%02d:%02d' % (self.month, self.day, sep, self.hour, self.minute, self.second)
if self.microsecond:
s += '.%06d' % self.microsecond
return s + _format_offset(self.utcoffset()) | [
"def",
"isoformat",
"(",
"self",
",",
"sep",
"=",
"'T'",
")",
":",
"s",
"=",
"'0000-%02d-%02d%c%02d:%02d:%02d'",
"%",
"(",
"self",
".",
"month",
",",
"self",
".",
"day",
",",
"sep",
",",
"self",
".",
"hour",
",",
"self",
".",
"minute",
",",
"self",
... | https://github.com/wbond/asn1crypto/blob/9ae350f212532dfee7f185f6b3eda24753249cf3/asn1crypto/util.py#L650-L667 | |
google-research/mixmatch | 1011a1d51eaa9ca6f5dba02096a848d1fe3fc38e | libml/data.py | python | compute_mean_std | (data: tf.data.Dataset) | return mean, std | [] | def compute_mean_std(data: tf.data.Dataset):
data = data.map(lambda x: x['image']).batch(1024).prefetch(1)
data = data.make_one_shot_iterator().get_next()
count = 0
stats = []
with tf.Session(config=utils.get_config()) as sess:
def iterator():
while True:
try:
yield sess.run(data)
except tf.errors.OutOfRangeError:
break
for batch in tqdm(iterator(), unit='kimg', desc='Computing dataset mean and std'):
ratio = batch.shape[0] / 1024.
count += ratio
stats.append((batch.mean((0, 1, 2)) * ratio, (batch ** 2).mean((0, 1, 2)) * ratio))
mean = sum(x[0] for x in stats) / count
sigma = sum(x[1] for x in stats) / count - mean ** 2
std = np.sqrt(sigma)
print('Mean %s Std: %s' % (mean, std))
return mean, std | [
"def",
"compute_mean_std",
"(",
"data",
":",
"tf",
".",
"data",
".",
"Dataset",
")",
":",
"data",
"=",
"data",
".",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"'image'",
"]",
")",
".",
"batch",
"(",
"1024",
")",
".",
"prefetch",
"(",
"1",
")",
"... | https://github.com/google-research/mixmatch/blob/1011a1d51eaa9ca6f5dba02096a848d1fe3fc38e/libml/data.py#L100-L121 | |||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AdminServer/appscale/admin/utils.py | python | extract_source | (revision_key, location, runtime) | Unpacks an archive from a given location.
Args:
revision_key: A string specifying the revision key.
location: A string specifying the location of the source archive.
runtime: A string specifying the revision's runtime.
Raises:
IOError if version source archive does not exist.
InvalidSource if the source archive is not valid. | Unpacks an archive from a given location. | [
"Unpacks",
"an",
"archive",
"from",
"a",
"given",
"location",
"."
] | def extract_source(revision_key, location, runtime):
""" Unpacks an archive from a given location.
Args:
revision_key: A string specifying the revision key.
location: A string specifying the location of the source archive.
runtime: A string specifying the revision's runtime.
Raises:
IOError if version source archive does not exist.
InvalidSource if the source archive is not valid.
"""
revision_base = os.path.join(UNPACK_ROOT, revision_key)
ensure_path(os.path.join(revision_base, 'log'))
app_path = os.path.join(revision_base, 'app')
ensure_path(app_path)
if runtime in (JAVA, JAVA8):
config_file_name = 'appengine-web.xml'
def is_version_config(path):
return path.endswith(config_file_name)
else:
config_file_name = 'app.yaml'
def is_version_config(path):
return canonical_path(path, app_path) == \
os.path.join(app_path, config_file_name)
with tarfile.open(location, 'r:gz') as archive:
# Check if the archive is valid before extracting it.
has_config = False
for file_info in archive:
file_name = file_info.name
if not canonical_path(file_name, app_path).startswith(app_path):
raise InvalidSource(
'Invalid location in archive: {}'.format(file_name))
if file_info.issym() or file_info.islnk():
if not valid_link(file_name, file_info.linkname, app_path):
raise InvalidSource('Invalid link in archive: {}'.format(file_name))
if is_version_config(file_name):
has_config = True
if not has_config:
raise InvalidSource('Archive must have {}'.format(config_file_name))
archive.extractall(path=app_path)
if runtime == GO:
try:
shutil.move(os.path.join(app_path, 'gopath'), revision_base)
except IOError:
logger.debug(
'{} does not have a gopath directory'.format(revision_key))
if runtime == JAVA:
remove_conflicting_jars(app_path)
copy_modified_jars(app_path) | [
"def",
"extract_source",
"(",
"revision_key",
",",
"location",
",",
"runtime",
")",
":",
"revision_base",
"=",
"os",
".",
"path",
".",
"join",
"(",
"UNPACK_ROOT",
",",
"revision_key",
")",
"ensure_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"revision_... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AdminServer/appscale/admin/utils.py#L196-L255 | ||
PacktPublishing/Artificial-Intelligence-with-Python | 03e0f39e3c0949ee219ec91e0145fdabe8ed7810 | Chapter 12/code/features/sigproc.py | python | powspec | (frames,NFFT) | return 1.0/NFFT * numpy.square(magspec(frames,NFFT)) | Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be NxNFFT.
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded.
:returns: If frames is an NxD matrix, output will be NxNFFT. Each row will be the power spectrum of the corresponding frame. | Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be NxNFFT. | [
"Compute",
"the",
"power",
"spectrum",
"of",
"each",
"frame",
"in",
"frames",
".",
"If",
"frames",
"is",
"an",
"NxD",
"matrix",
"output",
"will",
"be",
"NxNFFT",
"."
] | def powspec(frames,NFFT):
"""Compute the power spectrum of each frame in frames. If frames is an NxD matrix, output will be NxNFFT.
:param frames: the array of frames. Each row is a frame.
:param NFFT: the FFT length to use. If NFFT > frame_len, the frames are zero-padded.
:returns: If frames is an NxD matrix, output will be NxNFFT. Each row will be the power spectrum of the corresponding frame.
"""
return 1.0/NFFT * numpy.square(magspec(frames,NFFT)) | [
"def",
"powspec",
"(",
"frames",
",",
"NFFT",
")",
":",
"return",
"1.0",
"/",
"NFFT",
"*",
"numpy",
".",
"square",
"(",
"magspec",
"(",
"frames",
",",
"NFFT",
")",
")"
] | https://github.com/PacktPublishing/Artificial-Intelligence-with-Python/blob/03e0f39e3c0949ee219ec91e0145fdabe8ed7810/Chapter 12/code/features/sigproc.py#L78-L85 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/willow/image.py | python | Image.operation | (func) | return func | [] | def operation(func):
func._willow_operation = True
return func | [
"def",
"operation",
"(",
"func",
")",
":",
"func",
".",
"_willow_operation",
"=",
"True",
"return",
"func"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/willow/image.py#L18-L20 | |||
ProjectQ-Framework/ProjectQ | 0d32c1610ba4e9aefd7f19eb52dadb4fbe5f9005 | projectq/ops/_basics.py | python | MatrixGate.__hash__ | (self) | return hash(str(self)) | Compute the hash of the object. | Compute the hash of the object. | [
"Compute",
"the",
"hash",
"of",
"the",
"object",
"."
] | def __hash__(self):
"""Compute the hash of the object."""
return hash(str(self)) | [
"def",
"__hash__",
"(",
"self",
")",
":",
"return",
"hash",
"(",
"str",
"(",
"self",
")",
")"
] | https://github.com/ProjectQ-Framework/ProjectQ/blob/0d32c1610ba4e9aefd7f19eb52dadb4fbe5f9005/projectq/ops/_basics.py#L295-L297 | |
urwid/urwid | e2423b5069f51d318ea1ac0f355a0efe5448f7eb | examples/edit.py | python | EditDisplay.save_file | (self) | Write the file out to disk. | Write the file out to disk. | [
"Write",
"the",
"file",
"out",
"to",
"disk",
"."
] | def save_file(self):
"""Write the file out to disk."""
l = []
walk = self.walker
for edit in walk.lines:
# collect the text already stored in edit widgets
if edit.original_text.expandtabs() == edit.edit_text:
l.append(edit.original_text)
else:
l.append(re_tab(edit.edit_text))
# then the rest
while walk.file is not None:
l.append(walk.read_next_line())
# write back to disk
outfile = open(self.save_name, "w")
prefix = ""
for line in l:
outfile.write(prefix + line)
prefix = "\n" | [
"def",
"save_file",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"walk",
"=",
"self",
".",
"walker",
"for",
"edit",
"in",
"walk",
".",
"lines",
":",
"# collect the text already stored in edit widgets",
"if",
"edit",
".",
"original_text",
".",
"expandtabs",
"("... | https://github.com/urwid/urwid/blob/e2423b5069f51d318ea1ac0f355a0efe5448f7eb/examples/edit.py#L202-L224 | ||
python/cpython | e13cdca0f5224ec4e23bdd04bb3120506964bc8b | Lib/idlelib/config.py | python | IdleConf.GetUserCfgDir | (self) | return userDir | Return a filesystem directory for storing user config files.
Creates it if required. | Return a filesystem directory for storing user config files. | [
"Return",
"a",
"filesystem",
"directory",
"for",
"storing",
"user",
"config",
"files",
"."
] | def GetUserCfgDir(self):
"""Return a filesystem directory for storing user config files.
Creates it if required.
"""
cfgDir = '.idlerc'
userDir = os.path.expanduser('~')
if userDir != '~': # expanduser() found user home dir
if not os.path.exists(userDir):
if not idlelib.testing:
warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
userDir + ',\n but the path does not exist.')
try:
print(warn, file=sys.stderr)
except OSError:
pass
userDir = '~'
if userDir == "~": # still no path to home!
# traditionally IDLE has defaulted to os.getcwd(), is this adequate?
userDir = os.getcwd()
userDir = os.path.join(userDir, cfgDir)
if not os.path.exists(userDir):
try:
os.mkdir(userDir)
except OSError:
if not idlelib.testing:
warn = ('\n Warning: unable to create user config directory\n' +
userDir + '\n Check path and permissions.\n Exiting!\n')
try:
print(warn, file=sys.stderr)
except OSError:
pass
raise SystemExit
# TODO continue without userDIr instead of exit
return userDir | [
"def",
"GetUserCfgDir",
"(",
"self",
")",
":",
"cfgDir",
"=",
"'.idlerc'",
"userDir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
"if",
"userDir",
"!=",
"'~'",
":",
"# expanduser() found user home dir",
"if",
"not",
"os",
".",
"path",
".",
... | https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/idlelib/config.py#L178-L212 | |
jazzband/django-admin2 | 7770da8a4931db60326f87d9fa7a15b1ef704c4c | djadmin2/models.py | python | LogEntry.__str__ | (self) | return gettext('LogEntry Object') | [] | def __str__(self):
if self.action_flag == self.ADDITION:
return gettext('Added "%(object)s".') % {
'object': self.object_repr}
elif self.action_flag == self.CHANGE:
return gettext('Changed "%(object)s" - %(changes)s') % {
'object': self.object_repr,
'changes': self.change_message,
}
elif self.action_flag == self.DELETION:
return gettext('Deleted "%(object)s."') % {
'object': self.object_repr}
return gettext('LogEntry Object') | [
"def",
"__str__",
"(",
"self",
")",
":",
"if",
"self",
".",
"action_flag",
"==",
"self",
".",
"ADDITION",
":",
"return",
"gettext",
"(",
"'Added \"%(object)s\".'",
")",
"%",
"{",
"'object'",
":",
"self",
".",
"object_repr",
"}",
"elif",
"self",
".",
"act... | https://github.com/jazzband/django-admin2/blob/7770da8a4931db60326f87d9fa7a15b1ef704c4c/djadmin2/models.py#L47-L60 | |||
khalim19/gimp-plugin-export-layers | b37255f2957ad322f4d332689052351cdea6e563 | export_layers/pygimplib/_lib/mock/mock.py | python | NonCallableMagicMock.mock_add_spec | (self, spec, spec_set=False) | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set. | Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock. | [
"Add",
"a",
"spec",
"to",
"a",
"mock",
".",
"spec",
"can",
"either",
"be",
"an",
"object",
"or",
"a",
"list",
"of",
"strings",
".",
"Only",
"attributes",
"on",
"the",
"spec",
"can",
"be",
"fetched",
"as",
"attributes",
"from",
"the",
"mock",
"."
] | def mock_add_spec(self, spec, spec_set=False):
"""Add a spec to a mock. `spec` can either be an object or a
list of strings. Only attributes on the `spec` can be fetched as
attributes from the mock.
If `spec_set` is True then only attributes on the spec can be set."""
self._mock_add_spec(spec, spec_set)
self._mock_set_magics() | [
"def",
"mock_add_spec",
"(",
"self",
",",
"spec",
",",
"spec_set",
"=",
"False",
")",
":",
"self",
".",
"_mock_add_spec",
"(",
"spec",
",",
"spec_set",
")",
"self",
".",
"_mock_set_magics",
"(",
")"
] | https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/mock/mock.py#L1879-L1886 | ||
bitcraft/PyTMX | 2ef7dcac8526d9b5085c147b70b1078666542f12 | pytmx/pytmx.py | python | TiledObject.parse_xml | (self, node: ElementTree.Element) | return self | Parse an Object from ElementTree xml node
Args:
node: the node to be parsed | Parse an Object from ElementTree xml node | [
"Parse",
"an",
"Object",
"from",
"ElementTree",
"xml",
"node"
] | def parse_xml(self, node: ElementTree.Element):
"""
Parse an Object from ElementTree xml node
Args:
node: the node to be parsed
"""
def read_points(text):
"""parse a text string of float tuples and return [(x,...),...]"""
return tuple(tuple(map(float, i.split(","))) for i in text.split())
self._set_properties(node)
# correctly handle "tile objects" (object with gid set)
if self.gid:
self.gid = self.parent.register_gid(self.gid)
points = None
polygon = node.find("polygon")
if polygon is not None:
points = read_points(polygon.get("points"))
self.closed = True
polyline = node.find("polyline")
if polyline is not None:
points = read_points(polyline.get("points"))
self.closed = False
if points:
x1 = x2 = y1 = y2 = 0
for x, y in points:
if x < x1:
x1 = x
if x > x2:
x2 = x
if y < y1:
y1 = y
if y > y2:
y2 = y
self.width = abs(x1) + abs(x2)
self.height = abs(y1) + abs(y2)
self.points = tuple([Point(i[0] + self.x, i[1] + self.y) for i in points])
return self | [
"def",
"parse_xml",
"(",
"self",
",",
"node",
":",
"ElementTree",
".",
"Element",
")",
":",
"def",
"read_points",
"(",
"text",
")",
":",
"\"\"\"parse a text string of float tuples and return [(x,...),...]\"\"\"",
"return",
"tuple",
"(",
"tuple",
"(",
"map",
"(",
"... | https://github.com/bitcraft/PyTMX/blob/2ef7dcac8526d9b5085c147b70b1078666542f12/pytmx/pytmx.py#L1410-L1455 | |
replit-archive/empythoned | 977ec10ced29a3541a4973dc2b59910805695752 | dist/lib/python2.7/email/utils.py | python | formataddr | (pair) | return address | The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified. | The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header. | [
"The",
"inverse",
"of",
"parseaddr",
"()",
"this",
"takes",
"a",
"2",
"-",
"tuple",
"of",
"the",
"form",
"(",
"realname",
"email_address",
")",
"and",
"returns",
"the",
"string",
"value",
"suitable",
"for",
"an",
"RFC",
"2822",
"From",
"To",
"or",
"Cc",
... | def formataddr(pair):
"""The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified.
"""
name, address = pair
if name:
quotes = ''
if specialsre.search(name):
quotes = '"'
name = escapesre.sub(r'\\\g<0>', name)
return '%s%s%s <%s>' % (quotes, name, quotes, address)
return address | [
"def",
"formataddr",
"(",
"pair",
")",
":",
"name",
",",
"address",
"=",
"pair",
"if",
"name",
":",
"quotes",
"=",
"''",
"if",
"specialsre",
".",
"search",
"(",
"name",
")",
":",
"quotes",
"=",
"'\"'",
"name",
"=",
"escapesre",
".",
"sub",
"(",
"r'... | https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/email/utils.py#L85-L100 | |
wagtail/wagtail | ba8207a5d82c8a1de8f5f9693a7cd07421762999 | wagtail/core/blocks/struct_block.py | python | BaseStructBlock.get_default | (self) | return self._to_struct_value([
(
name,
self.meta.default[name] if name in self.meta.default else block.get_default()
)
for name, block in self.child_blocks.items()
]) | Any default value passed in the constructor or self.meta is going to be a dict
rather than a StructValue; for consistency, we need to convert it to a StructValue
for StructBlock to work with | Any default value passed in the constructor or self.meta is going to be a dict
rather than a StructValue; for consistency, we need to convert it to a StructValue
for StructBlock to work with | [
"Any",
"default",
"value",
"passed",
"in",
"the",
"constructor",
"or",
"self",
".",
"meta",
"is",
"going",
"to",
"be",
"a",
"dict",
"rather",
"than",
"a",
"StructValue",
";",
"for",
"consistency",
"we",
"need",
"to",
"convert",
"it",
"to",
"a",
"StructVa... | def get_default(self):
"""
Any default value passed in the constructor or self.meta is going to be a dict
rather than a StructValue; for consistency, we need to convert it to a StructValue
for StructBlock to work with
"""
return self._to_struct_value([
(
name,
self.meta.default[name] if name in self.meta.default else block.get_default()
)
for name, block in self.child_blocks.items()
]) | [
"def",
"get_default",
"(",
"self",
")",
":",
"return",
"self",
".",
"_to_struct_value",
"(",
"[",
"(",
"name",
",",
"self",
".",
"meta",
".",
"default",
"[",
"name",
"]",
"if",
"name",
"in",
"self",
".",
"meta",
".",
"default",
"else",
"block",
".",
... | https://github.com/wagtail/wagtail/blob/ba8207a5d82c8a1de8f5f9693a7cd07421762999/wagtail/core/blocks/struct_block.py#L92-L104 | |
numba/numba | bf480b9e0da858a65508c2b17759a72ee6a44c51 | numba/cpython/hashing.py | python | int_hash | (val) | return impl | [] | def int_hash(val):
_HASH_I64_MIN = -2 if sys.maxsize <= 2 ** 32 else -4
_SIGNED_MIN = types.int64(-0x8000000000000000)
# Find a suitable type to hold a "big" value, i.e. iinfo(ty).min/max
# this is to ensure e.g. int32.min is handled ok as it's abs() is its value
_BIG = types.int64 if getattr(val, 'signed', False) else types.uint64
# this is a bit involved due to the CPython repr of ints
def impl(val):
# If the magnitude is under PyHASH_MODULUS, just return the
# value val as the hash, couple of special cases if val == val:
# 1. it's 0, in which case return 0
# 2. it's signed int minimum value, return the value CPython computes
# but Numba cannot as there's no type wide enough to hold the shifts.
#
# If the magnitude is greater than PyHASH_MODULUS then... if the value
# is negative then negate it switch the sign on the hash once computed
# and use the standard wide unsigned hash implementation
val = _BIG(val)
mag = abs(val)
if mag < _PyHASH_MODULUS:
if val == 0:
ret = 0
elif val == _SIGNED_MIN: # e.g. int64 min, -0x8000000000000000
ret = _Py_hash_t(_HASH_I64_MIN)
else:
ret = _Py_hash_t(val)
else:
needs_negate = False
if val < 0:
val = -val
needs_negate = True
ret = _long_impl(val)
if needs_negate:
ret = -ret
return process_return(ret)
return impl | [
"def",
"int_hash",
"(",
"val",
")",
":",
"_HASH_I64_MIN",
"=",
"-",
"2",
"if",
"sys",
".",
"maxsize",
"<=",
"2",
"**",
"32",
"else",
"-",
"4",
"_SIGNED_MIN",
"=",
"types",
".",
"int64",
"(",
"-",
"0x8000000000000000",
")",
"# Find a suitable type to hold a... | https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cpython/hashing.py#L194-L232 | |||
ThomasKluiters/fetchy | dfe1a73aa72cad4338445bec370be064707bff0c | fetchy/plugins/packages/mirror.py | python | Mirror.url | (self) | The base url for this mirror. This URL should never be None
and will be used as a fallback if the locale cannot be used. | The base url for this mirror. This URL should never be None
and will be used as a fallback if the locale cannot be used. | [
"The",
"base",
"url",
"for",
"this",
"mirror",
".",
"This",
"URL",
"should",
"never",
"be",
"None",
"and",
"will",
"be",
"used",
"as",
"a",
"fallback",
"if",
"the",
"locale",
"cannot",
"be",
"used",
"."
] | def url(self):
"""
The base url for this mirror. This URL should never be None
and will be used as a fallback if the locale cannot be used.
"""
raise NotImplementedError() | [
"def",
"url",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/ThomasKluiters/fetchy/blob/dfe1a73aa72cad4338445bec370be064707bff0c/fetchy/plugins/packages/mirror.py#L38-L43 | ||
getsentry/sentry | 83b1f25aac3e08075e0e2495bc29efaf35aca18a | src/sentry/eventstore/models.py | python | Event.search_message | (self) | return trim(message.strip(), settings.SENTRY_MAX_MESSAGE_LENGTH) | The internal search_message attribute is only used for search purposes.
It adds a bunch of data from the metadata and the culprit. | The internal search_message attribute is only used for search purposes.
It adds a bunch of data from the metadata and the culprit. | [
"The",
"internal",
"search_message",
"attribute",
"is",
"only",
"used",
"for",
"search",
"purposes",
".",
"It",
"adds",
"a",
"bunch",
"of",
"data",
"from",
"the",
"metadata",
"and",
"the",
"culprit",
"."
] | def search_message(self):
"""
The internal search_message attribute is only used for search purposes.
It adds a bunch of data from the metadata and the culprit.
"""
data = self.data
culprit = self.culprit
event_metadata = self.get_event_metadata()
if event_metadata is None:
event_metadata = eventtypes.get(self.get_event_type())().get_metadata(self.data)
message = ""
if data.get("logentry"):
message += data["logentry"].get("formatted") or data["logentry"].get("message") or ""
if event_metadata:
for value in event_metadata.values():
value_u = force_text(value, errors="replace")
if value_u not in message:
message = f"{message} {value_u}"
if culprit and culprit not in message:
culprit_u = force_text(culprit, errors="replace")
message = f"{message} {culprit_u}"
return trim(message.strip(), settings.SENTRY_MAX_MESSAGE_LENGTH) | [
"def",
"search_message",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"data",
"culprit",
"=",
"self",
".",
"culprit",
"event_metadata",
"=",
"self",
".",
"get_event_metadata",
"(",
")",
"if",
"event_metadata",
"is",
"None",
":",
"event_metadata",
"=",
... | https://github.com/getsentry/sentry/blob/83b1f25aac3e08075e0e2495bc29efaf35aca18a/src/sentry/eventstore/models.py#L548-L576 | |
Alfanous-team/alfanous | 594514729473c24efa3908e3107b45a38255de4b | src/alfanous-import/transformer.py | python | Transformer.transfer_stopwords | ( self ) | return raw_str | load stopwords from database and save them as a list in a dynamic py | load stopwords from database and save them as a list in a dynamic py | [
"load",
"stopwords",
"from",
"database",
"and",
"save",
"them",
"as",
"a",
"list",
"in",
"a",
"dynamic",
"py"
] | def transfer_stopwords( self ):
""" load stopwords from database and save them as a list in a dynamic py """
cur = self.__mainDb.cursor()
cur.execute( "select word from stopwords" )
stoplist = "["
for item in cur.fetchall():
stoplist += "u'" + unicode( item[0] ) + "',"
stoplist += "]"
raw_str = self.dheader + u"\nstoplist=" + stoplist .replace( ",", ",\n" )
fich = open( self.__dypypath + "stopwords_dyn.py", "w+" )
fich.write( raw_str.encode( 'utf8' ) )
return raw_str | [
"def",
"transfer_stopwords",
"(",
"self",
")",
":",
"cur",
"=",
"self",
".",
"__mainDb",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"\"select word from stopwords\"",
")",
"stoplist",
"=",
"\"[\"",
"for",
"item",
"in",
"cur",
".",
"fetchall",
"(",... | https://github.com/Alfanous-team/alfanous/blob/594514729473c24efa3908e3107b45a38255de4b/src/alfanous-import/transformer.py#L226-L240 | |
shengqiangzhang/examples-of-web-crawlers | 89eb6c169b8824a6a9bc78e7a32e064d33560aa7 | 6.爬取豆瓣排行榜电影数据(含GUI界面版)/getMovieInRankingList.py | python | getMovieInRankingList.get_url_data_in_keyWord | (self, key_word) | return list, jsonData | [] | def get_url_data_in_keyWord(self, key_word):
# 浏览网页
self.browser.get('https://movie.douban.com/subject_search?search_text=' + urllib.parse.quote(
key_word) + '&cat=1002') # get方式获取返回数据
# js动态渲染的网页,必须等到搜索结果元素(DIV中class=root)出来后,才可以停止加载网页
# 等待DIV中class=root的元素出现
self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.root')))
dr = self.browser.find_elements_by_xpath("//div[@class='item-root']") # 获取class为item-root的DIV(因为有多个结果)
jsonData = []
list = []
for son in dr:
movieData = {'rating': ['', 'null'], 'cover_url': '', 'types': '', 'title': '', 'url': '',
'release_date': '', 'vote_count': '', 'actors': ''}
subList = ['', '', '', '']
url_element = son.find_elements_by_xpath(".//a") # 获取第一个a标签的url(因为有多个结果)
if (url_element):
movieData['url'] = (url_element[0].get_attribute("href"))
img_url_element = url_element[0].find_elements_by_xpath(".//img") # 获取影片海报图片地址
if (img_url_element):
movieData['cover_url'] = (img_url_element[0].get_attribute("src"))
title_element = son.find_elements_by_xpath(".//div[@class='title']") # 获取标题
if (title_element):
temp_title = (title_element[0].text)
movieData['title'] = (temp_title.split('('))[0]
movieData['release_date'] = temp_title[temp_title.find('(') + 1:temp_title.find(')')]
subList[0] = movieData['title']
rating_element = son.find_elements_by_xpath(".//span[@class='rating_nums']") # 获取评分
if (rating_element):
movieData['rating'][0] = (rating_element[0].text)
subList[1] = movieData['rating'][0]
vote_element = son.find_elements_by_xpath(".//span[@class='pl']") # 获取数量
if (vote_element):
movieData['vote_count'] = (vote_element[0].text).replace('(', '').replace(')', '').replace('人评价', '')
subList[3] = movieData['vote_count']
type_element = son.find_elements_by_xpath(".//div[@class='meta abstract']") # 获取类型
if (type_element):
movieData['types'] = (type_element[0].text)
subList[2] = movieData['types']
actors_element = son.find_elements_by_xpath(".//div[@class='meta abstract_2']") # 获取演员
if (actors_element):
movieData['actors'] = (actors_element[0].text)
jsonData.append(movieData)
list.append(subList)
# 关闭浏览器
self.browser.quit()
for data in list:
print(data)
return list, jsonData | [
"def",
"get_url_data_in_keyWord",
"(",
"self",
",",
"key_word",
")",
":",
"# 浏览网页",
"self",
".",
"browser",
".",
"get",
"(",
"'https://movie.douban.com/subject_search?search_text='",
"+",
"urllib",
".",
"parse",
".",
"quote",
"(",
"key_word",
")",
"+",
"'&cat=1002... | https://github.com/shengqiangzhang/examples-of-web-crawlers/blob/89eb6c169b8824a6a9bc78e7a32e064d33560aa7/6.爬取豆瓣排行榜电影数据(含GUI界面版)/getMovieInRankingList.py#L92-L153 | |||
osmr/imgclsmob | f2993d3ce73a2f7ddba05da3891defb08547d504 | chainer_/chainercv2/models/regnet.py | python | regnetx320 | (**kwargs) | return get_regnet(channels_init=320, channels_slope=69.86, channels_mult=2.0, depth=23, groups=168,
model_name="regnetx320", **kwargs) | RegNetX-32GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
Location for keeping the model parameters. | RegNetX-32GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678. | [
"RegNetX",
"-",
"32GF",
"model",
"from",
"Designing",
"Network",
"Design",
"Spaces",
"https",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"2003",
".",
"13678",
"."
] | def regnetx320(**kwargs):
"""
RegNetX-32GF model from 'Designing Network Design Spaces,' https://arxiv.org/abs/2003.13678.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/models'
Location for keeping the model parameters.
"""
return get_regnet(channels_init=320, channels_slope=69.86, channels_mult=2.0, depth=23, groups=168,
model_name="regnetx320", **kwargs) | [
"def",
"regnetx320",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"get_regnet",
"(",
"channels_init",
"=",
"320",
",",
"channels_slope",
"=",
"69.86",
",",
"channels_mult",
"=",
"2.0",
",",
"depth",
"=",
"23",
",",
"groups",
"=",
"168",
",",
"model_name"... | https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/chainer_/chainercv2/models/regnet.py#L446-L458 | |
jobovy/galpy | 8e6a230bbe24ce16938db10053f92eb17fe4bb52 | galpy/potential/DehnenBarPotential.py | python | DehnenBarPotential.OmegaP | (self) | return self._omegab | NAME:
OmegaP
PURPOSE:
return the pattern speed
INPUT:
(none)
OUTPUT:
pattern speed
HISTORY:
2011-10-10 - Written - Bovy (IAS) | NAME: | [
"NAME",
":"
] | def OmegaP(self):
"""
NAME:
OmegaP
PURPOSE:
return the pattern speed
INPUT:
(none)
OUTPUT:
pattern speed
HISTORY:
2011-10-10 - Written - Bovy (IAS)
"""
return self._omegab | [
"def",
"OmegaP",
"(",
"self",
")",
":",
"return",
"self",
".",
"_omegab"
] | https://github.com/jobovy/galpy/blob/8e6a230bbe24ce16938db10053f92eb17fe4bb52/galpy/potential/DehnenBarPotential.py#L538-L562 | |
tanghaibao/goatools | 647e9dd833695f688cd16c2f9ea18f1692e5c6bc | goatools/grouper/grprobj.py | python | Grouper.get_usrgo2hdrgo | (self) | return usrgo2hdrgo | Return a dict with all user GO IDs as keys and their respective header GOs as values. | Return a dict with all user GO IDs as keys and their respective header GOs as values. | [
"Return",
"a",
"dict",
"with",
"all",
"user",
"GO",
"IDs",
"as",
"keys",
"and",
"their",
"respective",
"header",
"GOs",
"as",
"values",
"."
] | def get_usrgo2hdrgo(self):
"""Return a dict with all user GO IDs as keys and their respective header GOs as values."""
usrgo2hdrgo = {}
for hdrgo, usrgos in self.hdrgo2usrgos.items():
for usrgo in usrgos:
assert usrgo not in usrgo2hdrgo
usrgo2hdrgo[usrgo] = hdrgo
# Add usrgos which are also a hdrgo and the GO group contains no other GO IDs
for goid in self.hdrgo_is_usrgo:
usrgo2hdrgo[goid] = goid
assert len(self.usrgos) <= len(usrgo2hdrgo), \
"USRGOS({U}) != USRGO2HDRGO({H}): {GOs}".format(
U=len(self.usrgos),
H=len(usrgo2hdrgo),
GOs=self.usrgos.symmetric_difference(set(usrgo2hdrgo.keys())))
return usrgo2hdrgo | [
"def",
"get_usrgo2hdrgo",
"(",
"self",
")",
":",
"usrgo2hdrgo",
"=",
"{",
"}",
"for",
"hdrgo",
",",
"usrgos",
"in",
"self",
".",
"hdrgo2usrgos",
".",
"items",
"(",
")",
":",
"for",
"usrgo",
"in",
"usrgos",
":",
"assert",
"usrgo",
"not",
"in",
"usrgo2hd... | https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/grouper/grprobj.py#L202-L217 | |
kristpapadopoulos/seriesnet | 56580bc618135c8b1a87b5b16d9ec4c68de44099 | seriesnet.py | python | evaluate_timeseries | (timeseries, predict_size) | return pred_array.flatten() | [] | def evaluate_timeseries(timeseries, predict_size):
# timeseries input is 1-D numpy array
# forecast_size is the forecast horizon
timeseries = timeseries[~pd.isna(timeseries)]
length = len(timeseries)-1
timeseries = np.atleast_2d(np.asarray(timeseries))
if timeseries.shape[0] == 1:
timeseries = timeseries.T
model = DC_CNN_Model(length)
print('\n\nModel with input size {}, output size {}'.
format(model.input_shape, model.output_shape))
model.summary()
X = timeseries[:-1].reshape(1,length,1)
y = timeseries[1:].reshape(1,length,1)
model.fit(X, y, epochs=3000)
pred_array = np.zeros(predict_size).reshape(1,predict_size,1)
X_test_initial = timeseries[1:].reshape(1,length,1)
#pred_array = model.predict(X_test_initial) if predictions of training samples required
#forecast is created by predicting next future value based on previous predictions
pred_array[:,0,:] = model.predict(X_test_initial)[:,-1:,:]
for i in range(predict_size-1):
pred_array[:,i+1:,:] = model.predict(np.append(X_test_initial[:,i+1:,:],
pred_array[:,:i+1,:]).reshape(1,length,1))[:,-1:,:]
return pred_array.flatten() | [
"def",
"evaluate_timeseries",
"(",
"timeseries",
",",
"predict_size",
")",
":",
"# timeseries input is 1-D numpy array",
"# forecast_size is the forecast horizon",
"timeseries",
"=",
"timeseries",
"[",
"~",
"pd",
".",
"isna",
"(",
"timeseries",
")",
"]",
"length",
"=",
... | https://github.com/kristpapadopoulos/seriesnet/blob/56580bc618135c8b1a87b5b16d9ec4c68de44099/seriesnet.py#L106-L139 | |||
josauder/procedural_city_generation | e53d9a48440c914f9aad65455b3aebc13d90bc98 | procedural_city_generation/building_generation/building_tools.py | python | Walls.__init__ | (self, verts, l) | Parameters
----------
verts: numpy.ndarray(l, 3)
l: int
shape[0] of verts | Parameters
----------
verts: numpy.ndarray(l, 3)
l: int
shape[0] of verts | [
"Parameters",
"----------",
"verts",
":",
"numpy",
".",
"ndarray",
"(",
"l",
"3",
")",
"l",
":",
"int",
"shape",
"[",
"0",
"]",
"of",
"verts"
] | def __init__(self, verts, l):
"""
Parameters
----------
verts: numpy.ndarray(l, 3)
l: int
shape[0] of verts
"""
self.vertices=verts
self.l=l
self.center=sum(self.vertices)/self.l
self.walls=None | [
"def",
"__init__",
"(",
"self",
",",
"verts",
",",
"l",
")",
":",
"self",
".",
"vertices",
"=",
"verts",
"self",
".",
"l",
"=",
"l",
"self",
".",
"center",
"=",
"sum",
"(",
"self",
".",
"vertices",
")",
"/",
"self",
".",
"l",
"self",
".",
"wall... | https://github.com/josauder/procedural_city_generation/blob/e53d9a48440c914f9aad65455b3aebc13d90bc98/procedural_city_generation/building_generation/building_tools.py#L37-L48 | ||
JimmXinu/FanFicFare | bc149a2deb2636320fe50a3e374af6eef8f61889 | fanficfare/adapters/adapter_finestoriescom.py | python | FineStoriesComAdapter.getTheme | (cls) | return "Modern" | [] | def getTheme(cls):
## only one theme is supported.
return "Modern" | [
"def",
"getTheme",
"(",
"cls",
")",
":",
"## only one theme is supported.",
"return",
"\"Modern\""
] | https://github.com/JimmXinu/FanFicFare/blob/bc149a2deb2636320fe50a3e374af6eef8f61889/fanficfare/adapters/adapter_finestoriescom.py#L43-L45 | |||
cronyo/cronyo | cd5abab0871b68bf31b18aac934303928130a441 | cronyo/vendor/urllib3/util/response.py | python | assert_header_parsing | (headers) | Asserts whether all headers have been successfully parsed.
Extracts encountered errors from the result of parsing headers.
Only works on Python 3.
:param headers: Headers to verify.
:type headers: `httplib.HTTPMessage`.
:raises urllib3.exceptions.HeaderParsingError:
If parsing errors are found. | Asserts whether all headers have been successfully parsed.
Extracts encountered errors from the result of parsing headers. | [
"Asserts",
"whether",
"all",
"headers",
"have",
"been",
"successfully",
"parsed",
".",
"Extracts",
"encountered",
"errors",
"from",
"the",
"result",
"of",
"parsing",
"headers",
"."
] | def assert_header_parsing(headers):
"""
Asserts whether all headers have been successfully parsed.
Extracts encountered errors from the result of parsing headers.
Only works on Python 3.
:param headers: Headers to verify.
:type headers: `httplib.HTTPMessage`.
:raises urllib3.exceptions.HeaderParsingError:
If parsing errors are found.
"""
# This will fail silently if we pass in the wrong kind of parameter.
# To make debugging easier add an explicit check.
if not isinstance(headers, httplib.HTTPMessage):
raise TypeError("expected httplib.Message, got {0}.".format(type(headers)))
defects = getattr(headers, "defects", None)
get_payload = getattr(headers, "get_payload", None)
unparsed_data = None
if get_payload:
# get_payload is actually email.message.Message.get_payload;
# we're only interested in the result if it's not a multipart message
if not headers.is_multipart():
payload = get_payload()
if isinstance(payload, (bytes, str)):
unparsed_data = payload
if defects or unparsed_data:
raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) | [
"def",
"assert_header_parsing",
"(",
"headers",
")",
":",
"# This will fail silently if we pass in the wrong kind of parameter.",
"# To make debugging easier add an explicit check.",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"httplib",
".",
"HTTPMessage",
")",
":",
"raise... | https://github.com/cronyo/cronyo/blob/cd5abab0871b68bf31b18aac934303928130a441/cronyo/vendor/urllib3/util/response.py#L38-L71 | ||
ElsevierDev/elsapy | 5fda0434f106fdd89fa851144c25d80d7e1100d5 | elsapy/elsdoc.py | python | FullDoc.uri | (self) | return self._uri | Gets the document's uri | Gets the document's uri | [
"Gets",
"the",
"document",
"s",
"uri"
] | def uri(self):
"""Gets the document's uri"""
return self._uri | [
"def",
"uri",
"(",
"self",
")",
":",
"return",
"self",
".",
"_uri"
] | https://github.com/ElsevierDev/elsapy/blob/5fda0434f106fdd89fa851144c25d80d7e1100d5/elsapy/elsdoc.py#L25-L27 | |
domlysz/BlenderGIS | 0c00bc361d05599467174b8721d4cfeb4c3db608 | core/lib/shapefile123.py | python | Reader.iterShapes | (self) | Serves up shapes in a shapefile as an iterator. Useful
for handling large shapefiles. | Serves up shapes in a shapefile as an iterator. Useful
for handling large shapefiles. | [
"Serves",
"up",
"shapes",
"in",
"a",
"shapefile",
"as",
"an",
"iterator",
".",
"Useful",
"for",
"handling",
"large",
"shapefiles",
"."
] | def iterShapes(self):
"""Serves up shapes in a shapefile as an iterator. Useful
for handling large shapefiles."""
shp = self.__getFileObj(self.shp)
shp.seek(0,2)
self.shpLength = shp.tell()
shp.seek(100)
while shp.tell() < self.shpLength:
yield self.__shape() | [
"def",
"iterShapes",
"(",
"self",
")",
":",
"shp",
"=",
"self",
".",
"__getFileObj",
"(",
"self",
".",
"shp",
")",
"shp",
".",
"seek",
"(",
"0",
",",
"2",
")",
"self",
".",
"shpLength",
"=",
"shp",
".",
"tell",
"(",
")",
"shp",
".",
"seek",
"("... | https://github.com/domlysz/BlenderGIS/blob/0c00bc361d05599467174b8721d4cfeb4c3db608/core/lib/shapefile123.py#L429-L437 | ||
neo4j/neo4j-python-driver | 97fd0e1da8223373018fa4755ac431b90a144f02 | neo4j/time/hydration.py | python | dehydrate_duration | (value) | return Structure(b"E", value.months, value.days, value.seconds, value.nanoseconds) | Dehydrator for `duration` values.
:param value:
:type value: Duration
:return: | Dehydrator for `duration` values. | [
"Dehydrator",
"for",
"duration",
"values",
"."
] | def dehydrate_duration(value):
""" Dehydrator for `duration` values.
:param value:
:type value: Duration
:return:
"""
return Structure(b"E", value.months, value.days, value.seconds, value.nanoseconds) | [
"def",
"dehydrate_duration",
"(",
"value",
")",
":",
"return",
"Structure",
"(",
"b\"E\"",
",",
"value",
".",
"months",
",",
"value",
".",
"days",
",",
"value",
".",
"seconds",
",",
"value",
".",
"nanoseconds",
")"
] | https://github.com/neo4j/neo4j-python-driver/blob/97fd0e1da8223373018fa4755ac431b90a144f02/neo4j/time/hydration.py#L185-L192 | |
504ensicsLabs/DAMM | 60e7ec7dacd6087cd6320b3615becca9b4cf9b24 | volatility/plugins/overlays/windows/pe_vtypes.py | python | _LDR_DATA_TABLE_ENTRY.exports | (self) | Generator for the PE's exported functions | Generator for the PE's exported functions | [
"Generator",
"for",
"the",
"PE",
"s",
"exported",
"functions"
] | def exports(self):
"""Generator for the PE's exported functions"""
try:
data_dir = self.export_dir()
except ValueError, why:
raise StopIteration(why)
expdir = obj.Object('_IMAGE_EXPORT_DIRECTORY',
offset = self.DllBase + data_dir.VirtualAddress,
vm = self.obj_native_vm,
parent = self)
if expdir.valid(self._nt_header()):
# Ordinal, Function RVA, and Name Object
for o, f, n in expdir._exported_functions():
yield o, f, n | [
"def",
"exports",
"(",
"self",
")",
":",
"try",
":",
"data_dir",
"=",
"self",
".",
"export_dir",
"(",
")",
"except",
"ValueError",
",",
"why",
":",
"raise",
"StopIteration",
"(",
"why",
")",
"expdir",
"=",
"obj",
".",
"Object",
"(",
"'_IMAGE_EXPORT_DIREC... | https://github.com/504ensicsLabs/DAMM/blob/60e7ec7dacd6087cd6320b3615becca9b4cf9b24/volatility/plugins/overlays/windows/pe_vtypes.py#L516-L532 | ||
saltstack/salt | fae5bc757ad0f1716483ce7ae180b451545c2058 | salt/runners/digicertapi.py | python | _paginate | (url, topkey, *args, **kwargs) | return aggregate_ret | Wrapper to assist with paginated responses from Digicert's REST API. | Wrapper to assist with paginated responses from Digicert's REST API. | [
"Wrapper",
"to",
"assist",
"with",
"paginated",
"responses",
"from",
"Digicert",
"s",
"REST",
"API",
"."
] | def _paginate(url, topkey, *args, **kwargs):
"""
Wrapper to assist with paginated responses from Digicert's REST API.
"""
ret = salt.utils.http.query(url, **kwargs)
if "errors" in ret["dict"]:
return ret["dict"]
lim = int(ret["dict"]["page"]["limit"])
total = int(ret["dict"]["page"]["total"])
if total == 0:
return {}
numpages = (total / lim) + 1
# If the count returned is less than the page size, just return the dict
if numpages == 1:
return ret["dict"][topkey]
aggregate_ret = ret["dict"][topkey]
url = args[0]
for p in range(2, numpages):
param_url = url + "?offset={}".format(lim * (p - 1))
next_ret = salt.utils.http.query(param_url, kwargs)
aggregate_ret[topkey].extend(next_ret["dict"][topkey])
return aggregate_ret | [
"def",
"_paginate",
"(",
"url",
",",
"topkey",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"http",
".",
"query",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"if",
"\"errors\"",
"in",
"ret",
"[",
"\"... | https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/runners/digicertapi.py#L91-L119 | |
mbusb/multibootusb | fa89b28f27891a9ce8d6e2a5737baa2e6ee83dfd | scripts/win32.py | python | findAvailableDrives | () | return [(d, win32file.GetDriveType(d)) for d in
win32api.GetLogicalDriveStrings().rstrip('\0').split('\0')] | [] | def findAvailableDrives():
return [(d, win32file.GetDriveType(d)) for d in
win32api.GetLogicalDriveStrings().rstrip('\0').split('\0')] | [
"def",
"findAvailableDrives",
"(",
")",
":",
"return",
"[",
"(",
"d",
",",
"win32file",
".",
"GetDriveType",
"(",
"d",
")",
")",
"for",
"d",
"in",
"win32api",
".",
"GetLogicalDriveStrings",
"(",
")",
".",
"rstrip",
"(",
"'\\0'",
")",
".",
"split",
"(",... | https://github.com/mbusb/multibootusb/blob/fa89b28f27891a9ce8d6e2a5737baa2e6ee83dfd/scripts/win32.py#L51-L53 | |||
TaipanRex/pyvisgraph | 9472e0df7ca7bfa5f45932ca348222bdc1f7e688 | pyvisgraph/vis_graph.py | python | VisGraph.update | (self, points, origin=None, destination=None) | Update visgraph by checking visibility of Points in list points. | Update visgraph by checking visibility of Points in list points. | [
"Update",
"visgraph",
"by",
"checking",
"visibility",
"of",
"Points",
"in",
"list",
"points",
"."
] | def update(self, points, origin=None, destination=None):
"""Update visgraph by checking visibility of Points in list points."""
for p in points:
for v in visible_vertices(p, self.graph, origin=origin,
destination=destination):
self.visgraph.add_edge(Edge(p, v)) | [
"def",
"update",
"(",
"self",
",",
"points",
",",
"origin",
"=",
"None",
",",
"destination",
"=",
"None",
")",
":",
"for",
"p",
"in",
"points",
":",
"for",
"v",
"in",
"visible_vertices",
"(",
"p",
",",
"self",
".",
"graph",
",",
"origin",
"=",
"ori... | https://github.com/TaipanRex/pyvisgraph/blob/9472e0df7ca7bfa5f45932ca348222bdc1f7e688/pyvisgraph/vis_graph.py#L100-L106 | ||
mrlesmithjr/Ansible | d44f0dc0d942bdf3bf7334b307e6048f0ee16e36 | roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/sandbox.py | python | UnpickleableException.dump | (type, exc) | Always return a dumped (pickled) type and exc. If exc can't be pickled,
wrap it in UnpickleableException first. | Always return a dumped (pickled) type and exc. If exc can't be pickled,
wrap it in UnpickleableException first. | [
"Always",
"return",
"a",
"dumped",
"(",
"pickled",
")",
"type",
"and",
"exc",
".",
"If",
"exc",
"can",
"t",
"be",
"pickled",
"wrap",
"it",
"in",
"UnpickleableException",
"first",
"."
] | def dump(type, exc):
"""
Always return a dumped (pickled) type and exc. If exc can't be pickled,
wrap it in UnpickleableException first.
"""
try:
return pickle.dumps(type), pickle.dumps(exc)
except Exception:
# get UnpickleableException inside the sandbox
from setuptools.sandbox import UnpickleableException as cls
return cls.dump(cls, cls(repr(exc))) | [
"def",
"dump",
"(",
"type",
",",
"exc",
")",
":",
"try",
":",
"return",
"pickle",
".",
"dumps",
"(",
"type",
")",
",",
"pickle",
".",
"dumps",
"(",
"exc",
")",
"except",
"Exception",
":",
"# get UnpickleableException inside the sandbox",
"from",
"setuptools"... | https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/setuptools/sandbox.py#L105-L115 | ||
bspaans/python-mingus | 6558cacffeaab4f084a3eedda12b0e86fd24c430 | mingus/containers/track.py | python | Track.set_tuning | (self, tuning) | return self | Set the tuning attribute on both the Track and its instrument (when
available).
Tuning should be a StringTuning or derivative object. | Set the tuning attribute on both the Track and its instrument (when
available). | [
"Set",
"the",
"tuning",
"attribute",
"on",
"both",
"the",
"Track",
"and",
"its",
"instrument",
"(",
"when",
"available",
")",
"."
] | def set_tuning(self, tuning):
"""Set the tuning attribute on both the Track and its instrument (when
available).
Tuning should be a StringTuning or derivative object.
"""
if self.instrument:
self.instrument.tuning = tuning
self.tuning = tuning
return self | [
"def",
"set_tuning",
"(",
"self",
",",
"tuning",
")",
":",
"if",
"self",
".",
"instrument",
":",
"self",
".",
"instrument",
".",
"tuning",
"=",
"tuning",
"self",
".",
"tuning",
"=",
"tuning",
"return",
"self"
] | https://github.com/bspaans/python-mingus/blob/6558cacffeaab4f084a3eedda12b0e86fd24c430/mingus/containers/track.py#L142-L151 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/josepy-1.1.0/src/josepy/util.py | python | ComparableKey.public_key | (self) | return self.__class__(self._wrapped.public_key()) | Get wrapped public key. | Get wrapped public key. | [
"Get",
"wrapped",
"public",
"key",
"."
] | def public_key(self):
"""Get wrapped public key."""
return self.__class__(self._wrapped.public_key()) | [
"def",
"public_key",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"self",
".",
"_wrapped",
".",
"public_key",
"(",
")",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/josepy-1.1.0/src/josepy/util.py#L110-L112 | |
uber-research/CoordConv | 27fab8b86efac87c262c7c596a0c384b83c9d806 | data/not_so_clevr_generator.py | python | multiobject_fixed_generator.__init__ | (self,img_size,objects,num_samples,bgcolor=(255,255,255)) | img_size: size of the canvas
obj: object to drag over the canvas to generate data | img_size: size of the canvas
obj: object to drag over the canvas to generate data | [
"img_size",
":",
"size",
"of",
"the",
"canvas",
"obj",
":",
"object",
"to",
"drag",
"over",
"the",
"canvas",
"to",
"generate",
"data"
] | def __init__(self,img_size,objects,num_samples,bgcolor=(255,255,255)):
"""
img_size: size of the canvas
obj: object to drag over the canvas to generate data
"""
self.canvas = canvas(img_size,bgcolor=bgcolor,overlap_allowed=False)
self.data = []
self.objects = objects
self.num_objects = len(objects)
self.num_samples = num_samples
self.img_size = img_size
self.obj_size = 4
self.generate() | [
"def",
"__init__",
"(",
"self",
",",
"img_size",
",",
"objects",
",",
"num_samples",
",",
"bgcolor",
"=",
"(",
"255",
",",
"255",
",",
"255",
")",
")",
":",
"self",
".",
"canvas",
"=",
"canvas",
"(",
"img_size",
",",
"bgcolor",
"=",
"bgcolor",
",",
... | https://github.com/uber-research/CoordConv/blob/27fab8b86efac87c262c7c596a0c384b83c9d806/data/not_so_clevr_generator.py#L192-L204 | ||
pycollada/pycollada | 5b2d53333f03047b0fdfc25e394f8b77b57b62fc | collada/geometry.py | python | Geometry.createPolylist | (self, indices, vcounts, inputlist, materialid) | return polylist.Polylist(inputdict, materialid, indices, vcounts) | Create a polylist for use with this geometry instance.
:param numpy.array indices:
unshaped numpy array that contains the indices for
the inputs referenced in inputlist
:param numpy.array vcounts:
unshaped numpy array that contains the vertex count
for each polygon in this polylist
:param collada.source.InputList inputlist:
The inputs for this primitive
:param str materialid:
A string containing a symbol that will get used to bind this polylist
to a material when instantiating into a scene
:rtype: :class:`collada.polylist.Polylist` | Create a polylist for use with this geometry instance. | [
"Create",
"a",
"polylist",
"for",
"use",
"with",
"this",
"geometry",
"instance",
"."
] | def createPolylist(self, indices, vcounts, inputlist, materialid):
"""Create a polylist for use with this geometry instance.
:param numpy.array indices:
unshaped numpy array that contains the indices for
the inputs referenced in inputlist
:param numpy.array vcounts:
unshaped numpy array that contains the vertex count
for each polygon in this polylist
:param collada.source.InputList inputlist:
The inputs for this primitive
:param str materialid:
A string containing a symbol that will get used to bind this polylist
to a material when instantiating into a scene
:rtype: :class:`collada.polylist.Polylist`
"""
inputdict = primitive.Primitive._getInputsFromList(self.collada, self.sourceById, inputlist.getList())
return polylist.Polylist(inputdict, materialid, indices, vcounts) | [
"def",
"createPolylist",
"(",
"self",
",",
"indices",
",",
"vcounts",
",",
"inputlist",
",",
"materialid",
")",
":",
"inputdict",
"=",
"primitive",
".",
"Primitive",
".",
"_getInputsFromList",
"(",
"self",
".",
"collada",
",",
"self",
".",
"sourceById",
",",... | https://github.com/pycollada/pycollada/blob/5b2d53333f03047b0fdfc25e394f8b77b57b62fc/collada/geometry.py#L133-L151 | |
wucng/TensorExpand | 4ea58f64f5c5082b278229b799c9f679536510b7 | TensorExpand/Object detection/SSD/balancap-SSD-Tensorflow/tf_extended/bboxes.py | python | bboxes_clip | (bbox_ref, bboxes, scope=None) | Clip bounding boxes to a reference box.
Batch-compatible if the first dimension of `bbox_ref` and `bboxes`
can be broadcasted.
Args:
bbox_ref: Reference bounding box. Nx4 or 4 shaped-Tensor;
bboxes: Bounding boxes to clip. Nx4 or 4 shaped-Tensor or dictionary.
Return:
Clipped bboxes. | Clip bounding boxes to a reference box.
Batch-compatible if the first dimension of `bbox_ref` and `bboxes`
can be broadcasted. | [
"Clip",
"bounding",
"boxes",
"to",
"a",
"reference",
"box",
".",
"Batch",
"-",
"compatible",
"if",
"the",
"first",
"dimension",
"of",
"bbox_ref",
"and",
"bboxes",
"can",
"be",
"broadcasted",
"."
] | def bboxes_clip(bbox_ref, bboxes, scope=None):
"""Clip bounding boxes to a reference box.
Batch-compatible if the first dimension of `bbox_ref` and `bboxes`
can be broadcasted.
Args:
bbox_ref: Reference bounding box. Nx4 or 4 shaped-Tensor;
bboxes: Bounding boxes to clip. Nx4 or 4 shaped-Tensor or dictionary.
Return:
Clipped bboxes.
"""
# Bboxes is dictionary.
if isinstance(bboxes, dict):
with tf.name_scope(scope, 'bboxes_clip_dict'):
d_bboxes = {}
for c in bboxes.keys():
d_bboxes[c] = bboxes_clip(bbox_ref, bboxes[c])
return d_bboxes
# Tensors inputs.
with tf.name_scope(scope, 'bboxes_clip'):
# Easier with transposed bboxes. Especially for broadcasting.
bbox_ref = tf.transpose(bbox_ref)
bboxes = tf.transpose(bboxes)
# Intersection bboxes and reference bbox.
ymin = tf.maximum(bboxes[0], bbox_ref[0])
xmin = tf.maximum(bboxes[1], bbox_ref[1])
ymax = tf.minimum(bboxes[2], bbox_ref[2])
xmax = tf.minimum(bboxes[3], bbox_ref[3])
# Double check! Empty boxes when no-intersection.
ymin = tf.minimum(ymin, ymax)
xmin = tf.minimum(xmin, xmax)
bboxes = tf.transpose(tf.stack([ymin, xmin, ymax, xmax], axis=0))
return bboxes | [
"def",
"bboxes_clip",
"(",
"bbox_ref",
",",
"bboxes",
",",
"scope",
"=",
"None",
")",
":",
"# Bboxes is dictionary.",
"if",
"isinstance",
"(",
"bboxes",
",",
"dict",
")",
":",
"with",
"tf",
".",
"name_scope",
"(",
"scope",
",",
"'bboxes_clip_dict'",
")",
"... | https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/SSD/balancap-SSD-Tensorflow/tf_extended/bboxes.py#L103-L136 | ||
djangonauts/django-hstore | aac755f587ff8ea95c1f43e7f3df8e339b848b6b | django_hstore/virtual.py | python | HStoreVirtualMixin.__set__ | (self, instance, value) | set value on hstore dictionary | set value on hstore dictionary | [
"set",
"value",
"on",
"hstore",
"dictionary"
] | def __set__(self, instance, value):
"""
set value on hstore dictionary
"""
hstore_dictionary = getattr(instance, self.hstore_field_name)
if hstore_dictionary is None:
# init empty HStoreDict
setattr(instance, self.hstore_field_name, HStoreDict())
# reassign
hstore_dictionary = getattr(instance, self.hstore_field_name)
hstore_dictionary[self.name] = value | [
"def",
"__set__",
"(",
"self",
",",
"instance",
",",
"value",
")",
":",
"hstore_dictionary",
"=",
"getattr",
"(",
"instance",
",",
"self",
".",
"hstore_field_name",
")",
"if",
"hstore_dictionary",
"is",
"None",
":",
"# init empty HStoreDict",
"setattr",
"(",
"... | https://github.com/djangonauts/django-hstore/blob/aac755f587ff8ea95c1f43e7f3df8e339b848b6b/django_hstore/virtual.py#L71-L81 | ||
SilenceDut/nbaplus-server | 368067f7a1de958c12fb35462afe2713760b52ae | beautifulsoup4-4.3.2/bs4/element.py | python | PageElement.find_previous_sibling | (self, name=None, attrs={}, text=None, **kwargs) | return self._find_one(self.find_previous_siblings, name, attrs, text,
**kwargs) | Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document. | Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document. | [
"Returns",
"the",
"closest",
"sibling",
"to",
"this",
"Tag",
"that",
"matches",
"the",
"given",
"criteria",
"and",
"appears",
"before",
"this",
"Tag",
"in",
"the",
"document",
"."
] | def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs):
"""Returns the closest sibling to this Tag that matches the
given criteria and appears before this Tag in the document."""
return self._find_one(self.find_previous_siblings, name, attrs, text,
**kwargs) | [
"def",
"find_previous_sibling",
"(",
"self",
",",
"name",
"=",
"None",
",",
"attrs",
"=",
"{",
"}",
",",
"text",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_find_one",
"(",
"self",
".",
"find_previous_siblings",
",",
"name"... | https://github.com/SilenceDut/nbaplus-server/blob/368067f7a1de958c12fb35462afe2713760b52ae/beautifulsoup4-4.3.2/bs4/element.py#L424-L428 | |
7sDream/zhihu-py3 | bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc | zhihu/answer.py | python | Answer.content | (self) | return content | 以处理过的Html代码形式返回答案内容.
:return: 答案内容
:rtype: str | 以处理过的Html代码形式返回答案内容. | [
"以处理过的Html代码形式返回答案内容",
"."
] | def content(self):
"""以处理过的Html代码形式返回答案内容.
:return: 答案内容
:rtype: str
"""
answer_wrap = self.soup.find('div', id='zh-question-answer-wrap')
content = answer_wrap.find('div', class_='zm-editable-content')
content = answer_content_process(content)
return content | [
"def",
"content",
"(",
"self",
")",
":",
"answer_wrap",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'div'",
",",
"id",
"=",
"'zh-question-answer-wrap'",
")",
"content",
"=",
"answer_wrap",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"'zm-editable-conte... | https://github.com/7sDream/zhihu-py3/blob/bcb4aa8325f8b54d3b44bd0bdc959edd9761fcfc/zhihu/answer.py#L145-L154 | |
Lextal/pspnet-pytorch | 4eb6ab61287e837f5e2d8c1ae09fadeaa0e31e37 | extractors.py | python | DenseNet.forward | (self, x) | return out, deep_features | [] | def forward(self, x):
out = self.start_features(x)
deep_features = None
for i, block in enumerate(self.blocks):
out = block(out)
if i == 5:
deep_features = out
return out, deep_features | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"out",
"=",
"self",
".",
"start_features",
"(",
"x",
")",
"deep_features",
"=",
"None",
"for",
"i",
",",
"block",
"in",
"enumerate",
"(",
"self",
".",
"blocks",
")",
":",
"out",
"=",
"block",
"(",
... | https://github.com/Lextal/pspnet-pytorch/blob/4eb6ab61287e837f5e2d8c1ae09fadeaa0e31e37/extractors.py#L249-L257 | |||
florath/rmtoo | 6ffe08703451358dca24b232ee4380b1da23bcad | rmtoo/lib/analytics/TopicCohe.py | python | TopicCohe._get_tcnt | (self) | return self.__tcnt | Returns the internal state.
This is only used by the unit tests. | Returns the internal state.
This is only used by the unit tests. | [
"Returns",
"the",
"internal",
"state",
".",
"This",
"is",
"only",
"used",
"by",
"the",
"unit",
"tests",
"."
] | def _get_tcnt(self):
'''Returns the internal state.
This is only used by the unit tests.'''
return self.__tcnt | [
"def",
"_get_tcnt",
"(",
"self",
")",
":",
"return",
"self",
".",
"__tcnt"
] | https://github.com/florath/rmtoo/blob/6ffe08703451358dca24b232ee4380b1da23bcad/rmtoo/lib/analytics/TopicCohe.py#L41-L44 | |
tensorflow/agents | 1407001d242f7f77fb9407f9b1ac78bcd8f73a09 | setup.py | python | get_reverb_packages | () | return reverb_packages | Returns list of required packages if using reverb. | Returns list of required packages if using reverb. | [
"Returns",
"list",
"of",
"required",
"packages",
"if",
"using",
"reverb",
"."
] | def get_reverb_packages():
"""Returns list of required packages if using reverb."""
reverb_packages = []
if FLAGS.release:
tf_version = TENSORFLOW_VERSION
reverb_version = REVERB_VERSION
else:
tf_version = TENSORFLOW_NIGHTLY
reverb_version = REVERB_NIGHTLY
# Overrides required versions if FLAGS are set.
if FLAGS.tf_version:
tf_version = FLAGS.tf_version
if FLAGS.reverb_version:
reverb_version = FLAGS.reverb_version
reverb_packages.append(reverb_version)
reverb_packages.append(tf_version)
return reverb_packages | [
"def",
"get_reverb_packages",
"(",
")",
":",
"reverb_packages",
"=",
"[",
"]",
"if",
"FLAGS",
".",
"release",
":",
"tf_version",
"=",
"TENSORFLOW_VERSION",
"reverb_version",
"=",
"REVERB_VERSION",
"else",
":",
"tf_version",
"=",
"TENSORFLOW_NIGHTLY",
"reverb_version... | https://github.com/tensorflow/agents/blob/1407001d242f7f77fb9407f9b1ac78bcd8f73a09/setup.py#L212-L230 | |
seantis/suitable | 047d8634c74498850911e2b14425fee6713adcca | suitable/module_runner.py | python | ModuleRunner.ignore_further_calls_to_server | (self, server) | Takes a server out of the list. | Takes a server out of the list. | [
"Takes",
"a",
"server",
"out",
"of",
"the",
"list",
"."
] | def ignore_further_calls_to_server(self, server):
""" Takes a server out of the list. """
log.error(u'ignoring further calls to {}'.format(server))
del self.api.inventory[server] | [
"def",
"ignore_further_calls_to_server",
"(",
"self",
",",
"server",
")",
":",
"log",
".",
"error",
"(",
"u'ignoring further calls to {}'",
".",
"format",
"(",
"server",
")",
")",
"del",
"self",
".",
"api",
".",
"inventory",
"[",
"server",
"]"
] | https://github.com/seantis/suitable/blob/047d8634c74498850911e2b14425fee6713adcca/suitable/module_runner.py#L272-L275 | ||
IntelAI/models | 1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c | models/image_recognition/tensorflow/resnet50v1_5/training/mlperf_utils/logs/hooks.py | python | ExamplesPerSecondHook.after_run | (self, run_context, run_values) | Called after each call to run().
Args:
run_context: A SessionRunContext object.
run_values: A SessionRunValues object. | Called after each call to run(). | [
"Called",
"after",
"each",
"call",
"to",
"run",
"()",
"."
] | def after_run(self, run_context, run_values): # pylint: disable=unused-argument
"""Called after each call to run().
Args:
run_context: A SessionRunContext object.
run_values: A SessionRunValues object.
"""
global_step = run_values.results
if self._timer.should_trigger_for_step(global_step):
elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(global_step)
if elapsed_time is not None:
# current examples per second is based on the elapsed training steps
# and training time per batch
current_examples_per_sec = self._batch_size * (
elapsed_steps / elapsed_time)
self._total_steps += elapsed_steps
if global_step > self._warm_steps:
self._step_train_time += elapsed_time
self._total_measured_steps += elapsed_steps
# average examples per second is based on the total (accumulative)
# training steps and training time so far
average_examples_per_sec = self._batch_size * (
self._total_measured_steps / self._step_train_time)
# Current examples/sec followed by average examples/sec
tf.compat.v1.logging.info('Batch [%g]: last %g steps exp/sec = %g, total average exp/sec = '
'%g', self._total_steps, elapsed_steps, current_examples_per_sec, average_examples_per_sec)
else:
# Current examples/sec followed by completed warmup steps
tf.compat.v1.logging.info('Batch [%g]: last %g steps exp/sec = %g, completed %g/%g wamrup steps'
, self._total_steps, elapsed_steps, current_examples_per_sec, self._total_steps, self._warm_steps) | [
"def",
"after_run",
"(",
"self",
",",
"run_context",
",",
"run_values",
")",
":",
"# pylint: disable=unused-argument",
"global_step",
"=",
"run_values",
".",
"results",
"if",
"self",
".",
"_timer",
".",
"should_trigger_for_step",
"(",
"global_step",
")",
":",
"ela... | https://github.com/IntelAI/models/blob/1d7a53ccfad3e6f0e7378c9e3c8840895d63df8c/models/image_recognition/tensorflow/resnet50v1_5/training/mlperf_utils/logs/hooks.py#L88-L117 | ||
fritzy/SleekXMPP | cc1d470397de768ffcc41d2ed5ac3118d19f09f5 | sleekxmpp/xmlstream/stanzabase.py | python | StanzaBase.exception | (self, e) | Handle exceptions raised during stanza processing.
Meant to be overridden. | Handle exceptions raised during stanza processing. | [
"Handle",
"exceptions",
"raised",
"during",
"stanza",
"processing",
"."
] | def exception(self, e):
"""Handle exceptions raised during stanza processing.
Meant to be overridden.
"""
log.exception('Error handling {%s}%s stanza', self.namespace,
self.name) | [
"def",
"exception",
"(",
"self",
",",
"e",
")",
":",
"log",
".",
"exception",
"(",
"'Error handling {%s}%s stanza'",
",",
"self",
".",
"namespace",
",",
"self",
".",
"name",
")"
] | https://github.com/fritzy/SleekXMPP/blob/cc1d470397de768ffcc41d2ed5ac3118d19f09f5/sleekxmpp/xmlstream/stanzabase.py#L1568-L1574 | ||
analyticalmindsltd/smote_variants | dedbc3d00b266954fedac0ae87775e1643bc920a | smote_variants/_smote_variants.py | python | MWMOTE.__init__ | (self,
proportion=1.0,
k1=5,
k2=5,
k3=5,
M=10,
cf_th=5.0,
cmax=10.0,
n_jobs=1,
random_state=None) | Constructor of the sampling object
Args:
proportion (float): proportion of the difference of n_maj and n_min
to sample e.g. 1.0 means that after sampling
the number of minority samples will be equal to
the number of majority samples
k1 (int): parameter of the NearestNeighbors component
k2 (int): parameter of the NearestNeighbors component
k3 (int): parameter of the NearestNeighbors component
M (int): number of clusters
cf_th (float): cutoff threshold
cmax (float): maximum closeness value
n_jobs (int): number of parallel jobs
random_state (int/RandomState/None): initializer of random_state,
like in sklearn | Constructor of the sampling object | [
"Constructor",
"of",
"the",
"sampling",
"object"
] | def __init__(self,
proportion=1.0,
k1=5,
k2=5,
k3=5,
M=10,
cf_th=5.0,
cmax=10.0,
n_jobs=1,
random_state=None):
"""
Constructor of the sampling object
Args:
proportion (float): proportion of the difference of n_maj and n_min
to sample e.g. 1.0 means that after sampling
the number of minority samples will be equal to
the number of majority samples
k1 (int): parameter of the NearestNeighbors component
k2 (int): parameter of the NearestNeighbors component
k3 (int): parameter of the NearestNeighbors component
M (int): number of clusters
cf_th (float): cutoff threshold
cmax (float): maximum closeness value
n_jobs (int): number of parallel jobs
random_state (int/RandomState/None): initializer of random_state,
like in sklearn
"""
super().__init__()
self.check_greater_or_equal(proportion, 'proportion', 0)
self.check_greater_or_equal(k1, 'k1', 1)
self.check_greater_or_equal(k2, 'k2', 1)
self.check_greater_or_equal(k3, 'k3', 1)
self.check_greater_or_equal(M, 'M', 1)
self.check_greater_or_equal(cf_th, 'cf_th', 0)
self.check_greater_or_equal(cmax, 'cmax', 0)
self.check_n_jobs(n_jobs, 'n_jobs')
self.proportion = proportion
self.k1 = k1
self.k2 = k2
self.k3 = k3
self.M = M
self.cf_th = cf_th
self.cmax = cmax
self.n_jobs = n_jobs
self.set_random_state(random_state) | [
"def",
"__init__",
"(",
"self",
",",
"proportion",
"=",
"1.0",
",",
"k1",
"=",
"5",
",",
"k2",
"=",
"5",
",",
"k3",
"=",
"5",
",",
"M",
"=",
"10",
",",
"cf_th",
"=",
"5.0",
",",
"cmax",
"=",
"10.0",
",",
"n_jobs",
"=",
"1",
",",
"random_state... | https://github.com/analyticalmindsltd/smote_variants/blob/dedbc3d00b266954fedac0ae87775e1643bc920a/smote_variants/_smote_variants.py#L7112-L7159 | ||
googlearchive/appengine-flask-skeleton | 8c25461d003a0bd99a9ff3b339c2791ee6919242 | lib/jinja2/sandbox.py | python | SandboxedEnvironment.is_safe_callable | (self, obj) | return not (getattr(obj, 'unsafe_callable', False) or
getattr(obj, 'alters_data', False)) | Check if an object is safely callable. Per default a function is
considered safe unless the `unsafe_callable` attribute exists and is
True. Override this method to alter the behavior, but this won't
affect the `unsafe` decorator from this module. | Check if an object is safely callable. Per default a function is
considered safe unless the `unsafe_callable` attribute exists and is
True. Override this method to alter the behavior, but this won't
affect the `unsafe` decorator from this module. | [
"Check",
"if",
"an",
"object",
"is",
"safely",
"callable",
".",
"Per",
"default",
"a",
"function",
"is",
"considered",
"safe",
"unless",
"the",
"unsafe_callable",
"attribute",
"exists",
"and",
"is",
"True",
".",
"Override",
"this",
"method",
"to",
"alter",
"... | def is_safe_callable(self, obj):
"""Check if an object is safely callable. Per default a function is
considered safe unless the `unsafe_callable` attribute exists and is
True. Override this method to alter the behavior, but this won't
affect the `unsafe` decorator from this module.
"""
return not (getattr(obj, 'unsafe_callable', False) or
getattr(obj, 'alters_data', False)) | [
"def",
"is_safe_callable",
"(",
"self",
",",
"obj",
")",
":",
"return",
"not",
"(",
"getattr",
"(",
"obj",
",",
"'unsafe_callable'",
",",
"False",
")",
"or",
"getattr",
"(",
"obj",
",",
"'alters_data'",
",",
"False",
")",
")"
] | https://github.com/googlearchive/appengine-flask-skeleton/blob/8c25461d003a0bd99a9ff3b339c2791ee6919242/lib/jinja2/sandbox.py#L276-L283 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/idlelib/ToolTip.py | python | main | () | [] | def main():
# Test code
root = Tk()
b = Button(root, text="Hello", command=root.destroy)
b.pack()
root.update()
tip = ListboxToolTip(b, ["Hello", "world"])
root.mainloop() | [
"def",
"main",
"(",
")",
":",
"# Test code",
"root",
"=",
"Tk",
"(",
")",
"b",
"=",
"Button",
"(",
"root",
",",
"text",
"=",
"\"Hello\"",
",",
"command",
"=",
"root",
".",
"destroy",
")",
"b",
".",
"pack",
"(",
")",
"root",
".",
"update",
"(",
... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/idlelib/ToolTip.py#L79-L86 | ||||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/UserString.py | python | MutableString.__imul__ | (self, n) | return self | [] | def __imul__(self, n):
self.data *= n
return self | [
"def",
"__imul__",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"data",
"*=",
"n",
"return",
"self"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/UserString.py#L214-L216 | |||
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework | cb692f527e4e819b6c228187c5702d990a180043 | bin/x86/Debug/scripting_engine/Lib/tempfile.py | python | _get_default_tempdir | () | Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is deleted. To prevent denial of
service, the name of the test file must be randomized. | Calculate the default directory to use for temporary files.
This routine should be called exactly once. | [
"Calculate",
"the",
"default",
"directory",
"to",
"use",
"for",
"temporary",
"files",
".",
"This",
"routine",
"should",
"be",
"called",
"exactly",
"once",
"."
] | def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is deleted. To prevent denial of
service, the name of the test file must be randomized."""
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
flags = _text_openflags
for dir in dirlist:
if dir != _os.curdir:
dir = _os.path.normcase(_os.path.abspath(dir))
# Try only a few names per directory.
for seq in xrange(100):
name = namer.next()
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, flags, 0600)
fp = _os.fdopen(fd, 'w')
fp.write('blat')
fp.close()
_os.unlink(filename)
del fp, fd
return dir
except (OSError, IOError), e:
if e[0] != _errno.EEXIST:
break # no point trying more names in this directory
pass
raise IOError, (_errno.ENOENT,
("No usable temporary directory found in %s" % dirlist)) | [
"def",
"_get_default_tempdir",
"(",
")",
":",
"namer",
"=",
"_RandomNameSequence",
"(",
")",
"dirlist",
"=",
"_candidate_tempdir_list",
"(",
")",
"flags",
"=",
"_text_openflags",
"for",
"dir",
"in",
"dirlist",
":",
"if",
"dir",
"!=",
"_os",
".",
"curdir",
":... | https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/tempfile.py#L168-L201 | ||
cclib/cclib | 81cd4a81cc4a3bbed7016b3e417ca9bff8ad3a92 | cclib/parser/gamessparser.py | python | GAMESS.normalisesym | (self, label) | return label[0] + end | Normalise the symmetries used by GAMESS.
To normalise, two rules need to be applied:
(1) Occurences of U/G in the 2/3 position of the label
must be lower-cased
(2) Two single quotation marks must be replaced by a double | Normalise the symmetries used by GAMESS. | [
"Normalise",
"the",
"symmetries",
"used",
"by",
"GAMESS",
"."
] | def normalisesym(self, label):
"""Normalise the symmetries used by GAMESS.
To normalise, two rules need to be applied:
(1) Occurences of U/G in the 2/3 position of the label
must be lower-cased
(2) Two single quotation marks must be replaced by a double
"""
if label[1:] == "''":
end = '"'
else:
end = label[1:].replace("U", "u").replace("G", "g")
return label[0] + end | [
"def",
"normalisesym",
"(",
"self",
",",
"label",
")",
":",
"if",
"label",
"[",
"1",
":",
"]",
"==",
"\"''\"",
":",
"end",
"=",
"'\"'",
"else",
":",
"end",
"=",
"label",
"[",
"1",
":",
"]",
".",
"replace",
"(",
"\"U\"",
",",
"\"u\"",
")",
".",
... | https://github.com/cclib/cclib/blob/81cd4a81cc4a3bbed7016b3e417ca9bff8ad3a92/cclib/parser/gamessparser.py#L61-L74 | |
profusion/sgqlc | 465a5e800f8b408ceafe25cde45ee0bde4912482 | sgqlc/codegen/operation.py | python | GraphQLToPython.report_unused_variables | (cls, variables) | [] | def report_unused_variables(cls, variables):
s = ', '.join(
'%s at %s' % (v.name, cls.get_node_location(v.node))
for v in variables
)
raise SystemExit('unused variable definitions: %s' % (s,)) | [
"def",
"report_unused_variables",
"(",
"cls",
",",
"variables",
")",
":",
"s",
"=",
"', '",
".",
"join",
"(",
"'%s at %s'",
"%",
"(",
"v",
".",
"name",
",",
"cls",
".",
"get_node_location",
"(",
"v",
".",
"node",
")",
")",
"for",
"v",
"in",
"variable... | https://github.com/profusion/sgqlc/blob/465a5e800f8b408ceafe25cde45ee0bde4912482/sgqlc/codegen/operation.py#L502-L507 | ||||
toxygen-project/toxygen | 0a54012cf5ee72434b923bcde7d8f1a4e575ce2f | toxygen/plugin_support.py | python | PluginLoader.get_menu | (self, menu, num) | return result | Return list of items for menu | Return list of items for menu | [
"Return",
"list",
"of",
"items",
"for",
"menu"
] | def get_menu(self, menu, num):
"""
Return list of items for menu
"""
result = []
for elem in self._plugins.values():
if elem[1]:
try:
result.extend(elem[0].get_menu(menu, num))
except:
continue
return result | [
"def",
"get_menu",
"(",
"self",
",",
"menu",
",",
"num",
")",
":",
"result",
"=",
"[",
"]",
"for",
"elem",
"in",
"self",
".",
"_plugins",
".",
"values",
"(",
")",
":",
"if",
"elem",
"[",
"1",
"]",
":",
"try",
":",
"result",
".",
"extend",
"(",
... | https://github.com/toxygen-project/toxygen/blob/0a54012cf5ee72434b923bcde7d8f1a4e575ce2f/toxygen/plugin_support.py#L141-L152 | |
PokemonGoF/PokemonGo-Bot-Backup | 11123a82cb18c172a262dc9e46e7b2c175666828 | pylint-recursive.py | python | check | (module) | apply pylint to the file specified if it is a *.py file | apply pylint to the file specified if it is a *.py file | [
"apply",
"pylint",
"to",
"the",
"file",
"specified",
"if",
"it",
"is",
"a",
"*",
".",
"py",
"file"
] | def check(module):
global passed, failed
'''
apply pylint to the file specified if it is a *.py file
'''
module_name = module.rsplit('/', 1)[1]
if module[-3:] == ".py" and module_name not in IGNORED_FILES:
print "CHECKING ", module
pout = os.popen('pylint %s'% module, 'r')
for line in pout:
if "Your code has been rated at" in line:
print "PASSED pylint inspection: " + line
passed += 1
return True
if "-error" in line:
print "FAILED pylint inspection: " + line
failed += 1
errors.append("FILE: " + module)
errors.append("FAILED pylint inspection: " + line)
return False | [
"def",
"check",
"(",
"module",
")",
":",
"global",
"passed",
",",
"failed",
"module_name",
"=",
"module",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"1",
"]",
"if",
"module",
"[",
"-",
"3",
":",
"]",
"==",
"\".py\"",
"and",
"module_name",
"not"... | https://github.com/PokemonGoF/PokemonGo-Bot-Backup/blob/11123a82cb18c172a262dc9e46e7b2c175666828/pylint-recursive.py#L17-L36 | ||
mesalock-linux/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | rpython/rlib/rposix_stat.py | python | make_stat_result | (tup) | return os.stat_result(positional, kwds) | Turn a tuple into an os.stat_result object. | Turn a tuple into an os.stat_result object. | [
"Turn",
"a",
"tuple",
"into",
"an",
"os",
".",
"stat_result",
"object",
"."
] | def make_stat_result(tup):
"""Turn a tuple into an os.stat_result object."""
assert len(tup) == len(STAT_FIELDS)
assert float not in [type(x) for x in tup]
positional = []
for i in range(N_INDEXABLE_FIELDS):
name, TYPE = STAT_FIELDS[i]
value = lltype.cast_primitive(TYPE, tup[i])
positional.append(value)
kwds = {}
kwds['st_atime'] = tup[7] + 1e-9 * tup[-3]
kwds['st_mtime'] = tup[8] + 1e-9 * tup[-2]
kwds['st_ctime'] = tup[9] + 1e-9 * tup[-1]
for value, (name, TYPE) in zip(tup, STAT_FIELDS)[N_INDEXABLE_FIELDS:]:
if name.startswith('nsec_'):
continue # ignore the nsec_Xtime here
kwds[name] = lltype.cast_primitive(TYPE, value)
return os.stat_result(positional, kwds) | [
"def",
"make_stat_result",
"(",
"tup",
")",
":",
"assert",
"len",
"(",
"tup",
")",
"==",
"len",
"(",
"STAT_FIELDS",
")",
"assert",
"float",
"not",
"in",
"[",
"type",
"(",
"x",
")",
"for",
"x",
"in",
"tup",
"]",
"positional",
"=",
"[",
"]",
"for",
... | https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/rpython/rlib/rposix_stat.py#L244-L261 | |
rdegges/django-twilio | 3716600b69d86cb2a6595c46c068d33f65eb8315 | django_twilio/utils.py | python | discover_twilio_credentials | (user=None) | Due to the multiple ways of providing SID / AUTH tokens through
this package, this function will search in the various places that
credentials might be stored.
The order this is done in is:
1. If a User is passed: the keys linked to the
user model from the Credentials model in the database.
2. Environment variables
3. django.conf settings
We recommend using environment variables were possible; it is the
most secure option | Due to the multiple ways of providing SID / AUTH tokens through
this package, this function will search in the various places that
credentials might be stored. | [
"Due",
"to",
"the",
"multiple",
"ways",
"of",
"providing",
"SID",
"/",
"AUTH",
"tokens",
"through",
"this",
"package",
"this",
"function",
"will",
"search",
"in",
"the",
"various",
"places",
"that",
"credentials",
"might",
"be",
"stored",
"."
] | def discover_twilio_credentials(user=None):
""" Due to the multiple ways of providing SID / AUTH tokens through
this package, this function will search in the various places that
credentials might be stored.
The order this is done in is:
1. If a User is passed: the keys linked to the
user model from the Credentials model in the database.
2. Environment variables
3. django.conf settings
We recommend using environment variables were possible; it is the
most secure option
"""
SID = 'TWILIO_ACCOUNT_SID'
AUTH = 'TWILIO_AUTH_TOKEN'
if user:
credentials = Credential.objects.filter(user=user.id)
if credentials.exists():
credentials = credentials[0]
return credentials.account_sid, credentials.auth_token
if SID in os.environ and AUTH in os.environ:
return os.environ[SID], os.environ[AUTH]
if hasattr(settings, SID) and hasattr(settings, AUTH):
return settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN
raise AttributeError(
"Could not find {sid} or {auth} in environment variables, "
"User credentials, or django project settings.".format(
sid=SID,
auth=AUTH,
)
) | [
"def",
"discover_twilio_credentials",
"(",
"user",
"=",
"None",
")",
":",
"SID",
"=",
"'TWILIO_ACCOUNT_SID'",
"AUTH",
"=",
"'TWILIO_AUTH_TOKEN'",
"if",
"user",
":",
"credentials",
"=",
"Credential",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
".",... | https://github.com/rdegges/django-twilio/blob/3716600b69d86cb2a6595c46c068d33f65eb8315/django_twilio/utils.py#L21-L58 | ||
TesterlifeRaymond/doraemon | d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333 | venv/lib/python3.6/site-packages/setuptools/command/egg_info.py | python | egg_info.write_file | (self, what, filename, data) | Write `data` to `filename` (if not a dry run) after announcing it
`what` is used in a log message to identify what is being written
to the file. | Write `data` to `filename` (if not a dry run) after announcing it | [
"Write",
"data",
"to",
"filename",
"(",
"if",
"not",
"a",
"dry",
"run",
")",
"after",
"announcing",
"it"
] | def write_file(self, what, filename, data):
"""Write `data` to `filename` (if not a dry run) after announcing it
`what` is used in a log message to identify what is being written
to the file.
"""
log.info("writing %s to %s", what, filename)
if six.PY3:
data = data.encode("utf-8")
if not self.dry_run:
f = open(filename, 'wb')
f.write(data)
f.close() | [
"def",
"write_file",
"(",
"self",
",",
"what",
",",
"filename",
",",
"data",
")",
":",
"log",
".",
"info",
"(",
"\"writing %s to %s\"",
",",
"what",
",",
"filename",
")",
"if",
"six",
".",
"PY3",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"\"utf-8... | https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/venv/lib/python3.6/site-packages/setuptools/command/egg_info.py#L238-L250 | ||
networkx/networkx | 1620568e36702b1cfeaf1c0277b167b6cb93e48d | networkx/generators/degree_seq.py | python | _to_stublist | (degree_sequence) | return list(chaini([n] * d for n, d in enumerate(degree_sequence))) | Returns a list of degree-repeated node numbers.
``degree_sequence`` is a list of nonnegative integers representing
the degrees of nodes in a graph.
This function returns a list of node numbers with multiplicities
according to the given degree sequence. For example, if the first
element of ``degree_sequence`` is ``3``, then the first node number,
``0``, will appear at the head of the returned list three times. The
node numbers are assumed to be the numbers zero through
``len(degree_sequence) - 1``.
Examples
--------
>>> degree_sequence = [1, 2, 3]
>>> _to_stublist(degree_sequence)
[0, 1, 1, 2, 2, 2]
If a zero appears in the sequence, that means the node exists but
has degree zero, so that number will be skipped in the returned
list::
>>> degree_sequence = [2, 0, 1]
>>> _to_stublist(degree_sequence)
[0, 0, 2] | Returns a list of degree-repeated node numbers. | [
"Returns",
"a",
"list",
"of",
"degree",
"-",
"repeated",
"node",
"numbers",
"."
] | def _to_stublist(degree_sequence):
"""Returns a list of degree-repeated node numbers.
``degree_sequence`` is a list of nonnegative integers representing
the degrees of nodes in a graph.
This function returns a list of node numbers with multiplicities
according to the given degree sequence. For example, if the first
element of ``degree_sequence`` is ``3``, then the first node number,
``0``, will appear at the head of the returned list three times. The
node numbers are assumed to be the numbers zero through
``len(degree_sequence) - 1``.
Examples
--------
>>> degree_sequence = [1, 2, 3]
>>> _to_stublist(degree_sequence)
[0, 1, 1, 2, 2, 2]
If a zero appears in the sequence, that means the node exists but
has degree zero, so that number will be skipped in the returned
list::
>>> degree_sequence = [2, 0, 1]
>>> _to_stublist(degree_sequence)
[0, 0, 2]
"""
return list(chaini([n] * d for n, d in enumerate(degree_sequence))) | [
"def",
"_to_stublist",
"(",
"degree_sequence",
")",
":",
"return",
"list",
"(",
"chaini",
"(",
"[",
"n",
"]",
"*",
"d",
"for",
"n",
",",
"d",
"in",
"enumerate",
"(",
"degree_sequence",
")",
")",
")"
] | https://github.com/networkx/networkx/blob/1620568e36702b1cfeaf1c0277b167b6cb93e48d/networkx/generators/degree_seq.py#L27-L56 | |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | 5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e | tensorflow_dl_models/research/textsum/seq2seq_attention_decode.py | python | BSDecoder._DecodeBatch | (self, article, abstract, output_ids) | Convert id to words and writing results.
Args:
article: The original article string.
abstract: The human (correct) abstract string.
output_ids: The abstract word ids output by machine. | Convert id to words and writing results. | [
"Convert",
"id",
"to",
"words",
"and",
"writing",
"results",
"."
] | def _DecodeBatch(self, article, abstract, output_ids):
"""Convert id to words and writing results.
Args:
article: The original article string.
abstract: The human (correct) abstract string.
output_ids: The abstract word ids output by machine.
"""
decoded_output = ' '.join(data.Ids2Words(output_ids, self._vocab))
end_p = decoded_output.find(data.SENTENCE_END, 0)
if end_p != -1:
decoded_output = decoded_output[:end_p]
tf.logging.info('article: %s', article)
tf.logging.info('abstract: %s', abstract)
tf.logging.info('decoded: %s', decoded_output)
self._decode_io.Write(abstract, decoded_output.strip()) | [
"def",
"_DecodeBatch",
"(",
"self",
",",
"article",
",",
"abstract",
",",
"output_ids",
")",
":",
"decoded_output",
"=",
"' '",
".",
"join",
"(",
"data",
".",
"Ids2Words",
"(",
"output_ids",
",",
"self",
".",
"_vocab",
")",
")",
"end_p",
"=",
"decoded_ou... | https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials/blob/5bb97d7e3ffd913abddb4cfa7d78a1b4c868890e/tensorflow_dl_models/research/textsum/seq2seq_attention_decode.py#L147-L162 | ||
more-itertools/more-itertools | b469c17e2bb48d7b9aca11365e112736b8e814f6 | more_itertools/more.py | python | split_at | (iterable, pred, maxsplit=-1, keep_separator=False) | Yield lists of items from *iterable*, where each list is delimited by
an item where callable *pred* returns ``True``.
>>> list(split_at('abcdcba', lambda x: x == 'b'))
[['a'], ['c', 'd', 'c'], ['a']]
>>> list(split_at(range(10), lambda n: n % 2 == 1))
[[0], [2], [4], [6], [8], []]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))
[[0], [2], [4, 5, 6, 7, 8, 9]]
By default, the delimiting items are not included in the output.
The include them, set *keep_separator* to ``True``.
>>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))
[['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']] | Yield lists of items from *iterable*, where each list is delimited by
an item where callable *pred* returns ``True``. | [
"Yield",
"lists",
"of",
"items",
"from",
"*",
"iterable",
"*",
"where",
"each",
"list",
"is",
"delimited",
"by",
"an",
"item",
"where",
"callable",
"*",
"pred",
"*",
"returns",
"True",
"."
] | def split_at(iterable, pred, maxsplit=-1, keep_separator=False):
"""Yield lists of items from *iterable*, where each list is delimited by
an item where callable *pred* returns ``True``.
>>> list(split_at('abcdcba', lambda x: x == 'b'))
[['a'], ['c', 'd', 'c'], ['a']]
>>> list(split_at(range(10), lambda n: n % 2 == 1))
[[0], [2], [4], [6], [8], []]
At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,
then there is no limit on the number of splits:
>>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))
[[0], [2], [4, 5, 6, 7, 8, 9]]
By default, the delimiting items are not included in the output.
The include them, set *keep_separator* to ``True``.
>>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))
[['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]
"""
if maxsplit == 0:
yield list(iterable)
return
buf = []
it = iter(iterable)
for item in it:
if pred(item):
yield buf
if keep_separator:
yield [item]
if maxsplit == 1:
yield list(it)
return
buf = []
maxsplit -= 1
else:
buf.append(item)
yield buf | [
"def",
"split_at",
"(",
"iterable",
",",
"pred",
",",
"maxsplit",
"=",
"-",
"1",
",",
"keep_separator",
"=",
"False",
")",
":",
"if",
"maxsplit",
"==",
"0",
":",
"yield",
"list",
"(",
"iterable",
")",
"return",
"buf",
"=",
"[",
"]",
"it",
"=",
"ite... | https://github.com/more-itertools/more-itertools/blob/b469c17e2bb48d7b9aca11365e112736b8e814f6/more_itertools/more.py#L1321-L1362 | ||
007gzs/dingtalk-sdk | 7979da2e259fdbc571728cae2425a04dbc65850a | dingtalk/client/api/taobao.py | python | TbXinXiLiu.taobao_feedflow_item_campaign_add | (
self,
campaign=None
) | return self._top_request(
"taobao.feedflow.item.campaign.add",
{
"campaign": campaign
}
) | 信息流增加推广计划
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=43264
:param campaign: 计划信息 | 信息流增加推广计划
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=43264 | [
"信息流增加推广计划",
"文档地址:https",
":",
"//",
"open",
"-",
"doc",
".",
"dingtalk",
".",
"com",
"/",
"docs",
"/",
"api",
".",
"htm?apiId",
"=",
"43264"
] | def taobao_feedflow_item_campaign_add(
self,
campaign=None
):
"""
信息流增加推广计划
文档地址:https://open-doc.dingtalk.com/docs/api.htm?apiId=43264
:param campaign: 计划信息
"""
return self._top_request(
"taobao.feedflow.item.campaign.add",
{
"campaign": campaign
}
) | [
"def",
"taobao_feedflow_item_campaign_add",
"(",
"self",
",",
"campaign",
"=",
"None",
")",
":",
"return",
"self",
".",
"_top_request",
"(",
"\"taobao.feedflow.item.campaign.add\"",
",",
"{",
"\"campaign\"",
":",
"campaign",
"}",
")"
] | https://github.com/007gzs/dingtalk-sdk/blob/7979da2e259fdbc571728cae2425a04dbc65850a/dingtalk/client/api/taobao.py#L109444-L109459 | |
mikew/ss-plex.bundle | 031566c06205e08a8cb15c57a0c143fba5270493 | Contents/Libraries/Shared/nose/plugins/attrib.py | python | AttributeSelector.wantMethod | (self, method) | return self.validateAttrib(method, cls) | Accept the method if its attributes match. | Accept the method if its attributes match. | [
"Accept",
"the",
"method",
"if",
"its",
"attributes",
"match",
"."
] | def wantMethod(self, method):
"""Accept the method if its attributes match.
"""
try:
cls = method.im_class
except AttributeError:
return False
return self.validateAttrib(method, cls) | [
"def",
"wantMethod",
"(",
"self",
",",
"method",
")",
":",
"try",
":",
"cls",
"=",
"method",
".",
"im_class",
"except",
"AttributeError",
":",
"return",
"False",
"return",
"self",
".",
"validateAttrib",
"(",
"method",
",",
"cls",
")"
] | https://github.com/mikew/ss-plex.bundle/blob/031566c06205e08a8cb15c57a0c143fba5270493/Contents/Libraries/Shared/nose/plugins/attrib.py#L279-L286 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/PIL/PdfParser.py | python | PdfParser.__exit__ | (self, exc_type, exc_value, traceback) | return False | [] | def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False | [
"def",
"__exit__",
"(",
"self",
",",
"exc_type",
",",
"exc_value",
",",
"traceback",
")",
":",
"self",
".",
"close",
"(",
")",
"return",
"False"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/PIL/PdfParser.py#L390-L392 | |||
uhlik/bpy | 698faa76b614904f4d29586ac10ed1234bd99dca | space_view3d_point_cloud_visualizer.py | python | PCV_PT_convert.draw | (self, context) | [] | def draw(self, context):
pcv = context.object.point_cloud_visualizer
l = self.layout
sub = l.column()
c = sub.column()
c.prop(pcv, 'mesh_type')
f = 0.245
r = c.row(align=True)
s = r.split(factor=f, align=True, )
s.prop(pcv, 'mesh_all', toggle=True, )
s = s.split(factor=1.0, align=True, )
s.prop(pcv, 'mesh_percentage')
if(pcv.mesh_all):
s.enabled = False
cc = c.column()
cc.prop(pcv, 'mesh_size')
if(pcv.mesh_type in ('INSTANCER', 'PARTICLES', )):
cc.prop(pcv, 'mesh_base_sphere_subdivisions')
cc_n = cc.row()
cc_n.prop(pcv, 'mesh_normal_align')
if(not pcv.has_normals):
cc_n.enabled = False
cc_c = cc.row()
cc_c.prop(pcv, 'mesh_vcols')
if(not pcv.has_vcols):
cc_c.enabled = False
if(pcv.mesh_type == 'VERTEX'):
cc.enabled = False
# c.operator('point_cloud_visualizer.convert')
r = c.row(align=True)
r.operator('point_cloud_visualizer.convert')
r.prop(pcv, 'mesh_use_instancer2', toggle=True, text='', icon='AUTO', )
c.enabled = PCV_OT_convert.poll(context) | [
"def",
"draw",
"(",
"self",
",",
"context",
")",
":",
"pcv",
"=",
"context",
".",
"object",
".",
"point_cloud_visualizer",
"l",
"=",
"self",
".",
"layout",
"sub",
"=",
"l",
".",
"column",
"(",
")",
"c",
"=",
"sub",
".",
"column",
"(",
")",
"c",
"... | https://github.com/uhlik/bpy/blob/698faa76b614904f4d29586ac10ed1234bd99dca/space_view3d_point_cloud_visualizer.py#L9059-L9100 | ||||
sahana/eden | 1696fa50e90ce967df69f66b571af45356cc18da | modules/s3/s3utils.py | python | S3MultiPath.__and__ | (self, sequence) | return 0 | Check whether sequence is the start sequence of any of
the paths in this multi-path (for de-duplication)
Args:
sequence: sequence of node IDs (or path) | Check whether sequence is the start sequence of any of
the paths in this multi-path (for de-duplication) | [
"Check",
"whether",
"sequence",
"is",
"the",
"start",
"sequence",
"of",
"any",
"of",
"the",
"paths",
"in",
"this",
"multi",
"-",
"path",
"(",
"for",
"de",
"-",
"duplication",
")"
] | def __and__(self, sequence):
"""
Check whether sequence is the start sequence of any of
the paths in this multi-path (for de-duplication)
Args:
sequence: sequence of node IDs (or path)
"""
for p in self.paths:
if p.startswith(sequence):
return 1
return 0 | [
"def",
"__and__",
"(",
"self",
",",
"sequence",
")",
":",
"for",
"p",
"in",
"self",
".",
"paths",
":",
"if",
"p",
".",
"startswith",
"(",
"sequence",
")",
":",
"return",
"1",
"return",
"0"
] | https://github.com/sahana/eden/blob/1696fa50e90ce967df69f66b571af45356cc18da/modules/s3/s3utils.py#L2734-L2745 | |
dropbox/PyHive | b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0 | TCLIService/ttypes.py | python | TGetTableTypesResp.write | (self, oprot) | [] | def write(self, oprot):
if oprot._fast_encode is not None and self.thrift_spec is not None:
oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('TGetTableTypesResp')
if self.status is not None:
oprot.writeFieldBegin('status', TType.STRUCT, 1)
self.status.write(oprot)
oprot.writeFieldEnd()
if self.operationHandle is not None:
oprot.writeFieldBegin('operationHandle', TType.STRUCT, 2)
self.operationHandle.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd() | [
"def",
"write",
"(",
"self",
",",
"oprot",
")",
":",
"if",
"oprot",
".",
"_fast_encode",
"is",
"not",
"None",
"and",
"self",
".",
"thrift_spec",
"is",
"not",
"None",
":",
"oprot",
".",
"trans",
".",
"write",
"(",
"oprot",
".",
"_fast_encode",
"(",
"s... | https://github.com/dropbox/PyHive/blob/b21c507a24ed2f2b0cf15b0b6abb1c43f31d3ee0/TCLIService/ttypes.py#L4862-L4876 | ||||
coderSkyChen/Action_Recognition_Zoo | 92ec5ec3efeee852aec5c057798298cd3a8e58ae | model_zoo/models/inception/inception/data/build_image_data.py | python | _process_image | (filename, coder) | return image_data, height, width | Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, image height in pixels.
width: integer, image width in pixels. | Process a single image file. | [
"Process",
"a",
"single",
"image",
"file",
"."
] | def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, image height in pixels.
width: integer, image width in pixels.
"""
# Read the image file.
with tf.gfile.FastGFile(filename, 'r') as f:
image_data = f.read()
# Convert any PNG to JPEG's for consistency.
if _is_png(filename):
print('Converting PNG to JPEG for %s' % filename)
image_data = coder.png_to_jpeg(image_data)
# Decode the RGB JPEG.
image = coder.decode_jpeg(image_data)
# Check that image converted to RGB
assert len(image.shape) == 3
height = image.shape[0]
width = image.shape[1]
assert image.shape[2] == 3
return image_data, height, width | [
"def",
"_process_image",
"(",
"filename",
",",
"coder",
")",
":",
"# Read the image file.",
"with",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"image_data",
"=",
"f",
".",
"read",
"(",
")",
"# Convert any PNG to... | https://github.com/coderSkyChen/Action_Recognition_Zoo/blob/92ec5ec3efeee852aec5c057798298cd3a8e58ae/model_zoo/models/inception/inception/data/build_image_data.py#L190-L219 | |
biopython/biopython | 2dd97e71762af7b046d7f7f8a4f1e38db6b06c86 | Bio/pairwise2.py | python | print_matrix | (matrix) | Print out a matrix for debugging purposes. | Print out a matrix for debugging purposes. | [
"Print",
"out",
"a",
"matrix",
"for",
"debugging",
"purposes",
"."
] | def print_matrix(matrix):
"""Print out a matrix for debugging purposes."""
# Transpose the matrix and get the length of the values in each column.
matrixT = [[] for x in range(len(matrix[0]))]
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrixT[j].append(len(str(matrix[i][j])))
ndigits = [max(x) for x in matrixT]
for i in range(len(matrix)):
# Using string formatting trick to add leading spaces,
print(
" ".join("%*s " % (ndigits[j], matrix[i][j]) for j in range(len(matrix[i])))
) | [
"def",
"print_matrix",
"(",
"matrix",
")",
":",
"# Transpose the matrix and get the length of the values in each column.",
"matrixT",
"=",
"[",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"matrix",
"[",
"0",
"]",
")",
")",
"]",
"for",
"i",
"in",
"r... | https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/pairwise2.py#L1329-L1341 | ||
BitBotFactory/MikaLendingBot | b59ab8709220b3be1481ca8949a80f944b05018e | modules/Data.py | python | timestamp | () | return datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') | Returns timestamp in UTC | Returns timestamp in UTC | [
"Returns",
"timestamp",
"in",
"UTC"
] | def timestamp():
'''
Returns timestamp in UTC
'''
return datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') | [
"def",
"timestamp",
"(",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")"
] | https://github.com/BitBotFactory/MikaLendingBot/blob/b59ab8709220b3be1481ca8949a80f944b05018e/modules/Data.py#L65-L69 | |
guildai/guildai | 1665985a3d4d788efc1a3180ca51cc417f71ca78 | guild/external/pip/_vendor/urllib3/connection.py | python | HTTPConnection._new_conn | (self) | return conn | Establish a socket connection and set nodelay settings on it.
:return: New socket connection. | Establish a socket connection and set nodelay settings on it. | [
"Establish",
"a",
"socket",
"connection",
"and",
"set",
"nodelay",
"settings",
"on",
"it",
"."
] | def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw['source_address'] = self.source_address
if self.socket_options:
extra_kw['socket_options'] = self.socket_options
try:
conn = connection.create_connection(
(self._dns_host, self.port), self.timeout, **extra_kw)
except SocketTimeout as e:
raise ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
(self.host, self.timeout))
except SocketError as e:
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e)
return conn | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"'source_address'",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"'socke... | https://github.com/guildai/guildai/blob/1665985a3d4d788efc1a3180ca51cc417f71ca78/guild/external/pip/_vendor/urllib3/connection.py#L157-L182 | |
cronyo/cronyo | cd5abab0871b68bf31b18aac934303928130a441 | cronyo/vendor/yaml/error.py | python | Mark.__str__ | (self) | return where | [] | def __str__(self):
snippet = self.get_snippet()
where = " in \"%s\", line %d, column %d" \
% (self.name, self.line+1, self.column+1)
if snippet is not None:
where += ":\n"+snippet
return where | [
"def",
"__str__",
"(",
"self",
")",
":",
"snippet",
"=",
"self",
".",
"get_snippet",
"(",
")",
"where",
"=",
"\" in \\\"%s\\\", line %d, column %d\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"line",
"+",
"1",
",",
"self",
".",
"column",
"+",
... | https://github.com/cronyo/cronyo/blob/cd5abab0871b68bf31b18aac934303928130a441/cronyo/vendor/yaml/error.py#L37-L43 | |||
bnpy/bnpy | d5b311e8f58ccd98477f4a0c8a4d4982e3fca424 | bnpy/obsmodel/AutoRegGaussObsModel.py | python | calcLogSoftEvMatrix_FromPost | (Dslice,
E_logdetL=None,
**kwargs) | return L | Calculate expected log soft ev matrix for variational.
Returns
------
L : 2D array, size N x K | Calculate expected log soft ev matrix for variational. | [
"Calculate",
"expected",
"log",
"soft",
"ev",
"matrix",
"for",
"variational",
"."
] | def calcLogSoftEvMatrix_FromPost(Dslice,
E_logdetL=None,
**kwargs):
''' Calculate expected log soft ev matrix for variational.
Returns
------
L : 2D array, size N x K
'''
K = kwargs['K']
L = np.zeros((Dslice.nObs, K))
for k in range(K):
L[:, k] = - 0.5 * Dslice.dim * LOGTWOPI \
+ 0.5 * E_logdetL[k] \
- 0.5 * _mahalDist_Post(Dslice.X, Dslice.Xprev, k, **kwargs)
return L | [
"def",
"calcLogSoftEvMatrix_FromPost",
"(",
"Dslice",
",",
"E_logdetL",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"K",
"=",
"kwargs",
"[",
"'K'",
"]",
"L",
"=",
"np",
".",
"zeros",
"(",
"(",
"Dslice",
".",
"nObs",
",",
"K",
")",
")",
"for",
... | https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/obsmodel/AutoRegGaussObsModel.py#L1064-L1079 | |
Pylons/substanced | a897f4a0518c51b6e093cc5af39fa326f23752c2 | substanced/interfaces.py | python | IFolder.__setitem__ | (name, other) | Set object ``other`` into this folder under the name ``name``.
``name`` must be a Unicode object or a bytestring object.
If ``name`` is a bytestring object, it must be decodable using the
system default encoding or the UTF-8 encoding.
``name`` cannot be the empty string.
When ``other`` is seated into this folder, it will also be
decorated with a ``__parent__`` attribute (a reference to the
folder into which it is being seated) and ``__name__``
attribute (the name passed in to this function.
If a value already exists in the foldr under the name ``name``, raise
:exc:`KeyError`.
When this method is called, emit an ``IObjectWillBeAdded`` event
before the object obtains a ``__name__`` or ``__parent__`` value.
Emit an ``IObjectAdded`` event after the object obtains a ``__name__``
and ``__parent__`` value. | Set object ``other`` into this folder under the name ``name``. | [
"Set",
"object",
"other",
"into",
"this",
"folder",
"under",
"the",
"name",
"name",
"."
] | def __setitem__(name, other):
""" Set object ``other`` into this folder under the name ``name``.
``name`` must be a Unicode object or a bytestring object.
If ``name`` is a bytestring object, it must be decodable using the
system default encoding or the UTF-8 encoding.
``name`` cannot be the empty string.
When ``other`` is seated into this folder, it will also be
decorated with a ``__parent__`` attribute (a reference to the
folder into which it is being seated) and ``__name__``
attribute (the name passed in to this function.
If a value already exists in the foldr under the name ``name``, raise
:exc:`KeyError`.
When this method is called, emit an ``IObjectWillBeAdded`` event
before the object obtains a ``__name__`` or ``__parent__`` value.
Emit an ``IObjectAdded`` event after the object obtains a ``__name__``
and ``__parent__`` value.
""" | [
"def",
"__setitem__",
"(",
"name",
",",
"other",
")",
":"
] | https://github.com/Pylons/substanced/blob/a897f4a0518c51b6e093cc5af39fa326f23752c2/substanced/interfaces.py#L450-L472 | ||
googleprojectzero/domato | 7625d1d27c71b45c273f27ee06cd9499cb1c2307 | grammar.py | python | Grammar._normalize_probabilities | (self) | Preprocessess probabilities for production rules.
Creates CDFs (cumulative distribution functions) and normalizes
probabilities in the [0,1] range for all creators. This is a
preprocessing function that makes subsequent creator selection
based on probability easier. | Preprocessess probabilities for production rules. | [
"Preprocessess",
"probabilities",
"for",
"production",
"rules",
"."
] | def _normalize_probabilities(self):
"""Preprocessess probabilities for production rules.
Creates CDFs (cumulative distribution functions) and normalizes
probabilities in the [0,1] range for all creators. This is a
preprocessing function that makes subsequent creator selection
based on probability easier.
"""
for symbol, creators in self._creators.items():
cdf = self._get_cdf(symbol, creators)
self._creator_cdfs[symbol] = cdf
for symbol, creators in self._nonrecursive_creators.items():
cdf = self._get_cdf(symbol, creators)
self._nonrecursivecreator_cdfs[symbol] = cdf | [
"def",
"_normalize_probabilities",
"(",
"self",
")",
":",
"for",
"symbol",
",",
"creators",
"in",
"self",
".",
"_creators",
".",
"items",
"(",
")",
":",
"cdf",
"=",
"self",
".",
"_get_cdf",
"(",
"symbol",
",",
"creators",
")",
"self",
".",
"_creator_cdfs... | https://github.com/googleprojectzero/domato/blob/7625d1d27c71b45c273f27ee06cd9499cb1c2307/grammar.py#L626-L640 | ||
CalebBell/thermo | 572a47d1b03d49fe609b8d5f826fa6a7cde00828 | thermo/uniquac.py | python | UNIQUAC.taus | (self) | return taus | r'''Calculate and return the `tau` terms for the UNIQUAC model for the
system temperature.
.. math::
\tau_{ij} = \exp\left[a_{ij}+\frac{b_{ij}}{T}+c_{ij}\ln T
+ d_{ij}T + \frac{e_{ij}}{T^2} + f_{ij}{T^2}\right]
Returns
-------
taus : list[list[float]]
tau terms, asymmetric matrix [-]
Notes
-----
These `tau ij` values (and the coefficients) are NOT symmetric. | r'''Calculate and return the `tau` terms for the UNIQUAC model for the
system temperature. | [
"r",
"Calculate",
"and",
"return",
"the",
"tau",
"terms",
"for",
"the",
"UNIQUAC",
"model",
"for",
"the",
"system",
"temperature",
"."
] | def taus(self):
r'''Calculate and return the `tau` terms for the UNIQUAC model for the
system temperature.
.. math::
\tau_{ij} = \exp\left[a_{ij}+\frac{b_{ij}}{T}+c_{ij}\ln T
+ d_{ij}T + \frac{e_{ij}}{T^2} + f_{ij}{T^2}\right]
Returns
-------
taus : list[list[float]]
tau terms, asymmetric matrix [-]
Notes
-----
These `tau ij` values (and the coefficients) are NOT symmetric.
'''
try:
return self._taus
except AttributeError:
pass
# 87% of the time of this routine is the exponential.
A = self.tau_coeffs_A
B = self.tau_coeffs_B
C = self.tau_coeffs_C
D = self.tau_coeffs_D
E = self.tau_coeffs_E
F = self.tau_coeffs_F
T = self.T
N = self.N
if self.scalar:
taus = [[0.0]*N for _ in range(N)]
else:
taus = zeros((N, N))
self._taus = interaction_exp(T, N, A, B, C, D, E, F, taus)
return taus | [
"def",
"taus",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_taus",
"except",
"AttributeError",
":",
"pass",
"# 87% of the time of this routine is the exponential.",
"A",
"=",
"self",
".",
"tau_coeffs_A",
"B",
"=",
"self",
".",
"tau_coeffs_B",
"C",... | https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/uniquac.py#L649-L684 | |
cheshirekow/cmake_format | eff5df1f41c665ea7cac799396042e4f406ef09a | cmakelang/parse/funs/random.py | python | parse_ctest_memcheck | (ctx, tokens, breakstack) | return StandardArgTree.parse(ctx, tokens, 0, kwargs, flags, breakstack) | ::
ctest_memcheck([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[DEFECT_COUNT <defect-count-var>]
[QUIET]
)
:see: https://cmake.org/cmake/help/latest/command/ctest_memcheck.html | :: | [
"::"
] | def parse_ctest_memcheck(ctx, tokens, breakstack):
"""
::
ctest_memcheck([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[DEFECT_COUNT <defect-count-var>]
[QUIET]
)
:see: https://cmake.org/cmake/help/latest/command/ctest_memcheck.html
"""
kwargs = {
"BUILD": PositionalParser(1),
"START": PositionalParser(1),
"END": PositionalParser(1),
"STRIDE": PositionalParser(1),
"EXCLUDE": PositionalParser(1),
"INCLUDE": PositionalParser(1),
"EXCLUDE_LABEL": PositionalParser(1),
"INCLUDE_LABEL": PositionalParser(1),
"EXCLUDE_FIXTURE": PositionalParser(1),
"EXCLUDE_FIXTURE_SETUP": PositionalParser(1),
"EXCLUDE_FIXTURE_CLEANUP": PositionalParser(1),
"PARALLEL_LEVEL": PositionalParser(1),
"TEST_LOAD": PositionalParser(1),
"SCHEDULE_RANDOM": PositionalParser(1, flags=["ON", "OFF"]),
"STOP_TIME": PositionalParser(1),
"RETURN_VALUE": PositionalParser(1),
"DEFECT_COUNT": PositionalParser(1),
}
flags = ["APPEND", "QUIET"]
return StandardArgTree.parse(ctx, tokens, 0, kwargs, flags, breakstack) | [
"def",
"parse_ctest_memcheck",
"(",
"ctx",
",",
"tokens",
",",
"breakstack",
")",
":",
"kwargs",
"=",
"{",
"\"BUILD\"",
":",
"PositionalParser",
"(",
"1",
")",
",",
"\"START\"",
":",
"PositionalParser",
"(",
"1",
")",
",",
"\"END\"",
":",
"PositionalParser",... | https://github.com/cheshirekow/cmake_format/blob/eff5df1f41c665ea7cac799396042e4f406ef09a/cmakelang/parse/funs/random.py#L96-L142 | |
awslabs/aws-data-wrangler | 548f5197bacd91bd50ebc66a0173eff9c56f69b1 | awswrangler/emr.py | python | _get_default_logging_path | (
subnet_id: Optional[str] = None,
account_id: Optional[str] = None,
region: Optional[str] = None,
boto3_session: Optional[boto3.Session] = None,
) | return f"s3://aws-logs-{_account_id}-{_region}/elasticmapreduce/" | Get EMR default logging path.
E.g. "s3://aws-logs-{account_id}-{region}/elasticmapreduce/"
Parameters
----------
subnet_id : str, optional
Subnet ID. If not provided, you must pass `account_id` and `region` explicit.
account_id: str, optional
Account ID.
region: str, optional
Region e.g. 'us-east-1'
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
Returns
-------
str
Default logging path.
E.g. "s3://aws-logs-{account_id}-{region}/elasticmapreduce/"
Examples
--------
>>> import awswrangler as wr
>>> state = wr.emr._get_default_logging_path("subnet-id")
's3://aws-logs-{account_id}-{region}/elasticmapreduce/' | Get EMR default logging path. | [
"Get",
"EMR",
"default",
"logging",
"path",
"."
] | def _get_default_logging_path(
subnet_id: Optional[str] = None,
account_id: Optional[str] = None,
region: Optional[str] = None,
boto3_session: Optional[boto3.Session] = None,
) -> str:
"""Get EMR default logging path.
E.g. "s3://aws-logs-{account_id}-{region}/elasticmapreduce/"
Parameters
----------
subnet_id : str, optional
Subnet ID. If not provided, you must pass `account_id` and `region` explicit.
account_id: str, optional
Account ID.
region: str, optional
Region e.g. 'us-east-1'
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
Returns
-------
str
Default logging path.
E.g. "s3://aws-logs-{account_id}-{region}/elasticmapreduce/"
Examples
--------
>>> import awswrangler as wr
>>> state = wr.emr._get_default_logging_path("subnet-id")
's3://aws-logs-{account_id}-{region}/elasticmapreduce/'
"""
if account_id is None:
boto3_session = _utils.ensure_session(session=boto3_session)
_account_id: str = sts.get_account_id(boto3_session=boto3_session)
else:
_account_id = account_id
if (region is None) and (subnet_id is not None):
_region: str = _utils.get_region_from_session(boto3_session=boto3_session)
elif (region is None) and (subnet_id is None):
raise exceptions.InvalidArgumentCombination("You must pass region or subnet_id or both.")
else:
_region = region # type: ignore
return f"s3://aws-logs-{_account_id}-{_region}/elasticmapreduce/" | [
"def",
"_get_default_logging_path",
"(",
"subnet_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"account_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"region",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"boto3_session",
":"... | https://github.com/awslabs/aws-data-wrangler/blob/548f5197bacd91bd50ebc66a0173eff9c56f69b1/awswrangler/emr.py#L33-L78 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/flask/json/tag.py | python | JSONTag.to_python | (self, value) | Convert the JSON representation back to the correct type. The tag
will already be removed. | Convert the JSON representation back to the correct type. The tag
will already be removed. | [
"Convert",
"the",
"JSON",
"representation",
"back",
"to",
"the",
"correct",
"type",
".",
"The",
"tag",
"will",
"already",
"be",
"removed",
"."
] | def to_python(self, value):
"""Convert the JSON representation back to the correct type. The tag
will already be removed."""
raise NotImplementedError | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/flask/json/tag.py#L78-L81 | ||
nlloyd/SubliminalCollaborator | 5c619e17ddbe8acb9eea8996ec038169ddcd50a1 | libs/twisted/persisted/aot.py | python | AOTUnjellier.unjellyAttribute | (self, instance, attrName, ao) | Utility method for unjellying into instances of attributes.
Use this rather than unjellyAO unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__. | Utility method for unjellying into instances of attributes. | [
"Utility",
"method",
"for",
"unjellying",
"into",
"instances",
"of",
"attributes",
"."
] | def unjellyAttribute(self, instance, attrName, ao):
#XXX this is unused????
"""Utility method for unjellying into instances of attributes.
Use this rather than unjellyAO unless you like surprising bugs!
Alternatively, you can use unjellyInto on your instance's __dict__.
"""
self.unjellyInto(instance.__dict__, attrName, ao) | [
"def",
"unjellyAttribute",
"(",
"self",
",",
"instance",
",",
"attrName",
",",
"ao",
")",
":",
"#XXX this is unused????",
"self",
".",
"unjellyInto",
"(",
"instance",
".",
"__dict__",
",",
"attrName",
",",
"ao",
")"
] | https://github.com/nlloyd/SubliminalCollaborator/blob/5c619e17ddbe8acb9eea8996ec038169ddcd50a1/libs/twisted/persisted/aot.py#L306-L313 | ||
yokonsan/yublog | cb92df57e0a1fe6fac313051329f171a0d9441d0 | yublog/views/api.py | python | views | (_type, id) | return resp | 浏览量 | 浏览量 | [
"浏览量"
] | def views(_type, id):
"""浏览量"""
# print(request.cookies)
view, cookie_flag, resp = None, False, None
cookie_flag = request.cookies.get('{0}_{1}'.format(_type, str(id)))
view = View.query.filter_by(type=_type, relationship_id=id).first()
if not view:
view = View(type=_type, count=0, relationship_id=id)
if cookie_flag:
return jsonify(count=view.count)
view.count += 1
db.session.add(view)
db.session.commit()
resp = jsonify(count=view.count)
resp.set_cookie('{0}_{1}'.format(_type, str(id)), '1', max_age=1 * 24 * 60 * 60)
return resp | [
"def",
"views",
"(",
"_type",
",",
"id",
")",
":",
"# print(request.cookies)",
"view",
",",
"cookie_flag",
",",
"resp",
"=",
"None",
",",
"False",
",",
"None",
"cookie_flag",
"=",
"request",
".",
"cookies",
".",
"get",
"(",
"'{0}_{1}'",
".",
"format",
"(... | https://github.com/yokonsan/yublog/blob/cb92df57e0a1fe6fac313051329f171a0d9441d0/yublog/views/api.py#L179-L196 | |
NixOS/nixops | 6de9d85747f05bbb6d069e85c6a465c90add115e | nixops/deployment.py | python | _create_state | (depl: Deployment, type: str, name: str, id: int) | Create a resource state object of the desired type. | Create a resource state object of the desired type. | [
"Create",
"a",
"resource",
"state",
"object",
"of",
"the",
"desired",
"type",
"."
] | def _create_state(depl: Deployment, type: str, name: str, id: int) -> Any:
"""Create a resource state object of the desired type."""
for cls in _subclasses(nixops.resources.ResourceState):
try:
if type == cls.get_type():
return cls(depl, name, id)
except NotImplementedError:
pass
raise nixops.deployment.UnknownBackend("unknown resource type ‘{0}’".format(type)) | [
"def",
"_create_state",
"(",
"depl",
":",
"Deployment",
",",
"type",
":",
"str",
",",
"name",
":",
"str",
",",
"id",
":",
"int",
")",
"->",
"Any",
":",
"for",
"cls",
"in",
"_subclasses",
"(",
"nixops",
".",
"resources",
".",
"ResourceState",
")",
":"... | https://github.com/NixOS/nixops/blob/6de9d85747f05bbb6d069e85c6a465c90add115e/nixops/deployment.py#L1675-L1685 | ||
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py | python | VersionConflict.with_context | (self, required_by) | return ContextualVersionConflict(*args) | If required_by is non-empty, return a version of self that is a
ContextualVersionConflict. | If required_by is non-empty, return a version of self that is a
ContextualVersionConflict. | [
"If",
"required_by",
"is",
"non",
"-",
"empty",
"return",
"a",
"version",
"of",
"self",
"that",
"is",
"a",
"ContextualVersionConflict",
"."
] | def with_context(self, required_by):
"""
If required_by is non-empty, return a version of self that is a
ContextualVersionConflict.
"""
if not required_by:
return self
args = self.args + (required_by,)
return ContextualVersionConflict(*args) | [
"def",
"with_context",
"(",
"self",
",",
"required_by",
")",
":",
"if",
"not",
"required_by",
":",
"return",
"self",
"args",
"=",
"self",
".",
"args",
"+",
"(",
"required_by",
",",
")",
"return",
"ContextualVersionConflict",
"(",
"*",
"args",
")"
] | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L354-L362 | |
ZeitOnline/briefkasten | f9c0657e1d78d0cca32c4d884183a738a05f186e | application/briefkasten/dropbox.py | python | Dropbox.dirty_archive_url | (self) | [] | def dirty_archive_url(self):
if 'dropbox_dirty_archive_url_format' in self.settings:
return self.settings['dropbox_dirty_archive_url_format'] % self.drop_id | [
"def",
"dirty_archive_url",
"(",
"self",
")",
":",
"if",
"'dropbox_dirty_archive_url_format'",
"in",
"self",
".",
"settings",
":",
"return",
"self",
".",
"settings",
"[",
"'dropbox_dirty_archive_url_format'",
"]",
"%",
"self",
".",
"drop_id"
] | https://github.com/ZeitOnline/briefkasten/blob/f9c0657e1d78d0cca32c4d884183a738a05f186e/application/briefkasten/dropbox.py#L483-L485 | ||||
brosner/everyblock_code | 25397148223dad81e7fbb9c7cf2f169162df4681 | ebdata/ebdata/templatemaker/htmlutils.py | python | brs_to_paragraphs | (tree, inline_tags=None) | return new_tree | Return an lxml tree with all <br> elements stripped and paragraphs put in
place where necessary. | Return an lxml tree with all <br> elements stripped and paragraphs put in
place where necessary. | [
"Return",
"an",
"lxml",
"tree",
"with",
"all",
"<br",
">",
"elements",
"stripped",
"and",
"paragraphs",
"put",
"in",
"place",
"where",
"necessary",
"."
] | def brs_to_paragraphs(tree, inline_tags=None):
"""
Return an lxml tree with all <br> elements stripped and paragraphs put in
place where necessary.
"""
# add these tags to p's that we're currently building, any other tags will
# close the current p
inline_tags = inline_tags or ['a']
# if this tree doesn't have any child elements, just return it as is
if len(tree) == 0:
return tree
# if this tree doesn't contain any <br> tags, we don't need to touch it
if tree.find('.//br') is None:
return tree
# XXX: We're building a whole new tree here and leaving out any attributes.
# A) That might be a little slower and more memory intensive than modifying
# the tree in place, and B) we're dropping any attributes on block elements.
# The latter is probably fine for current use, but certainly not ideal.
new_tree = Element(tree.tag)
# if this tree starts out with text, create a new paragraph for it, and
# add it to the tree
if tree.text:
p = E.P()
p.text = tree.text
new_tree.append(p)
for e in tree:
if e.tag == 'br':
# avoid adding empty p elements
if e.tail is None:
continue
# start a new p
p = E.P()
p.text = e.tail
new_tree.append(p)
# if this is a block tag, and it has trailing text, that text needs to
# go into a new paragraph... only if the tail has actual content and
# not just whitespace though.
elif e.tail and re.match('[^\s]', e.tail) and e.tag not in inline_tags:
p = E.P()
p.text = e.tail
e.tail = ''
new_tree.append(e)
new_tree.append(p)
# keep inline tags inside the current paragraph
elif e.tag in inline_tags:
p.append(e)
else:
new_tree.append(brs_to_paragraphs(e))
return new_tree | [
"def",
"brs_to_paragraphs",
"(",
"tree",
",",
"inline_tags",
"=",
"None",
")",
":",
"# add these tags to p's that we're currently building, any other tags will",
"# close the current p",
"inline_tags",
"=",
"inline_tags",
"or",
"[",
"'a'",
"]",
"# if this tree doesn't have any ... | https://github.com/brosner/everyblock_code/blob/25397148223dad81e7fbb9c7cf2f169162df4681/ebdata/ebdata/templatemaker/htmlutils.py#L92-L146 | |
maurosoria/dirsearch | b83e68c8fdf360ab06be670d7b92b263262ee5b1 | thirdparty/requests/hooks.py | python | dispatch_hook | (key, hooks, hook_data, **kwargs) | return hook_data | Dispatches a hook dictionary on a given piece of data. | Dispatches a hook dictionary on a given piece of data. | [
"Dispatches",
"a",
"hook",
"dictionary",
"on",
"a",
"given",
"piece",
"of",
"data",
"."
] | def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data | [
"def",
"dispatch_hook",
"(",
"key",
",",
"hooks",
",",
"hook_data",
",",
"*",
"*",
"kwargs",
")",
":",
"hooks",
"=",
"hooks",
"or",
"{",
"}",
"hooks",
"=",
"hooks",
".",
"get",
"(",
"key",
")",
"if",
"hooks",
":",
"if",
"hasattr",
"(",
"hooks",
"... | https://github.com/maurosoria/dirsearch/blob/b83e68c8fdf360ab06be670d7b92b263262ee5b1/thirdparty/requests/hooks.py#L23-L34 | |
emesene/emesene | 4548a4098310e21b16437bb36223a7f632a4f7bc | emesene/e3/base/Logger.py | python | Logger._fetch_sorted | (self) | return query_list | puts list from the query in the right order | puts list from the query in the right order | [
"puts",
"list",
"from",
"the",
"query",
"in",
"the",
"right",
"order"
] | def _fetch_sorted(self):
'''puts list from the query in the right order'''
query_list = self.cursor.fetchall()
query_list.reverse()
return query_list | [
"def",
"_fetch_sorted",
"(",
"self",
")",
":",
"query_list",
"=",
"self",
".",
"cursor",
".",
"fetchall",
"(",
")",
"query_list",
".",
"reverse",
"(",
")",
"return",
"query_list"
] | https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/base/Logger.py#L590-L595 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/posixpath.py | python | isabs | (s) | return s.startswith('/') | Test whether a path is absolute | Test whether a path is absolute | [
"Test",
"whether",
"a",
"path",
"is",
"absolute"
] | def isabs(s):
"""Test whether a path is absolute"""
return s.startswith('/') | [
"def",
"isabs",
"(",
"s",
")",
":",
"return",
"s",
".",
"startswith",
"(",
"'/'",
")"
] | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/posixpath.py#L60-L62 | |
AstroPrint/AstroBox | e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75 | src/ext/makerbot_driver/Encoder/Coding.py | python | encode_axis | (axis) | return axes_map[axis.lower()] | Encode an array of axes names into an axis bitfield
@param axes Array of axis names ['x', 'y', ...]
@return bitfield containing a representation of the axes map | Encode an array of axes names into an axis bitfield | [
"Encode",
"an",
"array",
"of",
"axes",
"names",
"into",
"an",
"axis",
"bitfield"
] | def encode_axis(axis):
"""
Encode an array of axes names into an axis bitfield
@param axes Array of axis names ['x', 'y', ...]
@return bitfield containing a representation of the axes map
"""
axes_map = {
'x': 0x01,
'y': 0x02,
'z': 0x03,
'a': 0x04,
'b': 0x05,
}
return axes_map[axis.lower()] | [
"def",
"encode_axis",
"(",
"axis",
")",
":",
"axes_map",
"=",
"{",
"'x'",
":",
"0x01",
",",
"'y'",
":",
"0x02",
",",
"'z'",
":",
"0x03",
",",
"'a'",
":",
"0x04",
",",
"'b'",
":",
"0x05",
",",
"}",
"return",
"axes_map",
"[",
"axis",
".",
"lower",
... | https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/ext/makerbot_driver/Encoder/Coding.py#L83-L97 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.