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
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/sprite.py
python
Sprite._from_radians
(self, new_value: float)
Converts a radian value into degrees and stores it into angle.
Converts a radian value into degrees and stores it into angle.
[ "Converts", "a", "radian", "value", "into", "degrees", "and", "stores", "it", "into", "angle", "." ]
def _from_radians(self, new_value: float): """ Converts a radian value into degrees and stores it into angle. """ self.angle = new_value * 180.0 / math.pi
[ "def", "_from_radians", "(", "self", ",", "new_value", ":", "float", ")", ":", "self", ".", "angle", "=", "new_value", "*", "180.0", "/", "math", ".", "pi" ]
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/sprite.py#L725-L729
scikit-learn/scikit-learn
1d1aadd0711b87d2a11c80aad15df6f8cf156712
sklearn/feature_selection/_base.py
python
SelectorMixin._get_support_mask
(self)
Get the boolean mask indicating which features are selected Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention.
Get the boolean mask indicating which features are selected
[ "Get", "the", "boolean", "mask", "indicating", "which", "features", "are", "selected" ]
def _get_support_mask(self): """ Get the boolean mask indicating which features are selected Returns ------- support : boolean array of shape [# input features] An element is True iff its corresponding feature is selected for retention. """
[ "def", "_get_support_mask", "(", "self", ")", ":" ]
https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/feature_selection/_base.py#L57-L66
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/pdb.py
python
Pdb.do_alias
(self, arg)
alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed. Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You *can* override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. As an example, here are two useful aliases (especially when placed in the .pdbrc file): # Print instance variables (usage "pi classInst") alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) # Print instance variables in self alias ps pi self
alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed.
[ "alias", "[", "name", "[", "command", "[", "parameter", "parameter", "...", "]", "]]", "Create", "an", "alias", "called", "name", "that", "executes", "command", ".", "The", "command", "must", "*", "not", "*", "be", "enclosed", "in", "quotes", ".", "Repla...
def do_alias(self, arg): """alias [name [command [parameter parameter ...] ]] Create an alias called 'name' that executes 'command'. The command must *not* be enclosed in quotes. Replaceable parameters can be indicated by %1, %2, and so on, while %* is replaced by all the parameters. If no command is given, the current alias for name is shown. If no name is given, all aliases are listed. Aliases may be nested and can contain anything that can be legally typed at the pdb prompt. Note! You *can* override internal pdb commands with aliases! Those internal commands are then hidden until the alias is removed. Aliasing is recursively applied to the first word of the command line; all other words in the line are left alone. As an example, here are two useful aliases (especially when placed in the .pdbrc file): # Print instance variables (usage "pi classInst") alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) # Print instance variables in self alias ps pi self """ args = arg.split() if len(args) == 0: keys = sorted(self.aliases.keys()) for alias in keys: self.message("%s = %s" % (alias, self.aliases[alias])) return if args[0] in self.aliases and len(args) == 1: self.message("%s = %s" % (args[0], self.aliases[args[0]])) else: self.aliases[args[0]] = ' '.join(args[1:])
[ "def", "do_alias", "(", "self", ",", "arg", ")", ":", "args", "=", "arg", ".", "split", "(", ")", "if", "len", "(", "args", ")", "==", "0", ":", "keys", "=", "sorted", "(", "self", ".", "aliases", ".", "keys", "(", ")", ")", "for", "alias", "...
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/pdb.py#L1374-L1407
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/modules/ejabberd_user.py
python
EjabberdUser.run_command
(self, cmd, options)
return self.module.run_command(cmd)
This method will run the any command specified and return the returns using the Ansible common module
This method will run the any command specified and return the returns using the Ansible common module
[ "This", "method", "will", "run", "the", "any", "command", "specified", "and", "return", "the", "returns", "using", "the", "Ansible", "common", "module" ]
def run_command(self, cmd, options): """ This method will run the any command specified and return the returns using the Ansible common module """ cmd = [self.module.get_bin_path('ejabberdctl'), cmd] + options self.log('command: %s' % " ".join(cmd)) return self.module.run_command(cmd)
[ "def", "run_command", "(", "self", ",", "cmd", ",", "options", ")", ":", "cmd", "=", "[", "self", ".", "module", ".", "get_bin_path", "(", "'ejabberdctl'", ")", ",", "cmd", "]", "+", "options", "self", ".", "log", "(", "'command: %s'", "%", "\" \"", ...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/modules/ejabberd_user.py#L113-L119
NeuralEnsemble/python-neo
34d4db8fb0dc950dbbc6defd7fb75e99ea877286
neo/rawio/baserawio.py
python
BaseRawIO.channel_name_to_index
(self, stream_index, channel_names)
return channel_indexes
Inside a stream, transform channel_names to channel_indexes. Based on self.header['signal_channels'] channel_indexes are zero-based offsets within the stream
Inside a stream, transform channel_names to channel_indexes. Based on self.header['signal_channels'] channel_indexes are zero-based offsets within the stream
[ "Inside", "a", "stream", "transform", "channel_names", "to", "channel_indexes", ".", "Based", "on", "self", ".", "header", "[", "signal_channels", "]", "channel_indexes", "are", "zero", "-", "based", "offsets", "within", "the", "stream" ]
def channel_name_to_index(self, stream_index, channel_names): """ Inside a stream, transform channel_names to channel_indexes. Based on self.header['signal_channels'] channel_indexes are zero-based offsets within the stream """ stream_id = self.header['signal_streams'][stream_index]['id'] mask = self.header['signal_channels']['stream_id'] == stream_id signal_channels = self.header['signal_channels'][mask] chan_names = list(signal_channels['name']) assert signal_channels.size == np.unique(chan_names).size, 'Channel names not unique' channel_indexes = np.array([chan_names.index(name) for name in channel_names]) return channel_indexes
[ "def", "channel_name_to_index", "(", "self", ",", "stream_index", ",", "channel_names", ")", ":", "stream_id", "=", "self", ".", "header", "[", "'signal_streams'", "]", "[", "stream_index", "]", "[", "'id'", "]", "mask", "=", "self", ".", "header", "[", "'...
https://github.com/NeuralEnsemble/python-neo/blob/34d4db8fb0dc950dbbc6defd7fb75e99ea877286/neo/rawio/baserawio.py#L455-L467
ycszen/TorchSeg
62eeb159aee77972048d9d7688a28249d3c56735
model/bisenet/cityscapes.bisenet.X39/network.py
python
BiSeNetHead.__init__
(self, in_planes, out_planes, scale, is_aux=False, norm_layer=nn.BatchNorm2d)
[]
def __init__(self, in_planes, out_planes, scale, is_aux=False, norm_layer=nn.BatchNorm2d): super(BiSeNetHead, self).__init__() if is_aux: self.conv_3x3 = ConvBnRelu(in_planes, 128, 3, 1, 1, has_bn=True, norm_layer=norm_layer, has_relu=True, has_bias=False) else: self.conv_3x3 = ConvBnRelu(in_planes, 64, 3, 1, 1, has_bn=True, norm_layer=norm_layer, has_relu=True, has_bias=False) # self.dropout = nn.Dropout(0.1) if is_aux: self.conv_1x1 = nn.Conv2d(128, out_planes, kernel_size=1, stride=1, padding=0) else: self.conv_1x1 = nn.Conv2d(64, out_planes, kernel_size=1, stride=1, padding=0) self.scale = scale
[ "def", "__init__", "(", "self", ",", "in_planes", ",", "out_planes", ",", "scale", ",", "is_aux", "=", "False", ",", "norm_layer", "=", "nn", ".", "BatchNorm2d", ")", ":", "super", "(", "BiSeNetHead", ",", "self", ")", ".", "__init__", "(", ")", "if", ...
https://github.com/ycszen/TorchSeg/blob/62eeb159aee77972048d9d7688a28249d3c56735/model/bisenet/cityscapes.bisenet.X39/network.py#L139-L157
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/protos/untrusted_runner_pb2_grpc.py
python
UntrustedRunnerServicer.RunAndWait
(self, request, context)
Run command using new_process.ProcessRunner
Run command using new_process.ProcessRunner
[ "Run", "command", "using", "new_process", ".", "ProcessRunner" ]
def RunAndWait(self, request, context): """Run command using new_process.ProcessRunner """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
[ "def", "RunAndWait", "(", "self", ",", "request", ",", "context", ")", ":", "context", ".", "set_code", "(", "grpc", ".", "StatusCode", ".", "UNIMPLEMENTED", ")", "context", ".", "set_details", "(", "'Method not implemented!'", ")", "raise", "NotImplementedError...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/protos/untrusted_runner_pb2_grpc.py#L159-L164
pyparsing/pyparsing
1ccf846394a055924b810faaf9628dac53633848
pyparsing/core.py
python
ParserElement.split
( self, instring: str, maxsplit: int = _MAX_INT, include_separators: bool = False, *, includeSeparators=False, )
Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``include_separators`` argument (default= ``False``), if the separating matching text should be included in the split results. Example:: punc = one_of(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``include_separators`` argument (default= ``False``), if the separating matching text should be included in the split results.
[ "Generator", "method", "to", "split", "a", "string", "using", "the", "given", "expression", "as", "a", "separator", ".", "May", "be", "called", "with", "optional", "maxsplit", "argument", "to", "limit", "the", "number", "of", "splits", ";", "and", "the", "...
def split( self, instring: str, maxsplit: int = _MAX_INT, include_separators: bool = False, *, includeSeparators=False, ) -> Generator[str, None, None]: """ Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``include_separators`` argument (default= ``False``), if the separating matching text should be included in the split results. Example:: punc = one_of(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] """ includeSeparators = includeSeparators or include_separators last = 0 for t, s, e in self.scan_string(instring, max_matches=maxsplit): yield instring[last:s] if includeSeparators: yield t[0] last = e yield instring[last:]
[ "def", "split", "(", "self", ",", "instring", ":", "str", ",", "maxsplit", ":", "int", "=", "_MAX_INT", ",", "include_separators", ":", "bool", "=", "False", ",", "*", ",", "includeSeparators", "=", "False", ",", ")", "->", "Generator", "[", "str", ","...
https://github.com/pyparsing/pyparsing/blob/1ccf846394a055924b810faaf9628dac53633848/pyparsing/core.py#L1313-L1343
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cpython/randomimpl.py
python
poisson_impl
(context, builder, sig, args)
return impl_ret_untracked(context, builder, sig.return_type, res)
[]
def poisson_impl(context, builder, sig, args): state_ptr = get_np_state_ptr(context, builder) retptr = cgutils.alloca_once(builder, int64_t, name="ret") bbcont = builder.append_basic_block("bbcont") bbend = builder.append_basic_block("bbend") if len(args) == 1: lam, = args big_lam = builder.fcmp_ordered('>=', lam, ir.Constant(double, 10.0)) with builder.if_then(big_lam): # For lambda >= 10.0, we switch to a more accurate # algorithm (see _random.c). fnty = ir.FunctionType(int64_t, (rnd_state_ptr_t, double)) fn = cgutils.get_or_insert_function(builder.function.module, fnty, "numba_poisson_ptrs") ret = builder.call(fn, (state_ptr, lam)) builder.store(ret, retptr) builder.branch(bbend) builder.branch(bbcont) builder.position_at_end(bbcont) _random = np.random.random _exp = math.exp def poisson_impl(lam): """Numpy's algorithm for poisson() on small *lam*. This method is invoked only if the parameter lambda of the distribution is small ( < 10 ). The algorithm used is described in "Knuth, D. 1969. 'Seminumerical Algorithms. The Art of Computer Programming' vol 2. """ if lam < 0.0: raise ValueError("poisson(): lambda < 0") if lam == 0.0: return 0 enlam = _exp(-lam) X = 0 prod = 1.0 while 1: U = _random() prod *= U if prod <= enlam: return X X += 1 if len(args) == 0: sig = signature(sig.return_type, types.float64) args = (ir.Constant(double, 1.0),) ret = context.compile_internal(builder, poisson_impl, sig, args) builder.store(ret, retptr) builder.branch(bbend) builder.position_at_end(bbend) res = builder.load(retptr) return impl_ret_untracked(context, builder, sig.return_type, res)
[ "def", "poisson_impl", "(", "context", ",", "builder", ",", "sig", ",", "args", ")", ":", "state_ptr", "=", "get_np_state_ptr", "(", "context", ",", "builder", ")", "retptr", "=", "cgutils", ".", "alloca_once", "(", "builder", ",", "int64_t", ",", "name", ...
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cpython/randomimpl.py#L1048-L1105
stacked-git/stgit
8254ffb2eee53f97e9c6210078db55c15340ead3
stgit/out.py
python
MessagePrinter.start
(self, msg)
Start a long-running operation.
Start a long-running operation.
[ "Start", "a", "long", "-", "running", "operation", "." ]
def start(self, msg): """Start a long-running operation.""" self._stderr.single_line('%s ... ' % msg, print_newline=False) self._stderr.level += 1
[ "def", "start", "(", "self", ",", "msg", ")", ":", "self", ".", "_stderr", ".", "single_line", "(", "'%s ... '", "%", "msg", ",", "print_newline", "=", "False", ")", "self", ".", "_stderr", ".", "level", "+=", "1" ]
https://github.com/stacked-git/stgit/blob/8254ffb2eee53f97e9c6210078db55c15340ead3/stgit/out.py#L116-L119
getavalon/core
31e8cb4760e00e3db64443f6f932b7fd8e96d41d
avalon/vendor/requests/sessions.py
python
Session.close
(self)
Closes all adapters and as such the session
Closes all adapters and as such the session
[ "Closes", "all", "adapters", "and", "as", "such", "the", "session" ]
def close(self): """Closes all adapters and as such the session""" for v in self.adapters.values(): v.close()
[ "def", "close", "(", "self", ")", ":", "for", "v", "in", "self", ".", "adapters", ".", "values", "(", ")", ":", "v", ".", "close", "(", ")" ]
https://github.com/getavalon/core/blob/31e8cb4760e00e3db64443f6f932b7fd8e96d41d/avalon/vendor/requests/sessions.py#L719-L722
21dotco/two1-python
4e833300fd5a58363e3104ed4c097631e5d296d3
two1/bitserv/payment_server.py
python
PaymentServer.close
(self, deposit_txid, deposit_txid_signature)
return str(payment_tx.hash)
Close a payment channel. Args: deposit_txid (string): string representation of the deposit transaction hash. This is used to look up the payment channel. deposit_txid_signature (two1.bitcoin.Signature): a signature consisting solely of the deposit_txid to verify the authenticity of the close request.
Close a payment channel.
[ "Close", "a", "payment", "channel", "." ]
def close(self, deposit_txid, deposit_txid_signature): """Close a payment channel. Args: deposit_txid (string): string representation of the deposit transaction hash. This is used to look up the payment channel. deposit_txid_signature (two1.bitcoin.Signature): a signature consisting solely of the deposit_txid to verify the authenticity of the close request. """ channel = self._db.pc.lookup(deposit_txid) # Verify that the requested channel exists if not channel: raise PaymentChannelNotFoundError('Related channel not found.') # Parse payment channel `close` parameters try: signature_der = codecs.decode(deposit_txid_signature, 'hex_codec') deposit_txid_signature = Signature.from_der(signature_der) except TypeError: raise TransactionVerificationError('Invalid signature provided.') # Verify that there is a valid payment to close if not channel.payment_tx: raise BadTransactionError('No payments made in channel.') # Verify that the user is authorized to close the channel payment_tx = channel.payment_tx redeem_script = PaymentChannelRedeemScript.from_bytes(payment_tx.inputs[0].script[-1]) sig_valid = redeem_script.customer_public_key.verify( deposit_txid.encode(), deposit_txid_signature) if not sig_valid: raise TransactionVerificationError('Invalid signature.') # Sign the final transaction self._wallet.sign_half_signed_payment(payment_tx, redeem_script) # Broadcast payment transaction to the blockchain self._blockchain.broadcast_tx(payment_tx.to_hex()) # Record the broadcast in the database self._db.pc.update_state(deposit_txid, ChannelSQLite3.CLOSED) return str(payment_tx.hash)
[ "def", "close", "(", "self", ",", "deposit_txid", ",", "deposit_txid_signature", ")", ":", "channel", "=", "self", ".", "_db", ".", "pc", ".", "lookup", "(", "deposit_txid", ")", "# Verify that the requested channel exists", "if", "not", "channel", ":", "raise",...
https://github.com/21dotco/two1-python/blob/4e833300fd5a58363e3104ed4c097631e5d296d3/two1/bitserv/payment_server.py#L340-L384
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
source/openerp/report/render/rml2txt/rml2txt.py
python
textbox.renderlines
(self,pad=0)
return result
Returns a list of lines, from the current object pad: all lines must be at least pad characters.
Returns a list of lines, from the current object pad: all lines must be at least pad characters.
[ "Returns", "a", "list", "of", "lines", "from", "the", "current", "object", "pad", ":", "all", "lines", "must", "be", "at", "least", "pad", "characters", "." ]
def renderlines(self,pad=0): """Returns a list of lines, from the current object pad: all lines must be at least pad characters. """ result = [] lineoff = "" for i in range(self.posx): lineoff+=" " for l in self.lines: lpad = "" if pad and len(l) < pad : for i in range(pad - len(l)): lpad += " " #elif pad and len(l) > pad ? result.append(lineoff+ l+lpad) return result
[ "def", "renderlines", "(", "self", ",", "pad", "=", "0", ")", ":", "result", "=", "[", "]", "lineoff", "=", "\"\"", "for", "i", "in", "range", "(", "self", ".", "posx", ")", ":", "lineoff", "+=", "\" \"", "for", "l", "in", "self", ".", "lines", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/source/openerp/report/render/rml2txt/rml2txt.py#L90-L105
maartenbreddels/ipyvolume
71eded3085ed5f00a961c90db8b84fde13a6dee3
setup.py
python
skip_if_exists
(paths, CommandClass)
return SkipIfExistCommand
Skip a command if list of paths exists.
Skip a command if list of paths exists.
[ "Skip", "a", "command", "if", "list", "of", "paths", "exists", "." ]
def skip_if_exists(paths, CommandClass): """Skip a command if list of paths exists.""" def should_skip(): return any(not Path(path).exist() for path in paths) class SkipIfExistCommand(Command): def initialize_options(self): if not should_skip: self.command = CommandClass(self.distribution) self.command.initialize_options() else: self.command = None def finalize_options(self): if self.command is not None: self.command.finalize_options() def run(self): if self.command is not None: self.command.run() return SkipIfExistCommand
[ "def", "skip_if_exists", "(", "paths", ",", "CommandClass", ")", ":", "def", "should_skip", "(", ")", ":", "return", "any", "(", "not", "Path", "(", "path", ")", ".", "exist", "(", ")", "for", "path", "in", "paths", ")", "class", "SkipIfExistCommand", ...
https://github.com/maartenbreddels/ipyvolume/blob/71eded3085ed5f00a961c90db8b84fde13a6dee3/setup.py#L20-L40
openyou/emokit
7f25321a1c3a240f5b64a1572e5f106807b1beea
python/key_solver.py
python
counter_check
(file_data, cipher, swap_data=False)
[]
def counter_check(file_data, cipher, swap_data=False): counter_misses = 0 counter_checks = 0 last_counter = 0 lines = 258 i = 0 for line in file_data: i += 1 if i > lines: continue data = line.split(',')[1:] data = [int(value, 2) for value in data] data = ''.join(map(chr, data)) if not swap_data: decrypted = cipher.decrypt(data[:16]) + cipher.decrypt(data[16:]) else: decrypted = cipher.decrypt(data[16:]) + cipher.decrypt(data[:16]) counter = ord(decrypted[0]) # (counter) strings_of_data = [ord(char) for char in decrypted] print(len(strings_of_data)) print(data_ouput.format(*strings_of_data)) # Uncomment this # print(counter) # if counter <= 127: # if counter != last_counter + 1: # counter_misses += 1 # elif not (counter == 0 and last_counter > 127): # counter_misses += 1 # if counter_misses > 2 and counter_checks > 16: # return False # if counter_checks > 16 and counter_misses < 2: # return True counter_checks += 1 last_counter = counter
[ "def", "counter_check", "(", "file_data", ",", "cipher", ",", "swap_data", "=", "False", ")", ":", "counter_misses", "=", "0", "counter_checks", "=", "0", "last_counter", "=", "0", "lines", "=", "258", "i", "=", "0", "for", "line", "in", "file_data", ":"...
https://github.com/openyou/emokit/blob/7f25321a1c3a240f5b64a1572e5f106807b1beea/python/key_solver.py#L154-L188
Blosc/bloscpack
5efdadf5b6f61e995df1817943afb9629ce28c89
bloscpack/numpy_io.py
python
unpack_ndarray
(source)
return sink.ndarray
Deserialize a Numpy array. Parameters ---------- source : CompressedSource the source containing the serialized Numpy array Returns ------- ndarray : ndarray the Numpy array Raises ------ NotANumpyArray if the source doesn't seem to contain a Numpy array
Deserialize a Numpy array.
[ "Deserialize", "a", "Numpy", "array", "." ]
def unpack_ndarray(source): """ Deserialize a Numpy array. Parameters ---------- source : CompressedSource the source containing the serialized Numpy array Returns ------- ndarray : ndarray the Numpy array Raises ------ NotANumpyArray if the source doesn't seem to contain a Numpy array """ sink = PlainNumpySink(source.metadata) unpack(source, sink) return sink.ndarray
[ "def", "unpack_ndarray", "(", "source", ")", ":", "sink", "=", "PlainNumpySink", "(", "source", ".", "metadata", ")", "unpack", "(", "source", ",", "sink", ")", "return", "sink", ".", "ndarray" ]
https://github.com/Blosc/bloscpack/blob/5efdadf5b6f61e995df1817943afb9629ce28c89/bloscpack/numpy_io.py#L286-L307
django/djangosnippets.org
0b273ce13135e157267009631d460835387d9975
cab/views/popular.py
python
top_authors
(request)
return object_list( request, queryset=Snippet.objects.top_authors(), template_name="cab/top_authors.html", paginate_by=20 )
[]
def top_authors(request): return object_list( request, queryset=Snippet.objects.top_authors(), template_name="cab/top_authors.html", paginate_by=20 )
[ "def", "top_authors", "(", "request", ")", ":", "return", "object_list", "(", "request", ",", "queryset", "=", "Snippet", ".", "objects", ".", "top_authors", "(", ")", ",", "template_name", "=", "\"cab/top_authors.html\"", ",", "paginate_by", "=", "20", ")" ]
https://github.com/django/djangosnippets.org/blob/0b273ce13135e157267009631d460835387d9975/cab/views/popular.py#L5-L8
google-research/bert
eedf5716ce1268e56f0a50264a88cafad334ac61
tokenization.py
python
convert_to_unicode
(text)
Converts `text` to Unicode (if it's not already), assuming utf-8 input.
Converts `text` to Unicode (if it's not already), assuming utf-8 input.
[ "Converts", "text", "to", "Unicode", "(", "if", "it", "s", "not", "already", ")", "assuming", "utf", "-", "8", "input", "." ]
def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise ValueError("Unsupported string type: %s" % (type(text))) elif six.PY2: if isinstance(text, str): return text.decode("utf-8", "ignore") elif isinstance(text, unicode): return text else: raise ValueError("Unsupported string type: %s" % (type(text))) else: raise ValueError("Not running on Python2 or Python 3?")
[ "def", "convert_to_unicode", "(", "text", ")", ":", "if", "six", ".", "PY3", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "return", "text", "elif", "isinstance", "(", "text", ",", "bytes", ")", ":", "return", "text", ".", "decode", "("...
https://github.com/google-research/bert/blob/eedf5716ce1268e56f0a50264a88cafad334ac61/tokenization.py#L78-L95
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/modeladmin/menus.py
python
SubMenu.__init__
(self, menuitem_list)
[]
def __init__(self, menuitem_list): self._registered_menu_items = menuitem_list self.construct_hook_name = None
[ "def", "__init__", "(", "self", ",", "menuitem_list", ")", ":", "self", ".", "_registered_menu_items", "=", "menuitem_list", "self", ".", "construct_hook_name", "=", "None" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/wagtail_bak/contrib/modeladmin/menus.py#L52-L54
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/redis/client.py
python
StrictRedis.zrange
(self, name, start, end, desc=False, withscores=False, score_cast_func=float)
return self.execute_command(*pieces, **options)
Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value
Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order.
[ "Return", "a", "range", "of", "values", "from", "sorted", "set", "name", "between", "start", "and", "end", "sorted", "in", "ascending", "order", "." ]
def zrange(self, name, start, end, desc=False, withscores=False, score_cast_func=float): """ Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value """ if desc: return self.zrevrange(name, start, end, withscores, score_cast_func) pieces = ['ZRANGE', name, start, end] if withscores: pieces.append(Token.get_token('WITHSCORES')) options = { 'withscores': withscores, 'score_cast_func': score_cast_func } return self.execute_command(*pieces, **options)
[ "def", "zrange", "(", "self", ",", "name", ",", "start", ",", "end", ",", "desc", "=", "False", ",", "withscores", "=", "False", ",", "score_cast_func", "=", "float", ")", ":", "if", "desc", ":", "return", "self", ".", "zrevrange", "(", "name", ",", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/redis/client.py#L1729-L1754
Matheus-Garbelini/sweyntooth_bluetooth_low_energy_attacks
40c985b9a9ff1189ddf278462440b120cf96b196
libs/scapy/contrib/bgp.py
python
has_extended_length
(flags)
return flags & _BGP_PA_EXTENDED_LENGTH == _BGP_PA_EXTENDED_LENGTH
Used in BGPPathAttr to check if the extended-length flag is set.
Used in BGPPathAttr to check if the extended-length flag is set.
[ "Used", "in", "BGPPathAttr", "to", "check", "if", "the", "extended", "-", "length", "flag", "is", "set", "." ]
def has_extended_length(flags): """ Used in BGPPathAttr to check if the extended-length flag is set. """ return flags & _BGP_PA_EXTENDED_LENGTH == _BGP_PA_EXTENDED_LENGTH
[ "def", "has_extended_length", "(", "flags", ")", ":", "return", "flags", "&", "_BGP_PA_EXTENDED_LENGTH", "==", "_BGP_PA_EXTENDED_LENGTH" ]
https://github.com/Matheus-Garbelini/sweyntooth_bluetooth_low_energy_attacks/blob/40c985b9a9ff1189ddf278462440b120cf96b196/libs/scapy/contrib/bgp.py#L193-L199
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/examples/sprite_bouncing_coins.py
python
MyGame.on_draw
(self)
Render the screen.
Render the screen.
[ "Render", "the", "screen", "." ]
def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() # Draw all the sprites. self.wall_list.draw() self.coin_list.draw()
[ "def", "on_draw", "(", "self", ")", ":", "# This command has to happen before we start drawing", "arcade", ".", "start_render", "(", ")", "# Draw all the sprites.", "self", ".", "wall_list", ".", "draw", "(", ")", "self", ".", "coin_list", ".", "draw", "(", ")" ]
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/examples/sprite_bouncing_coins.py#L98-L108
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/base.py
python
_bind_or_error
(schemaitem, msg=None)
return bind
[]
def _bind_or_error(schemaitem, msg=None): bind = schemaitem.bind if not bind: name = schemaitem.__class__.__name__ label = getattr(schemaitem, 'fullname', getattr(schemaitem, 'name', None)) if label: item = '%s object %r' % (name, label) else: item = '%s object' % name if msg is None: msg = "%s is not bound to an Engine or Connection. "\ "Execution can not proceed without a database to execute "\ "against." % item raise exc.UnboundExecutionError(msg) return bind
[ "def", "_bind_or_error", "(", "schemaitem", ",", "msg", "=", "None", ")", ":", "bind", "=", "schemaitem", ".", "bind", "if", "not", "bind", ":", "name", "=", "schemaitem", ".", "__class__", ".", "__name__", "label", "=", "getattr", "(", "schemaitem", ","...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/base.py#L622-L637
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/difflib.py
python
HtmlDiff._line_wrapper
(self,diffs)
Returns iterator that splits (wraps) mdiff text lines
Returns iterator that splits (wraps) mdiff text lines
[ "Returns", "iterator", "that", "splits", "(", "wraps", ")", "mdiff", "text", "lines" ]
def _line_wrapper(self,diffs): """Returns iterator that splits (wraps) mdiff text lines""" # pull from/to data and flags from mdiff iterator for fromdata,todata,flag in diffs: # check for context separators and pass them through if flag is None: yield fromdata,todata,flag continue (fromline,fromtext),(toline,totext) = fromdata,todata # for each from/to line split it at the wrap column to form # list of text lines. fromlist,tolist = [],[] self._split_line(fromlist,fromline,fromtext) self._split_line(tolist,toline,totext) # yield from/to line in pairs inserting blank lines as # necessary when one side has more wrapped lines while fromlist or tolist: if fromlist: fromdata = fromlist.pop(0) else: fromdata = ('',' ') if tolist: todata = tolist.pop(0) else: todata = ('',' ') yield fromdata,todata,flag
[ "def", "_line_wrapper", "(", "self", ",", "diffs", ")", ":", "# pull from/to data and flags from mdiff iterator", "for", "fromdata", ",", "todata", ",", "flag", "in", "diffs", ":", "# check for context separators and pass them through", "if", "flag", "is", "None", ":", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/difflib.py#L1851-L1877
RasaHQ/rasa
54823b68c1297849ba7ae841a4246193cd1223a1
rasa/shared/core/training_data/story_writer/story_writer.py
python
StoryWriter.dump
( target: Union[Text, Path, yaml.StringIO], story_steps: List["StoryStep"], is_appendable: bool = False, is_test_story: bool = False, )
Writes Story steps into a target file/stream. Args: target: name of the target file/stream to write the string to. story_steps: Original story steps to be converted to the string. is_appendable: Specify if result should not contain high level keys/definitions and can be appended to the existing story file. is_test_story: Identifies if the stories should be exported in test stories format.
Writes Story steps into a target file/stream.
[ "Writes", "Story", "steps", "into", "a", "target", "file", "/", "stream", "." ]
def dump( target: Union[Text, Path, yaml.StringIO], story_steps: List["StoryStep"], is_appendable: bool = False, is_test_story: bool = False, ) -> None: """Writes Story steps into a target file/stream. Args: target: name of the target file/stream to write the string to. story_steps: Original story steps to be converted to the string. is_appendable: Specify if result should not contain high level keys/definitions and can be appended to the existing story file. is_test_story: Identifies if the stories should be exported in test stories format. """ raise NotImplementedError
[ "def", "dump", "(", "target", ":", "Union", "[", "Text", ",", "Path", ",", "yaml", ".", "StringIO", "]", ",", "story_steps", ":", "List", "[", "\"StoryStep\"", "]", ",", "is_appendable", ":", "bool", "=", "False", ",", "is_test_story", ":", "bool", "="...
https://github.com/RasaHQ/rasa/blob/54823b68c1297849ba7ae841a4246193cd1223a1/rasa/shared/core/training_data/story_writer/story_writer.py#L34-L51
googleads/google-ads-python
2a1d6062221f6aad1992a6bcca0e7e4a93d2db86
google/ads/googleads/v8/services/services/detail_placement_view_service/client.py
python
DetailPlacementViewServiceClient.parse_common_billing_account_path
(path: str)
return m.groupdict() if m else {}
Parse a billing_account path into its component segments.
Parse a billing_account path into its component segments.
[ "Parse", "a", "billing_account", "path", "into", "its", "component", "segments", "." ]
def parse_common_billing_account_path(path: str) -> Dict[str, str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {}
[ "def", "parse_common_billing_account_path", "(", "path", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "m", "=", "re", ".", "match", "(", "r\"^billingAccounts/(?P<billing_account>.+?)$\"", ",", "path", ")", "return", "m", ".", "groupdict", ...
https://github.com/googleads/google-ads-python/blob/2a1d6062221f6aad1992a6bcca0e7e4a93d2db86/google/ads/googleads/v8/services/services/detail_placement_view_service/client.py#L191-L194
CERT-Polska/mquery
517598112e56f7b716ed0ed52b30b328df42affd
src/db.py
python
MatchInfo.to_json
(self)
return json.dumps( {"file": self.file, "meta": self.meta, "matches": self.matches} )
Converts match info to json
Converts match info to json
[ "Converts", "match", "info", "to", "json" ]
def to_json(self) -> str: """ Converts match info to json """ return json.dumps( {"file": self.file, "meta": self.meta, "matches": self.matches} )
[ "def", "to_json", "(", "self", ")", "->", "str", ":", "return", "json", ".", "dumps", "(", "{", "\"file\"", ":", "self", ".", "file", ",", "\"meta\"", ":", "self", ".", "meta", ",", "\"matches\"", ":", "self", ".", "matches", "}", ")" ]
https://github.com/CERT-Polska/mquery/blob/517598112e56f7b716ed0ed52b30b328df42affd/src/db.py#L58-L62
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/client/experiment.py
python
ExperimentClient.metadata
(self)
return self._experiment.metadata
Metadata of the experiment.
Metadata of the experiment.
[ "Metadata", "of", "the", "experiment", "." ]
def metadata(self): """Metadata of the experiment.""" return self._experiment.metadata
[ "def", "metadata", "(", "self", ")", ":", "return", "self", ".", "_experiment", ".", "metadata" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/client/experiment.py#L146-L148
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/vendor/pika/adapters/base_connection.py
python
BaseConnection._adapter_emit_data
(self, data)
Take ownership of data and send it to AMQP server as soon as possible. :param bytes data:
Take ownership of data and send it to AMQP server as soon as possible.
[ "Take", "ownership", "of", "data", "and", "send", "it", "to", "AMQP", "server", "as", "soon", "as", "possible", "." ]
def _adapter_emit_data(self, data): """Take ownership of data and send it to AMQP server as soon as possible. :param bytes data: """ self._transport.write(data)
[ "def", "_adapter_emit_data", "(", "self", ",", "data", ")", ":", "self", ".", "_transport", ".", "write", "(", "data", ")" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/vendor/pika/adapters/base_connection.py#L377-L384
biopython/biopython
2dd97e71762af7b046d7f7f8a4f1e38db6b06c86
Bio/SearchIO/ExonerateIO/_base.py
python
_get_fragments_phase
(frags)
return [(3 - (x % 3)) % 3 for x in _get_fragments_coord(frags)]
Return the phases of the given list of 3-letter amino acid fragments (PRIVATE). This is an internal private function and is meant for parsing Exonerate's three-letter amino acid output. >>> from Bio.SearchIO.ExonerateIO._base import _get_fragments_phase >>> _get_fragments_phase(['Thr', 'Ser', 'Ala']) [0, 0, 0] >>> _get_fragments_phase(['ThrSe', 'rAla']) [0, 1] >>> _get_fragments_phase(['ThrSe', 'rAlaLeu', 'ProCys']) [0, 1, 0] >>> _get_fragments_phase(['ThrSe', 'rAlaLeuP', 'roCys']) [0, 1, 2] >>> _get_fragments_phase(['ThrSe', 'rAlaLeuPr', 'oCys']) [0, 1, 1]
Return the phases of the given list of 3-letter amino acid fragments (PRIVATE).
[ "Return", "the", "phases", "of", "the", "given", "list", "of", "3", "-", "letter", "amino", "acid", "fragments", "(", "PRIVATE", ")", "." ]
def _get_fragments_phase(frags): """Return the phases of the given list of 3-letter amino acid fragments (PRIVATE). This is an internal private function and is meant for parsing Exonerate's three-letter amino acid output. >>> from Bio.SearchIO.ExonerateIO._base import _get_fragments_phase >>> _get_fragments_phase(['Thr', 'Ser', 'Ala']) [0, 0, 0] >>> _get_fragments_phase(['ThrSe', 'rAla']) [0, 1] >>> _get_fragments_phase(['ThrSe', 'rAlaLeu', 'ProCys']) [0, 1, 0] >>> _get_fragments_phase(['ThrSe', 'rAlaLeuP', 'roCys']) [0, 1, 2] >>> _get_fragments_phase(['ThrSe', 'rAlaLeuPr', 'oCys']) [0, 1, 1] """ return [(3 - (x % 3)) % 3 for x in _get_fragments_coord(frags)]
[ "def", "_get_fragments_phase", "(", "frags", ")", ":", "return", "[", "(", "3", "-", "(", "x", "%", "3", ")", ")", "%", "3", "for", "x", "in", "_get_fragments_coord", "(", "frags", ")", "]" ]
https://github.com/biopython/biopython/blob/2dd97e71762af7b046d7f7f8a4f1e38db6b06c86/Bio/SearchIO/ExonerateIO/_base.py#L85-L104
yaqwsx/PcbDraw
09720d46f3fdb8b01c2b0e2eca39d964552e94a0
versioneer.py
python
get_versions
(verbose=False)
return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'.
Get the project version from whatever source is available.
[ "Get", "the", "project", "version", "from", "whatever", "source", "is", "available", "." ]
def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None}
[ "def", "get_versions", "(", "verbose", "=", "False", ")", ":", "if", "\"versioneer\"", "in", "sys", ".", "modules", ":", "# see the discussion in cmdclass.py:get_cmdclass()", "del", "sys", ".", "modules", "[", "\"versioneer\"", "]", "root", "=", "get_root", "(", ...
https://github.com/yaqwsx/PcbDraw/blob/09720d46f3fdb8b01c2b0e2eca39d964552e94a0/versioneer.py#L1402-L1475
VainF/pytorch-msssim
6ceec02d64447216881423dd7428b68a2ad0905f
pytorch_msssim/ssim.py
python
MS_SSIM.__init__
( self, data_range=255, size_average=True, win_size=11, win_sigma=1.5, channel=3, spatial_dims=2, weights=None, K=(0.01, 0.03), )
r""" class for ms-ssim Args: data_range (float or int, optional): value range of input images. (usually 1.0 or 255) size_average (bool, optional): if size_average=True, ssim of all images will be averaged as a scalar win_size: (int, optional): the size of gauss kernel win_sigma: (float, optional): sigma of normal distribution channel (int, optional): input channels (default: 3) weights (list, optional): weights for different levels K (list or tuple, optional): scalar constants (K1, K2). Try a larger K2 constant (e.g. 0.4) if you get a negative or NaN results.
r""" class for ms-ssim Args: data_range (float or int, optional): value range of input images. (usually 1.0 or 255) size_average (bool, optional): if size_average=True, ssim of all images will be averaged as a scalar win_size: (int, optional): the size of gauss kernel win_sigma: (float, optional): sigma of normal distribution channel (int, optional): input channels (default: 3) weights (list, optional): weights for different levels K (list or tuple, optional): scalar constants (K1, K2). Try a larger K2 constant (e.g. 0.4) if you get a negative or NaN results.
[ "r", "class", "for", "ms", "-", "ssim", "Args", ":", "data_range", "(", "float", "or", "int", "optional", ")", ":", "value", "range", "of", "input", "images", ".", "(", "usually", "1", ".", "0", "or", "255", ")", "size_average", "(", "bool", "optiona...
def __init__( self, data_range=255, size_average=True, win_size=11, win_sigma=1.5, channel=3, spatial_dims=2, weights=None, K=(0.01, 0.03), ): r""" class for ms-ssim Args: data_range (float or int, optional): value range of input images. (usually 1.0 or 255) size_average (bool, optional): if size_average=True, ssim of all images will be averaged as a scalar win_size: (int, optional): the size of gauss kernel win_sigma: (float, optional): sigma of normal distribution channel (int, optional): input channels (default: 3) weights (list, optional): weights for different levels K (list or tuple, optional): scalar constants (K1, K2). Try a larger K2 constant (e.g. 0.4) if you get a negative or NaN results. """ super(MS_SSIM, self).__init__() self.win_size = win_size self.win = _fspecial_gauss_1d(win_size, win_sigma).repeat([channel, 1] + [1] * spatial_dims) self.size_average = size_average self.data_range = data_range self.weights = weights self.K = K
[ "def", "__init__", "(", "self", ",", "data_range", "=", "255", ",", "size_average", "=", "True", ",", "win_size", "=", "11", ",", "win_sigma", "=", "1.5", ",", "channel", "=", "3", ",", "spatial_dims", "=", "2", ",", "weights", "=", "None", ",", "K",...
https://github.com/VainF/pytorch-msssim/blob/6ceec02d64447216881423dd7428b68a2ad0905f/pytorch_msssim/ssim.py#L277-L305
django-oscar/django-oscar
ffcc530844d40283b6b1552778a140536b904f5f
src/oscar/templatetags/shipping_tags.py
python
shipping_charge_discount
(method, basket)
return method.discount(basket)
Template tag for calculating the shipping discount for a given shipping method and basket, and injecting it into the template context.
Template tag for calculating the shipping discount for a given shipping method and basket, and injecting it into the template context.
[ "Template", "tag", "for", "calculating", "the", "shipping", "discount", "for", "a", "given", "shipping", "method", "and", "basket", "and", "injecting", "it", "into", "the", "template", "context", "." ]
def shipping_charge_discount(method, basket): """ Template tag for calculating the shipping discount for a given shipping method and basket, and injecting it into the template context. """ return method.discount(basket)
[ "def", "shipping_charge_discount", "(", "method", ",", "basket", ")", ":", "return", "method", ".", "discount", "(", "basket", ")" ]
https://github.com/django-oscar/django-oscar/blob/ffcc530844d40283b6b1552778a140536b904f5f/src/oscar/templatetags/shipping_tags.py#L16-L21
arizvisa/ida-minsc
8627a60f047b5e55d3efeecde332039cd1a16eea
base/instruction.py
python
op_structure
(ea, opnum, sptr, *path, **force)
return op_structure(insn.ea, opnum)
Apply the structure identified by `sptr` along with the members in `path` to the instruction operand `opnum` at the address `ea`.
Apply the structure identified by `sptr` along with the members in `path` to the instruction operand `opnum` at the address `ea`.
[ "Apply", "the", "structure", "identified", "by", "sptr", "along", "with", "the", "members", "in", "path", "to", "the", "instruction", "operand", "opnum", "at", "the", "address", "ea", "." ]
def op_structure(ea, opnum, sptr, *path, **force): '''Apply the structure identified by `sptr` along with the members in `path` to the instruction operand `opnum` at the address `ea`.''' ea = interface.address.inside(ea) if not database.type.is_code(ea): raise E.InvalidTypeOrValueError(u"{:s}.op_structure({:#x}, {:d}, {!r}) : The requested address ({:#x}) is not defined as a code type.".format(__name__, ea, opnum, path, ea)) # Convert the path to a list, and then validate it before we use it. path, accepted = [item for item in path], (idaapi.member_t, structure.member_t, six.string_types, six.integer_types) if any(not isinstance(item, accepted) for item in path): index, item = next((index, item) for index, item in enumerate(path) if not isinstance(item, accepted)) raise E.InvalidParameterError(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : The path member at index {:d} has a type ({!s}) that is not supported.".format(__name__, ea, opnum, sptr.id, path, index, item.__class__)) # Grab information about our instruction and operand so that we can decode # it to get the structure offset to use. insn, op = at(ea), operand(ea, opnum) # If the operand type is not a valid type, then raise an exception so that # we don't accidentally apply a structure to an invalid operand type. if op.type not in {idaapi.o_mem, idaapi.o_phrase, idaapi.o_displ, idaapi.o_imm}: raise E.MissingTypeOrAttribute(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : Unable to apply structure path to the operand ({:d}) for the instruction at {:#x} due to its type ({:d}).".format(__name__, ea, opnum, sptr.id, path, opnum, insn.ea, op.type)) # Now we need to decode our operand and stash it so that we can later # use it to calculate the delta between it and the actual member offset # to use when traversing the structure path. We try every possible attribute # from our decoders until we find one. Otherwise, we bail. res = __optype__.decode(insn, op) if isinstance(res, six.integer_types): value = res elif any(hasattr(res, attribute) for attribute in ['offset', 'Offset', 'address']): value = res.offset if hasattr(res, 'offset') else res.Offset if hasattr(res, 'Offset') else res.address else: raise E.UnsupportedCapability(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : An unexpected type ({!s}) was decoded from the operand ({:d}) for the instruction at {:#x}).".format(__name__, ea, opnum, sptr.id, path, value.__class__, opnum, insn.ea)) # We have to start somewhere and our first element in the path should be a # a member of the sptr we were given. So, now we begin to traverse through # all of the members in the path the user gave us so that we can figure out # the user wanted and what mptrs and sptrs should be in that path. st, offset, delta = structure.__instance__(sptr.id), 0, 0 items = [] while path and sptr: item = path.pop(0) # If we found an integer in the path, then just use it to adjust the # delta and proceed through the rest of the path. if isinstance(item, six.integer_types): delta += item continue # Members can be specified in all sorts of ways, so we need to check # what the user gave us. If we were given a string, then look up the # member by its name. elif isinstance(item, six.string_types): mptr = idaapi.get_member_by_name(sptr, utils.string.to(item)) # If we were given a structure.member_t, then we can just take its # member_t.ptr property and use that. elif isinstance(item, structure.member_t): mptr = item.ptr # If we were given an explicit idaapi.member_t, then we can use it as-is. elif isinstance(item, idaapi.member_t): mptr = item # Anything else is not a supported type, and as such is an error. else: suggested = ((idaapi.get_struc_name(sptr.id), idaapi.get_member_name(mptr.id)) for sptr, mptr in items) suggested = ('.'.join(map(utils.string.of, pair)) for pair in suggested) summary = itertools.chain(suggested, [item], path) raise E.InvalidParameterError(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : The member ({!s}) at index {:d} of the suggested path is using an unsupported type ({!s}).".format(__name__, ea, opnum, st.ptr.id, [item for item in summary], item, len(items), item.__class__)) # If mptr is undefined, then that's it. We have to stop our traversal, # and warn the user about what happened. if mptr is None: suggested = ((idaapi.get_struc_name(sptr.id), idaapi.get_member_name(mptr.id)) for sptr, mptr in items) suggested = ('.'.join(map(utils.string.of, pair)) for pair in suggested) summary = itertools.chain(suggested, [item], path) logging.warn(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : The member ({!s}) at index {:d} of the suggested path was not found in the parent structure ({!s}).".format(__name__, ea, opnum, st.ptr.id, [item for item in summary], item, len(items), utils.string.of(idaapi.get_struc_name(sptr.id)))) break # We got an mptr, so now we can extract its owning sptr and verify that # it matches the structure that our path traversal is currently in. _, _, res = idaapi.get_member_by_id(mptr.id) if not interface.node.is_identifier(res.id): res = idaapi.get_member_struc(idaapi.get_member_fullname(mptr.id)) if res.id != sptr.id: suggested = ((idaapi.get_struc_name(sptr.id), idaapi.get_member_name(mptr.id)) for sptr, mptr in items) suggested = ('.'.join(map(utils.string.of, pair)) for pair in suggested) summary = itertools.chain(suggested, [utils.string.of(idaapi.get_member_fullname(mptr.id))], path) logging.warning(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : The member ({!s}) at index {:d} of the suggested path is using a structure ({:#x}) that is different from the expected structure ({:#x}).".format(__name__, ea, opnum, st.ptr.id, [item for item in summary], utils.string.of(idaapi.get_member_fullname(mptr.id)), len(items), res.id, sptr.id)) sptr = res # Now we can add the mptr to our list, and update the member offset that # we're tracking during this traversal. If it's a union, then our member # offset doesn't change at all. items.append((sptr, mptr)) offset += 0 if sptr.is_union() else mptr.soff # If the member that we're currently at during our traversal is not a # structure, then our loop should stop here. sptr = idaapi.get_sptr(mptr) # Consume the rest of the integers in the path so that we can finish # updating the delta that the user suggested to us. while path and isinstance(path[0], six.integer_types): delta += path.pop(0) # Verify that our path is empty and that we successfully consumed everything. if len(path): suggested = ((idaapi.get_struc_name(sptr.id), idaapi.get_member_name(mptr.id)) for sptr, mptr in items) suggested = ('.'.join(map(utils.string.of, pair)) for pair in suggested) summary = itertools.chain(suggested, path) logging.warning(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : There was an error trying to traverse the path for the list of members (path will be truncated).".format(__name__, ea, opnum, st.ptr.id, [item for item in summary])) # FIXME: figure out whether we really need to calculate the structure offset, # or we're just applying a reference or the structure size to the operand. # Now that we have the suggested path and thus the desired offset, we're # going to use it to generate a filter that we will use to determine the # union members to choose along the desired offset. We'll start by formatting # these items into a lookup table. table = {} for sptr, mptr in items: if sptr.is_union(): table.setdefault(sptr.id, []).append(mptr.id) continue # Now we can define a closure that uses this table to get as close as we can # to what the user suggsted. If the path doesn't correspond, then we're # forced to return all the members and bailing, which sorts itself out. def filter(sptr, members, table=table): if sptr.id not in table: return [] # Grab our choices and convert our candidates into identifiers. choices, candidates = table[sptr.id], {mptr.id for mptr in members} if len(choices) == 0: return [] # Check the next item on the stack is a valid candidate, and # pop it off it is. mid = choices[0] if mid not in candidates: return [] choice = choices.pop(0) # Filter our list of members for the one that matches our choice. res = [mptr for mptr in members if mptr.id == choice] return res # If our structure has some members, then we need to use the requested offset # to descend through the structure that we're starting with and then hope it # matches the path that was recommended to us. We need to shift whatever this # offset is by the delta that we were given, and then gather our results into # both an sptr and mptrs. if len(st.members): rp, rpdelta = st.members.__walk_to_realoffset__(offset + delta, filter=filter) results = [(item.parent.ptr, item.ptr) for item in rp] # Count the number of members that are unions because we will be using it # to allocate the path that we write to the supval for the designated # instruction operand. length = 1 + sum(1 for sptr, mptr in results if sptr.is_union()) # Now that we've carved an actual path through the structure and its # descendants, we can allocate the tid_array using the starting structure and # adding each individual member to it. If we didn't get any members for our # results, then that's okay since we still have the structure to start at. sptr, _ = results[0] if results else (st.ptr, None) index, tid = 1, idaapi.tid_array(length) tid[0] = sptr.id for sptr, mptr in results: if sptr.is_union(): tid[index] = mptr.id index += 1 continue # Verify our length just to be certain. if index != length: raise AssertionError(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : The number of elements in the path ({:d}) does not correspond to the number of elements that were calculated ({:d}).".format(__name__, ea, opnum, st.ptr.id, index, length)) rpoffset = sum(0 if sptr.is_union() else mptr.soff for sptr, mptr in results) # If there are no members in the structure, then we build a tid_array composed # of just the structure identifier, and then use the path that we were given # that includes just the offset and the delta. else: length, rpdelta, rpoffset = 1, delta, offset tid = idaapi.tid_array(length) tid[0] = sptr.id # If the user asked us to force this path, then we just trust the value # that was returned by our traversal. if any(k in force for k in ['force', 'forced']) and builtins.next((force[k] for k in ['force', 'forced'] if k in force), False): res = rpoffset + rpdelta # Otherwise, we take the difference between the user's offset and our # traversal's offset, and then add the delta we figured out. else: res = (rpoffset - offset) + rpdelta # Now we can apply our tid_array to the operand, and include our original # member offset from the path the user gave us so that way the user can # fetch it later if they so desire. if idaapi.__version__ < 7.0: ok = idaapi.op_stroff(insn.ea, opnum, tid.cast(), length, res) # If we're using IDAPython from v7.0 or later, then we're required to grab # the instruction to apply our tid_array to its operand. else: ok = idaapi.op_stroff(insn, opnum, tid.cast(), length, res) # If we failed applying our structure, then we'll just raise an exception. if not ok: suggested = ((idaapi.get_struc_name(sptr.id), idaapi.get_member_name(mptr.id)) for sptr, mptr in items) suggested = ('.'.join(map(utils.string.of, pair)) for pair in suggested) resolved = ((idaapi.get_struc_name(sptr.id), idaapi.get_member_name(mptr.id)) for sptr, mptr in results) resolved = ('.'.join(map(utils.string.of, pair)) for pair in resolved) raise E.DisassemblerError(u"{:s}.op_structure({:#x}, {:d}, {:#x}, {!r}) : Unable to apply the resolved structure path ({!r}) to the specified address ({:#x}).".format(__name__, ea, opnum, st.ptr.id, [item for item in suggested], [item for item in resolved], insn.ea)) # Otherwise, we can chain into our other case to return what was just applied. return op_structure(insn.ea, opnum)
[ "def", "op_structure", "(", "ea", ",", "opnum", ",", "sptr", ",", "*", "path", ",", "*", "*", "force", ")", ":", "ea", "=", "interface", ".", "address", ".", "inside", "(", "ea", ")", "if", "not", "database", ".", "type", ".", "is_code", "(", "ea...
https://github.com/arizvisa/ida-minsc/blob/8627a60f047b5e55d3efeecde332039cd1a16eea/base/instruction.py#L1225-L1445
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/conversations/v1/credential.py
python
CredentialPage.get_instance
(self, payload)
return CredentialInstance(self._version, payload, )
Build an instance of CredentialInstance :param dict payload: Payload response from the API :returns: twilio.rest.conversations.v1.credential.CredentialInstance :rtype: twilio.rest.conversations.v1.credential.CredentialInstance
Build an instance of CredentialInstance
[ "Build", "an", "instance", "of", "CredentialInstance" ]
def get_instance(self, payload): """ Build an instance of CredentialInstance :param dict payload: Payload response from the API :returns: twilio.rest.conversations.v1.credential.CredentialInstance :rtype: twilio.rest.conversations.v1.credential.CredentialInstance """ return CredentialInstance(self._version, payload, )
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "CredentialInstance", "(", "self", ".", "_version", ",", "payload", ",", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/conversations/v1/credential.py#L191-L200
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
ResourceCode/wswp-places-c573d29efa3a/modules/Captcha/Visual/Text.py
python
FontFactory.pick
(self)
return (fileName, size)
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()
[ "Returns", "a", "(", "fileName", "size", ")", "tuple", "that", "can", "be", "passed", "to", "ImageFont", ".", "truetype", "()" ]
def pick(self): """Returns a (fileName, size) tuple that can be passed to ImageFont.truetype()""" fileName = File.RandomFileFactory.pick(self) size = int(random.uniform(self.minSize, self.maxSize) + 0.5) return (fileName, size)
[ "def", "pick", "(", "self", ")", ":", "fileName", "=", "File", ".", "RandomFileFactory", ".", "pick", "(", "self", ")", "size", "=", "int", "(", "random", ".", "uniform", "(", "self", ".", "minSize", ",", "self", ".", "maxSize", ")", "+", "0.5", ")...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/ResourceCode/wswp-places-c573d29efa3a/modules/Captcha/Visual/Text.py#L34-L38
kirthevasank/nasbot
3c745dc986be30e3721087c8fa768099032a0802
opt/gpb_acquisitions.py
python
_get_ucb_beta_th
(dim, time_step)
return np.sqrt(0.5 * dim * np.log(2 * dim * time_step + 1))
Computes the beta t for UCB based methods.
Computes the beta t for UCB based methods.
[ "Computes", "the", "beta", "t", "for", "UCB", "based", "methods", "." ]
def _get_ucb_beta_th(dim, time_step): """ Computes the beta t for UCB based methods. """ return np.sqrt(0.5 * dim * np.log(2 * dim * time_step + 1))
[ "def", "_get_ucb_beta_th", "(", "dim", ",", "time_step", ")", ":", "return", "np", ".", "sqrt", "(", "0.5", "*", "dim", "*", "np", ".", "log", "(", "2", "*", "dim", "*", "time_step", "+", "1", ")", ")" ]
https://github.com/kirthevasank/nasbot/blob/3c745dc986be30e3721087c8fa768099032a0802/opt/gpb_acquisitions.py#L65-L67
mylar3/mylar3
fce4771c5b627f8de6868dd4ab6bc53f7b22d303
lib/comictaggerlib/comicvinetalker.py
python
ComicVineTalker.cleanup_html
(self, string, remove_html_tables)
return newstring
converter = html2text.HTML2Text() #converter.emphasis_mark = '*' #converter.ignore_links = True converter.body_width = 0 print(html2text.html2text(string)) return string #return converter.handle(string)
converter = html2text.HTML2Text() #converter.emphasis_mark = '*' #converter.ignore_links = True converter.body_width = 0
[ "converter", "=", "html2text", ".", "HTML2Text", "()", "#converter", ".", "emphasis_mark", "=", "*", "#converter", ".", "ignore_links", "=", "True", "converter", ".", "body_width", "=", "0" ]
def cleanup_html(self, string, remove_html_tables): """ converter = html2text.HTML2Text() #converter.emphasis_mark = '*' #converter.ignore_links = True converter.body_width = 0 print(html2text.html2text(string)) return string #return converter.handle(string) """ if string is None: return "" # find any tables soup = BeautifulSoup(string, "html.parser") tables = soup.findAll('table') # remove all newlines first string = string.replace("\n", "") # put in our own string = string.replace("<br>", "\n") string = string.replace("</p>", "\n\n") string = string.replace("<h4>", "*") string = string.replace("</h4>", "*\n") # remove the tables p = re.compile(r'<table[^<]*?>.*?<\/table>') if remove_html_tables: string = p.sub('', string) string = string.replace("*List of covers and their creators:*", "") else: string = p.sub('{}', string) # now strip all other tags p = re.compile(r'<[^<]*?>') newstring = p.sub('', string) newstring = newstring.replace('&nbsp;', ' ') newstring = newstring.replace('&amp;', '&') newstring = newstring.strip() if not remove_html_tables: # now rebuild the tables into text from BSoup try: table_strings = [] for table in tables: rows = [] hdrs = [] col_widths = [] for hdr in table.findAll('th'): item = hdr.string.strip() hdrs.append(item) col_widths.append(len(item)) rows.append(hdrs) for row in table.findAll('tr'): cols = [] col = row.findAll('td') i = 0 for c in col: item = c.string.strip() cols.append(item) if len(item) > col_widths[i]: col_widths[i] = len(item) i += 1 if len(cols) != 0: rows.append(cols) # now we have the data, make it into text fmtstr = "" for w in col_widths: fmtstr += " {{:{}}}|".format(w + 1) width = sum(col_widths) + len(col_widths) * 2 print("width=", width) table_text = "" counter = 0 for row in rows: table_text += fmtstr.format(*row) + "\n" if counter == 0 and len(hdrs) != 0: table_text += "-" * width + "\n" counter += 1 table_strings.append(table_text) newstring = newstring.format(*table_strings) except: # we caught an error rebuilding the table. # just bail and remove the formatting print("table parse error") newstring.replace("{}", "") return newstring
[ "def", "cleanup_html", "(", "self", ",", "string", ",", "remove_html_tables", ")", ":", "if", "string", "is", "None", ":", "return", "\"\"", "# find any tables", "soup", "=", "BeautifulSoup", "(", "string", ",", "\"html.parser\"", ")", "tables", "=", "soup", ...
https://github.com/mylar3/mylar3/blob/fce4771c5b627f8de6868dd4ab6bc53f7b22d303/lib/comictaggerlib/comicvinetalker.py#L564-L657
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/idlelib/PyShell.py
python
PyShell._close
(self)
Extend EditorWindow._close(), shut down debugger and execution server
Extend EditorWindow._close(), shut down debugger and execution server
[ "Extend", "EditorWindow", ".", "_close", "()", "shut", "down", "debugger", "and", "execution", "server" ]
def _close(self): "Extend EditorWindow._close(), shut down debugger and execution server" self.close_debugger() if use_subprocess: self.interp.kill_subprocess() # Restore std streams sys.stdout = self.save_stdout sys.stderr = self.save_stderr sys.stdin = self.save_stdin # Break cycles self.interp = None self.console = None self.flist.pyshell = None self.history = None EditorWindow._close(self)
[ "def", "_close", "(", "self", ")", ":", "self", ".", "close_debugger", "(", ")", "if", "use_subprocess", ":", "self", ".", "interp", ".", "kill_subprocess", "(", ")", "# Restore std streams", "sys", ".", "stdout", "=", "self", ".", "save_stdout", "sys", "....
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/idlelib/PyShell.py#L997-L1011
pyansys/pymapdl
c07291fc062b359abf0e92b95a92d753a95ef3d7
ansys/mapdl/core/_commands/session/processor_entry.py
python
ProcessorEntry.aux12
(self, **kwargs)
return self.run(command, **kwargs)
Enters the radiation processor. APDL Command: /AUX12 Notes ----- Enters the radiation processor (ANSYS auxiliary processor AUX12). This processor supports the Radiation Matrix and the Radiosity Solver methods. This command is valid only at the Begin Level.
Enters the radiation processor.
[ "Enters", "the", "radiation", "processor", "." ]
def aux12(self, **kwargs): """Enters the radiation processor. APDL Command: /AUX12 Notes ----- Enters the radiation processor (ANSYS auxiliary processor AUX12). This processor supports the Radiation Matrix and the Radiosity Solver methods. This command is valid only at the Begin Level. """ command = "/AUX12," return self.run(command, **kwargs)
[ "def", "aux12", "(", "self", ",", "*", "*", "kwargs", ")", ":", "command", "=", "\"/AUX12,\"", "return", "self", ".", "run", "(", "command", ",", "*", "*", "kwargs", ")" ]
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/_commands/session/processor_entry.py#L38-L52
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/calendar.py
python
TextCalendar.formatweekday
(self, day, width)
return names[day][:width].center(width)
Returns a formatted week day name.
Returns a formatted week day name.
[ "Returns", "a", "formatted", "week", "day", "name", "." ]
def formatweekday(self, day, width): """ Returns a formatted week day name. """ if width >= 9: names = day_name else: names = day_abbr return names[day][:width].center(width)
[ "def", "formatweekday", "(", "self", ",", "day", ",", "width", ")", ":", "if", "width", ">=", "9", ":", "names", "=", "day_name", "else", ":", "names", "=", "day_abbr", "return", "names", "[", "day", "]", "[", ":", "width", "]", ".", "center", "(",...
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/calendar.py#L321-L329
GNS3/gns3-server
aff06572d4173df945ad29ea8feb274f7885d9e4
gns3server/utils/asyncio/aiozipstream.py
python
ZipFile._run_in_executor
(self, task, *args, **kwargs)
return await loop.run_in_executor(futures.ThreadPoolExecutor(max_workers=1), task, *args, **kwargs)
Run synchronous task in separate thread and await for result.
Run synchronous task in separate thread and await for result.
[ "Run", "synchronous", "task", "in", "separate", "thread", "and", "await", "for", "result", "." ]
async def _run_in_executor(self, task, *args, **kwargs): """ Run synchronous task in separate thread and await for result. """ loop = asyncio.get_event_loop() return await loop.run_in_executor(futures.ThreadPoolExecutor(max_workers=1), task, *args, **kwargs)
[ "async", "def", "_run_in_executor", "(", "self", ",", "task", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "return", "await", "loop", ".", "run_in_executor", "(", "futures", ".", "ThreadPoo...
https://github.com/GNS3/gns3-server/blob/aff06572d4173df945ad29ea8feb274f7885d9e4/gns3server/utils/asyncio/aiozipstream.py#L174-L180
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/combinatorics/util.py
python
_remove_gens
(base, strong_gens, basic_orbits=None, strong_gens_distr=None)
return res
Remove redundant generators from a strong generating set. Parameters ========== ``base`` - a base ``strong_gens`` - a strong generating set relative to ``base`` ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= A strong generating set with respect to ``base`` which is a subset of ``strong_gens``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.util import _remove_gens >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(15) >>> base, strong_gens = S.schreier_sims_incremental() >>> new_gens = _remove_gens(base, strong_gens) >>> len(new_gens) 14 >>> _verify_bsgs(S, base, new_gens) True Notes ===== This procedure is outlined in [1],p.95. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory"
Remove redundant generators from a strong generating set.
[ "Remove", "redundant", "generators", "from", "a", "strong", "generating", "set", "." ]
def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None): """ Remove redundant generators from a strong generating set. Parameters ========== ``base`` - a base ``strong_gens`` - a strong generating set relative to ``base`` ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= A strong generating set with respect to ``base`` which is a subset of ``strong_gens``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.util import _remove_gens >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(15) >>> base, strong_gens = S.schreier_sims_incremental() >>> new_gens = _remove_gens(base, strong_gens) >>> len(new_gens) 14 >>> _verify_bsgs(S, base, new_gens) True Notes ===== This procedure is outlined in [1],p.95. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ from sympy.combinatorics.perm_groups import _orbit base_len = len(base) degree = strong_gens[0].size if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if basic_orbits is None: basic_orbits = [] for i in range(base_len): basic_orbit = _orbit(degree, strong_gens_distr[i], base[i]) basic_orbits.append(basic_orbit) strong_gens_distr.append([]) res = strong_gens[:] for i in range(base_len - 1, -1, -1): gens_copy = strong_gens_distr[i][:] for gen in strong_gens_distr[i]: if gen not in strong_gens_distr[i + 1]: temp_gens = gens_copy[:] temp_gens.remove(gen) if temp_gens == []: continue temp_orbit = _orbit(degree, temp_gens, base[i]) if temp_orbit == basic_orbits[i]: gens_copy.remove(gen) res.remove(gen) return res
[ "def", "_remove_gens", "(", "base", ",", "strong_gens", ",", "basic_orbits", "=", "None", ",", "strong_gens_distr", "=", "None", ")", ":", "from", "sympy", ".", "combinatorics", ".", "perm_groups", "import", "_orbit", "base_len", "=", "len", "(", "base", ")"...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/util.py#L315-L384
mu-editor/mu
5a5d7723405db588f67718a63a0ec0ecabebae33
mu/interface/main.py
python
Window.stop_timer
(self)
Stop the repeating timer.
Stop the repeating timer.
[ "Stop", "the", "repeating", "timer", "." ]
def stop_timer(self): """ Stop the repeating timer. """ if self.timer: self.timer.stop() self.timer = None
[ "def", "stop_timer", "(", "self", ")", ":", "if", "self", ".", "timer", ":", "self", ".", "timer", ".", "stop", "(", ")", "self", ".", "timer", "=", "None" ]
https://github.com/mu-editor/mu/blob/5a5d7723405db588f67718a63a0ec0ecabebae33/mu/interface/main.py#L1201-L1207
RJT1990/pyflux
297f2afc2095acd97c12e827dd500e8ea5da0c0f
pyflux/garch/lmegarch.py
python
LMEGARCH._create_latent_variables
(self)
Creates model latent variables Returns ---------- None (changes model attributes)
Creates model latent variables
[ "Creates", "model", "latent", "variables" ]
def _create_latent_variables(self): """ Creates model latent variables Returns ---------- None (changes model attributes) """ self.latent_variables.add_z('Vol Constant', fam.Normal(0,3,transform=None), fam.Normal(0,3)) for component in range(2): increment = 0.05 for p_term in range(self.p): self.latent_variables.add_z("Component " + str(component+1) + ' p(' + str(p_term+1) + ')', fam.Normal(0,0.5,transform='logit'), fam.Normal(0,3)) if p_term == 0: self.latent_variables.z_list[1+p_term+component*(self.p+self.q)].start = 3.00 else: self.latent_variables.z_list[1+p_term+component*(self.p+self.q)].start = 2.00 for q_term in range(self.q): self.latent_variables.add_z("Component " + str(component+1) + ' q(' + str(q_term+1) + ')', fam.Normal(0,0.5,transform='logit'), fam.Normal(0,3)) if p_term == 0 and component == 0: self.latent_variables.z_list[1+self.p+q_term+component*(self.p+self.q)].start = -4.00 elif p_term == 0 and component == 1: self.latent_variables.z_list[1+self.p+q_term+component*(self.p+self.q)].start = -3.00 self.latent_variables.add_z('v', fam.Flat(transform='exp'), fam.Normal(0,3)) self.latent_variables.add_z('Returns Constant', fam.Normal(0, 3, transform=None), fam.Normal(0,3)) self.latent_variables.z_list[-2].start = 2.0
[ "def", "_create_latent_variables", "(", "self", ")", ":", "self", ".", "latent_variables", ".", "add_z", "(", "'Vol Constant'", ",", "fam", ".", "Normal", "(", "0", ",", "3", ",", "transform", "=", "None", ")", ",", "fam", ".", "Normal", "(", "0", ",",...
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/garch/lmegarch.py#L59-L87
vilcans/screenplain
b3b4ab5716470449ad4845a34b959e0ef2301359
screenplain/richstring.py
python
RichString.__unicode__
(self)
return ''.join(str(s) for s in self.segments)
[]
def __unicode__(self): return ''.join(str(s) for s in self.segments)
[ "def", "__unicode__", "(", "self", ")", ":", "return", "''", ".", "join", "(", "str", "(", "s", ")", "for", "s", "in", "self", ".", "segments", ")" ]
https://github.com/vilcans/screenplain/blob/b3b4ab5716470449ad4845a34b959e0ef2301359/screenplain/richstring.py#L36-L37
cisco/mindmeld
809c36112e9ea8019fe29d54d136ca14eb4fd8db
mindmeld/system_entity_recognizer.py
python
DucklingRecognizer.get_response
(self, data)
Send a post request to Duckling, data is a dictionary with field `text`. Return a tuple consisting the JSON response and a response code. Args: data (dict) Returns: (dict, int)
Send a post request to Duckling, data is a dictionary with field `text`. Return a tuple consisting the JSON response and a response code.
[ "Send", "a", "post", "request", "to", "Duckling", "data", "is", "a", "dictionary", "with", "field", "text", ".", "Return", "a", "tuple", "consisting", "the", "JSON", "response", "and", "a", "response", "code", "." ]
def get_response(self, data): """ Send a post request to Duckling, data is a dictionary with field `text`. Return a tuple consisting the JSON response and a response code. Args: data (dict) Returns: (dict, int) """ try: response = requests.request( "POST", self.url, data=data, timeout=float(SYS_ENTITY_REQUEST_TIMEOUT) ) if response.status_code == requests.codes["ok"]: response_json = response.json() return response_json, response.status_code else: raise SystemEntityError("System entity status code is not 200.") except requests.ConnectionError: sys.exit( "Unable to connect to the system entity recognizer. Make sure it's " "running by typing 'mindmeld num-parse' at the command line." ) except Exception as ex: # pylint: disable=broad-except logger.error( "Numerical Entity Recognizer Error: %s\nURL: %r\nData: %s", ex, self.url, json.dumps(data), ) sys.exit( "\nThe system entity recognizer encountered the following " + "error:\n" + str(ex) + "\nURL: " + self.url + "\nRaw data: " + str(data) + "\nPlease check your data and ensure Numerical parsing service is running. " "Make sure it's running by typing " "'mindmeld num-parse' at the command line." )
[ "def", "get_response", "(", "self", ",", "data", ")", ":", "try", ":", "response", "=", "requests", ".", "request", "(", "\"POST\"", ",", "self", ".", "url", ",", "data", "=", "data", ",", "timeout", "=", "float", "(", "SYS_ENTITY_REQUEST_TIMEOUT", ")", ...
https://github.com/cisco/mindmeld/blob/809c36112e9ea8019fe29d54d136ca14eb4fd8db/mindmeld/system_entity_recognizer.py#L268-L312
vmware-archive/vsphere-storage-for-docker
96d2ce72457047af4ef05cb0a8794cf623803865
esx_service/utils/auth_api.py
python
get_default_datastore_url
(name)
return error_info, default_datastore_url
Get default_datastore url for given tenant Return value: --- error_info: return None on success or error info on failure --- default_datastore: return name of default_datastore on success or None on failure
Get default_datastore url for given tenant Return value: --- error_info: return None on success or error info on failure --- default_datastore: return name of default_datastore on success or None on failure
[ "Get", "default_datastore", "url", "for", "given", "tenant", "Return", "value", ":", "---", "error_info", ":", "return", "None", "on", "success", "or", "error", "info", "on", "failure", "---", "default_datastore", ":", "return", "name", "of", "default_datastore"...
def get_default_datastore_url(name): """ Get default_datastore url for given tenant Return value: --- error_info: return None on success or error info on failure --- default_datastore: return name of default_datastore on success or None on failure """ logging.debug("auth_api.get_default_datastore_url: for tenant with name=%s", name) error_info, auth_mgr = get_auth_mgr_object() if error_info: return error_info, None if auth_mgr.allow_all_access(): if name == auth_data_const.DEFAULT_TENANT: return None, auth_data_const.VM_DS_URL else: return generate_error_info(ErrorCode.INIT_NEEDED), None error_info, tenant = get_tenant_from_db(name) if error_info: return error_info, None if not tenant: error_info = generate_error_info(ErrorCode.TENANT_NOT_EXIST, name) return error_info, None # if default_datastore is not set for this tenant, default_datastore will be None error_msg, default_datastore_url = tenant.get_default_datastore(auth_mgr.conn) if error_msg: error_info = generate_error_info(ErrorCode.INTERNAL_ERROR, error_msg) logging.debug("returning url %s", default_datastore_url) return error_info, default_datastore_url
[ "def", "get_default_datastore_url", "(", "name", ")", ":", "logging", ".", "debug", "(", "\"auth_api.get_default_datastore_url: for tenant with name=%s\"", ",", "name", ")", "error_info", ",", "auth_mgr", "=", "get_auth_mgr_object", "(", ")", "if", "error_info", ":", ...
https://github.com/vmware-archive/vsphere-storage-for-docker/blob/96d2ce72457047af4ef05cb0a8794cf623803865/esx_service/utils/auth_api.py#L319-L351
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twill/twill/other_packages/_mechanize_dist/_beautifulsoup.py
python
Tag.__eq__
(self, other)
return True
Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?
Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag.
[ "Returns", "true", "iff", "this", "tag", "has", "the", "same", "name", "the", "same", "attributes", "and", "the", "same", "contents", "(", "recursively", ")", "as", "the", "given", "tag", "." ]
def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?""" if not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other): return False for i in range(0, len(self.contents)): if self.contents[i] != other.contents[i]: return False return True
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "not", "hasattr", "(", "other", ",", "'name'", ")", "or", "not", "hasattr", "(", "other", ",", "'attrs'", ")", "or", "not", "hasattr", "(", "other", ",", "'contents'", ")", "or", "self", "...
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twill/twill/other_packages/_mechanize_dist/_beautifulsoup.py#L355-L366
SolidCode/SolidPython
4715c827ad90db26ee37df57bc425e6f2de3cf8d
solid/solidpython.py
python
OpenSCADObject._repr_png_
(self)
return png_data
Allow rich clients such as the IPython Notebook, to display the current OpenSCAD rendering of this object.
Allow rich clients such as the IPython Notebook, to display the current OpenSCAD rendering of this object.
[ "Allow", "rich", "clients", "such", "as", "the", "IPython", "Notebook", "to", "display", "the", "current", "OpenSCAD", "rendering", "of", "this", "object", "." ]
def _repr_png_(self) -> Optional[bytes]: """ Allow rich clients such as the IPython Notebook, to display the current OpenSCAD rendering of this object. """ png_data = None tmp = tempfile.NamedTemporaryFile(suffix=".scad", delete=False) tmp_png = tempfile.NamedTemporaryFile(suffix=".png", delete=False) try: scad_text = scad_render(self).encode("utf-8") tmp.write(scad_text) tmp.close() tmp_png.close() subprocess.Popen([ "openscad", "--preview", "-o", tmp_png.name, tmp.name ]).communicate() with open(tmp_png.name, "rb") as png: png_data = png.read() finally: os.unlink(tmp.name) os.unlink(tmp_png.name) return png_data
[ "def", "_repr_png_", "(", "self", ")", "->", "Optional", "[", "bytes", "]", ":", "png_data", "=", "None", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "\".scad\"", ",", "delete", "=", "False", ")", "tmp_png", "=", "tempfile", "....
https://github.com/SolidCode/SolidPython/blob/4715c827ad90db26ee37df57bc425e6f2de3cf8d/solid/solidpython.py#L335-L361
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/asn1crypto/x509.py
python
Certificate._get_http_crl_distribution_points
(self, crl_distribution_points)
return output
Fetches the DistributionPoint object for non-relative, HTTP CRLs referenced by the certificate :param crl_distribution_points: A CRLDistributionPoints object to grab the DistributionPoints from :return: A list of zero or more DistributionPoint objects
Fetches the DistributionPoint object for non-relative, HTTP CRLs referenced by the certificate
[ "Fetches", "the", "DistributionPoint", "object", "for", "non", "-", "relative", "HTTP", "CRLs", "referenced", "by", "the", "certificate" ]
def _get_http_crl_distribution_points(self, crl_distribution_points): """ Fetches the DistributionPoint object for non-relative, HTTP CRLs referenced by the certificate :param crl_distribution_points: A CRLDistributionPoints object to grab the DistributionPoints from :return: A list of zero or more DistributionPoint objects """ output = [] if crl_distribution_points is None: return [] for distribution_point in crl_distribution_points: distribution_point_name = distribution_point['distribution_point'] if distribution_point_name is VOID: continue # RFC 5280 indicates conforming CA should not use the relative form if distribution_point_name.name == 'name_relative_to_crl_issuer': continue # This library is currently only concerned with HTTP-based CRLs for general_name in distribution_point_name.chosen: if general_name.name == 'uniform_resource_identifier': output.append(distribution_point) return output
[ "def", "_get_http_crl_distribution_points", "(", "self", ",", "crl_distribution_points", ")", ":", "output", "=", "[", "]", "if", "crl_distribution_points", "is", "None", ":", "return", "[", "]", "for", "distribution_point", "in", "crl_distribution_points", ":", "di...
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/asn1crypto/x509.py#L2665-L2694
Pymol-Scripts/Pymol-script-repo
bcd7bb7812dc6db1595953dfa4471fa15fb68c77
modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/Utility.py
python
ElementProxy.createElementNS
(self, namespace, qname)
return ElementProxy(self.sw, node)
Keyword arguments: namespace -- namespace of element to create qname -- qualified name of new element
Keyword arguments: namespace -- namespace of element to create qname -- qualified name of new element
[ "Keyword", "arguments", ":", "namespace", "--", "namespace", "of", "element", "to", "create", "qname", "--", "qualified", "name", "of", "new", "element" ]
def createElementNS(self, namespace, qname): ''' Keyword arguments: namespace -- namespace of element to create qname -- qualified name of new element ''' document = self._getOwnerDocument() node = document.createElementNS(namespace, qname) return ElementProxy(self.sw, node)
[ "def", "createElementNS", "(", "self", ",", "namespace", ",", "qname", ")", ":", "document", "=", "self", ".", "_getOwnerDocument", "(", ")", "node", "=", "document", ".", "createElementNS", "(", "namespace", ",", "qname", ")", "return", "ElementProxy", "(",...
https://github.com/Pymol-Scripts/Pymol-script-repo/blob/bcd7bb7812dc6db1595953dfa4471fa15fb68c77/modules/pdb2pqr/contrib/ZSI-2.1-a1/ZSI/wstools/Utility.py#L1012-L1020
marcosfede/algorithms
1ee7c815f9d556c9cef4d4b0d21ee3a409d21629
adventofcode/2018/21/d21.py
python
gtrr
(r, a, b)
return 1 if r[a] > r[b] else 0
[]
def gtrr(r, a, b): return 1 if r[a] > r[b] else 0
[ "def", "gtrr", "(", "r", ",", "a", ",", "b", ")", ":", "return", "1", "if", "r", "[", "a", "]", ">", "r", "[", "b", "]", "else", "0" ]
https://github.com/marcosfede/algorithms/blob/1ee7c815f9d556c9cef4d4b0d21ee3a409d21629/adventofcode/2018/21/d21.py#L50-L51
bashtage/linearmodels
9256269f01ff8c5f85e65342d66149a5636661b6
linearmodels/panel/model.py
python
_PanelModelBase.not_null
(self)
return self._not_null
Locations of non-missing observations
Locations of non-missing observations
[ "Locations", "of", "non", "-", "missing", "observations" ]
def not_null(self) -> Float64Array: """Locations of non-missing observations""" return self._not_null
[ "def", "not_null", "(", "self", ")", "->", "Float64Array", ":", "return", "self", ".", "_not_null" ]
https://github.com/bashtage/linearmodels/blob/9256269f01ff8c5f85e65342d66149a5636661b6/linearmodels/panel/model.py#L690-L692
pythonarcade/arcade
1ee3eb1900683213e8e8df93943327c2ea784564
arcade/examples/sprite_face_left_or_right.py
python
MyGame.on_key_release
(self, key, modifiers)
Called when the user releases a key.
Called when the user releases a key.
[ "Called", "when", "the", "user", "releases", "a", "key", "." ]
def on_key_release(self, key, modifiers): """Called when the user releases a key. """ if key == arcade.key.UP or key == arcade.key.DOWN: self.player_sprite.change_y = 0 elif key == arcade.key.LEFT or key == arcade.key.RIGHT: self.player_sprite.change_x = 0
[ "def", "on_key_release", "(", "self", ",", "key", ",", "modifiers", ")", ":", "if", "key", "==", "arcade", ".", "key", ".", "UP", "or", "key", "==", "arcade", ".", "key", ".", "DOWN", ":", "self", ".", "player_sprite", ".", "change_y", "=", "0", "e...
https://github.com/pythonarcade/arcade/blob/1ee3eb1900683213e8e8df93943327c2ea784564/arcade/examples/sprite_face_left_or_right.py#L122-L128
xtiankisutsa/MARA_Framework
ac4ac88bfd38f33ae8780a606ed09ab97177c562
tools/androguard/androguard/core/bytecodes/dvm.py
python
ClassDefItem.get_access_flags
(self)
return self.access_flags
Return the access flags for the class (public, final, etc.) :rtype: int
Return the access flags for the class (public, final, etc.)
[ "Return", "the", "access", "flags", "for", "the", "class", "(", "public", "final", "etc", ".", ")" ]
def get_access_flags(self): """ Return the access flags for the class (public, final, etc.) :rtype: int """ return self.access_flags
[ "def", "get_access_flags", "(", "self", ")", ":", "return", "self", ".", "access_flags" ]
https://github.com/xtiankisutsa/MARA_Framework/blob/ac4ac88bfd38f33ae8780a606ed09ab97177c562/tools/androguard/androguard/core/bytecodes/dvm.py#L3506-L3512
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/interface.py
python
SurfaceTension.test_method_validity
(self, T, method)
return validity
r'''Method to check the validity of a method. Follows the given ranges for all coefficient-based methods. For CSP methods, the models are considered valid from 0 K to the critical point. For tabular data, extrapolation outside of the range is used if :obj:`tabular_extrapolation_permitted` is set; if it is, the extrapolation is considered valid for all temperatures. It is not guaranteed that a method will work or give an accurate prediction simply because this method considers the method valid. Parameters ---------- T : float Temperature at which to test the method, [K] method : str Name of the method to test Returns ------- validity : bool Whether or not a method is valid
r'''Method to check the validity of a method. Follows the given ranges for all coefficient-based methods. For CSP methods, the models are considered valid from 0 K to the critical point. For tabular data, extrapolation outside of the range is used if :obj:`tabular_extrapolation_permitted` is set; if it is, the extrapolation is considered valid for all temperatures.
[ "r", "Method", "to", "check", "the", "validity", "of", "a", "method", ".", "Follows", "the", "given", "ranges", "for", "all", "coefficient", "-", "based", "methods", ".", "For", "CSP", "methods", "the", "models", "are", "considered", "valid", "from", "0", ...
def test_method_validity(self, T, method): r'''Method to check the validity of a method. Follows the given ranges for all coefficient-based methods. For CSP methods, the models are considered valid from 0 K to the critical point. For tabular data, extrapolation outside of the range is used if :obj:`tabular_extrapolation_permitted` is set; if it is, the extrapolation is considered valid for all temperatures. It is not guaranteed that a method will work or give an accurate prediction simply because this method considers the method valid. Parameters ---------- T : float Temperature at which to test the method, [K] method : str Name of the method to test Returns ------- validity : bool Whether or not a method is valid ''' validity = True if method == STREFPROP: if T < self.STREFPROP_Tmin or T > self.STREFPROP_Tmax: validity = False elif method == VDI_PPDS: if T > self.VDI_PPDS_Tc: # Could also check for low temp, but not necessary as it extrapolates validity = False elif method == SOMAYAJULU2: if T < self.SOMAYAJULU2_Tt or T > self.SOMAYAJULU2_Tc: validity = False elif method == SOMAYAJULU: if T < self.SOMAYAJULU_Tt or T > self.SOMAYAJULU_Tc: validity = False elif method == JASPER: if T < self.JASPER_Tmin or T > self.JASPER_Tmax: validity = False elif method in [BROCK_BIRD, SASTRI_RAO, PITZER, ZUO_STENBY, MIQUEU]: if T > self.Tc: validity = False elif method == ALEEM: if T > self.Tb + self.Hvap_Tb/self.Cpl_Tb: validity = False else: return super(SurfaceTension, self).test_method_validity(T, method) return validity
[ "def", "test_method_validity", "(", "self", ",", "T", ",", "method", ")", ":", "validity", "=", "True", "if", "method", "==", "STREFPROP", ":", "if", "T", "<", "self", ".", "STREFPROP_Tmin", "or", "T", ">", "self", ".", "STREFPROP_Tmax", ":", "validity",...
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/interface.py#L429-L477
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/html5lib/_tokenizer.py
python
HTMLTokenizer.scriptDataEndTagNameState
(self)
return True
[]
def scriptDataEndTagNameState(self): appropriate = self.currentToken and self.currentToken["name"].lower() == self.temporaryBuffer.lower() data = self.stream.char() if data in spaceCharacters and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.beforeAttributeNameState elif data == "/" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.state = self.selfClosingStartTagState elif data == ">" and appropriate: self.currentToken = {"type": tokenTypes["EndTag"], "name": self.temporaryBuffer, "data": [], "selfClosing": False} self.emitCurrentToken() self.state = self.dataState elif data in asciiLetters: self.temporaryBuffer += data else: self.tokenQueue.append({"type": tokenTypes["Characters"], "data": "</" + self.temporaryBuffer}) self.stream.unget(data) self.state = self.scriptDataState return True
[ "def", "scriptDataEndTagNameState", "(", "self", ")", ":", "appropriate", "=", "self", ".", "currentToken", "and", "self", ".", "currentToken", "[", "\"name\"", "]", ".", "lower", "(", ")", "==", "self", ".", "temporaryBuffer", ".", "lower", "(", ")", "dat...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/_vendor/html5lib/_tokenizer.py#L567-L593
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/filters/inject_meta_charset.py
python
Filter.__iter__
(self)
[]
def __iter__(self): state = "pre_head" meta_found = (self.encoding is None) pending = [] for token in base.Filter.__iter__(self): type = token["type"] if type == "StartTag": if token["name"].lower() == "head": state = "in_head" elif type == "EmptyTag": if token["name"].lower() == "meta": # replace charset with actual encoding has_http_equiv_content_type = False for (namespace, name), value in token["data"].items(): if namespace is not None: continue elif name.lower() == 'charset': token["data"][(namespace, name)] = self.encoding meta_found = True break elif name == 'http-equiv' and value.lower() == 'content-type': has_http_equiv_content_type = True else: if has_http_equiv_content_type and (None, "content") in token["data"]: token["data"][(None, "content")] = 'text/html; charset=%s' % self.encoding meta_found = True elif token["name"].lower() == "head" and not meta_found: # insert meta into empty head yield {"type": "StartTag", "name": "head", "data": token["data"]} yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} yield {"type": "EndTag", "name": "head"} meta_found = True continue elif type == "EndTag": if token["name"].lower() == "head" and pending: # insert meta into head (if necessary) and flush pending queue yield pending.pop(0) if not meta_found: yield {"type": "EmptyTag", "name": "meta", "data": {(None, "charset"): self.encoding}} while pending: yield pending.pop(0) meta_found = True state = "post_head" if state == "in_head": pending.append(token) else: yield token
[ "def", "__iter__", "(", "self", ")", ":", "state", "=", "\"pre_head\"", "meta_found", "=", "(", "self", ".", "encoding", "is", "None", ")", "pending", "=", "[", "]", "for", "token", "in", "base", ".", "Filter", ".", "__iter__", "(", "self", ")", ":",...
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/_vendor/html5lib/filters/inject_meta_charset.py#L11-L65
seppius-xbmc-repo/ru
d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2
plugin.video.online.anidub.com/resources/lib/BeautifulSoup.py
python
BeautifulStoneSoup.popTag
(self)
return self.currentTag
[]
def popTag(self): tag = self.tagStack.pop() #print "Pop", tag.name if self.tagStack: self.currentTag = self.tagStack[-1] return self.currentTag
[ "def", "popTag", "(", "self", ")", ":", "tag", "=", "self", ".", "tagStack", ".", "pop", "(", ")", "#print \"Pop\", tag.name", "if", "self", ".", "tagStack", ":", "self", ".", "currentTag", "=", "self", ".", "tagStack", "[", "-", "1", "]", "return", ...
https://github.com/seppius-xbmc-repo/ru/blob/d0879d56ec8243b2c7af44fda5cf3d1ff77fd2e2/plugin.video.online.anidub.com/resources/lib/BeautifulSoup.py#L1221-L1227
tav/pylibs
3c16b843681f54130ee6a022275289cadb2f2a69
paramiko/pkey.py
python
PKey.get_fingerprint
(self)
return MD5.new(str(self)).digest()
Return an MD5 fingerprint of the public part of this key. Nothing secret is revealed. @return: a 16-byte string (binary) of the MD5 fingerprint, in SSH format. @rtype: str
Return an MD5 fingerprint of the public part of this key. Nothing secret is revealed.
[ "Return", "an", "MD5", "fingerprint", "of", "the", "public", "part", "of", "this", "key", ".", "Nothing", "secret", "is", "revealed", "." ]
def get_fingerprint(self): """ Return an MD5 fingerprint of the public part of this key. Nothing secret is revealed. @return: a 16-byte string (binary) of the MD5 fingerprint, in SSH format. @rtype: str """ return MD5.new(str(self)).digest()
[ "def", "get_fingerprint", "(", "self", ")", ":", "return", "MD5", ".", "new", "(", "str", "(", "self", ")", ")", ".", "digest", "(", ")" ]
https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/paramiko/pkey.py#L124-L133
sktime/sktime-dl
e519bf5983f9ed60b04b0d14f4fe3fa049a82f04
sktime_dl/utils/layer_utils.py
python
_time_distributed_dense
(x, w, b=None, dropout=None, input_dim=None, output_dim=None, timesteps=None, training=None)
return x
Apply `y . w + b` for every temporal slice y of x. # Arguments x: input tensor. w: weight matrix. b: optional bias vector. dropout: wether to apply dropout (same dropout mask for every temporal slice of the input). input_dim: integer; optional dimensionality of the input. output_dim: integer; optional dimensionality of the output. timesteps: integer; optional number of timesteps. training: training phase tensor or boolean. # Returns Output tensor.
Apply `y . w + b` for every temporal slice y of x. # Arguments x: input tensor. w: weight matrix. b: optional bias vector. dropout: wether to apply dropout (same dropout mask for every temporal slice of the input). input_dim: integer; optional dimensionality of the input. output_dim: integer; optional dimensionality of the output. timesteps: integer; optional number of timesteps. training: training phase tensor or boolean. # Returns Output tensor.
[ "Apply", "y", ".", "w", "+", "b", "for", "every", "temporal", "slice", "y", "of", "x", ".", "#", "Arguments", "x", ":", "input", "tensor", ".", "w", ":", "weight", "matrix", ".", "b", ":", "optional", "bias", "vector", ".", "dropout", ":", "wether"...
def _time_distributed_dense(x, w, b=None, dropout=None, input_dim=None, output_dim=None, timesteps=None, training=None): """Apply `y . w + b` for every temporal slice y of x. # Arguments x: input tensor. w: weight matrix. b: optional bias vector. dropout: wether to apply dropout (same dropout mask for every temporal slice of the input). input_dim: integer; optional dimensionality of the input. output_dim: integer; optional dimensionality of the output. timesteps: integer; optional number of timesteps. training: training phase tensor or boolean. # Returns Output tensor. """ if not input_dim: input_dim = K.shape(x)[2] if not timesteps: timesteps = K.shape(x)[1] if not output_dim: output_dim = K.int_shape(w)[1] if dropout is not None and 0. < dropout < 1.: # apply the same dropout pattern at every timestep ones = K.ones_like(K.reshape(x[:, 0, :], (-1, input_dim))) dropout_matrix = K.dropout(ones, dropout) expanded_dropout_matrix = K.repeat(dropout_matrix, timesteps) x = K.in_train_phase(x * expanded_dropout_matrix, x, training=training) # collapse time dimension and batch dimension together x = K.reshape(x, (-1, input_dim)) x = K.dot(x, w) if b is not None: x = K.bias_add(x, b) # reshape to 3D tensor if K.backend() == 'tensorflow': x = K.reshape(x, K.stack([-1, timesteps, output_dim])) x.set_shape([None, None, output_dim]) else: x = K.reshape(x, (-1, timesteps, output_dim)) return x
[ "def", "_time_distributed_dense", "(", "x", ",", "w", ",", "b", "=", "None", ",", "dropout", "=", "None", ",", "input_dim", "=", "None", ",", "output_dim", "=", "None", ",", "timesteps", "=", "None", ",", "training", "=", "None", ")", ":", "if", "not...
https://github.com/sktime/sktime-dl/blob/e519bf5983f9ed60b04b0d14f4fe3fa049a82f04/sktime_dl/utils/layer_utils.py#L15-L57
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/gdata/Crypto/PublicKey/qNEW.py
python
qNEWobj.has_private
(self)
return hasattr(self, 'x')
Return a Boolean denoting whether the object contains private components.
Return a Boolean denoting whether the object contains private components.
[ "Return", "a", "Boolean", "denoting", "whether", "the", "object", "contains", "private", "components", "." ]
def has_private(self): """Return a Boolean denoting whether the object contains private components.""" return hasattr(self, 'x')
[ "def", "has_private", "(", "self", ")", ":", "return", "hasattr", "(", "self", ",", "'x'", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/gdata/Crypto/PublicKey/qNEW.py#L152-L155
Nekmo/amazon-dash
ac2b2f98282ec08036e1671fe937dfda381a911f
amazon_dash/exceptions.py
python
InvalidConfig.__init__
(self, file=None, extra_body='')
:param str file: Path to config file :param extra_body: complementary message
:param str file: Path to config file :param extra_body: complementary message
[ ":", "param", "str", "file", ":", "Path", "to", "config", "file", ":", "param", "extra_body", ":", "complementary", "message" ]
def __init__(self, file=None, extra_body=''): """ :param str file: Path to config file :param extra_body: complementary message """ body = 'The configuration file is invalid' if file: file = os.path.abspath(file) body += ' ({})'.format(file) body += '. Check the file and read the documentation.'.format(file) if extra_body: body += ' {}'.format(extra_body) super(InvalidConfig, self).__init__(body)
[ "def", "__init__", "(", "self", ",", "file", "=", "None", ",", "extra_body", "=", "''", ")", ":", "body", "=", "'The configuration file is invalid'", "if", "file", ":", "file", "=", "os", ".", "path", ".", "abspath", "(", "file", ")", "body", "+=", "' ...
https://github.com/Nekmo/amazon-dash/blob/ac2b2f98282ec08036e1671fe937dfda381a911f/amazon_dash/exceptions.py#L41-L53
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/operator.py
python
indexOf
(a, b)
Return the first index of b in a.
Return the first index of b in a.
[ "Return", "the", "first", "index", "of", "b", "in", "a", "." ]
def indexOf(a, b): "Return the first index of b in a." for i, j in enumerate(a): if j is b or j == b: return i else: raise ValueError('sequence.index(x): x not in sequence')
[ "def", "indexOf", "(", "a", ",", "b", ")", ":", "for", "i", ",", "j", "in", "enumerate", "(", "a", ")", ":", "if", "j", "is", "b", "or", "j", "==", "b", ":", "return", "i", "else", ":", "raise", "ValueError", "(", "'sequence.index(x): x not in sequ...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/operator.py#L173-L179
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/appengine/libs/handler.py
python
check_user_access
(need_privileged_access)
return decorator
Wrap a handler with check_user_access. This decorator must be below post(..) and get(..) when used.
Wrap a handler with check_user_access.
[ "Wrap", "a", "handler", "with", "check_user_access", "." ]
def check_user_access(need_privileged_access): """Wrap a handler with check_user_access. This decorator must be below post(..) and get(..) when used. """ def decorator(func): """Decorator.""" @functools.wraps(func) def wrapper(self, *args, **kwargs): """Wrapper.""" if not access.has_access(need_privileged_access=need_privileged_access): raise helpers.AccessDeniedException() return func(self, *args, **kwargs) return wrapper return decorator
[ "def", "check_user_access", "(", "need_privileged_access", ")", ":", "def", "decorator", "(", "func", ")", ":", "\"\"\"Decorator.\"\"\"", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwa...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/appengine/libs/handler.py#L307-L326
Digital-Sapphire/PyUpdater
d408f54a38ab63ab5f4bcf6471ac1a546357b29f
pyupdater/_version.py
python
render_pep440_pre
(pieces)
return rendered
TAG[.post0.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE
TAG[.post0.devDISTANCE] -- No -dirty.
[ "TAG", "[", ".", "post0", ".", "devDISTANCE", "]", "--", "No", "-", "dirty", "." ]
def render_pep440_pre(pieces): """TAG[.post0.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post0.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered
[ "def", "render_pep440_pre", "(", "pieces", ")", ":", "if", "pieces", "[", "\"closest-tag\"", "]", ":", "rendered", "=", "pieces", "[", "\"closest-tag\"", "]", "if", "pieces", "[", "\"distance\"", "]", ":", "rendered", "+=", "\".post0.dev%d\"", "%", "pieces", ...
https://github.com/Digital-Sapphire/PyUpdater/blob/d408f54a38ab63ab5f4bcf6471ac1a546357b29f/pyupdater/_version.py#L369-L382
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/maasserver/api/ssl_keys.py
python
SSLKeyHandler.read
(self, request, id)
return key
@description-title Retrieve an SSL key @description Retrieves an SSL key with the given ID. @param (int) "id" [required=true] An SSL key ID. @success (http-status-code) "200" 200 @success (json) "success-json" A JSON object containing a list of imported keys. @success-example "success-json" [exkey=ssl-keys-get] placeholder text @error (http-status-code) "404" 404 @error (content) "not-found" The requested SSH key is not found. @error-example "not-found" Not Found @error (http-status-code) "403" 403 @error (content) "no-perms" The requesting user does not own the key. @error-example "no-perms" Can't get a key you don't own.
@description-title Retrieve an SSL key @description Retrieves an SSL key with the given ID.
[ "@description", "-", "title", "Retrieve", "an", "SSL", "key", "@description", "Retrieves", "an", "SSL", "key", "with", "the", "given", "ID", "." ]
def read(self, request, id): """@description-title Retrieve an SSL key @description Retrieves an SSL key with the given ID. @param (int) "id" [required=true] An SSL key ID. @success (http-status-code) "200" 200 @success (json) "success-json" A JSON object containing a list of imported keys. @success-example "success-json" [exkey=ssl-keys-get] placeholder text @error (http-status-code) "404" 404 @error (content) "not-found" The requested SSH key is not found. @error-example "not-found" Not Found @error (http-status-code) "403" 403 @error (content) "no-perms" The requesting user does not own the key. @error-example "no-perms" Can't get a key you don't own. """ key = get_object_or_404(SSLKey, id=id) if key.user != request.user: return HttpResponseForbidden("Can't get a key you don't own.") return key
[ "def", "read", "(", "self", ",", "request", ",", "id", ")", ":", "key", "=", "get_object_or_404", "(", "SSLKey", ",", "id", "=", "id", ")", "if", "key", ".", "user", "!=", "request", ".", "user", ":", "return", "HttpResponseForbidden", "(", "\"Can't ge...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/maasserver/api/ssl_keys.py#L95-L120
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.83/Libs/immlib.py
python
Debugger.setComment
(self, address, comment)
return debugger.set_comment(address, comment)
Set a comment. @type address: DWORD @param address: Address of the Comment @type comment: STRING @param comment: Comment to add
Set a comment.
[ "Set", "a", "comment", "." ]
def setComment(self, address, comment): """ Set a comment. @type address: DWORD @param address: Address of the Comment @type comment: STRING @param comment: Comment to add """ return debugger.set_comment(address, comment)
[ "def", "setComment", "(", "self", ",", "address", ",", "comment", ")", ":", "return", "debugger", ".", "set_comment", "(", "address", ",", "comment", ")" ]
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.83/Libs/immlib.py#L1783-L1793
materialsproject/pymatgen
8128f3062a334a2edd240e4062b5b9bdd1ae6f58
pymatgen/core/interface.py
python
Interface.substrate_indicies
(self)
return sub_indicies
Site indicies for the substrate atoms
Site indicies for the substrate atoms
[ "Site", "indicies", "for", "the", "substrate", "atoms" ]
def substrate_indicies(self) -> List[int]: """ Site indicies for the substrate atoms """ sub_indicies = [i for i, tag in enumerate(self.site_properties["interface_label"]) if "substrate" in tag] return sub_indicies
[ "def", "substrate_indicies", "(", "self", ")", "->", "List", "[", "int", "]", ":", "sub_indicies", "=", "[", "i", "for", "i", ",", "tag", "in", "enumerate", "(", "self", ".", "site_properties", "[", "\"interface_label\"", "]", ")", "if", "\"substrate\"", ...
https://github.com/materialsproject/pymatgen/blob/8128f3062a334a2edd240e4062b5b9bdd1ae6f58/pymatgen/core/interface.py#L151-L156
metabrainz/picard
535bf8c7d9363ffc7abb3f69418ec11823c38118
picard/ui/options/releases.py
python
TipSlider.showEvent
(self, event)
[]
def showEvent(self, event): super().showEvent(event) if not IS_WIN: self.valueChanged.connect(self.show_tip)
[ "def", "showEvent", "(", "self", ",", "event", ")", ":", "super", "(", ")", ".", "showEvent", "(", "event", ")", "if", "not", "IS_WIN", ":", "self", ".", "valueChanged", ".", "connect", "(", "self", ".", "show_tip", ")" ]
https://github.com/metabrainz/picard/blob/535bf8c7d9363ffc7abb3f69418ec11823c38118/picard/ui/options/releases.py#L80-L83
Azure/blobxfer
c6c6c143e8ee413d09a1110abafdb92e9e8afc39
blobxfer/models/resume.py
python
SyncCopy.src_block_list
(self)
return self._src_block_list
Source committed block list :param SyncCopy self: this :rtype: list :return: source committed block list
Source committed block list :param SyncCopy self: this :rtype: list :return: source committed block list
[ "Source", "committed", "block", "list", ":", "param", "SyncCopy", "self", ":", "this", ":", "rtype", ":", "list", ":", "return", ":", "source", "committed", "block", "list" ]
def src_block_list(self): # type: (SyncCopy) -> list """Source committed block list :param SyncCopy self: this :rtype: list :return: source committed block list """ return self._src_block_list
[ "def", "src_block_list", "(", "self", ")", ":", "# type: (SyncCopy) -> list", "return", "self", ".", "_src_block_list" ]
https://github.com/Azure/blobxfer/blob/c6c6c143e8ee413d09a1110abafdb92e9e8afc39/blobxfer/models/resume.py#L326-L333
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/pupylib/payloads/dependencies.py
python
bundle
(platform, arch)
return ZipFile(arch_bundle, 'r')
[]
def bundle(platform, arch): arch_bundle = os.path.join( 'payload_templates', platform+'-'+arch+'.zip' ) if not os.path.isfile(arch_bundle): arch_bundle = os.path.join( ROOT, 'payload_templates', platform+'-'+arch+'.zip' ) if not os.path.exists(arch_bundle): return None return ZipFile(arch_bundle, 'r')
[ "def", "bundle", "(", "platform", ",", "arch", ")", ":", "arch_bundle", "=", "os", ".", "path", ".", "join", "(", "'payload_templates'", ",", "platform", "+", "'-'", "+", "arch", "+", "'.zip'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(",...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/pupylib/payloads/dependencies.py#L664-L677
hasegaw/IkaLog
bd476da541fcc296f792d4db76a6b9174c4777ad
ikalog/outputs/twitter.py
python
Twitter.refresh_ui
(self)
[]
def refresh_ui(self): self._internal_update = True self.checkEnable.SetValue(self.enabled) self.checkAttachImage.SetValue(self.attach_image) self.checkTweetKd.SetValue(self.tweet_kd) self.checkTweetMyScore.SetValue(self.tweet_my_score) self.checkTweetUdemae.SetValue(self.tweet_udemae) self.checkUseReply.SetValue(self.use_reply) try: { 'ikalog': self.radioIkaLogKey, 'own': self.radioOwnKey, }[self.consumer_key_type].SetValue(True) except: pass if not self.consumer_key is None: self.editConsumerKey.SetValue(self.consumer_key) else: self.editConsumerKey.SetValue('') if not self.consumer_secret is None: self.editConsumerSecret.SetValue(self.consumer_secret) else: self.editConsumerSecret.SetValue('') if not self.access_token is None: self.editAccessToken.SetValue(self.access_token) else: self.editAccessToken.SetValue('') if not self.access_token_secret is None: self.editAccessTokenSecret.SetValue(self.access_token_secret) else: self.editAccessTokenSecret.SetValue('') if not self.footer is None: self.editFooter.SetValue(self.footer) else: self.editFooter.SetValue('') self.on_consumer_key_mode_switch() self._internal_update = False
[ "def", "refresh_ui", "(", "self", ")", ":", "self", ".", "_internal_update", "=", "True", "self", ".", "checkEnable", ".", "SetValue", "(", "self", ".", "enabled", ")", "self", ".", "checkAttachImage", ".", "SetValue", "(", "self", ".", "attach_image", ")"...
https://github.com/hasegaw/IkaLog/blob/bd476da541fcc296f792d4db76a6b9174c4777ad/ikalog/outputs/twitter.py#L93-L135
schaul/py-vgdl
b595d3f94d286a8a3369786b055a2f7a554bb982
vgdl/ontology.py
python
conveySprite
(sprite, partner, game)
Moves the partner in target direction by some step size.
Moves the partner in target direction by some step size.
[ "Moves", "the", "partner", "in", "target", "direction", "by", "some", "step", "size", "." ]
def conveySprite(sprite, partner, game): """ Moves the partner in target direction by some step size. """ tmp = sprite.lastrect v = unitVector(partner.orientation) sprite.physics.activeMovement(sprite, v, speed=partner.strength) sprite.lastrect = tmp game._updateCollisionDict(sprite)
[ "def", "conveySprite", "(", "sprite", ",", "partner", ",", "game", ")", ":", "tmp", "=", "sprite", ".", "lastrect", "v", "=", "unitVector", "(", "partner", ".", "orientation", ")", "sprite", ".", "physics", ".", "activeMovement", "(", "sprite", ",", "v",...
https://github.com/schaul/py-vgdl/blob/b595d3f94d286a8a3369786b055a2f7a554bb982/vgdl/ontology.py#L752-L758
explosion/srsly
8617ecc099d1f34a60117b5287bef5424ea2c837
srsly/ruamel_yaml/comments.py
python
CommentedMap.merge
(self)
return getattr(self, merge_attrib)
[]
def merge(self): # type: () -> Any if not hasattr(self, merge_attrib): setattr(self, merge_attrib, []) return getattr(self, merge_attrib)
[ "def", "merge", "(", "self", ")", ":", "# type: () -> Any", "if", "not", "hasattr", "(", "self", ",", "merge_attrib", ")", ":", "setattr", "(", "self", ",", "merge_attrib", ",", "[", "]", ")", "return", "getattr", "(", "self", ",", "merge_attrib", ")" ]
https://github.com/explosion/srsly/blob/8617ecc099d1f34a60117b5287bef5424ea2c837/srsly/ruamel_yaml/comments.py#L911-L915
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/combinat/words/finite_word.py
python
FiniteWord_class.is_proper_prefix
(self, other)
return self.is_prefix(other) and self.length() < other.length()
r""" Return ``True`` if ``self`` is a proper prefix of ``other``, and ``False`` otherwise. EXAMPLES:: sage: Word('12').is_proper_prefix(Word('123')) True sage: Word('12').is_proper_prefix(Word('12')) False sage: Word().is_proper_prefix(Word('123')) True sage: Word('123').is_proper_prefix(Word('12')) False sage: Word().is_proper_prefix(Word()) False
r""" Return ``True`` if ``self`` is a proper prefix of ``other``, and ``False`` otherwise.
[ "r", "Return", "True", "if", "self", "is", "a", "proper", "prefix", "of", "other", "and", "False", "otherwise", "." ]
def is_proper_prefix(self, other): r""" Return ``True`` if ``self`` is a proper prefix of ``other``, and ``False`` otherwise. EXAMPLES:: sage: Word('12').is_proper_prefix(Word('123')) True sage: Word('12').is_proper_prefix(Word('12')) False sage: Word().is_proper_prefix(Word('123')) True sage: Word('123').is_proper_prefix(Word('12')) False sage: Word().is_proper_prefix(Word()) False """ return self.is_prefix(other) and self.length() < other.length()
[ "def", "is_proper_prefix", "(", "self", ",", "other", ")", ":", "return", "self", ".", "is_prefix", "(", "other", ")", "and", "self", ".", "length", "(", ")", "<", "other", ".", "length", "(", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/combinat/words/finite_word.py#L1001-L1018
pan-unit42/public_tools
9ef8b06fdf18784d1729c8b9d7f804190a2d68c7
macro_loader/olevba.py
python
is_printable
(s)
return set(s).issubset(_PRINTABLE_SET)
returns True if string s only contains printable ASCII characters (i.e. contained in string.printable) This is similar to Python 3's str.isprintable, for Python 2.x. :param s: str :return: bool
returns True if string s only contains printable ASCII characters (i.e. contained in string.printable) This is similar to Python 3's str.isprintable, for Python 2.x. :param s: str :return: bool
[ "returns", "True", "if", "string", "s", "only", "contains", "printable", "ASCII", "characters", "(", "i", ".", "e", ".", "contained", "in", "string", ".", "printable", ")", "This", "is", "similar", "to", "Python", "3", "s", "str", ".", "isprintable", "fo...
def is_printable(s): """ returns True if string s only contains printable ASCII characters (i.e. contained in string.printable) This is similar to Python 3's str.isprintable, for Python 2.x. :param s: str :return: bool """ # inspired from http://stackoverflow.com/questions/3636928/test-if-a-python-string-is-printable # check if the set of chars from s is contained into the set of printable chars: return set(s).issubset(_PRINTABLE_SET)
[ "def", "is_printable", "(", "s", ")", ":", "# inspired from http://stackoverflow.com/questions/3636928/test-if-a-python-string-is-printable", "# check if the set of chars from s is contained into the set of printable chars:", "return", "set", "(", "s", ")", ".", "issubset", "(", "_PR...
https://github.com/pan-unit42/public_tools/blob/9ef8b06fdf18784d1729c8b9d7f804190a2d68c7/macro_loader/olevba.py#L727-L737
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-windows/x86/psutil/_pswindows.py
python
Process._get_raw_meminfo
(self)
[]
def _get_raw_meminfo(self): try: return cext.proc_memory_info(self.pid) except OSError as err: if is_permission_err(err): # TODO: the C ext can probably be refactored in order # to get this from cext.proc_info() info = self._proc_info() return ( info[pinfo_map['num_page_faults']], info[pinfo_map['peak_wset']], info[pinfo_map['wset']], info[pinfo_map['peak_paged_pool']], info[pinfo_map['paged_pool']], info[pinfo_map['peak_non_paged_pool']], info[pinfo_map['non_paged_pool']], info[pinfo_map['pagefile']], info[pinfo_map['peak_pagefile']], info[pinfo_map['mem_private']], ) raise
[ "def", "_get_raw_meminfo", "(", "self", ")", ":", "try", ":", "return", "cext", ".", "proc_memory_info", "(", "self", ".", "pid", ")", "except", "OSError", "as", "err", ":", "if", "is_permission_err", "(", "err", ")", ":", "# TODO: the C ext can probably be re...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-windows/x86/psutil/_pswindows.py#L807-L827
pyglet/pyglet
2833c1df902ca81aeeffa786c12e7e87d402434b
pyglet/image/__init__.py
python
ImageData.set_data
(self, fmt, pitch, data)
Set the byte data of the image. :Parameters: `fmt` : str Format string of the return data. `pitch` : int Number of bytes per row. Negative values indicate a top-to-bottom arrangement. `data` : str or sequence of bytes Image data. .. versionadded:: 1.1
Set the byte data of the image.
[ "Set", "the", "byte", "data", "of", "the", "image", "." ]
def set_data(self, fmt, pitch, data): """Set the byte data of the image. :Parameters: `fmt` : str Format string of the return data. `pitch` : int Number of bytes per row. Negative values indicate a top-to-bottom arrangement. `data` : str or sequence of bytes Image data. .. versionadded:: 1.1 """ self._current_format = fmt self._current_pitch = pitch self._current_data = data self._current_texture = None self._current_mipmap_texture = None
[ "def", "set_data", "(", "self", ",", "fmt", ",", "pitch", ",", "data", ")", ":", "self", ".", "_current_format", "=", "fmt", "self", ".", "_current_pitch", "=", "pitch", "self", ".", "_current_data", "=", "data", "self", ".", "_current_texture", "=", "No...
https://github.com/pyglet/pyglet/blob/2833c1df902ca81aeeffa786c12e7e87d402434b/pyglet/image/__init__.py#L721-L739
udacity/artificial-intelligence
d8bc7ee2511f8aff486e0fba010a7f12a7d268d4
Projects/2_Classical Planning/layers.py
python
makeNoOp
(literal)
return (Action(action, [set([literal]), []], [set([literal]), []]), Action(~action, [set([~literal]), []], [set([~literal]), []]))
Create so-called 'no-op' actions, which only exist in a planning graph (they are not real actions in the problem domain) to persist a literal from one layer of the planning graph to the next. no-op actions are created such that logical negation is correctly evaluated. i.e., the no-op action of the negative literal ~At(place) is the logical negation of the no-op action of positive literal At(place); in other words NoOp::~At(place) == ~(NoOp::At(place) -- NOTE: NoOp::~At(place) is not a valid action, but the correct semantics are handled and enforced automatically.
Create so-called 'no-op' actions, which only exist in a planning graph (they are not real actions in the problem domain) to persist a literal from one layer of the planning graph to the next.
[ "Create", "so", "-", "called", "no", "-", "op", "actions", "which", "only", "exist", "in", "a", "planning", "graph", "(", "they", "are", "not", "real", "actions", "in", "the", "problem", "domain", ")", "to", "persist", "a", "literal", "from", "one", "l...
def makeNoOp(literal): """ Create so-called 'no-op' actions, which only exist in a planning graph (they are not real actions in the problem domain) to persist a literal from one layer of the planning graph to the next. no-op actions are created such that logical negation is correctly evaluated. i.e., the no-op action of the negative literal ~At(place) is the logical negation of the no-op action of positive literal At(place); in other words NoOp::~At(place) == ~(NoOp::At(place) -- NOTE: NoOp::~At(place) is not a valid action, but the correct semantics are handled and enforced automatically. """ action = Expr("NoOp::" + literal.op, literal.args) return (Action(action, [set([literal]), []], [set([literal]), []]), Action(~action, [set([~literal]), []], [set([~literal]), []]))
[ "def", "makeNoOp", "(", "literal", ")", ":", "action", "=", "Expr", "(", "\"NoOp::\"", "+", "literal", ".", "op", ",", "literal", ".", "args", ")", "return", "(", "Action", "(", "action", ",", "[", "set", "(", "[", "literal", "]", ")", ",", "[", ...
https://github.com/udacity/artificial-intelligence/blob/d8bc7ee2511f8aff486e0fba010a7f12a7d268d4/Projects/2_Classical Planning/layers.py#L28-L41
SebKuzminsky/pycam
55e3129f518e470040e79bb00515b4bfcf36c172
pycam/Plugins/OpenGLWindow.py
python
Camera.scale_distance
(self, scale)
[]
def scale_distance(self, scale): if scale != 0: scale = number(scale) dist = self.view["distance"] self.view["distance"] = (scale * dist[0], scale * dist[1], scale * dist[2])
[ "def", "scale_distance", "(", "self", ",", "scale", ")", ":", "if", "scale", "!=", "0", ":", "scale", "=", "number", "(", "scale", ")", "dist", "=", "self", ".", "view", "[", "\"distance\"", "]", "self", ".", "view", "[", "\"distance\"", "]", "=", ...
https://github.com/SebKuzminsky/pycam/blob/55e3129f518e470040e79bb00515b4bfcf36c172/pycam/Plugins/OpenGLWindow.py#L797-L801
GPflow/GPflowOpt
3d86bcc000b0367f19e9f03f4458f5641e5dde60
gpflowopt/acquisition/pof.py
python
ProbabilityOfFeasibility.__init__
(self, model, threshold=0.0, minimum_pof=0.5)
:param model: GPflow model (single output) representing our belief of the constraint :param threshold: Observed values lower than the threshold are considered valid :param minimum_pof: minimum pof score required for a point to be valid. For more information, see docstring of feasible_data_index
:param model: GPflow model (single output) representing our belief of the constraint :param threshold: Observed values lower than the threshold are considered valid :param minimum_pof: minimum pof score required for a point to be valid. For more information, see docstring of feasible_data_index
[ ":", "param", "model", ":", "GPflow", "model", "(", "single", "output", ")", "representing", "our", "belief", "of", "the", "constraint", ":", "param", "threshold", ":", "Observed", "values", "lower", "than", "the", "threshold", "are", "considered", "valid", ...
def __init__(self, model, threshold=0.0, minimum_pof=0.5): """ :param model: GPflow model (single output) representing our belief of the constraint :param threshold: Observed values lower than the threshold are considered valid :param minimum_pof: minimum pof score required for a point to be valid. For more information, see docstring of feasible_data_index """ super(ProbabilityOfFeasibility, self).__init__(model) self.threshold = threshold self.minimum_pof = minimum_pof
[ "def", "__init__", "(", "self", ",", "model", ",", "threshold", "=", "0.0", ",", "minimum_pof", "=", "0.5", ")", ":", "super", "(", "ProbabilityOfFeasibility", ",", "self", ")", ".", "__init__", "(", "model", ")", "self", ".", "threshold", "=", "threshol...
https://github.com/GPflow/GPflowOpt/blob/3d86bcc000b0367f19e9f03f4458f5641e5dde60/gpflowopt/acquisition/pof.py#L49-L58
bnpy/bnpy
d5b311e8f58ccd98477f4a0c8a4d4982e3fca424
bnpy/obsmodel/ZeroMeanGaussObsModel.py
python
ZeroMeanGaussObsModel.getDatasetScale
(self, SS)
return SS.N.sum() * SS.D
Get number of observed scalars in dataset from suff stats. Used for normalizing the ELBO so it has reasonable range. Returns --------- s : scalar positive integer
Get number of observed scalars in dataset from suff stats.
[ "Get", "number", "of", "observed", "scalars", "in", "dataset", "from", "suff", "stats", "." ]
def getDatasetScale(self, SS): ''' Get number of observed scalars in dataset from suff stats. Used for normalizing the ELBO so it has reasonable range. Returns --------- s : scalar positive integer ''' return SS.N.sum() * SS.D
[ "def", "getDatasetScale", "(", "self", ",", "SS", ")", ":", "return", "SS", ".", "N", ".", "sum", "(", ")", "*", "SS", ".", "D" ]
https://github.com/bnpy/bnpy/blob/d5b311e8f58ccd98477f4a0c8a4d4982e3fca424/bnpy/obsmodel/ZeroMeanGaussObsModel.py#L463-L472
vsjha18/nsetools
b0e99c8decac0cba0bc19427428fd2d7b8836eaf
datemgr.py
python
get_nearest_business_day
(d)
takes datetime object
takes datetime object
[ "takes", "datetime", "object" ]
def get_nearest_business_day(d): """ takes datetime object""" if d.isoweekday() is 7 or d.isoweekday() is 6: d = d - relativedelta(days=1) return get_nearest_business_day(d) # republic day elif d.month is 1 and d.day is 26: d = d - relativedelta(days=1) return get_nearest_business_day(d) # labour day elif d.month is 5 and d.day is 1: d = d - relativedelta(days=1) return get_nearest_business_day(d) # independece day elif d.month is 8 and d.day is 15: d = d - relativedelta(days=1) return get_nearest_business_day(d) # Gandhi Jayanti elif d.month is 10 and d.day is 2: d = d - relativedelta(days=1) return get_nearest_business_day(d) # chirstmas elif d.month is 12 and d.day is 25: d = d - relativedelta(days=1) return get_nearest_business_day(d) else: return d
[ "def", "get_nearest_business_day", "(", "d", ")", ":", "if", "d", ".", "isoweekday", "(", ")", "is", "7", "or", "d", ".", "isoweekday", "(", ")", "is", "6", ":", "d", "=", "d", "-", "relativedelta", "(", "days", "=", "1", ")", "return", "get_neares...
https://github.com/vsjha18/nsetools/blob/b0e99c8decac0cba0bc19427428fd2d7b8836eaf/datemgr.py#L8-L35
largelymfs/topical_word_embeddings
1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6
TWE-3/gensim/corpora/hashdictionary.py
python
HashDictionary.__len__
(self)
return self.id_range
Return the number of distinct ids = the entire dictionary size.
Return the number of distinct ids = the entire dictionary size.
[ "Return", "the", "number", "of", "distinct", "ids", "=", "the", "entire", "dictionary", "size", "." ]
def __len__(self): """ Return the number of distinct ids = the entire dictionary size. """ return self.id_range
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "id_range" ]
https://github.com/largelymfs/topical_word_embeddings/blob/1ae3d15d0afcd3fcd39cc81eec4ad9463413a9f6/TWE-3/gensim/corpora/hashdictionary.py#L97-L101
NetEaseGame/ATX
f4415c57b45cb0730e08899cbc92a2af1c047ffb
atx/drivers/mixin.py
python
DeviceMixin.click_image
(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs)
return point
Simulate click according image position Args: - pattern (str or Pattern): filename or an opencv image object. - timeout (float): if image not found during this time, ImageNotFoundError will raise. - action (str): click or long_click - safe (bool): if safe is True, Exception will not raise and return None instead. - method (str): image match method, choice of <template|sift> - delay (float): wait for a moment then perform click Returns: None Raises: ImageNotFoundError: An error occured when img not found in current screen.
Simulate click according image position
[ "Simulate", "click", "according", "image", "position" ]
def click_image(self, pattern, timeout=20.0, action='click', safe=False, desc=None, delay=None, **match_kwargs): """Simulate click according image position Args: - pattern (str or Pattern): filename or an opencv image object. - timeout (float): if image not found during this time, ImageNotFoundError will raise. - action (str): click or long_click - safe (bool): if safe is True, Exception will not raise and return None instead. - method (str): image match method, choice of <template|sift> - delay (float): wait for a moment then perform click Returns: None Raises: ImageNotFoundError: An error occured when img not found in current screen. """ pattern = self.pattern_open(pattern) log.info('click image:%s %s', desc or '', pattern) start_time = time.time() found = False point = None while time.time() - start_time < timeout: point = self.match(pattern, **match_kwargs) if point is None: sys.stdout.write('.') sys.stdout.flush() continue log.debug('confidence: %s', point.confidence) if not point.matched: log.info('Ignore confidence: %s', point.confidence) continue # wait for program ready if delay and delay > 0: self.delay(delay) func = getattr(self, action) func(*point.pos) found = True break sys.stdout.write('\n') if not found: if safe: log.info("Image(%s) not found, safe=True, skip", pattern) return None raise errors.ImageNotFoundError('Not found image %s' % pattern, point) # FIXME(ssx): maybe this function is too complex return point
[ "def", "click_image", "(", "self", ",", "pattern", ",", "timeout", "=", "20.0", ",", "action", "=", "'click'", ",", "safe", "=", "False", ",", "desc", "=", "None", ",", "delay", "=", "None", ",", "*", "*", "match_kwargs", ")", ":", "pattern", "=", ...
https://github.com/NetEaseGame/ATX/blob/f4415c57b45cb0730e08899cbc92a2af1c047ffb/atx/drivers/mixin.py#L503-L555
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/idlelib/searchengine.py
python
SearchEngine.getcookedpat
(self)
return pat
[]
def getcookedpat(self): pat = self.getpat() if not self.isre(): # if True, see setcookedpat pat = re.escape(pat) if self.isword(): pat = r"\b%s\b" % pat return pat
[ "def", "getcookedpat", "(", "self", ")", ":", "pat", "=", "self", ".", "getpat", "(", ")", "if", "not", "self", ".", "isre", "(", ")", ":", "# if True, see setcookedpat", "pat", "=", "re", ".", "escape", "(", "pat", ")", "if", "self", ".", "isword", ...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/idlelib/searchengine.py#L67-L73
Jenyay/outwiker
50530cf7b3f71480bb075b2829bc0669773b835b
src/outwiker/gui/controls/ultimatelistctrl.py
python
UltimateListMainWindow.GetSubItemRect
(self, item, subItem)
return rect
Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row `item` in the column `subItem`. :param `item`: the row in which the item lives; :param `subItem`: the column in which the item lives. If set equal to the special value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for :meth:`~UltimateListMainWindow.GetItemRect`. :note: This method is only meaningful when the :class:`UltimateListCtrl` is in the report mode.
Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row `item` in the column `subItem`.
[ "Returns", "the", "rectangle", "representing", "the", "size", "and", "position", "in", "physical", "coordinates", "of", "the", "given", "subitem", "i", ".", "e", ".", "the", "part", "of", "the", "row", "item", "in", "the", "column", "subItem", "." ]
def GetSubItemRect(self, item, subItem): """ Returns the rectangle representing the size and position, in physical coordinates, of the given subitem, i.e. the part of the row `item` in the column `subItem`. :param `item`: the row in which the item lives; :param `subItem`: the column in which the item lives. If set equal to the special value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for :meth:`~UltimateListMainWindow.GetItemRect`. :note: This method is only meaningful when the :class:`UltimateListCtrl` is in the report mode. """ if not self.InReportView() and subItem == ULC_GETSUBITEMRECT_WHOLEITEM: raise Exception("GetSubItemRect only meaningful in report view") if item < 0 or item >= self.GetItemCount(): raise Exception("invalid item in GetSubItemRect") # ensure that we're laid out, otherwise we could return nonsense if self._dirty: self.RecalculatePositions(True) rect = self.GetLineRect(item) # Adjust rect to specified column if subItem != ULC_GETSUBITEMRECT_WHOLEITEM: if subItem < 0 or subItem >= self.GetColumnCount(): raise Exception("invalid subItem in GetSubItemRect") for i in range(subItem): rect.x += self.GetColumnWidth(i) rect.width = self.GetColumnWidth(subItem) rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y) return rect
[ "def", "GetSubItemRect", "(", "self", ",", "item", ",", "subItem", ")", ":", "if", "not", "self", ".", "InReportView", "(", ")", "and", "subItem", "==", "ULC_GETSUBITEMRECT_WHOLEITEM", ":", "raise", "Exception", "(", "\"GetSubItemRect only meaningful in report view\...
https://github.com/Jenyay/outwiker/blob/50530cf7b3f71480bb075b2829bc0669773b835b/src/outwiker/gui/controls/ultimatelistctrl.py#L9509-L9546
behave/behave
e6364fe3d62c2befe34bc56471cfb317a218cd01
behave/matchers.py
python
Matcher.regex_pattern
(self)
return self.pattern
Return the used textual regex pattern.
Return the used textual regex pattern.
[ "Return", "the", "used", "textual", "regex", "pattern", "." ]
def regex_pattern(self): """Return the used textual regex pattern.""" # -- ASSUMPTION: pattern attribute provides regex-pattern # NOTE: Method must be overridden if assumption is not met. return self.pattern
[ "def", "regex_pattern", "(", "self", ")", ":", "# -- ASSUMPTION: pattern attribute provides regex-pattern", "# NOTE: Method must be overridden if assumption is not met.", "return", "self", ".", "pattern" ]
https://github.com/behave/behave/blob/e6364fe3d62c2befe34bc56471cfb317a218cd01/behave/matchers.py#L177-L181
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/fallback_lib_py352/asyncio/sslproto.py
python
_SSLPipe.feed_eof
(self)
Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected.
Send a potentially "ragged" EOF.
[ "Send", "a", "potentially", "ragged", "EOF", "." ]
def feed_eof(self): """Send a potentially "ragged" EOF. This method will raise an SSL_ERROR_EOF exception if the EOF is unexpected. """ self._incoming.write_eof() ssldata, appdata = self.feed_ssldata(b'') assert appdata == [] or appdata == [b'']
[ "def", "feed_eof", "(", "self", ")", ":", "self", ".", "_incoming", ".", "write_eof", "(", ")", "ssldata", ",", "appdata", "=", "self", ".", "feed_ssldata", "(", "b''", ")", "assert", "appdata", "==", "[", "]", "or", "appdata", "==", "[", "b''", "]" ...
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/fallback_lib_py352/asyncio/sslproto.py#L147-L155
pypa/pipenv
b21baade71a86ab3ee1429f71fbc14d4f95fb75d
pipenv/vendor/tomlkit/exceptions.py
python
ParseError.line
(self)
return self._line
[]
def line(self): return self._line
[ "def", "line", "(", "self", ")", ":", "return", "self", ".", "_line" ]
https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/tomlkit/exceptions.py#L32-L33
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/asn1crypto/ocsp.py
python
Request.critical_extensions
(self)
return self._critical_extensions
Returns a set of the names (or OID if not a known extension) of the extensions marked as critical :return: A set of unicode strings
Returns a set of the names (or OID if not a known extension) of the extensions marked as critical
[ "Returns", "a", "set", "of", "the", "names", "(", "or", "OID", "if", "not", "a", "known", "extension", ")", "of", "the", "extensions", "marked", "as", "critical" ]
def critical_extensions(self): """ Returns a set of the names (or OID if not a known extension) of the extensions marked as critical :return: A set of unicode strings """ if not self._processed_extensions: self._set_extensions() return self._critical_extensions
[ "def", "critical_extensions", "(", "self", ")", ":", "if", "not", "self", ".", "_processed_extensions", ":", "self", ".", "_set_extensions", "(", ")", "return", "self", ".", "_critical_extensions" ]
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/asn1crypto/ocsp.py#L114-L125
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/Python3/mailbox.py
python
Mailbox.unlock
(self)
Unlock the mailbox if it is locked.
Unlock the mailbox if it is locked.
[ "Unlock", "the", "mailbox", "if", "it", "is", "locked", "." ]
def unlock(self): """Unlock the mailbox if it is locked.""" raise NotImplementedError('Method must be implemented by subclass')
[ "def", "unlock", "(", "self", ")", ":", "raise", "NotImplementedError", "(", "'Method must be implemented by subclass'", ")" ]
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/Python3/mailbox.py#L188-L190
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/core/as_dataframe.py
python
_get_feature
( path: Tuple[str, ...], feature: features.FeatureConnector, )
return feature, sequence_rank
Recursively extracts the feature and sequence rank (plain, ragged, ...).
Recursively extracts the feature and sequence rank (plain, ragged, ...).
[ "Recursively", "extracts", "the", "feature", "and", "sequence", "rank", "(", "plain", "ragged", "...", ")", "." ]
def _get_feature( path: Tuple[str, ...], feature: features.FeatureConnector, ) -> Tuple[features.FeatureConnector, int]: """Recursively extracts the feature and sequence rank (plain, ragged, ...).""" sequence_rank = 0 # Collapse the nested sequences while isinstance(feature, features.Sequence): # Subclasses like `Video` shouldn't be recursed into. # But sequence of dict like `TranslationVariableLanguages` should. # Currently, there is no good way for a composed sub-feature to only # display a single column instead of one per sub-feature. # So `MyFeature({'x': tf.int32, 'y': tf.bool})` will have 2 columns `x` # and `y`. if type(feature) != features.Sequence and not path: # pylint: disable=unidiomatic-typecheck break sequence_rank += 1 feature = feature.feature # Extract inner feature # pytype: disable=attribute-error if path: # Has level deeper, recurse feature = typing.cast(features.FeaturesDict, feature) feature, nested_sequence_rank = _get_feature(path[1:], feature[path[0]]) # pytype: disable=wrong-arg-types sequence_rank += nested_sequence_rank return feature, sequence_rank
[ "def", "_get_feature", "(", "path", ":", "Tuple", "[", "str", ",", "...", "]", ",", "feature", ":", "features", ".", "FeatureConnector", ",", ")", "->", "Tuple", "[", "features", ".", "FeatureConnector", ",", "int", "]", ":", "sequence_rank", "=", "0", ...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/core/as_dataframe.py#L97-L122
broadinstitute/viral-ngs
e144969e4c57060d53f38a4c3a270e8227feace1
util/file.py
python
mkdir_p
(dirpath)
Verify that the directory given exists, and if not, create it.
Verify that the directory given exists, and if not, create it.
[ "Verify", "that", "the", "directory", "given", "exists", "and", "if", "not", "create", "it", "." ]
def mkdir_p(dirpath): ''' Verify that the directory given exists, and if not, create it. ''' try: os.makedirs(dirpath) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(dirpath): pass else: raise
[ "def", "mkdir_p", "(", "dirpath", ")", ":", "try", ":", "os", ".", "makedirs", "(", "dirpath", ")", "except", "OSError", "as", "exc", ":", "# Python >2.5", "if", "exc", ".", "errno", "==", "errno", ".", "EEXIST", "and", "os", ".", "path", ".", "isdir...
https://github.com/broadinstitute/viral-ngs/blob/e144969e4c57060d53f38a4c3a270e8227feace1/util/file.py#L311-L320
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
Utils/Connection/UnixConnection.py
python
UnixConnection.addCommand
(self, string)
[]
def addCommand(self, string): self.commands.append(string)
[ "def", "addCommand", "(", "self", ",", "string", ")", ":", "self", ".", "commands", ".", "append", "(", "string", ")" ]
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/Utils/Connection/UnixConnection.py#L278-L279
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/db/backends/creation.py
python
BaseDatabaseCreation.sql_for_pending_references
(self, model, style, pending_references)
return final_output
Returns any ALTER TABLE statements to add constraints after the fact.
Returns any ALTER TABLE statements to add constraints after the fact.
[ "Returns", "any", "ALTER", "TABLE", "statements", "to", "add", "constraints", "after", "the", "fact", "." ]
def sql_for_pending_references(self, model, style, pending_references): "Returns any ALTER TABLE statements to add constraints after the fact." from django.db.backends.util import truncate_name if not model._meta.managed or model._meta.proxy: return [] qn = self.connection.ops.quote_name final_output = [] opts = model._meta if model in pending_references: for rel_class, f in pending_references[model]: rel_opts = rel_class._meta r_table = rel_opts.db_table r_col = f.column table = opts.db_table col = opts.get_field(f.rel.field_name).column # For MySQL, r_name must be unique in the first 64 characters. # So we are careful with character usage here. r_name = '%s_refs_%s_%s' % (r_col, col, self._digest(r_table, table)) final_output.append(style.SQL_KEYWORD('ALTER TABLE') + ' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' % \ (qn(r_table), qn(truncate_name(r_name, self.connection.ops.max_name_length())), qn(r_col), qn(table), qn(col), self.connection.ops.deferrable_sql())) del pending_references[model] return final_output
[ "def", "sql_for_pending_references", "(", "self", ",", "model", ",", "style", ",", "pending_references", ")", ":", "from", "django", ".", "db", ".", "backends", ".", "util", "import", "truncate_name", "if", "not", "model", ".", "_meta", ".", "managed", "or",...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/db/backends/creation.py#L109-L133
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-linux/x64/tornado/httputil.py
python
parse_request_start_line
(line: str)
return RequestStartLine(method, path, version)
Returns a (method, path, version) tuple for an HTTP 1.x request line. The response is a `collections.namedtuple`. >>> parse_request_start_line("GET /foo HTTP/1.1") RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
Returns a (method, path, version) tuple for an HTTP 1.x request line.
[ "Returns", "a", "(", "method", "path", "version", ")", "tuple", "for", "an", "HTTP", "1", ".", "x", "request", "line", "." ]
def parse_request_start_line(line: str) -> RequestStartLine: """Returns a (method, path, version) tuple for an HTTP 1.x request line. The response is a `collections.namedtuple`. >>> parse_request_start_line("GET /foo HTTP/1.1") RequestStartLine(method='GET', path='/foo', version='HTTP/1.1') """ try: method, path, version = line.split(" ") except ValueError: # https://tools.ietf.org/html/rfc7230#section-3.1.1 # invalid request-line SHOULD respond with a 400 (Bad Request) raise HTTPInputError("Malformed HTTP request line") if not re.match(r"^HTTP/1\.[0-9]$", version): raise HTTPInputError( "Malformed HTTP version in HTTP Request-Line: %r" % version ) return RequestStartLine(method, path, version)
[ "def", "parse_request_start_line", "(", "line", ":", "str", ")", "->", "RequestStartLine", ":", "try", ":", "method", ",", "path", ",", "version", "=", "line", ".", "split", "(", "\" \"", ")", "except", "ValueError", ":", "# https://tools.ietf.org/html/rfc7230#s...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/tornado/httputil.py#L899-L917
pygments/pygments
cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7
pygments/lexers/__init__.py
python
_iter_lexerclasses
(plugins=True)
Return an iterator over all lexer classes.
Return an iterator over all lexer classes.
[ "Return", "an", "iterator", "over", "all", "lexer", "classes", "." ]
def _iter_lexerclasses(plugins=True): """Return an iterator over all lexer classes.""" for key in sorted(LEXERS): module_name, name = LEXERS[key][:2] if name not in _lexer_cache: _load_lexers(module_name) yield _lexer_cache[name] if plugins: yield from find_plugin_lexers()
[ "def", "_iter_lexerclasses", "(", "plugins", "=", "True", ")", ":", "for", "key", "in", "sorted", "(", "LEXERS", ")", ":", "module_name", ",", "name", "=", "LEXERS", "[", "key", "]", "[", ":", "2", "]", "if", "name", "not", "in", "_lexer_cache", ":",...
https://github.com/pygments/pygments/blob/cd3ad20dfc8a6cb43e2c0b22b14446dcc0a554d7/pygments/lexers/__init__.py#L229-L237