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
sdv-dev/CTGAN
d38b99a153bac032ca2ab3cb855fdb28efc2d59d
tasks.py
python
minimum
(c)
[]
def minimum(c): install_minimum(c) check_dependencies(c) unit(c) integration(c)
[ "def", "minimum", "(", "c", ")", ":", "install_minimum", "(", "c", ")", "check_dependencies", "(", "c", ")", "unit", "(", "c", ")", "integration", "(", "c", ")" ]
https://github.com/sdv-dev/CTGAN/blob/d38b99a153bac032ca2ab3cb855fdb28efc2d59d/tasks.py#L95-L99
openstack-archive/syntribos
df49ebf749ab3c79bf79fad518565690b563abd3
syntribos/runner.py
python
Runner.setup_config
(cls, use_file=False, argv=None)
Register CLI options & parse config file.
Register CLI options & parse config file.
[ "Register", "CLI", "options", "&", "parse", "config", "file", "." ]
def setup_config(cls, use_file=False, argv=None): """Register CLI options & parse config file.""" if argv is None: argv = sys.argv[1:] try: syntribos.config.register_opts() if use_file: # Parsing the args first in case a custom_install_root # was specified. CONF(argv, default_config_files=[]) CONF(argv, default_config_files=[ENV.get_default_conf_file()]) else: CONF(argv, default_config_files=[]) except Exception as exc: syntribos.config.handle_config_exception(exc) if cls.worker: raise exc else: sys.exit(1)
[ "def", "setup_config", "(", "cls", ",", "use_file", "=", "False", ",", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "try", ":", "syntribos", ".", "config", ".", "register_opts"...
https://github.com/openstack-archive/syntribos/blob/df49ebf749ab3c79bf79fad518565690b563abd3/syntribos/runner.py#L135-L153
meduza-corp/interstellar
40a801ccd7856491726f5a126621d9318cabe2e1
gsutil/third_party/boto/boto/auth.py
python
S3HmacAuthV4Handler.mangle_path_and_params
(self, req)
return modified_req
Returns a copy of the request object with fixed ``auth_path/params`` attributes from the original.
Returns a copy of the request object with fixed ``auth_path/params`` attributes from the original.
[ "Returns", "a", "copy", "of", "the", "request", "object", "with", "fixed", "auth_path", "/", "params", "attributes", "from", "the", "original", "." ]
def mangle_path_and_params(self, req): """ Returns a copy of the request object with fixed ``auth_path/params`` attributes from the original. """ modified_req = copy.copy(req) # Unlike the most other services, in S3, ``req.params`` isn't the only # source of query string parameters. # Because of the ``query_args``, we may already have a query string # **ON** the ``path/auth_path``. # Rip them apart, so the ``auth_path/params`` can be signed # appropriately. parsed_path = urlparse.urlparse(modified_req.auth_path) modified_req.auth_path = parsed_path.path if modified_req.params is None: modified_req.params = {} raw_qs = parsed_path.query existing_qs = urlparse.parse_qs( raw_qs, keep_blank_values=True ) # ``parse_qs`` will return lists. Don't do that unless there's a real, # live list provided. for key, value in existing_qs.items(): if isinstance(value, (list, tuple)): if len(value) == 1: existing_qs[key] = value[0] modified_req.params.update(existing_qs) return modified_req
[ "def", "mangle_path_and_params", "(", "self", ",", "req", ")", ":", "modified_req", "=", "copy", ".", "copy", "(", "req", ")", "# Unlike the most other services, in S3, ``req.params`` isn't the only", "# source of query string parameters.", "# Because of the ``query_args``, we ma...
https://github.com/meduza-corp/interstellar/blob/40a801ccd7856491726f5a126621d9318cabe2e1/gsutil/third_party/boto/boto/auth.py#L623-L656
deanishe/alfred-fixum
34cc2232789af5373befcffe8cd50536c88b20bf
src/docopt.py
python
parse_seq
(tokens, options)
return result
seq ::= ( atom [ '...' ] )* ;
seq ::= ( atom [ '...' ] )* ;
[ "seq", "::", "=", "(", "atom", "[", "...", "]", ")", "*", ";" ]
def parse_seq(tokens, options): """seq ::= ( atom [ '...' ] )* ;""" result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move() result += atom return result
[ "def", "parse_seq", "(", "tokens", ",", "options", ")", ":", "result", "=", "[", "]", "while", "tokens", ".", "current", "(", ")", "not", "in", "[", "None", ",", "']'", ",", "')'", ",", "'|'", "]", ":", "atom", "=", "parse_atom", "(", "tokens", "...
https://github.com/deanishe/alfred-fixum/blob/34cc2232789af5373befcffe8cd50536c88b20bf/src/docopt.py#L392-L401
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/codecs.py
python
IncrementalEncoder.setstate
(self, state)
Set the current state of the encoder. state must have been returned by getstate().
Set the current state of the encoder. state must have been returned by getstate().
[ "Set", "the", "current", "state", "of", "the", "encoder", ".", "state", "must", "have", "been", "returned", "by", "getstate", "()", "." ]
def setstate(self, state): """ Set the current state of the encoder. state must have been returned by getstate(). """
[ "def", "setstate", "(", "self", ",", "state", ")", ":" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/codecs.py#L190-L194
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/matplotlib-3.0.3-py3.7-macosx-10.9-x86_64.egg/matplotlib/pyplot.py
python
subplot
(*args, **kwargs)
return a
Add a subplot to the current figure. Wrapper of `.Figure.add_subplot` with a difference in behavior explained in the notes section. Call signatures:: subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(ax) Parameters ---------- *args Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are *nrows*, *ncols*, and *index* in order, the subplot will take the *index* position on a grid with *nrows* rows and *ncols* columns. *index* starts at 1 in the upper left corner and increases to the right. *pos* is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ 'polar', 'rectilinear', str}, optional The projection type of the subplot (`~.axes.Axes`). *str* is the name of a costum projection, see `~matplotlib.projections`. The default None results in a 'rectilinear' projection. polar : boolean, optional If True, equivalent to projection='polar'. sharex, sharey : `~.axes.Axes`, optional Share the x or y `~matplotlib.axis` with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes. label : str A label for the returned axes. Other Parameters ---------------- **kwargs This method also takes the keyword arguments for the returned axes base class. The keyword arguments for the rectilinear base class `~.axes.Axes` can be found in the following table but there might also be other keyword arguments if another projection is used. %(Axes)s Returns ------- axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a subclass \ of `~.axes.Axes`) The axes of the subplot. The returned axes base class depends on the projection used. It is `~.axes.Axes` if rectilinear projection are used and `.projections.polar.PolarAxes` if polar projection are used. The returned axes is then a subplot subclass of the base class. Notes ----- Creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary:: import matplotlib.pyplot as plt # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) # now create a subplot which represents the top plot of a grid # with 2 rows and 1 column. Since this subplot will overlap the # first, the plot (and its axes) previously created, will be removed plt.subplot(211) If you do not want this behavior, use the `.Figure.add_subplot` method or the `.pyplot.axes` function instead. If the figure already has a subplot with key (*args*, *kwargs*) then it will simply make that subplot current and return it. This behavior is deprecated. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new suplot), you must use a unique set of args and kwargs. The axes *label* attribute has been exposed for this purpose: if you want two subplots that are otherwise identical to be added to the figure, make sure you give them unique labels. In rare circumstances, `.add_subplot` may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes. See Also -------- .Figure.add_subplot .pyplot.subplots .pyplot.axes .Figure.subplots Examples -------- :: plt.subplot(221) # equivalent but more general ax1=plt.subplot(2, 2, 1) # add a subplot with no frame ax2=plt.subplot(222, frameon=False) # add a polar subplot plt.subplot(223, projection='polar') # add a red subplot that shares the x-axis with ax1 plt.subplot(224, sharex=ax1, facecolor='red') #delete ax2 from the figure plt.delaxes(ax2) #add ax2 to the figure again plt.subplot(ax2)
Add a subplot to the current figure.
[ "Add", "a", "subplot", "to", "the", "current", "figure", "." ]
def subplot(*args, **kwargs): """ Add a subplot to the current figure. Wrapper of `.Figure.add_subplot` with a difference in behavior explained in the notes section. Call signatures:: subplot(nrows, ncols, index, **kwargs) subplot(pos, **kwargs) subplot(ax) Parameters ---------- *args Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are *nrows*, *ncols*, and *index* in order, the subplot will take the *index* position on a grid with *nrows* rows and *ncols* columns. *index* starts at 1 in the upper left corner and increases to the right. *pos* is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \ 'polar', 'rectilinear', str}, optional The projection type of the subplot (`~.axes.Axes`). *str* is the name of a costum projection, see `~matplotlib.projections`. The default None results in a 'rectilinear' projection. polar : boolean, optional If True, equivalent to projection='polar'. sharex, sharey : `~.axes.Axes`, optional Share the x or y `~matplotlib.axis` with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes. label : str A label for the returned axes. Other Parameters ---------------- **kwargs This method also takes the keyword arguments for the returned axes base class. The keyword arguments for the rectilinear base class `~.axes.Axes` can be found in the following table but there might also be other keyword arguments if another projection is used. %(Axes)s Returns ------- axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a subclass \ of `~.axes.Axes`) The axes of the subplot. The returned axes base class depends on the projection used. It is `~.axes.Axes` if rectilinear projection are used and `.projections.polar.PolarAxes` if polar projection are used. The returned axes is then a subplot subclass of the base class. Notes ----- Creating a subplot will delete any pre-existing subplot that overlaps with it beyond sharing a boundary:: import matplotlib.pyplot as plt # plot a line, implicitly creating a subplot(111) plt.plot([1,2,3]) # now create a subplot which represents the top plot of a grid # with 2 rows and 1 column. Since this subplot will overlap the # first, the plot (and its axes) previously created, will be removed plt.subplot(211) If you do not want this behavior, use the `.Figure.add_subplot` method or the `.pyplot.axes` function instead. If the figure already has a subplot with key (*args*, *kwargs*) then it will simply make that subplot current and return it. This behavior is deprecated. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new suplot), you must use a unique set of args and kwargs. The axes *label* attribute has been exposed for this purpose: if you want two subplots that are otherwise identical to be added to the figure, make sure you give them unique labels. In rare circumstances, `.add_subplot` may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes. See Also -------- .Figure.add_subplot .pyplot.subplots .pyplot.axes .Figure.subplots Examples -------- :: plt.subplot(221) # equivalent but more general ax1=plt.subplot(2, 2, 1) # add a subplot with no frame ax2=plt.subplot(222, frameon=False) # add a polar subplot plt.subplot(223, projection='polar') # add a red subplot that shares the x-axis with ax1 plt.subplot(224, sharex=ax1, facecolor='red') #delete ax2 from the figure plt.delaxes(ax2) #add ax2 to the figure again plt.subplot(ax2) """ # if subplot called without arguments, create subplot(1,1,1) if len(args) == 0: args = (1, 1, 1) # This check was added because it is very easy to type # subplot(1, 2, False) when subplots(1, 2, False) was intended # (sharex=False, that is). In most cases, no error will # ever occur, but mysterious behavior can result because what was # intended to be the sharex argument is instead treated as a # subplot index for subplot() if len(args) >= 3 and isinstance(args[2], bool): warnings.warn("The subplot index argument to subplot() appears " "to be a boolean. Did you intend to use subplots()?") fig = gcf() a = fig.add_subplot(*args, **kwargs) bbox = a.bbox byebye = [] for other in fig.axes: if other == a: continue if bbox.fully_overlaps(other.bbox): byebye.append(other) for ax in byebye: delaxes(ax) return a
[ "def", "subplot", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# if subplot called without arguments, create subplot(1,1,1)", "if", "len", "(", "args", ")", "==", "0", ":", "args", "=", "(", "1", ",", "1", ",", "1", ")", "# This check was added beca...
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/pyplot.py#L941-L1095
tensorflow/models
6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3
orbit/actions/export_saved_model.py
python
ExportFileManager.__init__
(self, base_name: str, max_to_keep: int = 5, next_id_fn: Optional[Callable[[], int]] = None)
Initializes the instance. Args: base_name: A shared base name for file names generated by this class. max_to_keep: The maximum number of files matching `base_name` to keep after each call to `cleanup`. The most recent (as determined by file modification time) `max_to_keep` files are preserved; the rest are deleted. If < 0, all files are preserved. next_id_fn: An optional callable that returns integer IDs to append to base name (formatted as `'{base_name}-{id}'`). The order of integers is used to sort files to determine the oldest ones deleted by `clean_up`. If not supplied, a default ID based on an incrementing counter is used. One common alternative maybe be to use the current global step count, for instance passing `next_id_fn=global_step.numpy`.
Initializes the instance.
[ "Initializes", "the", "instance", "." ]
def __init__(self, base_name: str, max_to_keep: int = 5, next_id_fn: Optional[Callable[[], int]] = None): """Initializes the instance. Args: base_name: A shared base name for file names generated by this class. max_to_keep: The maximum number of files matching `base_name` to keep after each call to `cleanup`. The most recent (as determined by file modification time) `max_to_keep` files are preserved; the rest are deleted. If < 0, all files are preserved. next_id_fn: An optional callable that returns integer IDs to append to base name (formatted as `'{base_name}-{id}'`). The order of integers is used to sort files to determine the oldest ones deleted by `clean_up`. If not supplied, a default ID based on an incrementing counter is used. One common alternative maybe be to use the current global step count, for instance passing `next_id_fn=global_step.numpy`. """ self._base_name = base_name self._max_to_keep = max_to_keep self._next_id_fn = next_id_fn or _CounterIdFn(base_name)
[ "def", "__init__", "(", "self", ",", "base_name", ":", "str", ",", "max_to_keep", ":", "int", "=", "5", ",", "next_id_fn", ":", "Optional", "[", "Callable", "[", "[", "]", ",", "int", "]", "]", "=", "None", ")", ":", "self", ".", "_base_name", "=",...
https://github.com/tensorflow/models/blob/6b8bb0cbeb3e10415c7a87448f08adc3c484c1d3/orbit/actions/export_saved_model.py#L61-L82
sidewalklabs/s2sphere
d1d067e8c06e5fbaf0cc0158bade947b4a03a438
s2sphere/sphere.py
python
LatLng.__eq__
(self, other)
return isinstance(other, LatLng) and self.__coords == other.__coords
[]
def __eq__(self, other): return isinstance(other, LatLng) and self.__coords == other.__coords
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "isinstance", "(", "other", ",", "LatLng", ")", "and", "self", ".", "__coords", "==", "other", ".", "__coords" ]
https://github.com/sidewalklabs/s2sphere/blob/d1d067e8c06e5fbaf0cc0158bade947b4a03a438/s2sphere/sphere.py#L200-L201
tensorlayer/RLzoo
8dd3ff1003d1c7a446f45119bbd6b48c048990f4
rlzoo/algorithms/dppo_clip_distributed/dppo_clip.py
python
DPPO_CLIP.save_ckpt
(self, env_name)
save trained weights :return: None
save trained weights
[ "save", "trained", "weights" ]
def save_ckpt(self, env_name): """ save trained weights :return: None """ save_model(self.actor, 'actor', self.name, env_name) save_model(self.critic, 'critic', self.name, env_name)
[ "def", "save_ckpt", "(", "self", ",", "env_name", ")", ":", "save_model", "(", "self", ".", "actor", ",", "'actor'", ",", "self", ".", "name", ",", "env_name", ")", "save_model", "(", "self", ".", "critic", ",", "'critic'", ",", "self", ".", "name", ...
https://github.com/tensorlayer/RLzoo/blob/8dd3ff1003d1c7a446f45119bbd6b48c048990f4/rlzoo/algorithms/dppo_clip_distributed/dppo_clip.py#L183-L190
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/physics/mechanics/kane.py
python
KanesMethod._form_frstar
(self, bl)
return FRSTAR
Form the generalized inertia force. Computes the vector of the generalized inertia force vector. Used to compute E.o.M. in the form Fr + Fr* = 0. Parameters ========== bl : list A list of all RigidBody's and Particle's in the system.
Form the generalized inertia force.
[ "Form", "the", "generalized", "inertia", "force", "." ]
def _form_frstar(self, bl): """Form the generalized inertia force. Computes the vector of the generalized inertia force vector. Used to compute E.o.M. in the form Fr + Fr* = 0. Parameters ========== bl : list A list of all RigidBody's and Particle's in the system. """ if not hasattr(bl, '__iter__'): raise TypeError('Bodies must be supplied in an iterable.') t = dynamicsymbols._t N = self._inertial self._bodylist = bl u = self._u # all speeds udep = self._udep # dependent speeds o = len(u) m = len(udep) p = o - m udot = self._udot udotzero = dict(list(zip(udot, [0] * o))) # auxiliary speeds uaux = self._uaux uauxdot = [diff(i, t) for i in uaux] # dictionary of auxiliary speeds which are equal to zero uaz = dict(list(zip(uaux, [0] * len(uaux)))) uadz = dict(list(zip(uauxdot, [0] * len(uauxdot)))) # dictionary of qdot's to u's qdots = dict(list(zip(list(self._qdot_u_map.keys()), list(self._qdot_u_map.values())))) for k, v in list(qdots.items()): qdots[k.diff(t)] = v.diff(t) MM = zeros(o, o) nonMM = zeros(o, 1) partials = [] # Fill up the list of partials: format is a list with no. elements # equal to number of entries in body list. Each of these elements is a # list - either of length 1 for the translational components of # particles or of length 2 for the translational and rotational # components of rigid bodies. The inner most list is the list of # partial velocities. for v in bl: if isinstance(v, RigidBody): partials += [self._partial_velocity([v.masscenter.vel(N), v.frame.ang_vel_in(N)], u, N)] elif isinstance(v, Particle): partials += [self._partial_velocity([v.point.vel(N)], u, N)] else: raise TypeError('The body list needs RigidBody or ' 'Particle as list elements.') # This section does 2 things - computes the parts of Fr* that are # associated with the udots, and the parts that are not associated with # the udots. This happens for RigidBody and Particle a little # differently, but similar process overall. for i, v in enumerate(bl): if isinstance(v, RigidBody): M = v.mass.subs(uaz).doit() vel = v.masscenter.vel(N).subs(uaz).doit() acc = v.masscenter.acc(N).subs(udotzero).subs(uaz).doit() inertial_force = (M.diff(t) * vel + M * acc) omega = v.frame.ang_vel_in(N).subs(uaz).doit() I = v.central_inertia.subs(uaz).doit() inertial_torque = ((I.dt(v.frame) & omega).subs(uaz).doit() + (I & v.frame.ang_acc_in(N)).subs(udotzero).subs(uaz).doit() + (omega ^ (I & omega)).subs(uaz).doit()) for j in range(o): tmp_vel = partials[i][0][j].subs(uaz).doit() tmp_ang = (I & partials[i][1][j].subs(uaz).doit()) for k in range(o): # translational MM[j, k] += M * (tmp_vel & partials[i][0][k]) # rotational MM[j, k] += (tmp_ang & partials[i][1][k]) nonMM[j] += inertial_force & partials[i][0][j] nonMM[j] += inertial_torque & partials[i][1][j] if isinstance(v, Particle): M = v.mass.subs(uaz).doit() vel = v.point.vel(N).subs(uaz).doit() acc = v.point.acc(N).subs(udotzero).subs(uaz).doit() inertial_force = (M.diff(t) * vel + M * acc) for j in range(o): temp = partials[i][0][j].subs(uaz).doit() for k in range(o): MM[j, k] += M * (temp & partials[i][0][k]) nonMM[j] += inertial_force & partials[i][0][j] # Negate FRSTAR since Kane defines the inertia forces/torques # to be negative and we didn't do so above. MM = MM.subs(qdots).subs(uaz).doit() nonMM = nonMM.subs(qdots).subs(udotzero).subs(uadz).subs(uaz).doit() FRSTAR = -(MM * Matrix(udot).subs(uadz) + nonMM) # For motion constraints, m is the number of constraints # Really, one should just look at Kane's book for descriptions of this # process if m != 0: FRSTARtilde = FRSTAR[:p, 0] FRSTARold = FRSTAR[p:o, 0] FRSTARtilde += self._Ars.T * FRSTARold FRSTAR = FRSTARtilde MMi = MM[:p, :] MMd = MM[p:o, :] MM = MMi + self._Ars.T * MMd self._frstar = FRSTAR zeroeq = -(self._fr + self._frstar) zeroeq = zeroeq.subs(udotzero) self._k_d = MM self._f_d = zeroeq return FRSTAR
[ "def", "_form_frstar", "(", "self", ",", "bl", ")", ":", "if", "not", "hasattr", "(", "bl", ",", "'__iter__'", ")", ":", "raise", "TypeError", "(", "'Bodies must be supplied in an iterable.'", ")", "t", "=", "dynamicsymbols", ".", "_t", "N", "=", "self", "...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/physics/mechanics/kane.py#L425-L544
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/addons/addon.py
python
Addon.dns
(self)
return [f"{self.hostname}.{DNS_SUFFIX}"]
Return list of DNS name for that add-on.
Return list of DNS name for that add-on.
[ "Return", "list", "of", "DNS", "name", "for", "that", "add", "-", "on", "." ]
def dns(self) -> list[str]: """Return list of DNS name for that add-on.""" return [f"{self.hostname}.{DNS_SUFFIX}"]
[ "def", "dns", "(", "self", ")", "->", "list", "[", "str", "]", ":", "return", "[", "f\"{self.hostname}.{DNS_SUFFIX}\"", "]" ]
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/addons/addon.py#L197-L199
fengsp/rc
32c4d4e2cb7ba734b2dbd9bd83bcc85a2f09499f
rc/cache.py
python
BaseCache.client
(self)
return self.get_client()
Returns the redis client that is used for cache.
Returns the redis client that is used for cache.
[ "Returns", "the", "redis", "client", "that", "is", "used", "for", "cache", "." ]
def client(self): """Returns the redis client that is used for cache.""" return self.get_client()
[ "def", "client", "(", "self", ")", ":", "return", "self", ".", "get_client", "(", ")" ]
https://github.com/fengsp/rc/blob/32c4d4e2cb7ba734b2dbd9bd83bcc85a2f09499f/rc/cache.py#L58-L60
stoq/stoq
c26991644d1affcf96bc2e0a0434796cabdf8448
stoq/lib/gui/interfaces.py
python
ISearchResultView.get_selected_item
()
Fetches the currently selected item :return: the selected item
Fetches the currently selected item
[ "Fetches", "the", "currently", "selected", "item" ]
def get_selected_item(): """ Fetches the currently selected item :return: the selected item """
[ "def", "get_selected_item", "(", ")", ":" ]
https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoq/lib/gui/interfaces.py#L100-L105
danielplohmann/apiscout
8622b54302cb2712fe35ce971e77d1f3d5849a2a
apiscout/db_builder/pefile.py
python
PE.is_exe
(self)
return False
Check whether the file is a standard executable. This will return true only if the file has the IMAGE_FILE_EXECUTABLE_IMAGE flag set and the IMAGE_FILE_DLL not set and the file does not appear to be a driver either.
Check whether the file is a standard executable.
[ "Check", "whether", "the", "file", "is", "a", "standard", "executable", "." ]
def is_exe(self): """Check whether the file is a standard executable. This will return true only if the file has the IMAGE_FILE_EXECUTABLE_IMAGE flag set and the IMAGE_FILE_DLL not set and the file does not appear to be a driver either. """ EXE_flag = IMAGE_CHARACTERISTICS['IMAGE_FILE_EXECUTABLE_IMAGE'] if (not self.is_dll()) and (not self.is_driver()) and ( EXE_flag & self.FILE_HEADER.Characteristics) == EXE_flag: return True return False
[ "def", "is_exe", "(", "self", ")", ":", "EXE_flag", "=", "IMAGE_CHARACTERISTICS", "[", "'IMAGE_FILE_EXECUTABLE_IMAGE'", "]", "if", "(", "not", "self", ".", "is_dll", "(", ")", ")", "and", "(", "not", "self", ".", "is_driver", "(", ")", ")", "and", "(", ...
https://github.com/danielplohmann/apiscout/blob/8622b54302cb2712fe35ce971e77d1f3d5849a2a/apiscout/db_builder/pefile.py#L5924-L5937
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/storage/reset.py
python
ScanDevicesTask.__init__
(self, storage)
Create a new task. :param storage: an instance of Blivet
Create a new task.
[ "Create", "a", "new", "task", "." ]
def __init__(self, storage): """Create a new task. :param storage: an instance of Blivet """ super().__init__() self._storage = storage
[ "def", "__init__", "(", "self", ",", "storage", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "_storage", "=", "storage" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/storage/reset.py#L44-L50
akfamily/akshare
590e50eece9ec067da3538c7059fd660b71f1339
akshare/futures/cot.py
python
_table_cut_cal
(table_cut, symbol)
return table_cut
表格切分 :param table_cut: 需要切分的表格 :type table_cut: pandas.DataFrame :param symbol: 具体合约的代码 :type symbol: str :return: 表格切分后的结果 :rtype: pandas.DataFrame
表格切分 :param table_cut: 需要切分的表格 :type table_cut: pandas.DataFrame :param symbol: 具体合约的代码 :type symbol: str :return: 表格切分后的结果 :rtype: pandas.DataFrame
[ "表格切分", ":", "param", "table_cut", ":", "需要切分的表格", ":", "type", "table_cut", ":", "pandas", ".", "DataFrame", ":", "param", "symbol", ":", "具体合约的代码", ":", "type", "symbol", ":", "str", ":", "return", ":", "表格切分后的结果", ":", "rtype", ":", "pandas", ".", "...
def _table_cut_cal(table_cut, symbol): """ 表格切分 :param table_cut: 需要切分的表格 :type table_cut: pandas.DataFrame :param symbol: 具体合约的代码 :type symbol: str :return: 表格切分后的结果 :rtype: pandas.DataFrame """ var = symbol_varieties(symbol) table_cut[intColumns + ['rank']] = table_cut[intColumns + ['rank']].astype(int) table_cut_sum = table_cut.sum() table_cut_sum['rank'] = 999 for col in ['vol_party_name', 'long_party_name', 'short_party_name']: table_cut_sum[col] = None table_cut = table_cut.append(pd.DataFrame(table_cut_sum).T, sort=True) table_cut['symbol'] = symbol table_cut['variety'] = var table_cut[intColumns + ['rank']] = table_cut[intColumns + ['rank']].astype(int) return table_cut
[ "def", "_table_cut_cal", "(", "table_cut", ",", "symbol", ")", ":", "var", "=", "symbol_varieties", "(", "symbol", ")", "table_cut", "[", "intColumns", "+", "[", "'rank'", "]", "]", "=", "table_cut", "[", "intColumns", "+", "[", "'rank'", "]", "]", ".", ...
https://github.com/akfamily/akshare/blob/590e50eece9ec067da3538c7059fd660b71f1339/akshare/futures/cot.py#L581-L601
rsmusllp/king-phisher
6acbbd856f849d407cc904c075441e0cf13c25cf
king_phisher/client/mailer.py
python
MailSenderThread.tab_notify_sent
(self, emails_done, emails_total)
Notify the tab that messages have been sent. :param int emails_done: The number of emails that have been sent. :param int emails_total: The total number of emails that are going to be sent.
Notify the tab that messages have been sent.
[ "Notify", "the", "tab", "that", "messages", "have", "been", "sent", "." ]
def tab_notify_sent(self, emails_done, emails_total): """ Notify the tab that messages have been sent. :param int emails_done: The number of emails that have been sent. :param int emails_total: The total number of emails that are going to be sent. """ if isinstance(self.tab, gui_utilities.GladeGObject): GLib.idle_add(lambda x: self.tab.notify_sent(*x), (emails_done, emails_total))
[ "def", "tab_notify_sent", "(", "self", ",", "emails_done", ",", "emails_total", ")", ":", "if", "isinstance", "(", "self", ".", "tab", ",", "gui_utilities", ".", "GladeGObject", ")", ":", "GLib", ".", "idle_add", "(", "lambda", "x", ":", "self", ".", "ta...
https://github.com/rsmusllp/king-phisher/blob/6acbbd856f849d407cc904c075441e0cf13c25cf/king_phisher/client/mailer.py#L430-L438
enzienaudio/hvcc
30e47328958d600c54889e2a254c3f17f2b2fd06
generators/ir2c/SignalLine.py
python
SignalLine.get_C_free
(clazz, obj_type, obj_id, args)
return []
[]
def get_C_free(clazz, obj_type, obj_id, args): return []
[ "def", "get_C_free", "(", "clazz", ",", "obj_type", ",", "obj_id", ",", "args", ")", ":", "return", "[", "]" ]
https://github.com/enzienaudio/hvcc/blob/30e47328958d600c54889e2a254c3f17f2b2fd06/generators/ir2c/SignalLine.py#L38-L39
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/manifolds/differentiable/characteristic_cohomology_class.py
python
PontryaginEulerAlgorithm.get
(self, nab)
return EulerAlgorithm().get(nab) + PontryaginAlgorithm().get(nab)
r""" Return the global characteristic forms of the generators w.r.t. a given connection. OUTPUT: - a list containing the global Euler form in the first entry, and the global Pontryagin forms in the remaining entries. EXAMPLES: 4-dimensional Euclidean space:: sage: M = manifolds.EuclideanSpace(4) sage: g = M.metric() sage: nab = g.connection() sage: nab.set_immutable() Import the algorithm:: sage: from sage.manifolds.differentiable.characteristic_cohomology_class import PontryaginEulerAlgorithm sage: algorithm = PontryaginEulerAlgorithm() sage: algorithm.get(nab) # long time [4-form on the 4-dimensional Euclidean space E^4, 4-form on the 4-dimensional Euclidean space E^4]
r""" Return the global characteristic forms of the generators w.r.t. a given connection.
[ "r", "Return", "the", "global", "characteristic", "forms", "of", "the", "generators", "w", ".", "r", ".", "t", ".", "a", "given", "connection", "." ]
def get(self, nab): r""" Return the global characteristic forms of the generators w.r.t. a given connection. OUTPUT: - a list containing the global Euler form in the first entry, and the global Pontryagin forms in the remaining entries. EXAMPLES: 4-dimensional Euclidean space:: sage: M = manifolds.EuclideanSpace(4) sage: g = M.metric() sage: nab = g.connection() sage: nab.set_immutable() Import the algorithm:: sage: from sage.manifolds.differentiable.characteristic_cohomology_class import PontryaginEulerAlgorithm sage: algorithm = PontryaginEulerAlgorithm() sage: algorithm.get(nab) # long time [4-form on the 4-dimensional Euclidean space E^4, 4-form on the 4-dimensional Euclidean space E^4] """ return EulerAlgorithm().get(nab) + PontryaginAlgorithm().get(nab)
[ "def", "get", "(", "self", ",", "nab", ")", ":", "return", "EulerAlgorithm", "(", ")", ".", "get", "(", "nab", ")", "+", "PontryaginAlgorithm", "(", ")", ".", "get", "(", "nab", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/manifolds/differentiable/characteristic_cohomology_class.py#L1743-L1770
AuHau/toggl-cli
f7a12ba821f258189f0b734bc39aca4cb1b7dc15
toggl/utils/bootstrap.py
python
ConfigBootstrap._map_answers
(self, **answers)
return output
Creates dict which follows the ConfigParser convention from the provided user's answers.
Creates dict which follows the ConfigParser convention from the provided user's answers.
[ "Creates", "dict", "which", "follows", "the", "ConfigParser", "convention", "from", "the", "provided", "user", "s", "answers", "." ]
def _map_answers(self, **answers): # type: (**str) -> dict """ Creates dict which follows the ConfigParser convention from the provided user's answers. """ from toggl.cli.themes import themes output = { 'version': __version__, 'api_token': answers['api_token'], 'file_logging': answers['file_logging'], } for theme in themes.values(): if theme.name == answers['theme']: output['theme'] = theme.code break if answers['timezone'] == self.SYSTEM_TIMEZONE: output['tz'] = 'local' elif answers['timezone'] == self.TOGGL_TIMEZONE: pass else: output['tz'] = answers['timezone'] if output['file_logging']: output['file_logging_path'] = os.path.expanduser(answers.get('file_logging_path')) if answers['default workspace'] != self.KEEP_TOGGLS_DEFAULT_WORKSPACE: from ..api import Workspace config = self._build_tmp_config(api_token=answers['api_token']) output['default_wid'] = str(Workspace.objects.get(name=answers['default workspace'], config=config).id) return output
[ "def", "_map_answers", "(", "self", ",", "*", "*", "answers", ")", ":", "# type: (**str) -> dict", "from", "toggl", ".", "cli", ".", "themes", "import", "themes", "output", "=", "{", "'version'", ":", "__version__", ",", "'api_token'", ":", "answers", "[", ...
https://github.com/AuHau/toggl-cli/blob/f7a12ba821f258189f0b734bc39aca4cb1b7dc15/toggl/utils/bootstrap.py#L58-L90
GlacierProtocol/GlacierProtocol
bda9582eda7280f6b154d63eb1c5359ab76fe369
glacierscript.py
python
get_utxos
(tx, address)
return utxos
Given a transaction, find all the outputs that were sent to an address returns => List<Dictionary> list of UTXOs in bitcoin core format tx - <Dictionary> in bitcoin core format address - <string>
Given a transaction, find all the outputs that were sent to an address returns => List<Dictionary> list of UTXOs in bitcoin core format
[ "Given", "a", "transaction", "find", "all", "the", "outputs", "that", "were", "sent", "to", "an", "address", "returns", "=", ">", "List<Dictionary", ">", "list", "of", "UTXOs", "in", "bitcoin", "core", "format" ]
def get_utxos(tx, address): """ Given a transaction, find all the outputs that were sent to an address returns => List<Dictionary> list of UTXOs in bitcoin core format tx - <Dictionary> in bitcoin core format address - <string> """ utxos = [] for output in tx["vout"]: if "addresses" not in output["scriptPubKey"]: # In Bitcoin Core versions older than v0.16, native segwit outputs have no address decoded continue out_addresses = output["scriptPubKey"]["addresses"] amount_btc = output["value"] if address in out_addresses: utxos.append(output) return utxos
[ "def", "get_utxos", "(", "tx", ",", "address", ")", ":", "utxos", "=", "[", "]", "for", "output", "in", "tx", "[", "\"vout\"", "]", ":", "if", "\"addresses\"", "not", "in", "output", "[", "\"scriptPubKey\"", "]", ":", "# In Bitcoin Core versions older than v...
https://github.com/GlacierProtocol/GlacierProtocol/blob/bda9582eda7280f6b154d63eb1c5359ab76fe369/glacierscript.py#L360-L379
pallets/werkzeug
9efe8c00dcb2b6fc086961ba304729db01912652
src/werkzeug/_reloader.py
python
_iter_module_paths
()
Find the filesystem paths associated with imported modules.
Find the filesystem paths associated with imported modules.
[ "Find", "the", "filesystem", "paths", "associated", "with", "imported", "modules", "." ]
def _iter_module_paths() -> t.Iterator[str]: """Find the filesystem paths associated with imported modules.""" # List is in case the value is modified by the app while updating. for module in list(sys.modules.values()): name = getattr(module, "__file__", None) if name is None: continue while not os.path.isfile(name): # Zip file, find the base file without the module path. old = name name = os.path.dirname(name) if name == old: # skip if it was all directories somehow break else: yield name
[ "def", "_iter_module_paths", "(", ")", "->", "t", ".", "Iterator", "[", "str", "]", ":", "# List is in case the value is modified by the app while updating.", "for", "module", "in", "list", "(", "sys", ".", "modules", ".", "values", "(", ")", ")", ":", "name", ...
https://github.com/pallets/werkzeug/blob/9efe8c00dcb2b6fc086961ba304729db01912652/src/werkzeug/_reloader.py#L26-L43
intel/virtual-storage-manager
00706ab9701acbd0d5e04b19cc80c6b66a2973b8
source/vsm/vsm/openstack/common/rpc/impl_kombu.py
python
Connection.reconnect
(self)
Handles reconnecting and re-establishing queues. Will retry up to self.max_retries number of times. self.max_retries = 0 means to retry forever. Sleep between tries, starting at self.interval_start seconds, backing off self.interval_stepping number of seconds each attempt.
Handles reconnecting and re-establishing queues. Will retry up to self.max_retries number of times. self.max_retries = 0 means to retry forever. Sleep between tries, starting at self.interval_start seconds, backing off self.interval_stepping number of seconds each attempt.
[ "Handles", "reconnecting", "and", "re", "-", "establishing", "queues", ".", "Will", "retry", "up", "to", "self", ".", "max_retries", "number", "of", "times", ".", "self", ".", "max_retries", "=", "0", "means", "to", "retry", "forever", ".", "Sleep", "betwe...
def reconnect(self): """Handles reconnecting and re-establishing queues. Will retry up to self.max_retries number of times. self.max_retries = 0 means to retry forever. Sleep between tries, starting at self.interval_start seconds, backing off self.interval_stepping number of seconds each attempt. """ attempt = 0 while True: params = self.params_list[attempt % len(self.params_list)] attempt += 1 try: self._connect(params) return except (IOError, self.connection_errors) as e: pass except Exception, e: # NOTE(comstud): Unfortunately it's possible for amqplib # to return an error not covered by its transport # connection_errors in the case of a timeout waiting for # a protocol response. (See paste link in LP888621) # So, we check all exceptions for 'timeout' in them # and try to reconnect in this case. if 'timeout' not in str(e): raise log_info = {} log_info['err_str'] = str(e) log_info['max_retries'] = self.max_retries log_info.update(params) if self.max_retries and attempt == self.max_retries: LOG.error(_('Unable to connect to AMQP server on ' '%(hostname)s:%(port)d after %(max_retries)d ' 'tries: %(err_str)s') % log_info) # NOTE(comstud): Copied from original code. There's # really no better recourse because if this was a queue we # need to consume on, we have no way to consume anymore. sys.exit(1) if attempt == 1: sleep_time = self.interval_start or 1 elif attempt > 1: sleep_time += self.interval_stepping if self.interval_max: sleep_time = min(sleep_time, self.interval_max) log_info['sleep_time'] = sleep_time LOG.error(_('AMQP server on %(hostname)s:%(port)d is ' 'unreachable: %(err_str)s. Trying again in ' '%(sleep_time)d seconds.') % log_info) time.sleep(sleep_time)
[ "def", "reconnect", "(", "self", ")", ":", "attempt", "=", "0", "while", "True", ":", "params", "=", "self", ".", "params_list", "[", "attempt", "%", "len", "(", "self", ".", "params_list", ")", "]", "attempt", "+=", "1", "try", ":", "self", ".", "...
https://github.com/intel/virtual-storage-manager/blob/00706ab9701acbd0d5e04b19cc80c6b66a2973b8/source/vsm/vsm/openstack/common/rpc/impl_kombu.py#L494-L547
spectralpython/spectral
e1cd919f5f66abddc219b76926450240feaaed8f
spectral/algorithms/algorithms.py
python
covariance
(*args)
return mean_cov(*args)[1]
Returns the covariance of the set of vectors. Usage:: C = covariance(vectors [, mask=None [, index=None]]) Arguments: `vectors` (ndarrray, :class:`~spectral.Image`, or :class:`spectral.Iterator`): If an ndarray, it should have shape `MxNxB` and the mean & covariance will be calculated for each band (third dimension). `mask` (ndarray): If `mask` is specified, mean & covariance will be calculated for all pixels indicated in the mask array. If `index` is specified, all pixels in `image` for which `mask == index` will be used; otherwise, all nonzero elements of `mask` will be used. `index` (int): Specifies which value in `mask` to use to select pixels from `image`. If not specified but `mask` is, then all nonzero elements of `mask` will be used. If neither `mask` nor `index` are specified, all samples in `vectors` will be used. Returns: `C` (ndarray): The `BxB` unbiased estimate (dividing by N-1) of the covariance of the vectors. To also return the mean vector and number of samples, call :func:`~spectral.algorithms.algorithms.mean_cov` instead.
Returns the covariance of the set of vectors.
[ "Returns", "the", "covariance", "of", "the", "set", "of", "vectors", "." ]
def covariance(*args): ''' Returns the covariance of the set of vectors. Usage:: C = covariance(vectors [, mask=None [, index=None]]) Arguments: `vectors` (ndarrray, :class:`~spectral.Image`, or :class:`spectral.Iterator`): If an ndarray, it should have shape `MxNxB` and the mean & covariance will be calculated for each band (third dimension). `mask` (ndarray): If `mask` is specified, mean & covariance will be calculated for all pixels indicated in the mask array. If `index` is specified, all pixels in `image` for which `mask == index` will be used; otherwise, all nonzero elements of `mask` will be used. `index` (int): Specifies which value in `mask` to use to select pixels from `image`. If not specified but `mask` is, then all nonzero elements of `mask` will be used. If neither `mask` nor `index` are specified, all samples in `vectors` will be used. Returns: `C` (ndarray): The `BxB` unbiased estimate (dividing by N-1) of the covariance of the vectors. To also return the mean vector and number of samples, call :func:`~spectral.algorithms.algorithms.mean_cov` instead. ''' return mean_cov(*args)[1]
[ "def", "covariance", "(", "*", "args", ")", ":", "return", "mean_cov", "(", "*", "args", ")", "[", "1", "]" ]
https://github.com/spectralpython/spectral/blob/e1cd919f5f66abddc219b76926450240feaaed8f/spectral/algorithms/algorithms.py#L291-L333
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/sorcery.py
python
get_sorcery_ver
(module)
return stdout.strip()
Get Sorcery version.
Get Sorcery version.
[ "Get", "Sorcery", "version", "." ]
def get_sorcery_ver(module): """ Get Sorcery version. """ cmd_sorcery = "%s --version" % SORCERY['sorcery'] rc, stdout, stderr = module.run_command(cmd_sorcery) if rc != 0 or not stdout: module.fail_json(msg="unable to get Sorcery version") return stdout.strip()
[ "def", "get_sorcery_ver", "(", "module", ")", ":", "cmd_sorcery", "=", "\"%s --version\"", "%", "SORCERY", "[", "'sorcery'", "]", "rc", ",", "stdout", ",", "stderr", "=", "module", ".", "run_command", "(", "cmd_sorcery", ")", "if", "rc", "!=", "0", "or", ...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/sorcery.py#L173-L183
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/registry/models/versioned_processor.py
python
VersionedProcessor.style
(self)
return self._style
Gets the style of this VersionedProcessor. Stylistic data for rendering in a UI :return: The style of this VersionedProcessor. :rtype: dict(str, str)
Gets the style of this VersionedProcessor. Stylistic data for rendering in a UI
[ "Gets", "the", "style", "of", "this", "VersionedProcessor", ".", "Stylistic", "data", "for", "rendering", "in", "a", "UI" ]
def style(self): """ Gets the style of this VersionedProcessor. Stylistic data for rendering in a UI :return: The style of this VersionedProcessor. :rtype: dict(str, str) """ return self._style
[ "def", "style", "(", "self", ")", ":", "return", "self", ".", "_style" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/registry/models/versioned_processor.py#L272-L280
Maluuba/newsqa
d5bb9e9640e2ed7a31e209393376549d737d276b
maluuba/newsqa/span_utils.py
python
span_rack_from_tag_text
(tagged_text, untagged_text)
return span_rack
Get spans in the tagged, tokenized text and convert.
Get spans in the tagged, tokenized text and convert.
[ "Get", "spans", "in", "the", "tagged", "tokenized", "text", "and", "convert", "." ]
def span_rack_from_tag_text(tagged_text, untagged_text): """Get spans in the tagged, tokenized text and convert. """ span_rack = [] for num, tt in enumerate(tagged_text): matches = regex.finditer(tt) span_array = [Span(s=match.start(), e=match.end()) for match in matches] span_array = char_to_word_index(rebase_span_array(span_array), untagged_text) span_rack.append(span_array) return span_rack
[ "def", "span_rack_from_tag_text", "(", "tagged_text", ",", "untagged_text", ")", ":", "span_rack", "=", "[", "]", "for", "num", ",", "tt", "in", "enumerate", "(", "tagged_text", ")", ":", "matches", "=", "regex", ".", "finditer", "(", "tt", ")", "span_arra...
https://github.com/Maluuba/newsqa/blob/d5bb9e9640e2ed7a31e209393376549d737d276b/maluuba/newsqa/span_utils.py#L105-L114
sagemath/sagenb
67a73cbade02639bc08265f28f3165442113ad4d
sagenb/notebook/run_notebook.py
python
NotebookRunTwisted.get_old_settings
(self, conf)
Returns three settings from the Twisted configuration file conf: the interface, port number, and whether the server is secure. If there are any errors, this returns (None, None, None).
Returns three settings from the Twisted configuration file conf: the interface, port number, and whether the server is secure. If there are any errors, this returns (None, None, None).
[ "Returns", "three", "settings", "from", "the", "Twisted", "configuration", "file", "conf", ":", "the", "interface", "port", "number", "and", "whether", "the", "server", "is", "secure", ".", "If", "there", "are", "any", "errors", "this", "returns", "(", "None...
def get_old_settings(self, conf): """ Returns three settings from the Twisted configuration file conf: the interface, port number, and whether the server is secure. If there are any errors, this returns (None, None, None). """ import re # This should match the format written to twistedconf.tac below. p = re.compile(r'interface="(.*)",port=(\d*),secure=(True|False)') try: interface, port, secure = p.search(open(conf, 'r').read()).groups() if secure == 'True': secure = True else: secure = False return interface, port, secure except (IOError, AttributeError): return None, None, None
[ "def", "get_old_settings", "(", "self", ",", "conf", ")", ":", "import", "re", "# This should match the format written to twistedconf.tac below.", "p", "=", "re", ".", "compile", "(", "r'interface=\"(.*)\",port=(\\d*),secure=(True|False)'", ")", "try", ":", "interface", "...
https://github.com/sagemath/sagenb/blob/67a73cbade02639bc08265f28f3165442113ad4d/sagenb/notebook/run_notebook.py#L342-L359
nose-devs/nose2
e0dc345da06995fdf00abeb3ed4ae65050d552bd
nose2/loader.py
python
PluggableTestLoader.loadTestsFromModule
(self, module)
return filterevt.suite
Load tests from module. Fires :func:`loadTestsFromModule` hook.
Load tests from module.
[ "Load", "tests", "from", "module", "." ]
def loadTestsFromModule(self, module): """Load tests from module. Fires :func:`loadTestsFromModule` hook. """ evt = events.LoadFromModuleEvent(self, module) result = self.session.hooks.loadTestsFromModule(evt) if evt.handled: suite = result or self.suiteClass() else: suite = self.suiteClass(evt.extraTests) filterevt = events.ModuleSuiteEvent(self, module, suite) result = self.session.hooks.moduleLoadedSuite(filterevt) if result: return result or self.suiteClass() return filterevt.suite
[ "def", "loadTestsFromModule", "(", "self", ",", "module", ")", ":", "evt", "=", "events", ".", "LoadFromModuleEvent", "(", "self", ",", "module", ")", "result", "=", "self", ".", "session", ".", "hooks", ".", "loadTestsFromModule", "(", "evt", ")", "if", ...
https://github.com/nose-devs/nose2/blob/e0dc345da06995fdf00abeb3ed4ae65050d552bd/nose2/loader.py#L36-L52
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
removeQuotes
(s,l,t)
return t[0][1:-1]
Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
Helper parse action for removing quotation marks from parsed quoted strings.
[ "Helper", "parse", "action", "for", "removing", "quotation", "marks", "from", "parsed", "quoted", "strings", "." ]
def removeQuotes(s,l,t): """ Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] """ return t[0][1:-1]
[ "def", "removeQuotes", "(", "s", ",", "l", ",", "t", ")", ":", "return", "t", "[", "0", "]", "[", "1", ":", "-", "1", "]" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py#L4770-L4782
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/gcs-oauth2-boto-plugin-2.5/gcs_oauth2_boto_plugin/oauth2_client.py
python
OAuth2UserAccountClient.FetchAccessToken
(self, rapt_token=None)
Fetches an access token from the provider's token endpoint. Fetches an access token from this client's OAuth2 provider's token endpoint. Args: rapt_token: (str) The RAPT to be passed when refreshing the access token. Returns: The fetched AccessToken.
Fetches an access token from the provider's token endpoint.
[ "Fetches", "an", "access", "token", "from", "the", "provider", "s", "token", "endpoint", "." ]
def FetchAccessToken(self, rapt_token=None): """Fetches an access token from the provider's token endpoint. Fetches an access token from this client's OAuth2 provider's token endpoint. Args: rapt_token: (str) The RAPT to be passed when refreshing the access token. Returns: The fetched AccessToken. """ try: http = self.CreateHttpRequest() credentials = reauth_creds.Oauth2WithReauthCredentials( None, # access_token self.client_id, self.client_secret, self.refresh_token, None, # token_expiry self.token_uri, None, # user_agent scopes=RAPT_SCOPES, rapt_token=rapt_token) credentials.refresh(http) return AccessToken( credentials.access_token, credentials.token_expiry, datetime_strategy=self.datetime_strategy, rapt_token=credentials.rapt_token) except oauth2client.client.AccessTokenRefreshError as e: if 'Invalid response 403' in e.message: # This is the most we can do at the moment to accurately detect rate # limiting errors since they come back as 403s with no further # information. raise GsAccessTokenRefreshError(e) elif 'invalid_grant' in e.message: LOG.info(""" Attempted to retrieve an access token from an invalid refresh token. Two common cases in which you will see this error are: 1. Your refresh token was revoked. 2. Your refresh token was typed incorrectly. """) raise GsInvalidRefreshTokenError(e) else: raise
[ "def", "FetchAccessToken", "(", "self", ",", "rapt_token", "=", "None", ")", ":", "try", ":", "http", "=", "self", ".", "CreateHttpRequest", "(", ")", "credentials", "=", "reauth_creds", ".", "Oauth2WithReauthCredentials", "(", "None", ",", "# access_token", "...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/gcs-oauth2-boto-plugin-2.5/gcs_oauth2_boto_plugin/oauth2_client.py#L598-L642
DataDog/integrations-core
934674b29d94b70ccc008f76ea172d0cdae05e1e
pgbouncer/datadog_checks/pgbouncer/config_models/__init__.py
python
ConfigMixin.shared_config
(self)
return self._config_model_shared
[]
def shared_config(self) -> SharedConfig: return self._config_model_shared
[ "def", "shared_config", "(", "self", ")", "->", "SharedConfig", ":", "return", "self", ".", "_config_model_shared" ]
https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/pgbouncer/datadog_checks/pgbouncer/config_models/__init__.py#L23-L24
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/SymantecManagementCenter/Integrations/SymantecManagementCenter/SymantecManagementCenter.py
python
update_policy_content_request
(uuid, content_type, change_description, schema_version, ips=None, urls=None, categories=None, content_description=None, content_enabled=None)
return response
Update content of a specified policy using the provided arguments :param uuid: Policy UUID :param content_type: Policy content type :param change_description: Policy update change description :param schema_version: Policy schema version :param ips: IPs to update from the content :param urls: URLs to update from the content :param categories: Category names to update from the content :param content_description: Content description to update. :param content_enabled: Content enablement to update. :return: Content update response
Update content of a specified policy using the provided arguments :param uuid: Policy UUID :param content_type: Policy content type :param change_description: Policy update change description :param schema_version: Policy schema version :param ips: IPs to update from the content :param urls: URLs to update from the content :param categories: Category names to update from the content :param content_description: Content description to update. :param content_enabled: Content enablement to update. :return: Content update response
[ "Update", "content", "of", "a", "specified", "policy", "using", "the", "provided", "arguments", ":", "param", "uuid", ":", "Policy", "UUID", ":", "param", "content_type", ":", "Policy", "content", "type", ":", "param", "change_description", ":", "Policy", "upd...
def update_policy_content_request(uuid, content_type, change_description, schema_version, ips=None, urls=None, categories=None, content_description=None, content_enabled=None): """ Update content of a specified policy using the provided arguments :param uuid: Policy UUID :param content_type: Policy content type :param change_description: Policy update change description :param schema_version: Policy schema version :param ips: IPs to update from the content :param urls: URLs to update from the content :param categories: Category names to update from the content :param content_description: Content description to update. :param content_enabled: Content enablement to update. :return: Content update response """ path = 'policies/' + uuid + '/content' body = { 'contentType': content_type, 'changeDescription': change_description } if schema_version: body['schemaVersion'] = schema_version content = get_policy_content_request(uuid) if not content or 'content' not in content: return_error('Could not update policy content - failed retrieving the current content') found_object_to_update = False if content_type == LOCAL_CATEGORY_DB_TYPE: if 'categories' in content['content']: content_entities = [] if ips: content_entities.extend(ips) if urls: content_entities.extend(urls) for category in content['content']['categories']: if category.get('name') in categories: for entry_index, entry in enumerate(category.get('entries')): if entry.get('url') in content_entities: found_object_to_update = True category['entries'][entry_index]['comment'] = content_description elif ips: if 'ipAddresses' in content['content']: for ip in content['content']['ipAddresses']: if ip['ipAddress'] in ips: found_object_to_update = True if content_description: ip['description'] = content_description if content_enabled: ip['enabled'] = bool(strtobool(content_enabled)) elif urls: if 'urls' in content['content']: for url in content['content']['urls']: found_object_to_update = True if url['url'] in urls: found_object_to_update = True if content_description: url['description'] = content_description if content_enabled: url['enabled'] = bool(strtobool(content_enabled)) if not found_object_to_update: raise Exception('Update failed - Could not find object to update.') body['content'] = content['content'] response = http_request('POST', path, data=body) return response
[ "def", "update_policy_content_request", "(", "uuid", ",", "content_type", ",", "change_description", ",", "schema_version", ",", "ips", "=", "None", ",", "urls", "=", "None", ",", "categories", "=", "None", ",", "content_description", "=", "None", ",", "content_...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/SymantecManagementCenter/Integrations/SymantecManagementCenter/SymantecManagementCenter.py#L1045-L1116
Georce/lepus
5b01bae82b5dc1df00c9e058989e2eb9b89ff333
lepus/redis-2.10.3/redis/client.py
python
StrictRedis.object
(self, infotype, key)
return self.execute_command('OBJECT', infotype, key, infotype=infotype)
Return the encoding, idletime, or refcount about the key
Return the encoding, idletime, or refcount about the key
[ "Return", "the", "encoding", "idletime", "or", "refcount", "about", "the", "key" ]
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" return self.execute_command('OBJECT', infotype, key, infotype=infotype)
[ "def", "object", "(", "self", ",", "infotype", ",", "key", ")", ":", "return", "self", ".", "execute_command", "(", "'OBJECT'", ",", "infotype", ",", "key", ",", "infotype", "=", "infotype", ")" ]
https://github.com/Georce/lepus/blob/5b01bae82b5dc1df00c9e058989e2eb9b89ff333/lepus/redis-2.10.3/redis/client.py#L668-L670
chainer/chainercv
7159616642e0be7c5b3ef380b848e16b7e99355b
examples/fpn/train_multi.py
python
Transform.__call__
(self, in_data)
[]
def __call__(self, in_data): if len(in_data) == 4: img, mask, label, bbox = in_data else: img, bbox, label = in_data # Flipping img, params = transforms.random_flip( img, x_random=True, return_param=True) x_flip = params['x_flip'] bbox = transforms.flip_bbox( bbox, img.shape[1:], x_flip=x_flip) # Scaling and mean subtraction img, scale = scale_img( img, self.min_size, self.max_size) img -= self.mean bbox = bbox * scale if len(in_data) == 4: mask = transforms.flip(mask, x_flip=x_flip) mask = transforms.resize( mask.astype(np.float32), img.shape[1:], interpolation=PIL.Image.NEAREST).astype(np.bool) return img, bbox, label, mask else: return img, bbox, label
[ "def", "__call__", "(", "self", ",", "in_data", ")", ":", "if", "len", "(", "in_data", ")", "==", "4", ":", "img", ",", "mask", ",", "label", ",", "bbox", "=", "in_data", "else", ":", "img", ",", "bbox", ",", "label", "=", "in_data", "# Flipping", ...
https://github.com/chainer/chainercv/blob/7159616642e0be7c5b3ef380b848e16b7e99355b/examples/fpn/train_multi.py#L141-L167
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32com/server/policy.py
python
BasicWrapPolicy._CreateInstance_
(self, clsid, reqIID)
Creates a new instance of a **wrapped** object This method looks up a "@win32com.server.policy.regSpec@" % clsid entry in the registry (using @DefaultPolicy@)
Creates a new instance of a **wrapped** object
[ "Creates", "a", "new", "instance", "of", "a", "**", "wrapped", "**", "object" ]
def _CreateInstance_(self, clsid, reqIID): """Creates a new instance of a **wrapped** object This method looks up a "@win32com.server.policy.regSpec@" % clsid entry in the registry (using @DefaultPolicy@) """ try: classSpec = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regSpec % clsid) except win32api.error: raise error("The object is not correctly registered - %s key can not be read" % (regSpec % clsid)) myob = call_func(classSpec) self._wrap_(myob) try: return pythoncom.WrapObject(self, reqIID) except pythoncom.com_error, (hr, desc, exc, arg): from win32com.util import IIDToInterfaceName desc = "The object '%r' was created, but does not support the " \ "interface '%s'(%s): %s" \ % (myob, IIDToInterfaceName(reqIID), reqIID, desc) raise pythoncom.com_error(hr, desc, exc, arg)
[ "def", "_CreateInstance_", "(", "self", ",", "clsid", ",", "reqIID", ")", ":", "try", ":", "classSpec", "=", "win32api", ".", "RegQueryValue", "(", "win32con", ".", "HKEY_CLASSES_ROOT", ",", "regSpec", "%", "clsid", ")", "except", "win32api", ".", "error", ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32com/server/policy.py#L183-L203
mr-karan/swiggy-analytics
3b19171432a13fb8b0b57040dacb862c6d67b0fc
swiggy_analytics/helper.py
python
fetch_and_store_orders
(db)
Fetches all the historical orders for the user and saves them in db
Fetches all the historical orders for the user and saves them in db
[ "Fetches", "all", "the", "historical", "orders", "for", "the", "user", "and", "saves", "them", "in", "db" ]
def fetch_and_store_orders(db): """ Fetches all the historical orders for the user and saves them in db """ response = session.get(SWIGGY_ORDER_URL) if not response.json().get('data', None): raise SwiggyAPIError("Unable to fetch orders") # get the last order_id to use as offset param for next order fetch call orders = response.json().get('data').get('orders', None) # check if user has zero orders if isinstance(orders, list) and len(orders)==0: sys.exit("You have not placed any order, no data to fetch :)") if not orders: raise SwiggyAPIError("Unable to fetch orders") # extract order meta data and insert in db insert_orders_data(db, orders) offset_id = orders[-1]['order_id'] count = response.json().get('data')['total_orders'] pages = ceil(count/10) label = "Fetching {} orders".format(count) # Updates the progress bar on every orders fetch call (i.e. after 10 unique orders) with ProgressBar(style=PROGRESS_BAR_STYLE, formatters=PROGRESS_BAR_FORMATTER) as pb: for i in pb(range(pages), label=label): try: orders = fetch_orders(offset_id) except SwiggyAPIError as e: raise SwiggyAPIError(e) if len(orders) == 0: break # extract order meta data and insert in db insert_orders_data(db, orders) # Responsible Scraping. Code word for "dont wanna overload their servers :P" :) time.sleep(SWIGGY_API_CALL_INTERVAL) # SAD PANDA FACE BEGIN # The way it works is that, the first API call returns a paginated set of 10 orders and to fetch the next result, you need # to send the last order_id from this result set as an offset parameter. Because the way this offset/cursor # is designed it makes it impossible to use any kind of async/await magic. # SAD PANDA FACE OVER offset_id = orders[-1]['order_id']
[ "def", "fetch_and_store_orders", "(", "db", ")", ":", "response", "=", "session", ".", "get", "(", "SWIGGY_ORDER_URL", ")", "if", "not", "response", ".", "json", "(", ")", ".", "get", "(", "'data'", ",", "None", ")", ":", "raise", "SwiggyAPIError", "(", ...
https://github.com/mr-karan/swiggy-analytics/blob/3b19171432a13fb8b0b57040dacb862c6d67b0fc/swiggy_analytics/helper.py#L177-L221
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/nn/hetero_nn/model/interactive_layer.py
python
InterActiveGuestDenseLayer.forward
(self, guest_input, epoch=0, batch=0, train=True)
return activation_out
[]
def forward(self, guest_input, epoch=0, batch=0, train=True): LOGGER.info("interactive layer start forward propagation of epoch {} batch {}".format(epoch, batch)) encrypted_host_input = PaillierTensor(self.get_host_encrypted_forward_from_host(epoch, batch)) if not self.partitions: self.partitions = encrypted_host_input.partitions self.encrypted_host_input = encrypted_host_input self.guest_input = guest_input if self.guest_model is None: LOGGER.info("building interactive layers' training model") self.host_input_shape = encrypted_host_input.shape[1] self.guest_input_shape = guest_input.shape[1] if guest_input is not None else 0 self.__build_model() if not self.sync_output_unit: self.sync_output_unit = True self.sync_interactive_layer_output_unit(self.host_model.output_shape[0]) host_output = self.forward_interactive(encrypted_host_input, epoch, batch, train) guest_output = self.guest_model.forward_dense(guest_input) if not self.guest_model.empty: dense_output_data = host_output + PaillierTensor(guest_output, partitions=self.partitions) else: dense_output_data = host_output self.dense_output_data = dense_output_data self.guest_output = guest_output self.host_output = host_output LOGGER.info("start to get interactive layer's activation output of epoch {} batch {}".format(epoch, batch)) activation_out = self.host_model.forward_activation(self.dense_output_data.numpy()) LOGGER.info("end to get interactive layer's activation output of epoch {} batch {}".format(epoch, batch)) if train and self.drop_out: activation_out = self.drop_out.forward(activation_out) return activation_out
[ "def", "forward", "(", "self", ",", "guest_input", ",", "epoch", "=", "0", ",", "batch", "=", "0", ",", "train", "=", "True", ")", ":", "LOGGER", ".", "info", "(", "\"interactive layer start forward propagation of epoch {} batch {}\"", ".", "format", "(", "epo...
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/nn/hetero_nn/model/interactive_layer.py#L90-L131
deanishe/zothero
5b057ef080ee730d82d5dd15e064d2a4730c2b11
src/lib/workflow/workflow.py
python
Item.__init__
(self, title, subtitle='', modifier_subtitles=None, arg=None, autocomplete=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None)
Same arguments as :meth:`Workflow.add_item`.
Same arguments as :meth:`Workflow.add_item`.
[ "Same", "arguments", "as", ":", "meth", ":", "Workflow", ".", "add_item", "." ]
def __init__(self, title, subtitle='', modifier_subtitles=None, arg=None, autocomplete=None, valid=False, uid=None, icon=None, icontype=None, type=None, largetext=None, copytext=None, quicklookurl=None): """Same arguments as :meth:`Workflow.add_item`.""" self.title = title self.subtitle = subtitle self.modifier_subtitles = modifier_subtitles or {} self.arg = arg self.autocomplete = autocomplete self.valid = valid self.uid = uid self.icon = icon self.icontype = icontype self.type = type self.largetext = largetext self.copytext = copytext self.quicklookurl = quicklookurl
[ "def", "__init__", "(", "self", ",", "title", ",", "subtitle", "=", "''", ",", "modifier_subtitles", "=", "None", ",", "arg", "=", "None", ",", "autocomplete", "=", "None", ",", "valid", "=", "False", ",", "uid", "=", "None", ",", "icon", "=", "None"...
https://github.com/deanishe/zothero/blob/5b057ef080ee730d82d5dd15e064d2a4730c2b11/src/lib/workflow/workflow.py#L720-L737
nucypher/nucypher
f420caeb1c974f511f689fd1e5a9c6bbdf97f2d7
nucypher/policy/identity.py
python
Card.lookup
(cls, identifier: str, card_dir: Optional[Path] = CARD_DIR)
return filepath
Resolve a card ID or nickname into a Path object
Resolve a card ID or nickname into a Path object
[ "Resolve", "a", "card", "ID", "or", "nickname", "into", "a", "Path", "object" ]
def lookup(cls, identifier: str, card_dir: Optional[Path] = CARD_DIR) -> Path: """Resolve a card ID or nickname into a Path object""" try: nickname, _id = identifier.split(cls.__DELIMITER) except ValueError: nickname = identifier filenames = [f for f in Card.CARD_DIR.iterdir() if nickname.lower() in f.name.lower()] if not filenames: raise cls.UnknownCard(f'Unknown card nickname or ID "{nickname}".') elif len(filenames) == 1: filename = filenames[0] else: raise ValueError(f'Ambiguous card nickname: {nickname}. Try using card ID instead.') filepath = card_dir / filename return filepath
[ "def", "lookup", "(", "cls", ",", "identifier", ":", "str", ",", "card_dir", ":", "Optional", "[", "Path", "]", "=", "CARD_DIR", ")", "->", "Path", ":", "try", ":", "nickname", ",", "_id", "=", "identifier", ".", "split", "(", "cls", ".", "__DELIMITE...
https://github.com/nucypher/nucypher/blob/f420caeb1c974f511f689fd1e5a9c6bbdf97f2d7/nucypher/policy/identity.py#L307-L321
dipu-bd/lightnovel-crawler
eca7a71f217ce7a6b0a54d2e2afb349571871880
sources/en/r/readlightnovelcc.py
python
ReadlightnovelCcCrawler.read_novel_info
(self)
Get novel title, autor, cover etc
Get novel title, autor, cover etc
[ "Get", "novel", "title", "autor", "cover", "etc" ]
def read_novel_info(self): '''Get novel title, autor, cover etc''' url = self.novel_url.replace('https://m', 'https://www') logger.debug('Visiting %s', url) soup = self.get_soup(url) self.novel_title = soup.select_one('div.book-name').text.strip() logger.info('Novel title: %s', self.novel_title) self.novel_author = soup.select_one('div.author span.name').text.strip() logger.info('Novel author: %s', self.novel_author) self.novel_cover = self.absolute_url( soup.select_one('div.book-img img')['src']) logger.info('Novel cover: %s', self.novel_cover) # Extract volume-wise chapter entries chapters = soup.select('ul.chapter-list a') for a in chapters: chap_id = len(self.chapters) + 1 if len(self.chapters) % 100 == 0: vol_id = chap_id//100 + 1 vol_title = 'Volume ' + str(vol_id) self.volumes.append({ 'id': vol_id, 'title': vol_title, }) # end if self.chapters.append({ 'id': chap_id, 'volume': vol_id, 'url': self.absolute_url(a['href']), 'title': a.select_one('p.chapter-name').text.strip() or ('Chapter %d' % chap_id), })
[ "def", "read_novel_info", "(", "self", ")", ":", "url", "=", "self", ".", "novel_url", ".", "replace", "(", "'https://m'", ",", "'https://www'", ")", "logger", ".", "debug", "(", "'Visiting %s'", ",", "url", ")", "soup", "=", "self", ".", "get_soup", "("...
https://github.com/dipu-bd/lightnovel-crawler/blob/eca7a71f217ce7a6b0a54d2e2afb349571871880/sources/en/r/readlightnovelcc.py#L46-L80
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1_csi_driver_spec.py
python
V1CSIDriverSpec.to_str
(self)
return pprint.pformat(self.to_dict())
Returns the string representation of the model
Returns the string representation of the model
[ "Returns", "the", "string", "representation", "of", "the", "model" ]
def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ "def", "to_str", "(", "self", ")", ":", "return", "pprint", ".", "pformat", "(", "self", ".", "to_dict", "(", ")", ")" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1_csi_driver_spec.py#L214-L216
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/bert/tokenization_bert.py
python
BertTokenizer.convert_tokens_to_string
(self, tokens)
return out_string
Converts a sequence of tokens (string) in a single string.
Converts a sequence of tokens (string) in a single string.
[ "Converts", "a", "sequence", "of", "tokens", "(", "string", ")", "in", "a", "single", "string", "." ]
def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" out_string = " ".join(tokens).replace(" ##", "").strip() return out_string
[ "def", "convert_tokens_to_string", "(", "self", ",", "tokens", ")", ":", "out_string", "=", "\" \"", ".", "join", "(", "tokens", ")", ".", "replace", "(", "\" ##\"", ",", "\"\"", ")", ".", "strip", "(", ")", "return", "out_string" ]
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/bert/tokenization_bert.py#L243-L246
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/dns/_asyncio_backend.py
python
Backend.name
(self)
return 'asyncio'
[]
def name(self): return 'asyncio'
[ "def", "name", "(", "self", ")", ":", "return", "'asyncio'" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/dns/_asyncio_backend.py#L113-L114
phonopy/phonopy
816586d0ba8177482ecf40e52f20cbdee2260d51
phonopy/harmonic/dynamical_matrix.py
python
DynamicalMatrixNAC.nac_params
(self)
return {"born": self.born, "factor": self.factor, "dielectric": self.dielectric}
Return NAC basic parameters.
Return NAC basic parameters.
[ "Return", "NAC", "basic", "parameters", "." ]
def nac_params(self): """Return NAC basic parameters.""" return {"born": self.born, "factor": self.factor, "dielectric": self.dielectric}
[ "def", "nac_params", "(", "self", ")", ":", "return", "{", "\"born\"", ":", "self", ".", "born", ",", "\"factor\"", ":", "self", ".", "factor", ",", "\"dielectric\"", ":", "self", ".", "dielectric", "}" ]
https://github.com/phonopy/phonopy/blob/816586d0ba8177482ecf40e52f20cbdee2260d51/phonopy/harmonic/dynamical_matrix.py#L471-L473
reviewboard/reviewboard
7395902e4c181bcd1d633f61105012ffb1d18e1b
reviewboard/ssh/client.py
python
SSHClient.generate_user_key
(self, bits=2048)
return key
Generates a new RSA keypair for the user running Review Board. This will store the new key in the backend storage and return the resulting key as an instance of :py:mod:`paramiko.RSAKey`. If a key already exists, it's returned instead. Callers are expected to handle any exceptions. This may raise IOError for any problems in writing the key file, or paramiko.SSHException for any other problems.
Generates a new RSA keypair for the user running Review Board.
[ "Generates", "a", "new", "RSA", "keypair", "for", "the", "user", "running", "Review", "Board", "." ]
def generate_user_key(self, bits=2048): """Generates a new RSA keypair for the user running Review Board. This will store the new key in the backend storage and return the resulting key as an instance of :py:mod:`paramiko.RSAKey`. If a key already exists, it's returned instead. Callers are expected to handle any exceptions. This may raise IOError for any problems in writing the key file, or paramiko.SSHException for any other problems. """ key = self.get_user_key() if not key: key = paramiko.RSAKey.generate(bits) self._write_user_key(key) return key
[ "def", "generate_user_key", "(", "self", ",", "bits", "=", "2048", ")", ":", "key", "=", "self", ".", "get_user_key", "(", ")", "if", "not", "key", ":", "key", "=", "paramiko", ".", "RSAKey", ".", "generate", "(", "bits", ")", "self", ".", "_write_us...
https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/ssh/client.py#L228-L246
GoogleCloudPlatform/professional-services
0c707aa97437f3d154035ef8548109b7882f71da
examples/dataflow-production-ready/python/ml_preproc/pipeline/model/data_classes.py
python
line2record
(line: str, sep: str = ";")
return Record(*elements)
Transform a line of data into a Record. Args: line: A line from the CSV data file sep: The separator used in the line. Default is ; Returns: object: A Record object
Transform a line of data into a Record.
[ "Transform", "a", "line", "of", "data", "into", "a", "Record", "." ]
def line2record(line: str, sep: str = ";") -> Iterable[Record]: """ Transform a line of data into a Record. Args: line: A line from the CSV data file sep: The separator used in the line. Default is ; Returns: object: A Record object """ elements = line.split(sep) return Record(*elements)
[ "def", "line2record", "(", "line", ":", "str", ",", "sep", ":", "str", "=", "\";\"", ")", "->", "Iterable", "[", "Record", "]", ":", "elements", "=", "line", ".", "split", "(", "sep", ")", "return", "Record", "(", "*", "elements", ")" ]
https://github.com/GoogleCloudPlatform/professional-services/blob/0c707aa97437f3d154035ef8548109b7882f71da/examples/dataflow-production-ready/python/ml_preproc/pipeline/model/data_classes.py#L30-L42
modflowpy/flopy
eecd1ad193c5972093c9712e5c4b7a83284f0688
flopy/mf6/mfpackage.py
python
MFPackage.build_child_package
(self, pkg_type, data, parameter_name, filerecord)
Builds a child package. This method is only intended for FloPy internal use.
Builds a child package. This method is only intended for FloPy internal use.
[ "Builds", "a", "child", "package", ".", "This", "method", "is", "only", "intended", "for", "FloPy", "internal", "use", "." ]
def build_child_package(self, pkg_type, data, parameter_name, filerecord): """Builds a child package. This method is only intended for FloPy internal use.""" if not hasattr(self, pkg_type): self.build_child_packages_container(pkg_type, filerecord) if data is not None: package_group = getattr(self, pkg_type) # build child package file name child_path = package_group._next_default_file_path() # create new empty child package package_obj = self.package_factory( pkg_type, self.model_or_sim.model_type ) package = package_obj( self.model_or_sim, filename=child_path, parent_file=self ) assert hasattr(package, parameter_name) if isinstance(data, dict): # evaluate and add data to package unused_data = {} for key, value in data.items(): # if key is an attribute of the child package if isinstance(key, str) and hasattr(package, key): # set child package attribute child_data_attr = getattr(package, key) if isinstance(child_data_attr, mfdatalist.MFList): child_data_attr.set_data(value, autofill=True) elif isinstance(child_data_attr, mfdata.MFData): child_data_attr.set_data(value) elif key == "fname" or key == "filename": child_path = value package._filename = value else: setattr(package, key, value) else: unused_data[key] = value if unused_data: setattr(package, parameter_name, unused_data) else: setattr(package, parameter_name, data) # append package to list package_group._init_package(package, child_path)
[ "def", "build_child_package", "(", "self", ",", "pkg_type", ",", "data", ",", "parameter_name", ",", "filerecord", ")", ":", "if", "not", "hasattr", "(", "self", ",", "pkg_type", ")", ":", "self", ".", "build_child_packages_container", "(", "pkg_type", ",", ...
https://github.com/modflowpy/flopy/blob/eecd1ad193c5972093c9712e5c4b7a83284f0688/flopy/mf6/mfpackage.py#L2220-L2263
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/boto-2.46.1/boto/mws/connection.py
python
MWSConnection.cancel_order_reference
(self, request, response, **kw)
return self._post_request(request, kw, response)
Cancel an order reference; all authorizations associated with this order reference are also closed.
Cancel an order reference; all authorizations associated with this order reference are also closed.
[ "Cancel", "an", "order", "reference", ";", "all", "authorizations", "associated", "with", "this", "order", "reference", "are", "also", "closed", "." ]
def cancel_order_reference(self, request, response, **kw): """Cancel an order reference; all authorizations associated with this order reference are also closed. """ return self._post_request(request, kw, response)
[ "def", "cancel_order_reference", "(", "self", ",", "request", ",", "response", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "_post_request", "(", "request", ",", "kw", ",", "response", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/boto-2.46.1/boto/mws/connection.py#L1092-L1096
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/contrib/gis/geos/linestring.py
python
LineString._checkdim
(self, dim)
[]
def _checkdim(self, dim): if dim not in (2, 3): raise TypeError('Dimension mismatch.')
[ "def", "_checkdim", "(", "self", ",", "dim", ")", ":", "if", "dim", "not", "in", "(", "2", ",", "3", ")", ":", "raise", "TypeError", "(", "'Dimension mismatch.'", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/gis/geos/linestring.py#L105-L106
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/words/protocols/irc.py
python
ServerSupportedFeatures.parse
(self, params)
Parse ISUPPORT parameters. If an unknown parameter is encountered, it is simply added to the dictionary, keyed by its name, as a tuple of the parameters provided. @type params: C{iterable} of C{str} @param params: Iterable of ISUPPORT parameters to parse
Parse ISUPPORT parameters.
[ "Parse", "ISUPPORT", "parameters", "." ]
def parse(self, params): """ Parse ISUPPORT parameters. If an unknown parameter is encountered, it is simply added to the dictionary, keyed by its name, as a tuple of the parameters provided. @type params: C{iterable} of C{str} @param params: Iterable of ISUPPORT parameters to parse """ for param in params: key, value = self._splitParam(param) if key.startswith('-'): self._features.pop(key[1:], None) else: self._features[key] = self.dispatch(key, value)
[ "def", "parse", "(", "self", ",", "params", ")", ":", "for", "param", "in", "params", ":", "key", ",", "value", "=", "self", ".", "_splitParam", "(", "param", ")", "if", "key", ".", "startswith", "(", "'-'", ")", ":", "self", ".", "_features", ".",...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/words/protocols/irc.py#L790-L805
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/compiler/future.py
python
FutureParser.get_features
(self)
return self.found.keys()
Return list of features enabled by future statements
Return list of features enabled by future statements
[ "Return", "list", "of", "features", "enabled", "by", "future", "statements" ]
def get_features(self): """Return list of features enabled by future statements""" return self.found.keys()
[ "def", "get_features", "(", "self", ")", ":", "return", "self", ".", "found", ".", "keys", "(", ")" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/compiler/future.py#L43-L45
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/course_blocks/api.py
python
get_course_block_access_transformers
(user)
return course_block_access_transformers
Default list of transformers for manipulating course block structures based on the user's access to the course blocks. Arguments: user (django.contrib.auth.models.User) - User object for which the block structure is to be transformed.
Default list of transformers for manipulating course block structures based on the user's access to the course blocks.
[ "Default", "list", "of", "transformers", "for", "manipulating", "course", "block", "structures", "based", "on", "the", "user", "s", "access", "to", "the", "course", "blocks", "." ]
def get_course_block_access_transformers(user): """ Default list of transformers for manipulating course block structures based on the user's access to the course blocks. Arguments: user (django.contrib.auth.models.User) - User object for which the block structure is to be transformed. """ course_block_access_transformers = [ library_content.ContentLibraryTransformer(), library_content.ContentLibraryOrderTransformer(), start_date.StartDateTransformer(), ContentTypeGateTransformer(), user_partitions.UserPartitionTransformer(), visibility.VisibilityTransformer(), field_data.DateOverrideTransformer(user), ] if has_individual_student_override_provider(): course_block_access_transformers += [load_override_data.OverrideDataTransformer(user)] return course_block_access_transformers
[ "def", "get_course_block_access_transformers", "(", "user", ")", ":", "course_block_access_transformers", "=", "[", "library_content", ".", "ContentLibraryTransformer", "(", ")", ",", "library_content", ".", "ContentLibraryOrderTransformer", "(", ")", ",", "start_date", "...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/course_blocks/api.py#L31-L54
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/south/logger.py
python
init_logger
()
return logger
Initialize the south logger
Initialize the south logger
[ "Initialize", "the", "south", "logger" ]
def init_logger(): "Initialize the south logger" logger = logging.getLogger("south") logger.addHandler(NullHandler()) return logger
[ "def", "init_logger", "(", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"south\"", ")", "logger", ".", "addHandler", "(", "NullHandler", "(", ")", ")", "return", "logger" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/south/logger.py#L32-L36
albertz/music-player
d23586f5bf657cbaea8147223be7814d117ae73d
mac/pyobjc-core/Lib/objc/_properties.py
python
set_proxy.__le__
(self, other)
[]
def __le__(self, other): if isinstance(other, set_proxy): return self._wrapped <= other._wrapped else: return self._wrapped <= other
[ "def", "__le__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "set_proxy", ")", ":", "return", "self", ".", "_wrapped", "<=", "other", ".", "_wrapped", "else", ":", "return", "self", ".", "_wrapped", "<=", "other" ]
https://github.com/albertz/music-player/blob/d23586f5bf657cbaea8147223be7814d117ae73d/mac/pyobjc-core/Lib/objc/_properties.py#L760-L765
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/view/fanchart2wayview.py
python
FanChart2WayView.get_stock
(self)
return 'gramps-pedigree'
The category stock icon
The category stock icon
[ "The", "category", "stock", "icon" ]
def get_stock(self): """ The category stock icon """ return 'gramps-pedigree'
[ "def", "get_stock", "(", "self", ")", ":", "return", "'gramps-pedigree'" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/view/fanchart2wayview.py#L142-L146
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_arch/abc/_storage.py
python
StorageTableMetaABC.update_metas
(self, schema=None, count=None, part_of_data=None, description=None, partitions=None, **kwargs)
[]
def update_metas(self, schema=None, count=None, part_of_data=None, description=None, partitions=None, **kwargs): ...
[ "def", "update_metas", "(", "self", ",", "schema", "=", "None", ",", "count", "=", "None", ",", "part_of_data", "=", "None", ",", "description", "=", "None", ",", "partitions", "=", "None", ",", "*", "*", "kwargs", ")", ":", "..." ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_arch/abc/_storage.py#L40-L41
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/detailed_demographic_service/client.py
python
DetailedDemographicServiceClient._get_default_mtls_endpoint
(api_endpoint)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint.
Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint.
[ "Convert", "api", "endpoint", "to", "mTLS", "endpoint", ".", "Convert", "*", ".", "sandbox", ".", "googleapis", ".", "com", "and", "*", ".", "googleapis", ".", "com", "to", "*", ".", "mtls", ".", "sandbox", ".", "googleapis", ".", "com", "and", "*", ...
def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
[ "def", "_get_default_mtls_endpoint", "(", "api_endpoint", ")", ":", "if", "not", "api_endpoint", ":", "return", "api_endpoint", "mtls_endpoint_re", "=", "re", ".", "compile", "(", "r\"(?P<name>[^.]+)(?P<mtls>\\.mtls)?(?P<sandbox>\\.sandbox)?(?P<googledomain>\\.googleapis\\.com)?\...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/detailed_demographic_service/client.py#L81-L107
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/wireless/__init__.py
python
Wireless.__init__
(self, twilio)
Initialize the Wireless Domain :returns: Domain for Wireless :rtype: twilio.rest.wireless.Wireless
Initialize the Wireless Domain
[ "Initialize", "the", "Wireless", "Domain" ]
def __init__(self, twilio): """ Initialize the Wireless Domain :returns: Domain for Wireless :rtype: twilio.rest.wireless.Wireless """ super(Wireless, self).__init__(twilio) self.base_url = 'https://wireless.twilio.com' # Versions self._v1 = None
[ "def", "__init__", "(", "self", ",", "twilio", ")", ":", "super", "(", "Wireless", ",", "self", ")", ".", "__init__", "(", "twilio", ")", "self", ".", "base_url", "=", "'https://wireless.twilio.com'", "# Versions", "self", ".", "_v1", "=", "None" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/wireless/__init__.py#L15-L27
bendmorris/static-python
2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473
Lib/importlib/abc.py
python
ExecutionLoader.init_module_attrs
(self, module)
Initialize the module's attributes. It is assumed that the module's name has been set on module.__name__. It is also assumed that any path returned by self.get_filename() uses (one of) the operating system's path separator(s) to separate filenames from directories in order to set __path__ intelligently. InspectLoader.init_module_attrs() sets __loader__ and __package__.
Initialize the module's attributes.
[ "Initialize", "the", "module", "s", "attributes", "." ]
def init_module_attrs(self, module): """Initialize the module's attributes. It is assumed that the module's name has been set on module.__name__. It is also assumed that any path returned by self.get_filename() uses (one of) the operating system's path separator(s) to separate filenames from directories in order to set __path__ intelligently. InspectLoader.init_module_attrs() sets __loader__ and __package__. """ super().init_module_attrs(module) _bootstrap._init_file_attrs(self, module)
[ "def", "init_module_attrs", "(", "self", ",", "module", ")", ":", "super", "(", ")", ".", "init_module_attrs", "(", "module", ")", "_bootstrap", ".", "_init_file_attrs", "(", "self", ",", "module", ")" ]
https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/importlib/abc.py#L228-L238
StanfordHCI/termite
f795be291a1598cb2ae1df1a598c989f369e9ce8
pipeline/utf8_utils.py
python
UnicodeReader.next
(self)
return [unicode(s, "utf-8") for s in row]
[]
def next(self): row = self.reader.next() return [unicode(s, "utf-8") for s in row]
[ "def", "next", "(", "self", ")", ":", "row", "=", "self", ".", "reader", ".", "next", "(", ")", "return", "[", "unicode", "(", "s", ",", "\"utf-8\"", ")", "for", "s", "in", "row", "]" ]
https://github.com/StanfordHCI/termite/blob/f795be291a1598cb2ae1df1a598c989f369e9ce8/pipeline/utf8_utils.py#L35-L37
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/pupylib/PupyOffload.py
python
MsgPackMessages.recv
(self)
return msgpack.loads(data)
[]
def recv(self): datalen_b = self._conn.recv(4) if datalen_b == '': raise EOFError datalen, = struct.unpack('>I', datalen_b) data = self._conn.recv(datalen) if data == '': raise EOFError return msgpack.loads(data)
[ "def", "recv", "(", "self", ")", ":", "datalen_b", "=", "self", ".", "_conn", ".", "recv", "(", "4", ")", "if", "datalen_b", "==", "''", ":", "raise", "EOFError", "datalen", ",", "=", "struct", ".", "unpack", "(", "'>I'", ",", "datalen_b", ")", "da...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/pupylib/PupyOffload.py#L46-L56
sony/nnabla-examples
068be490aacf73740502a1c3b10f8b2d15a52d32
GANs/pggan/networks.py
python
Generator.to_RGB
(self, h, resolution)
return h
To RGB layer To RGB projects feature maps to RGB maps.
To RGB layer
[ "To", "RGB", "layer" ]
def to_RGB(self, h, resolution): """To RGB layer To RGB projects feature maps to RGB maps. """ with nn.parameter_scope("to_rgb_{}".format(resolution)): h = conv(h, 3, kernel=(1, 1), pad=(0, 0), stride=(1, 1), with_bias=True, use_wscale=self.use_wscale, use_he_backward=self.use_he_backward) return h
[ "def", "to_RGB", "(", "self", ",", "h", ",", "resolution", ")", ":", "with", "nn", ".", "parameter_scope", "(", "\"to_rgb_{}\"", ".", "format", "(", "resolution", ")", ")", ":", "h", "=", "conv", "(", "h", ",", "3", ",", "kernel", "=", "(", "1", ...
https://github.com/sony/nnabla-examples/blob/068be490aacf73740502a1c3b10f8b2d15a52d32/GANs/pggan/networks.py#L86-L96
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/discussion/rest_api/api.py
python
_check_initializable_comment_fields
(data, context)
Checks if the given data contains a comment field that is not initializable by the requesting user Arguments: data (dict): The data to compare the allowed_fields against context (dict): The context appropriate for use with the comment which includes the requesting user Raises: ValidationError if the given data contains a comment field that is not initializable by the requesting user
Checks if the given data contains a comment field that is not initializable by the requesting user
[ "Checks", "if", "the", "given", "data", "contains", "a", "comment", "field", "that", "is", "not", "initializable", "by", "the", "requesting", "user" ]
def _check_initializable_comment_fields(data, context): """ Checks if the given data contains a comment field that is not initializable by the requesting user Arguments: data (dict): The data to compare the allowed_fields against context (dict): The context appropriate for use with the comment which includes the requesting user Raises: ValidationError if the given data contains a comment field that is not initializable by the requesting user """ _check_fields( get_initializable_comment_fields(context), data, "This field is not initializable." )
[ "def", "_check_initializable_comment_fields", "(", "data", ",", "context", ")", ":", "_check_fields", "(", "get_initializable_comment_fields", "(", "context", ")", ",", "data", ",", "\"This field is not initializable.\"", ")" ]
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/discussion/rest_api/api.py#L847-L865
sideeffects/SideFXLabs
956bc1eef6710882ae8d3a31b4a33dd631a56d5f
scripts/python/labsopui/networkwalk.py
python
get_network_editor
(node=None)
return editor
Get all Network editors. If there's not one under curser than get the first one.
Get all Network editors. If there's not one under curser than get the first one.
[ "Get", "all", "Network", "editors", ".", "If", "there", "s", "not", "one", "under", "curser", "than", "get", "the", "first", "one", "." ]
def get_network_editor(node=None): """ Get all Network editors. If there's not one under curser than get the first one. """ # Find all network editors in that are showing this node. paneTabs = hou.ui.paneTabs() editors = list() for paneTab in paneTabs: if paneTab.type() == hou.paneTabType.NetworkEditor: if node.parent() == paneTab.pwd(): try: isUnder = paneTab.isUnderCursor() except: isUnder = False if isUnder: editor = paneTab return editor editors.append(editor) # TO DO: check tab is current? # Pick first. if len(editors)>0: editor = editors[0] else: editor = None return editor
[ "def", "get_network_editor", "(", "node", "=", "None", ")", ":", "# Find all network editors in that are showing this node. ", "paneTabs", "=", "hou", ".", "ui", ".", "paneTabs", "(", ")", "editors", "=", "list", "(", ")", "for", "paneTab", "in", "paneTabs", "...
https://github.com/sideeffects/SideFXLabs/blob/956bc1eef6710882ae8d3a31b4a33dd631a56d5f/scripts/python/labsopui/networkwalk.py#L263-L289
SoCo/SoCo
e83fef84d2645d05265dbd574598518655a9c125
soco/core.py
python
SoCo.surround_enabled
(self, enable)
Enable/disable the connected surround speakers. :param enable: Enable or disable surround speakers :type enable: bool
Enable/disable the connected surround speakers.
[ "Enable", "/", "disable", "the", "connected", "surround", "speakers", "." ]
def surround_enabled(self, enable): """Enable/disable the connected surround speakers. :param enable: Enable or disable surround speakers :type enable: bool """ if not self.is_soundbar: message = "This device does not support surrounds" raise NotSupportedException(message) self.renderingControl.SetEQ( [ ("InstanceID", 0), ("EQType", "SurroundEnable"), ("DesiredValue", int(enable)), ] )
[ "def", "surround_enabled", "(", "self", ",", "enable", ")", ":", "if", "not", "self", ".", "is_soundbar", ":", "message", "=", "\"This device does not support surrounds\"", "raise", "NotSupportedException", "(", "message", ")", "self", ".", "renderingControl", ".", ...
https://github.com/SoCo/SoCo/blob/e83fef84d2645d05265dbd574598518655a9c125/soco/core.py#L1038-L1054
SpriteLink/NIPAP
de09cd7c4c55521f26f00201d694ea9e388b21a9
nipap/nipap/backend.py
python
Nipap.add_pool
(self, auth, attr)
return pool
Create a pool according to `attr`. * `auth` [BaseAuth] AAA options. * `attr` [pool_attr] A dict containing the attributes the new pool should have. Returns a dict describing the pool which was added. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.add_pool` for full understanding.
Create a pool according to `attr`.
[ "Create", "a", "pool", "according", "to", "attr", "." ]
def add_pool(self, auth, attr): """ Create a pool according to `attr`. * `auth` [BaseAuth] AAA options. * `attr` [pool_attr] A dict containing the attributes the new pool should have. Returns a dict describing the pool which was added. This is the documentation of the internal backend function. It's exposed over XML-RPC, please also see the XML-RPC documentation for :py:func:`nipap.xmlrpc.NipapXMLRPC.add_pool` for full understanding. """ self._logger.debug("add_pool called; attrs: %s" % unicode(attr)) # sanity check - do we have all attributes? req_attr = ['name', 'description', 'default_type'] self._check_pool_attr(attr, req_attr) insert, params = self._sql_expand_insert(attr) sql = "INSERT INTO ip_net_pool " + insert self._execute(sql, params) pool_id = self._lastrowid() pool = self.list_pool(auth, { 'id': pool_id })[0] # write to audit table audit_params = { 'pool_id': pool['id'], 'pool_name': pool['name'], 'username': auth.username, 'authenticated_as': auth.authenticated_as, 'full_name': auth.full_name, 'authoritative_source': auth.authoritative_source, 'description': 'Added pool %s with attr: %s' % (pool['name'], unicode(attr)) } sql, params = self._sql_expand_insert(audit_params) self._execute('INSERT INTO ip_net_log %s' % sql, params) return pool
[ "def", "add_pool", "(", "self", ",", "auth", ",", "attr", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"add_pool called; attrs: %s\"", "%", "unicode", "(", "attr", ")", ")", "# sanity check - do we have all attributes?", "req_attr", "=", "[", "'name'",...
https://github.com/SpriteLink/NIPAP/blob/de09cd7c4c55521f26f00201d694ea9e388b21a9/nipap/nipap/backend.py#L1811-L1853
Trusted-AI/adversarial-robustness-toolbox
9fabffdbb92947efa1ecc5d825d634d30dfbaf29
art/attacks/evasion/hclu.py
python
HighConfidenceLowUncertainty.generate
(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs)
return x_adv
Generate adversarial examples and return them as an array. :param x: An array with the original inputs to be attacked. :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape (nb_samples,). :return: An array holding the adversarial examples.
Generate adversarial examples and return them as an array.
[ "Generate", "adversarial", "examples", "and", "return", "them", "as", "an", "array", "." ]
def generate(self, x: np.ndarray, y: Optional[np.ndarray] = None, **kwargs) -> np.ndarray: """ Generate adversarial examples and return them as an array. :param x: An array with the original inputs to be attacked. :param y: Target values (class labels) one-hot-encoded of shape (nb_samples, nb_classes) or indices of shape (nb_samples,). :return: An array holding the adversarial examples. """ x_adv = copy.copy(x) def minfun(x, args): # minimize L2 norm return np.sum(np.sqrt((x - args["orig"]) ** 2)) def constraint_conf(x, args): # constraint for confidence pred = args["classifier"].predict(x.reshape(1, -1))[0, 0] if args["class_zero"]: pred = 1.0 - pred return (pred - args["conf"]).reshape(-1) def constraint_unc(x, args): # constraint for uncertainty cur_unc = (args["classifier"].predict_uncertainty(x.reshape(1, -1))).reshape(-1) return (args["max_uncertainty"] - cur_unc)[0] bounds = [] # adding bounds, to not go away from original data for i in range(np.shape(x)[1]): bounds.append((self.min_val, self.max_val)) for i in trange(x.shape[0], desc="HCLU", disable=not self.verbose): # go through data and craft # get properties for attack max_uncertainty = self.unc_increase * self.estimator.predict_uncertainty(x_adv[i].reshape(1, -1)) class_zero = not self.estimator.predict(x_adv[i].reshape(1, -1))[0, 0] < 0.5 init_args = { "classifier": self.estimator, "class_zero": class_zero, "max_uncertainty": max_uncertainty, "conf": self.conf, } constr_conf = {"type": "ineq", "fun": constraint_conf, "args": (init_args,)} constr_unc = {"type": "ineq", "fun": constraint_unc, "args": (init_args,)} args = {"args": init_args, "orig": x[i].reshape(-1)} # finally, run optimization x_adv[i] = minimize( minfun, x_adv[i], args=args, bounds=bounds, constraints=[constr_conf, constr_unc], )["x"] logger.info( "Success rate of HCLU attack: %.2f%%", 100 * compute_success(self.estimator, x, y, x_adv), ) return x_adv
[ "def", "generate", "(", "self", ",", "x", ":", "np", ".", "ndarray", ",", "y", ":", "Optional", "[", "np", ".", "ndarray", "]", "=", "None", ",", "*", "*", "kwargs", ")", "->", "np", ".", "ndarray", ":", "x_adv", "=", "copy", ".", "copy", "(", ...
https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/9fabffdbb92947efa1ecc5d825d634d30dfbaf29/art/attacks/evasion/hclu.py#L75-L128
OneDrive/onedrive-sdk-python
e5642f8cad8eea37a4f653c1a23dfcfc06c37110
src/python2/request/versions_collection.py
python
VersionsCollectionRequestBuilder.get
(self)
return self.request().get()
Gets the VersionsCollectionPage Returns: :class:`VersionsCollectionPage<onedrivesdk.model.versions_collection_page.VersionsCollectionPage>`: The VersionsCollectionPage
Gets the VersionsCollectionPage
[ "Gets", "the", "VersionsCollectionPage" ]
def get(self): """Gets the VersionsCollectionPage Returns: :class:`VersionsCollectionPage<onedrivesdk.model.versions_collection_page.VersionsCollectionPage>`: The VersionsCollectionPage """ return self.request().get()
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "request", "(", ")", ".", "get", "(", ")" ]
https://github.com/OneDrive/onedrive-sdk-python/blob/e5642f8cad8eea37a4f653c1a23dfcfc06c37110/src/python2/request/versions_collection.py#L98-L105
open-io/oio-sds
16041950b6056a55d5ce7ca77795defe6dfa6c61
oio/account/server.py
python
Account._get_item_id
(self, req, key='id', what='account')
return item_id
Fetch the name of the requested item, raise an error if missing.
Fetch the name of the requested item, raise an error if missing.
[ "Fetch", "the", "name", "of", "the", "requested", "item", "raise", "an", "error", "if", "missing", "." ]
def _get_item_id(self, req, key='id', what='account'): """Fetch the name of the requested item, raise an error if missing.""" item_id = req.args.get(key) if not item_id: raise BadRequest('Missing %s ID' % what) return item_id
[ "def", "_get_item_id", "(", "self", ",", "req", ",", "key", "=", "'id'", ",", "what", "=", "'account'", ")", ":", "item_id", "=", "req", ".", "args", ".", "get", "(", "key", ")", "if", "not", "item_id", ":", "raise", "BadRequest", "(", "'Missing %s I...
https://github.com/open-io/oio-sds/blob/16041950b6056a55d5ce7ca77795defe6dfa6c61/oio/account/server.py#L123-L128
selimsef/dfdc_deepfake_challenge
89c6290490bac96b29193a4061b3db9dd3933e36
training/zoo/classifiers.py
python
DeepFakeClassifierGWAP.forward
(self, x)
return x
[]
def forward(self, x): x = self.encoder.forward_features(x) x = self.avg_pool(x).flatten(1) x = self.dropout(x) x = self.fc(x) return x
[ "def", "forward", "(", "self", ",", "x", ")", ":", "x", "=", "self", ".", "encoder", ".", "forward_features", "(", "x", ")", "x", "=", "self", ".", "avg_pool", "(", "x", ")", ".", "flatten", "(", "1", ")", "x", "=", "self", ".", "dropout", "(",...
https://github.com/selimsef/dfdc_deepfake_challenge/blob/89c6290490bac96b29193a4061b3db9dd3933e36/training/zoo/classifiers.py#L167-L172
inkandswitch/livebook
93c8d467734787366ad084fc3566bf5cbe249c51
public/pypyjs/modules/logging/handlers.py
python
SocketHandler.emit
(self, record)
Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. Pickles the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket. """ try: s = self.makePickle(record) self.send(s) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "s", "=", "self", ".", "makePickle", "(", "record", ")", "self", ".", "send", "(", "s", ")", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "except", ":", "...
https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/logging/handlers.py#L568-L583
ustayready/CredKing
68b612e4cdf01d2b65b14ab2869bb8a5531056ee
plugins/gmail/urllib3/packages/ordered_dict.py
python
OrderedDict.clear
(self)
od.clear() -> None. Remove all items from od.
od.clear() -> None. Remove all items from od.
[ "od", ".", "clear", "()", "-", ">", "None", ".", "Remove", "all", "items", "from", "od", "." ]
def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
[ "def", "clear", "(", "self", ")", ":", "try", ":", "for", "node", "in", "self", ".", "__map", ".", "itervalues", "(", ")", ":", "del", "node", "[", ":", "]", "root", "=", "self", ".", "__root", "root", "[", ":", "]", "=", "[", "root", ",", "r...
https://github.com/ustayready/CredKing/blob/68b612e4cdf01d2b65b14ab2869bb8a5531056ee/plugins/gmail/urllib3/packages/ordered_dict.py#L79-L89
rowliny/DiffHelper
ab3a96f58f9579d0023aed9ebd785f4edf26f8af
Tool/SitePackages/nltk/twitter/twitterclient.py
python
Query.register
(self, handler)
Register a method for handling Tweets. :param TweetHandlerI handler: method for viewing or writing Tweets to a file.
Register a method for handling Tweets.
[ "Register", "a", "method", "for", "handling", "Tweets", "." ]
def register(self, handler): """ Register a method for handling Tweets. :param TweetHandlerI handler: method for viewing or writing Tweets to a file. """ self.handler = handler
[ "def", "register", "(", "self", ",", "handler", ")", ":", "self", ".", "handler", "=", "handler" ]
https://github.com/rowliny/DiffHelper/blob/ab3a96f58f9579d0023aed9ebd785f4edf26f8af/Tool/SitePackages/nltk/twitter/twitterclient.py#L133-L139
benedekrozemberczki/GEMSEC
c023122bdafe88278cdbd24b7fcf9dafe8e95b34
src/calculation_helper.py
python
SecondOrderRandomWalker.get_alias_edge
(self, src, dst)
return alias_setup(normalized_probs)
Get the alias edge setup lists for a given edge.
Get the alias edge setup lists for a given edge.
[ "Get", "the", "alias", "edge", "setup", "lists", "for", "a", "given", "edge", "." ]
def get_alias_edge(self, src, dst): """ Get the alias edge setup lists for a given edge. """ G = self.G p = self.p q = self.q unnormalized_probs = [] for dst_nbr in sorted(G.neighbors(dst)): if dst_nbr == src: unnormalized_probs.append(G[dst][dst_nbr]["weight"]/p) elif G.has_edge(dst_nbr, src): unnormalized_probs.append(G[dst][dst_nbr]["weight"]) else: unnormalized_probs.append(G[dst][dst_nbr]["weight"]/q) norm_const = sum(unnormalized_probs) normalized_probs = [float(u_prob)/norm_const for u_prob in unnormalized_probs] return alias_setup(normalized_probs)
[ "def", "get_alias_edge", "(", "self", ",", "src", ",", "dst", ")", ":", "G", "=", "self", ".", "G", "p", "=", "self", ".", "p", "q", "=", "self", ".", "q", "unnormalized_probs", "=", "[", "]", "for", "dst_nbr", "in", "sorted", "(", "G", ".", "n...
https://github.com/benedekrozemberczki/GEMSEC/blob/c023122bdafe88278cdbd24b7fcf9dafe8e95b34/src/calculation_helper.py#L247-L266
cloudera/impyla
0c736af4cad2bade9b8e313badc08ec50e81c948
impala/_thrift_gen/ImpalaService/ImpalaHiveServer2Service.py
python
GetRuntimeProfile_result.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('GetRuntimeProfile_result') if self.success is not None: oprot.writeFieldBegin('success', TType.STRUCT, 0) self.success.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/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/ImpalaService/ImpalaHiveServer2Service.py#L389-L399
home-assistant/supervisor
69c2517d5211b483fdfe968b0a2b36b672ee7ab2
supervisor/dbus/agent/__init__.py
python
OSAgent.update
(self)
Update Properties.
Update Properties.
[ "Update", "Properties", "." ]
async def update(self): """Update Properties.""" self.properties = await self.dbus.get_properties(DBUS_IFACE_HAOS) await self.apparmor.update() await self.datadisk.update()
[ "async", "def", "update", "(", "self", ")", ":", "self", ".", "properties", "=", "await", "self", ".", "dbus", ".", "get_properties", "(", "DBUS_IFACE_HAOS", ")", "await", "self", ".", "apparmor", ".", "update", "(", ")", "await", "self", ".", "datadisk"...
https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/dbus/agent/__init__.py#L97-L101
quodlibet/quodlibet
e3099c89f7aa6524380795d325cc14630031886c
gdist/gettextutil.py
python
list_languages
(po_path: Path)
return sorted([os.path.basename(str(po)[:-3]) for po in po_files])
Returns a list of available language codes
Returns a list of available language codes
[ "Returns", "a", "list", "of", "available", "language", "codes" ]
def list_languages(po_path: Path) -> List[str]: """Returns a list of available language codes""" po_files = po_path.glob("*.po") return sorted([os.path.basename(str(po)[:-3]) for po in po_files])
[ "def", "list_languages", "(", "po_path", ":", "Path", ")", "->", "List", "[", "str", "]", ":", "po_files", "=", "po_path", ".", "glob", "(", "\"*.po\"", ")", "return", "sorted", "(", "[", "os", ".", "path", ".", "basename", "(", "str", "(", "po", "...
https://github.com/quodlibet/quodlibet/blob/e3099c89f7aa6524380795d325cc14630031886c/gdist/gettextutil.py#L195-L199
tensorflow/federated
5a60a032360087b8f4c7fcfd97ed1c0131c3eac3
tensorflow_federated/python/learning/reconstruction/reconstruction_utils.py
python
get_global_variables
(model: model_lib.Model)
return model_utils.ModelWeights( trainable=model.global_trainable_variables, non_trainable=model.global_non_trainable_variables)
Gets global variables from a `Model` as `ModelWeights`.
Gets global variables from a `Model` as `ModelWeights`.
[ "Gets", "global", "variables", "from", "a", "Model", "as", "ModelWeights", "." ]
def get_global_variables(model: model_lib.Model) -> model_utils.ModelWeights: """Gets global variables from a `Model` as `ModelWeights`.""" return model_utils.ModelWeights( trainable=model.global_trainable_variables, non_trainable=model.global_non_trainable_variables)
[ "def", "get_global_variables", "(", "model", ":", "model_lib", ".", "Model", ")", "->", "model_utils", ".", "ModelWeights", ":", "return", "model_utils", ".", "ModelWeights", "(", "trainable", "=", "model", ".", "global_trainable_variables", ",", "non_trainable", ...
https://github.com/tensorflow/federated/blob/5a60a032360087b8f4c7fcfd97ed1c0131c3eac3/tensorflow_federated/python/learning/reconstruction/reconstruction_utils.py#L152-L156
nlplab/brat
44ecd825810167eed2a5d8ad875d832218e734e8
server/src/projectconfig.py
python
ProjectConfiguration.get_entity_attribute_type_hierarchy
(self)
return self._get_filtered_attribute_type_hierarchy(attr_types)
Returns the attribute type hierarchy filtered to include only attributes that apply to at least one entity.
Returns the attribute type hierarchy filtered to include only attributes that apply to at least one entity.
[ "Returns", "the", "attribute", "type", "hierarchy", "filtered", "to", "include", "only", "attributes", "that", "apply", "to", "at", "least", "one", "entity", "." ]
def get_entity_attribute_type_hierarchy(self): """Returns the attribute type hierarchy filtered to include only attributes that apply to at least one entity.""" attr_types = self.attributes_for_types(self.get_entity_types()) return self._get_filtered_attribute_type_hierarchy(attr_types)
[ "def", "get_entity_attribute_type_hierarchy", "(", "self", ")", ":", "attr_types", "=", "self", ".", "attributes_for_types", "(", "self", ".", "get_entity_types", "(", ")", ")", "return", "self", ".", "_get_filtered_attribute_type_hierarchy", "(", "attr_types", ")" ]
https://github.com/nlplab/brat/blob/44ecd825810167eed2a5d8ad875d832218e734e8/server/src/projectconfig.py#L1863-L1867
Mindwerks/worldengine
64dff8eb7824ce46b5b6cb8006bcef21822ef144
worldengine/model/world.py
python
World.is_temperature_cool
(self, pos)
return th_max > t >= th_min
[]
def is_temperature_cool(self, pos): th_min = self.layers['temperature'].thresholds[2][1] th_max = self.layers['temperature'].thresholds[3][1] x, y = pos t = self.layers['temperature'].data[y, x] return th_max > t >= th_min
[ "def", "is_temperature_cool", "(", "self", ",", "pos", ")", ":", "th_min", "=", "self", ".", "layers", "[", "'temperature'", "]", ".", "thresholds", "[", "2", "]", "[", "1", "]", "th_max", "=", "self", ".", "layers", "[", "'temperature'", "]", ".", "...
https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/model/world.py#L530-L535
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/class/oc_adm_registry.py
python
Registry.service
(self, config)
setter for service property
setter for service property
[ "setter", "for", "service", "property" ]
def service(self, config): ''' setter for service property ''' self.svc = config
[ "def", "service", "(", "self", ",", "config", ")", ":", "self", ".", "svc", "=", "config" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/src/class/oc_adm_registry.py#L81-L83
4shadoww/hakkuframework
409a11fc3819d251f86faa3473439f8c19066a21
lib/packaging/specifiers.py
python
BaseSpecifier.prereleases
(self, value: bool)
Sets whether or not pre-releases as a whole are allowed by this specifier.
Sets whether or not pre-releases as a whole are allowed by this specifier.
[ "Sets", "whether", "or", "not", "pre", "-", "releases", "as", "a", "whole", "are", "allowed", "by", "this", "specifier", "." ]
def prereleases(self, value: bool) -> None: """ Sets whether or not pre-releases as a whole are allowed by this specifier. """
[ "def", "prereleases", "(", "self", ",", "value", ":", "bool", ")", "->", "None", ":" ]
https://github.com/4shadoww/hakkuframework/blob/409a11fc3819d251f86faa3473439f8c19066a21/lib/packaging/specifiers.py#L75-L79
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
server/lib/server.py
python
ClientCommunication._checkMsgRegManagerDict
(self, manager: Dict[str, Any], messageType: str)
return True
Internal function to check sanity of the registration manager dictionary. :param manager: :param messageType: :return:
Internal function to check sanity of the registration manager dictionary.
[ "Internal", "function", "to", "check", "sanity", "of", "the", "registration", "manager", "dictionary", "." ]
def _checkMsgRegManagerDict(self, manager: Dict[str, Any], messageType: str) -> bool: """ Internal function to check sanity of the registration manager dictionary. :param manager: :param messageType: :return: """ isCorrect = True if not isinstance(manager, dict): isCorrect = False else: if "description" not in manager.keys(): isCorrect = False elif not self._checkMsgDescription(manager["description"], messageType): isCorrect = False if not isCorrect: # send error message back try: message = {"message": messageType, "error": "manager dictionary not valid"} self._send(json.dumps(message)) except Exception as e: pass return False return True
[ "def", "_checkMsgRegManagerDict", "(", "self", ",", "manager", ":", "Dict", "[", "str", ",", "Any", "]", ",", "messageType", ":", "str", ")", "->", "bool", ":", "isCorrect", "=", "True", "if", "not", "isinstance", "(", "manager", ",", "dict", ")", ":",...
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/server/lib/server.py#L607-L642
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/number_field/number_field_ideal_rel.py
python
NumberFieldFractionalIdeal_rel.pari_rhnf
(self)
Return PARI's representation of this relative ideal in Hermite normal form. EXAMPLES:: sage: K.<a, b> = NumberField([x^2 + 23, x^2 - 7]) sage: I = K.ideal(2, (a + 2*b + 3)/2) sage: I.pari_rhnf() [[1, -2; 0, 1], [[2, 1; 0, 1], 1/2]]
Return PARI's representation of this relative ideal in Hermite normal form.
[ "Return", "PARI", "s", "representation", "of", "this", "relative", "ideal", "in", "Hermite", "normal", "form", "." ]
def pari_rhnf(self): """ Return PARI's representation of this relative ideal in Hermite normal form. EXAMPLES:: sage: K.<a, b> = NumberField([x^2 + 23, x^2 - 7]) sage: I = K.ideal(2, (a + 2*b + 3)/2) sage: I.pari_rhnf() [[1, -2; 0, 1], [[2, 1; 0, 1], 1/2]] """ try: return self.__pari_rhnf except AttributeError: nfzk = self.number_field().pari_nf().nf_subst('x').nf_get_zk() rnf = self.number_field().pari_rnf() L_hnf = self.absolute_ideal().pari_hnf() self.__pari_rhnf = rnf.rnfidealabstorel(nfzk * L_hnf) return self.__pari_rhnf
[ "def", "pari_rhnf", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__pari_rhnf", "except", "AttributeError", ":", "nfzk", "=", "self", ".", "number_field", "(", ")", ".", "pari_nf", "(", ")", ".", "nf_subst", "(", "'x'", ")", ".", "nf_get_z...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/number_field/number_field_ideal_rel.py#L111-L130
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/celery/app/backends.py
python
by_url
(backend=None, loader=None)
return by_name(backend, loader), url
Get backend class by URL.
Get backend class by URL.
[ "Get", "backend", "class", "by", "URL", "." ]
def by_url(backend=None, loader=None): """Get backend class by URL.""" url = None if backend and '://' in backend: url = backend scheme, _, _ = url.partition('://') if '+' in scheme: backend, url = url.split('+', 1) else: backend = scheme return by_name(backend, loader), url
[ "def", "by_url", "(", "backend", "=", "None", ",", "loader", "=", "None", ")", ":", "url", "=", "None", "if", "backend", "and", "'://'", "in", "backend", ":", "url", "=", "backend", "scheme", ",", "_", ",", "_", "=", "url", ".", "partition", "(", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/celery/app/backends.py#L55-L65
sabri-zaki/EasY_HaCk
2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9
.modules/.metagoofil/hachoir_parser/program/java.py
python
CPIndex.__init__
(self, parent, name, description=None, target_types=None, target_text_handler=(lambda x: x), allow_zero=False)
Initialize a CPIndex. - target_type is the tuple of expected type for the target CPInfo (if None, then there will be no type check) - target_text_handler is a string transformation function used for pretty printing the target str() result - allow_zero states whether null index is allowed (sometimes, constant pool index is optionnal)
Initialize a CPIndex. - target_type is the tuple of expected type for the target CPInfo (if None, then there will be no type check) - target_text_handler is a string transformation function used for pretty printing the target str() result - allow_zero states whether null index is allowed (sometimes, constant pool index is optionnal)
[ "Initialize", "a", "CPIndex", ".", "-", "target_type", "is", "the", "tuple", "of", "expected", "type", "for", "the", "target", "CPInfo", "(", "if", "None", "then", "there", "will", "be", "no", "type", "check", ")", "-", "target_text_handler", "is", "a", ...
def __init__(self, parent, name, description=None, target_types=None, target_text_handler=(lambda x: x), allow_zero=False): """ Initialize a CPIndex. - target_type is the tuple of expected type for the target CPInfo (if None, then there will be no type check) - target_text_handler is a string transformation function used for pretty printing the target str() result - allow_zero states whether null index is allowed (sometimes, constant pool index is optionnal) """ UInt16.__init__(self, parent, name, description) if isinstance(target_types, str): self.target_types = (target_types,) else: self.target_types = target_types self.allow_zero = allow_zero self.target_text_handler = target_text_handler self.getOriginalDisplay = lambda: self.value
[ "def", "__init__", "(", "self", ",", "parent", ",", "name", ",", "description", "=", "None", ",", "target_types", "=", "None", ",", "target_text_handler", "=", "(", "lambda", "x", ":", "x", ")", ",", "allow_zero", "=", "False", ")", ":", "UInt16", ".",...
https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.metagoofil/hachoir_parser/program/java.py#L216-L234
SCSSoftware/BlenderTools
96f323d3bdf2d8cb8ed7f882dcdf036277a802dd
addon/io_scs_tools/utils/mesh.py
python
make_points_to_weld_list
(mesh_vertices, mesh_normals, mesh_rgb, mesh_rgba, equal_decimals_count)
return verts_map
Makes a map of duplicated vertices indices into it's original counter part.
Makes a map of duplicated vertices indices into it's original counter part.
[ "Makes", "a", "map", "of", "duplicated", "vertices", "indices", "into", "it", "s", "original", "counter", "part", "." ]
def make_points_to_weld_list(mesh_vertices, mesh_normals, mesh_rgb, mesh_rgba, equal_decimals_count): """Makes a map of duplicated vertices indices into it's original counter part.""" # take first present vertex color data if mesh_rgb: mesh_final_rgba = mesh_rgb elif mesh_rgba: mesh_final_rgba = mesh_rgba else: mesh_final_rgba = {} posnorm_dict_tmp = {} perc = 10 ** equal_decimals_count # represent precision for duplicates for val_i, val in enumerate(mesh_vertices): key = (str(int(val[0] * perc)) + str(int(val[1] * perc)) + str(int(val[2] * perc)) + str(int(mesh_normals[val_i][0] * perc)) + str(int(mesh_normals[val_i][1] * perc)) + str(int(mesh_normals[val_i][2] * perc))) # also include vertex colors in key if present for vc_layer_name in mesh_final_rgba: for col_channel in mesh_final_rgba[vc_layer_name][val_i]: key += str(int(col_channel * perc)) if key not in posnorm_dict_tmp: posnorm_dict_tmp[key] = [val_i] else: posnorm_dict_tmp[key].append(val_i) # create map for quick access to original vertex index via double vertex indices: (key: double vert index; value: original vert index) verts_map = {} for indices in posnorm_dict_tmp.values(): # ignore entry if only one vertex was added to it (means there was no duplicates for it) if len(indices) <= 1: continue for idx in indices[1:]: verts_map[idx] = indices[0] # fist index is original, rest are duplicates return verts_map
[ "def", "make_points_to_weld_list", "(", "mesh_vertices", ",", "mesh_normals", ",", "mesh_rgb", ",", "mesh_rgba", ",", "equal_decimals_count", ")", ":", "# take first present vertex color data", "if", "mesh_rgb", ":", "mesh_final_rgba", "=", "mesh_rgb", "elif", "mesh_rgba"...
https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/utils/mesh.py#L115-L153
blampe/IbPy
cba912d2ecc669b0bf2980357ea7942e49c0825e
ib/ext/AnyWrapper.py
python
AnyWrapper.connectionClosed
(self)
generated source for method connectionClosed
generated source for method connectionClosed
[ "generated", "source", "for", "method", "connectionClosed" ]
def connectionClosed(self): """ generated source for method connectionClosed """
[ "def", "connectionClosed", "(", "self", ")", ":" ]
https://github.com/blampe/IbPy/blob/cba912d2ecc669b0bf2980357ea7942e49c0825e/ib/ext/AnyWrapper.py#L35-L36
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/backends/base/operations.py
python
BaseSpatialOperations.check_expression_support
(self, expression)
[]
def check_expression_support(self, expression): if isinstance(expression, self.disallowed_aggregates): raise NotImplementedError( "%s spatial aggregation is not supported by this database backend." % expression.name ) super(BaseSpatialOperations, self).check_expression_support(expression)
[ "def", "check_expression_support", "(", "self", ",", "expression", ")", ":", "if", "isinstance", "(", "expression", ",", "self", ".", "disallowed_aggregates", ")", ":", "raise", "NotImplementedError", "(", "\"%s spatial aggregation is not supported by this database backend....
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/contrib/gis/db/backends/base/operations.py#L117-L122
archlinux/archweb
19e5da892ef2af7bf045576f8114c256589e16c4
packages/utils.py
python
Difference.__key
(self)
return (self.pkgname, hash(self.repo), hash(self.pkg_a), hash(self.pkg_b))
[]
def __key(self): return (self.pkgname, hash(self.repo), hash(self.pkg_a), hash(self.pkg_b))
[ "def", "__key", "(", "self", ")", ":", "return", "(", "self", ".", "pkgname", ",", "hash", "(", "self", ".", "repo", ")", ",", "hash", "(", "self", ".", "pkg_a", ")", ",", "hash", "(", "self", ".", "pkg_b", ")", ")" ]
https://github.com/archlinux/archweb/blob/19e5da892ef2af7bf045576f8114c256589e16c4/packages/utils.py#L113-L115
ruiminshen/yolo-tf
eae65c8071fe5069f5e3bb1e26f19a761b1b68bc
utils/__init__.py
python
get_logdir
(config)
return os.path.join(basedir, model, inference, name)
[]
def get_logdir(config): basedir = os.path.expanduser(os.path.expandvars(config.get('config', 'basedir'))) model = config.get('config', 'model') inference = config.get(model, 'inference') name = os.path.basename(config.get('cache', 'names')) return os.path.join(basedir, model, inference, name)
[ "def", "get_logdir", "(", "config", ")", ":", "basedir", "=", "os", ".", "path", ".", "expanduser", "(", "os", ".", "path", ".", "expandvars", "(", "config", ".", "get", "(", "'config'", ",", "'basedir'", ")", ")", ")", "model", "=", "config", ".", ...
https://github.com/ruiminshen/yolo-tf/blob/eae65c8071fe5069f5e3bb1e26f19a761b1b68bc/utils/__init__.py#L34-L39
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-0.96/django/utils/itercompat.py
python
compat_tee
(iterable)
return gen(next), gen(next)
Return two independent iterators from a single iterable. Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html
Return two independent iterators from a single iterable.
[ "Return", "two", "independent", "iterators", "from", "a", "single", "iterable", "." ]
def compat_tee(iterable): """Return two independent iterators from a single iterable. Based on http://www.python.org/doc/2.3.5/lib/itertools-example.html """ # Note: Using a dictionary and a list as the default arguments here is # deliberate and safe in this instance. def gen(next, data={}, cnt=[0]): dpop = data.pop for i in itertools.count(): if i == cnt[0]: item = data[i] = next() cnt[0] += 1 else: item = dpop(i) yield item next = iter(iterable).next return gen(next), gen(next)
[ "def", "compat_tee", "(", "iterable", ")", ":", "# Note: Using a dictionary and a list as the default arguments here is", "# deliberate and safe in this instance.", "def", "gen", "(", "next", ",", "data", "=", "{", "}", ",", "cnt", "=", "[", "0", "]", ")", ":", "dpo...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-0.96/django/utils/itercompat.py#L9-L26
Kozea/cairocffi
2473d1bb82a52ca781edec595a95951509db2969
cairocffi/context.py
python
Context.line_to
(self, x, y)
Adds a line to the path from the current point to position ``(x, y)`` in user-space coordinates. After this call the current point will be ``(x, y)``. If there is no current point before the call to :meth:`line_to` this method will behave as ``context.move_to(x, y)``. :param x: X coordinate of the end of the new line. :param y: Y coordinate of the end of the new line. :type float: x :type float: y
Adds a line to the path from the current point to position ``(x, y)`` in user-space coordinates. After this call the current point will be ``(x, y)``.
[ "Adds", "a", "line", "to", "the", "path", "from", "the", "current", "point", "to", "position", "(", "x", "y", ")", "in", "user", "-", "space", "coordinates", ".", "After", "this", "call", "the", "current", "point", "will", "be", "(", "x", "y", ")", ...
def line_to(self, x, y): """Adds a line to the path from the current point to position ``(x, y)`` in user-space coordinates. After this call the current point will be ``(x, y)``. If there is no current point before the call to :meth:`line_to` this method will behave as ``context.move_to(x, y)``. :param x: X coordinate of the end of the new line. :param y: Y coordinate of the end of the new line. :type float: x :type float: y """ cairo.cairo_line_to(self._pointer, x, y) self._check_status()
[ "def", "line_to", "(", "self", ",", "x", ",", "y", ")", ":", "cairo", ".", "cairo_line_to", "(", "self", ".", "_pointer", ",", "x", ",", "y", ")", "self", ".", "_check_status", "(", ")" ]
https://github.com/Kozea/cairocffi/blob/2473d1bb82a52ca781edec595a95951509db2969/cairocffi/context.py#L959-L974
mediacloud/backend
d36b489e4fbe6e44950916a04d9543a1d6cd5df0
apps/crawler-fetcher/src/python/crawler_fetcher/handlers/feed_univision.py
python
DownloadFeedUnivisionHandler._get_stories_from_univision_feed
(cls, content: str, media_id: int)
return stories
Parse the feed. Return a (non-db-backed) story dict for each story found in the feed.
Parse the feed. Return a (non-db-backed) story dict for each story found in the feed.
[ "Parse", "the", "feed", ".", "Return", "a", "(", "non", "-", "db", "-", "backed", ")", "story", "dict", "for", "each", "story", "found", "in", "the", "feed", "." ]
def _get_stories_from_univision_feed(cls, content: str, media_id: int) -> List[Dict[str, Any]]: """Parse the feed. Return a (non-db-backed) story dict for each story found in the feed.""" content = decode_object_from_bytes_if_needed(content) if isinstance(media_id, bytes): media_id = decode_object_from_bytes_if_needed(media_id) media_id = int(media_id) if not content: raise McCrawlerFetcherSoftError("Feed content is empty or undefined.") try: feed_json = decode_json(content) except Exception as ex: raise McCrawlerFetcherSoftError(f"Unable to decode Univision feed JSON: {ex}") try: # Intentionally raise exception on KeyError: if not feed_json['status'] == 'success': raise McCrawlerFetcherSoftError(f"Univision feed response is not 'success': {content}") except Exception as ex: raise McCrawlerFetcherSoftError(f"Unable to verify Univision feed status: {ex}") try: # Intentionally raise exception on KeyError: feed_items = feed_json.get('data', None).get('items', None) except Exception as ex: raise McCrawlerFetcherSoftError(f"Univision feed response does not have 'data'/'items' key: {ex}") stories = [] for item in feed_items: url = item.get('url', None) if not url: # Some items in the feed don't have their URLs set log.warning(f"'url' for item is not set: {item}") continue # sic -- we take "uid" (without "g") and call it "guid" (with "g") guid = item.get('uid', None) if not guid: raise McCrawlerFetcherSoftError(f"Item does not have its 'uid' set: {item}") title = item.get('title', '(no title)') description = item.get('description', '') try: # Intentionally raise exception on KeyError: str_publish_date = item['publishDate'] publish_timestamp = str2time_21st_century(str_publish_date) publish_date = get_sql_date_from_epoch(publish_timestamp) except Exception as ex: # Die for good because Univision's dates should be pretty predictable raise McCrawlerFetcherSoftError(f"Unable to parse item's {item} publish date: {ex}") log.debug(f"Story found in Univision feed: URL '{url}', title '{title}', publish date '{publish_date}'") stories.append({ 'url': url, 'guid': guid, 'media_id': media_id, 'publish_date': publish_date, 'title': title, 'description': description, }) return stories
[ "def", "_get_stories_from_univision_feed", "(", "cls", ",", "content", ":", "str", ",", "media_id", ":", "int", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "content", "=", "decode_object_from_bytes_if_needed", "(", "content", ")", ...
https://github.com/mediacloud/backend/blob/d36b489e4fbe6e44950916a04d9543a1d6cd5df0/apps/crawler-fetcher/src/python/crawler_fetcher/handlers/feed_univision.py#L123-L188
windelbouwman/ppci
915c069e0667042c085ec42c78e9e3c9a5295324
ppci/lang/c/parser.py
python
CParser.parse_asm_operands
(self)
return operands
Parse a series of assembly operands. Empty list is allowed.
Parse a series of assembly operands. Empty list is allowed.
[ "Parse", "a", "series", "of", "assembly", "operands", ".", "Empty", "list", "is", "allowed", "." ]
def parse_asm_operands(self): """ Parse a series of assembly operands. Empty list is allowed. """ operands = [] if self.has_consumed(":"): if self.peek not in [")", ":"]: operand = self.parse_asm_operand() operands.append(operand) while self.has_consumed(","): operand = self.parse_asm_operand() operands.append(operand) return operands
[ "def", "parse_asm_operands", "(", "self", ")", ":", "operands", "=", "[", "]", "if", "self", ".", "has_consumed", "(", "\":\"", ")", ":", "if", "self", ".", "peek", "not", "in", "[", "\")\"", ",", "\":\"", "]", ":", "operand", "=", "self", ".", "pa...
https://github.com/windelbouwman/ppci/blob/915c069e0667042c085ec42c78e9e3c9a5295324/ppci/lang/c/parser.py#L1014-L1024
pyg-team/pytorch_geometric
b920e9a3a64e22c8356be55301c88444ff051cae
torch_geometric/nn/conv/point_transformer_conv.py
python
PointTransformerConv.__init__
(self, in_channels: Union[int, Tuple[int, int]], out_channels: int, pos_nn: Optional[Callable] = None, attn_nn: Optional[Callable] = None, add_self_loops: bool = True, **kwargs)
[]
def __init__(self, in_channels: Union[int, Tuple[int, int]], out_channels: int, pos_nn: Optional[Callable] = None, attn_nn: Optional[Callable] = None, add_self_loops: bool = True, **kwargs): kwargs.setdefault('aggr', 'mean') super().__init__(**kwargs) self.in_channels = in_channels self.out_channels = out_channels self.add_self_loops = add_self_loops if isinstance(in_channels, int): in_channels = (in_channels, in_channels) self.pos_nn = pos_nn if self.pos_nn is None: self.pos_nn = Linear(3, out_channels) self.attn_nn = attn_nn self.lin = Linear(in_channels[0], out_channels, bias=False) self.lin_src = Linear(in_channels[0], out_channels, bias=False) self.lin_dst = Linear(in_channels[1], out_channels, bias=False) self.reset_parameters()
[ "def", "__init__", "(", "self", ",", "in_channels", ":", "Union", "[", "int", ",", "Tuple", "[", "int", ",", "int", "]", "]", ",", "out_channels", ":", "int", ",", "pos_nn", ":", "Optional", "[", "Callable", "]", "=", "None", ",", "attn_nn", ":", "...
https://github.com/pyg-team/pytorch_geometric/blob/b920e9a3a64e22c8356be55301c88444ff051cae/torch_geometric/nn/conv/point_transformer_conv.py#L73-L96
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py-rest/gluon/contrib/simplejson/encoder.py
python
encode_basestring
(s)
return u'"' + ESCAPE.sub(replace, s) + u'"'
Return a JSON representation of a Python string
Return a JSON representation of a Python string
[ "Return", "a", "JSON", "representation", "of", "a", "Python", "string" ]
def encode_basestring(s): """Return a JSON representation of a Python string """ if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): return ESCAPE_DCT[match.group(0)] return u'"' + ESCAPE.sub(replace, s) + u'"'
[ "def", "encode_basestring", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "str", ")", "and", "HAS_UTF8", ".", "search", "(", "s", ")", "is", "not", "None", ":", "s", "=", "s", ".", "decode", "(", "'utf-8'", ")", "def", "replace", "(", "m...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/gluon/contrib/simplejson/encoder.py#L35-L43
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/quantum/quantum/openstack/common/rpc/amqp.py
python
MulticallWaiter.__call__
(self, data)
The consume() callback will call this. Store the result.
The consume() callback will call this. Store the result.
[ "The", "consume", "()", "callback", "will", "call", "this", ".", "Store", "the", "result", "." ]
def __call__(self, data): """The consume() callback will call this. Store the result.""" self.msg_id_cache.check_duplicate_message(data) if data['failure']: failure = data['failure'] self._result = rpc_common.deserialize_remote_exception(self._conf, failure) elif data.get('ending', False): self._got_ending = True else: self._result = data['result']
[ "def", "__call__", "(", "self", ",", "data", ")", ":", "self", ".", "msg_id_cache", ".", "check_duplicate_message", "(", "data", ")", "if", "data", "[", "'failure'", "]", ":", "failure", "=", "data", "[", "'failure'", "]", "self", ".", "_result", "=", ...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/quantum/quantum/openstack/common/rpc/amqp.py#L533-L544
google/mysql-tools
02d18542735a528c4a6cca951207393383266bb9
parser_lib/validator.py
python
OnlyIfDescendedFrom
(tag_names)
return CalledOncePerDefinition
Decorator that only executes this visitor if we have the named ancestor. If one of the specified parent tag names is in the tree above us, run the decorated function. Otherwise, continue down the tree by using the default visitor, as if the decorated function didn't exist.
Decorator that only executes this visitor if we have the named ancestor.
[ "Decorator", "that", "only", "executes", "this", "visitor", "if", "we", "have", "the", "named", "ancestor", "." ]
def OnlyIfDescendedFrom(tag_names): """Decorator that only executes this visitor if we have the named ancestor. If one of the specified parent tag names is in the tree above us, run the decorated function. Otherwise, continue down the tree by using the default visitor, as if the decorated function didn't exist. """ def CalledOncePerDefinition(func): def CalledOncePerInvocation(self, *args, **kwargs): if self.IsDescendedFrom(tag_names): return func(self, *args, **kwargs) else: return self.visit(*args, **kwargs) return CalledOncePerInvocation return CalledOncePerDefinition
[ "def", "OnlyIfDescendedFrom", "(", "tag_names", ")", ":", "def", "CalledOncePerDefinition", "(", "func", ")", ":", "def", "CalledOncePerInvocation", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "IsDescendedFrom", "(", ...
https://github.com/google/mysql-tools/blob/02d18542735a528c4a6cca951207393383266bb9/parser_lib/validator.py#L62-L76