repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
adobe-apiplatform/umapi-client.py
umapi_client/legacy.py
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/legacy.py#L214-L257
def make_call(query, org_id, page): """ Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_...
[ "def", "make_call", "(", "query", ",", "org_id", ",", "page", ")", ":", "wait_time", "=", "0", "num_attempts", "=", "0", "while", "num_attempts", "<", "retry_max_attempts", ":", "if", "wait_time", ">", "0", ":", "sleep", "(", "wait_time", ")", "wait_time",...
Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param pa...
[ "Make", "a", "single", "UMAPI", "call", "with", "error", "handling", "and", "server", "-", "controlled", "throttling", ".", "(", "Adapted", "from", "sample", "code", "at", "https", ":", "//", "www", ".", "adobe", ".", "io", "/", "products", "/", "userman...
python
train
markovmodel/msmtools
msmtools/estimation/dense/covariance.py
https://github.com/markovmodel/msmtools/blob/54dc76dd2113a0e8f3d15d5316abab41402941be/msmtools/estimation/dense/covariance.py#L131-L146
def error_perturbation_var(C, S): r"""Error-perturbation arising from a given sensitivity Parameters ---------- C : (M, M) ndarray Count matrix S : (K, M, M) ndarray Sensitivity tensor """ K = S.shape[0] cov = tmatrix_cov(C) for i in range(K): R = S[i, :, :]...
[ "def", "error_perturbation_var", "(", "C", ",", "S", ")", ":", "K", "=", "S", ".", "shape", "[", "0", "]", "cov", "=", "tmatrix_cov", "(", "C", ")", "for", "i", "in", "range", "(", "K", ")", ":", "R", "=", "S", "[", "i", ",", ":", ",", ":",...
r"""Error-perturbation arising from a given sensitivity Parameters ---------- C : (M, M) ndarray Count matrix S : (K, M, M) ndarray Sensitivity tensor
[ "r", "Error", "-", "perturbation", "arising", "from", "a", "given", "sensitivity" ]
python
train
phaethon/kamene
kamene/utils.py
https://github.com/phaethon/kamene/blob/11d4064844f4f68ac5d7546f5633ac7d02082914/kamene/utils.py#L545-L551
def wrpcap(filename, pkt, *args, **kargs): """Write a list of packets to a pcap file gz: set to 1 to save a gzipped capture linktype: force linktype value endianness: "<" or ">", force endianness""" with PcapWriter(filename, *args, **kargs) as pcap: pcap.write(pkt)
[ "def", "wrpcap", "(", "filename", ",", "pkt", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "with", "PcapWriter", "(", "filename", ",", "*", "args", ",", "*", "*", "kargs", ")", "as", "pcap", ":", "pcap", ".", "write", "(", "pkt", ")" ]
Write a list of packets to a pcap file gz: set to 1 to save a gzipped capture linktype: force linktype value endianness: "<" or ">", force endianness
[ "Write", "a", "list", "of", "packets", "to", "a", "pcap", "file", "gz", ":", "set", "to", "1", "to", "save", "a", "gzipped", "capture", "linktype", ":", "force", "linktype", "value", "endianness", ":", "<", "or", ">", "force", "endianness" ]
python
train
kevinconway/confpy
confpy/loaders/base.py
https://github.com/kevinconway/confpy/blob/1ee8afcab46ac6915a5ff4184180434ac7b84a60/confpy/loaders/base.py#L47-L78
def config(self): """Get a Configuration object from the file contents.""" conf = config.Configuration() for namespace in self.namespaces: if not hasattr(conf, namespace): if not self._strict: continue raise exc.NamespaceNotRegi...
[ "def", "config", "(", "self", ")", ":", "conf", "=", "config", ".", "Configuration", "(", ")", "for", "namespace", "in", "self", ".", "namespaces", ":", "if", "not", "hasattr", "(", "conf", ",", "namespace", ")", ":", "if", "not", "self", ".", "_stri...
Get a Configuration object from the file contents.
[ "Get", "a", "Configuration", "object", "from", "the", "file", "contents", "." ]
python
train
saltstack/salt
salt/netapi/rest_cherrypy/app.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/netapi/rest_cherrypy/app.py#L1561-L1646
def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| ...
[ "def", "GET", "(", "self", ",", "mid", "=", "None", ")", ":", "if", "mid", ":", "lowstate", "=", "[", "{", "'client'", ":", "'wheel'", ",", "'fun'", ":", "'key.finger'", ",", "'match'", ":", "mid", ",", "}", "]", "else", ":", "lowstate", "=", "["...
Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :status 200: |200| :sta...
[ "Show", "the", "list", "of", "minion", "keys", "or", "detail", "on", "a", "specific", "key" ]
python
train
niklasf/python-chess
chess/__init__.py
https://github.com/niklasf/python-chess/blob/d91f986ca3e046b300a0d7d9ee2a13b07610fe1a/chess/__init__.py#L3040-L3108
def status(self) -> Status: """ Gets a bitmask of possible problems with the position. Move making, generation and validation are only guaranteed to work on a completely valid board. :data:`~chess.STATUS_VALID` for a completely valid board. Otherwise, bitwise combinati...
[ "def", "status", "(", "self", ")", "->", "Status", ":", "errors", "=", "STATUS_VALID", "# There must be at least one piece.", "if", "not", "self", ".", "occupied", ":", "errors", "|=", "STATUS_EMPTY", "# There must be exactly one king of each color.", "if", "not", "se...
Gets a bitmask of possible problems with the position. Move making, generation and validation are only guaranteed to work on a completely valid board. :data:`~chess.STATUS_VALID` for a completely valid board. Otherwise, bitwise combinations of: :data:`~chess.STATUS_NO_WHITE_KI...
[ "Gets", "a", "bitmask", "of", "possible", "problems", "with", "the", "position", "." ]
python
train
softlayer/softlayer-python
SoftLayer/CLI/config/__init__.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/config/__init__.py#L43-L52
def config_table(settings): """Returns a config table.""" table = formatting.KeyValueTable(['name', 'value']) table.align['name'] = 'r' table.align['value'] = 'l' table.add_row(['Username', settings['username'] or 'not set']) table.add_row(['API Key', settings['api_key'] or 'not set']) table...
[ "def", "config_table", "(", "settings", ")", ":", "table", "=", "formatting", ".", "KeyValueTable", "(", "[", "'name'", ",", "'value'", "]", ")", "table", ".", "align", "[", "'name'", "]", "=", "'r'", "table", ".", "align", "[", "'value'", "]", "=", ...
Returns a config table.
[ "Returns", "a", "config", "table", "." ]
python
train
pypa/pipenv
pipenv/vendor/distlib/_backport/shutil.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/distlib/_backport/shutil.py#L654-L658
def _ensure_directory(path): """Ensure that the parent directory of `path` exists""" dirname = os.path.dirname(path) if not os.path.isdir(dirname): os.makedirs(dirname)
[ "def", "_ensure_directory", "(", "path", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ":", "os", ".", "makedirs", "(", "dirname", ")" ]
Ensure that the parent directory of `path` exists
[ "Ensure", "that", "the", "parent", "directory", "of", "path", "exists" ]
python
train
CZ-NIC/python-rt
rt.py
https://github.com/CZ-NIC/python-rt/blob/e7a9f555e136708aec3317f857045145a2271e16/rt.py#L839-L866
def __correspond(self, ticket_id, text='', action='correspond', cc='', bcc='', content_type='text/plain', files=[]): """ Sends out the correspondence :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword action: correspond or comment ...
[ "def", "__correspond", "(", "self", ",", "ticket_id", ",", "text", "=", "''", ",", "action", "=", "'correspond'", ",", "cc", "=", "''", ",", "bcc", "=", "''", ",", "content_type", "=", "'text/plain'", ",", "files", "=", "[", "]", ")", ":", "post_data...
Sends out the correspondence :param ticket_id: ID of ticket to which message belongs :keyword text: Content of email message :keyword action: correspond or comment :keyword content_type: Content type of email message, default to text/plain :keyword cc: Carbon copy just for this ...
[ "Sends", "out", "the", "correspondence" ]
python
train
mlperf/training
translation/tensorflow/transformer/model/beam_search.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/translation/tensorflow/transformer/model/beam_search.py#L73-L95
def search(self, initial_ids, initial_cache): """Beam search for sequences with highest scores.""" state, state_shapes = self._create_initial_state(initial_ids, initial_cache) finished_state = tf.while_loop( self._continue_search, self._search_step, loop_vars=[state], shape_invariants=[stat...
[ "def", "search", "(", "self", ",", "initial_ids", ",", "initial_cache", ")", ":", "state", ",", "state_shapes", "=", "self", ".", "_create_initial_state", "(", "initial_ids", ",", "initial_cache", ")", "finished_state", "=", "tf", ".", "while_loop", "(", "self...
Beam search for sequences with highest scores.
[ "Beam", "search", "for", "sequences", "with", "highest", "scores", "." ]
python
train
boriel/zxbasic
zxbpp.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L605-L611
def p_exprgt(p): """ expr : expr GT expr """ a = int(p[1]) if p[1].isdigit() else 0 b = int(p[3]) if p[3].isdigit() else 0 p[0] = '1' if a > b else '0'
[ "def", "p_exprgt", "(", "p", ")", ":", "a", "=", "int", "(", "p", "[", "1", "]", ")", "if", "p", "[", "1", "]", ".", "isdigit", "(", ")", "else", "0", "b", "=", "int", "(", "p", "[", "3", "]", ")", "if", "p", "[", "3", "]", ".", "isdi...
expr : expr GT expr
[ "expr", ":", "expr", "GT", "expr" ]
python
train
hannes-brt/hebel
hebel/pycuda_ops/matrix.py
https://github.com/hannes-brt/hebel/blob/1e2c3a9309c2646103901b26a55be4e312dd5005/hebel/pycuda_ops/matrix.py#L182-L194
def vector_normalize(mat, max_vec_norm=1.): """ Normalize each column vector in mat to length max_vec_norm if it is longer than max_vec_norm """ assert mat.flags.c_contiguous n, m = mat.shape vector_normalize_kernel.prepared_call( (m, 1, 1), (32, 1, 1), mat.gpudata, np.f...
[ "def", "vector_normalize", "(", "mat", ",", "max_vec_norm", "=", "1.", ")", ":", "assert", "mat", ".", "flags", ".", "c_contiguous", "n", ",", "m", "=", "mat", ".", "shape", "vector_normalize_kernel", ".", "prepared_call", "(", "(", "m", ",", "1", ",", ...
Normalize each column vector in mat to length max_vec_norm if it is longer than max_vec_norm
[ "Normalize", "each", "column", "vector", "in", "mat", "to", "length", "max_vec_norm", "if", "it", "is", "longer", "than", "max_vec_norm" ]
python
train
blockstack/pybitcoin
pybitcoin/transactions/network.py
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L139-L151
def send_to_address(recipient_address, amount, private_key, blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE, change_address=None): """ Builds, signs, and dispatches a "send to address" transaction. """ # build and sign the tx signed_tx = make_send_to_address_tx(recipient_addre...
[ "def", "send_to_address", "(", "recipient_address", ",", "amount", ",", "private_key", ",", "blockchain_client", "=", "BlockchainInfoClient", "(", ")", ",", "fee", "=", "STANDARD_FEE", ",", "change_address", "=", "None", ")", ":", "# build and sign the tx", "signed_...
Builds, signs, and dispatches a "send to address" transaction.
[ "Builds", "signs", "and", "dispatches", "a", "send", "to", "address", "transaction", "." ]
python
train
CZ-NIC/yangson
yangson/parser.py
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L124-L141
def match_regex(self, regex: Pattern, required: bool = False, meaning: str = "") -> str: """Parse input based on a regular expression . Args: regex: Compiled regular expression object. required: Should the exception be raised on unexpected input? ...
[ "def", "match_regex", "(", "self", ",", "regex", ":", "Pattern", ",", "required", ":", "bool", "=", "False", ",", "meaning", ":", "str", "=", "\"\"", ")", "->", "str", ":", "mo", "=", "regex", ".", "match", "(", "self", ".", "input", ",", "self", ...
Parse input based on a regular expression . Args: regex: Compiled regular expression object. required: Should the exception be raised on unexpected input? meaning: Meaning of `regex` (for use in error messages). Raises: UnexpectedInput: If no syntactical...
[ "Parse", "input", "based", "on", "a", "regular", "expression", "." ]
python
train
plone/plone.app.mosaic
src/plone/app/mosaic/browser/main_template.py
https://github.com/plone/plone.app.mosaic/blob/73b6acb18905025a76b239c86de9543ed9350991/src/plone/app/mosaic/browser/main_template.py#L65-L107
def parse_data_slots(value): """Parse data-slots value into slots used to wrap node, prepend to node or append to node. >>> parse_data_slots('') ([], [], []) >>> parse_data_slots('foo bar') (['foo', 'bar'], [], []) >>> parse_data_slots('foo bar > foobar') (['foo', 'b...
[ "def", "parse_data_slots", "(", "value", ")", ":", "value", "=", "unquote", "(", "value", ")", "if", "'>'", "in", "value", ":", "wrappers", ",", "children", "=", "value", ".", "split", "(", "'>'", ",", "1", ")", "else", ":", "wrappers", "=", "value",...
Parse data-slots value into slots used to wrap node, prepend to node or append to node. >>> parse_data_slots('') ([], [], []) >>> parse_data_slots('foo bar') (['foo', 'bar'], [], []) >>> parse_data_slots('foo bar > foobar') (['foo', 'bar'], ['foobar'], []) >>> pa...
[ "Parse", "data", "-", "slots", "value", "into", "slots", "used", "to", "wrap", "node", "prepend", "to", "node", "or", "append", "to", "node", "." ]
python
train
kadrlica/pymodeler
pymodeler/model.py
https://github.com/kadrlica/pymodeler/blob/f426c01416fd4b8fc3afeeb6d3b5d1cb0cb8f8e3/pymodeler/model.py#L335-L355
def param_values(self, pnames=None): """ Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Ret...
[ "def", "param_values", "(", "self", ",", "pnames", "=", "None", ")", ":", "l", "=", "self", ".", "get_params", "(", "pnames", ")", "v", "=", "[", "p", ".", "value", "for", "p", "in", "l", "]", "return", "np", ".", "array", "(", "v", ")" ]
Return an array with the parameter values Parameters ---------- pname : list or None If a list, get the values of the `Parameter` objects with those names If none, get all values of all the `Parameter` objects Returns ------- values : `np.array`...
[ "Return", "an", "array", "with", "the", "parameter", "values" ]
python
test
kennethreitz/xerox
xerox/x11.py
https://github.com/kennethreitz/xerox/blob/c34d2fb03ff892b31016173c520e784e86cc2d70/xerox/x11.py#L10-L22
def copy(string, xsel=False): """Copy given string into system clipboard. If 'xsel' is True, this will also copy into the primary x selection for middle click.""" try: _cmd = ["xclip", "-selection", "clipboard"] subprocess.Popen(_cmd, stdin=subprocess.PIPE).communicate( strin...
[ "def", "copy", "(", "string", ",", "xsel", "=", "False", ")", ":", "try", ":", "_cmd", "=", "[", "\"xclip\"", ",", "\"-selection\"", ",", "\"clipboard\"", "]", "subprocess", ".", "Popen", "(", "_cmd", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", ...
Copy given string into system clipboard. If 'xsel' is True, this will also copy into the primary x selection for middle click.
[ "Copy", "given", "string", "into", "system", "clipboard", ".", "If", "xsel", "is", "True", "this", "will", "also", "copy", "into", "the", "primary", "x", "selection", "for", "middle", "click", "." ]
python
train
ailionx/cloudflare-ddns
cloudflare_ddns/cloudflare.py
https://github.com/ailionx/cloudflare-ddns/blob/e4808b8314e447f69fab77b5bd3880846e59adbe/cloudflare_ddns/cloudflare.py#L164-L191
def update_record(self, dns_type, name, content, **kwargs): """ Update dns record :param dns_type: :param name: :param content: :param kwargs: :return: """ record = self.get_record(dns_type, name) data = { 'type': dns_type, ...
[ "def", "update_record", "(", "self", ",", "dns_type", ",", "name", ",", "content", ",", "*", "*", "kwargs", ")", ":", "record", "=", "self", ".", "get_record", "(", "dns_type", ",", "name", ")", "data", "=", "{", "'type'", ":", "dns_type", ",", "'nam...
Update dns record :param dns_type: :param name: :param content: :param kwargs: :return:
[ "Update", "dns", "record", ":", "param", "dns_type", ":", ":", "param", "name", ":", ":", "param", "content", ":", ":", "param", "kwargs", ":", ":", "return", ":" ]
python
train
iotile/coretools
iotilesensorgraph/iotile/sg/engine/in_memory.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/engine/in_memory.py#L90-L130
def scan_storage(self, area_name, callable, start=0, stop=None): """Iterate over streaming or storage areas, calling callable. Args: area_name (str): Either 'storage' or 'streaming' to indicate which storage area to scan. callable (callable): A function that will...
[ "def", "scan_storage", "(", "self", ",", "area_name", ",", "callable", ",", "start", "=", "0", ",", "stop", "=", "None", ")", ":", "if", "area_name", "==", "u'storage'", ":", "data", "=", "self", ".", "storage_data", "elif", "area_name", "==", "u'streami...
Iterate over streaming or storage areas, calling callable. Args: area_name (str): Either 'storage' or 'streaming' to indicate which storage area to scan. callable (callable): A function that will be called as (offset, reading) for each reading between sta...
[ "Iterate", "over", "streaming", "or", "storage", "areas", "calling", "callable", "." ]
python
train
splunk/splunk-sdk-python
examples/job.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L233-L237
def searchlog(self, argv): """Retrieve the searchlog for the specified search jobs.""" opts = cmdline(argv, FLAGS_SEARCHLOG) self.foreach(opts.args, lambda job: output(job.searchlog(**opts.kwargs)))
[ "def", "searchlog", "(", "self", ",", "argv", ")", ":", "opts", "=", "cmdline", "(", "argv", ",", "FLAGS_SEARCHLOG", ")", "self", ".", "foreach", "(", "opts", ".", "args", ",", "lambda", "job", ":", "output", "(", "job", ".", "searchlog", "(", "*", ...
Retrieve the searchlog for the specified search jobs.
[ "Retrieve", "the", "searchlog", "for", "the", "specified", "search", "jobs", "." ]
python
train
explosion/spaCy
spacy/pipeline/entityruler.py
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/pipeline/entityruler.py#L108-L122
def patterns(self): """Get all patterns that were added to the entity ruler. RETURNS (list): The original patterns, one dictionary per pattern. DOCS: https://spacy.io/api/entityruler#patterns """ all_patterns = [] for label, patterns in self.token_patterns.items(): ...
[ "def", "patterns", "(", "self", ")", ":", "all_patterns", "=", "[", "]", "for", "label", ",", "patterns", "in", "self", ".", "token_patterns", ".", "items", "(", ")", ":", "for", "pattern", "in", "patterns", ":", "all_patterns", ".", "append", "(", "{"...
Get all patterns that were added to the entity ruler. RETURNS (list): The original patterns, one dictionary per pattern. DOCS: https://spacy.io/api/entityruler#patterns
[ "Get", "all", "patterns", "that", "were", "added", "to", "the", "entity", "ruler", "." ]
python
train
tcalmant/ipopo
pelix/ipopo/instance.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/instance.py#L167-L182
def check_event(self, event): # type: (ServiceEvent) -> bool """ Tests if the given service event must be handled or ignored, based on the state of the iPOPO service and on the content of the event. :param event: A service event :return: True if the event can be handled,...
[ "def", "check_event", "(", "self", ",", "event", ")", ":", "# type: (ServiceEvent) -> bool", "with", "self", ".", "_lock", ":", "if", "self", ".", "state", "==", "StoredInstance", ".", "KILLED", ":", "# This call may have been blocked by the internal state lock,", "# ...
Tests if the given service event must be handled or ignored, based on the state of the iPOPO service and on the content of the event. :param event: A service event :return: True if the event can be handled, False if it must be ignored
[ "Tests", "if", "the", "given", "service", "event", "must", "be", "handled", "or", "ignored", "based", "on", "the", "state", "of", "the", "iPOPO", "service", "and", "on", "the", "content", "of", "the", "event", "." ]
python
train
SamLau95/nbinteract
nbinteract/plotting.py
https://github.com/SamLau95/nbinteract/blob/9f346452283831aad3f4416c04879f1d187ec3b7/nbinteract/plotting.py#L657-L694
def _create_fig( *, x_sc=bq.LinearScale, y_sc=bq.LinearScale, x_ax=bq.Axis, y_ax=bq.Axis, fig=bq.Figure, options={}, params={} ): """ Initializes scales and axes for a bqplot figure and returns the resulting blank figure. Each plot component is passed in as a class. The plot ...
[ "def", "_create_fig", "(", "*", ",", "x_sc", "=", "bq", ".", "LinearScale", ",", "y_sc", "=", "bq", ".", "LinearScale", ",", "x_ax", "=", "bq", ".", "Axis", ",", "y_ax", "=", "bq", ".", "Axis", ",", "fig", "=", "bq", ".", "Figure", ",", "options"...
Initializes scales and axes for a bqplot figure and returns the resulting blank figure. Each plot component is passed in as a class. The plot options should be passed into options. Any additional parameters to initialize plot components are passed into params as a dict of { plot_component: { trait: val...
[ "Initializes", "scales", "and", "axes", "for", "a", "bqplot", "figure", "and", "returns", "the", "resulting", "blank", "figure", ".", "Each", "plot", "component", "is", "passed", "in", "as", "a", "class", ".", "The", "plot", "options", "should", "be", "pas...
python
train
gabstopper/smc-python
smc/administration/scheduled_tasks.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/administration/scheduled_tasks.py#L136-L168
def log_target_types(all_logs=False, **kwargs): """ Log targets for log tasks. A log target defines the log types that will be affected by the operation. For example, when creating a DeleteLogTask, you can specify which log types are deleted. :param bool for_alert_event_log: alert events traces...
[ "def", "log_target_types", "(", "all_logs", "=", "False", ",", "*", "*", "kwargs", ")", ":", "log_types", "=", "{", "'for_alert_event_log'", ":", "False", ",", "'for_alert_log'", ":", "False", ",", "'for_audit_log'", ":", "False", ",", "'for_fw_log'", ":", "...
Log targets for log tasks. A log target defines the log types that will be affected by the operation. For example, when creating a DeleteLogTask, you can specify which log types are deleted. :param bool for_alert_event_log: alert events traces (default: False) :param bool for_alert_log: alerts (def...
[ "Log", "targets", "for", "log", "tasks", ".", "A", "log", "target", "defines", "the", "log", "types", "that", "will", "be", "affected", "by", "the", "operation", ".", "For", "example", "when", "creating", "a", "DeleteLogTask", "you", "can", "specify", "whi...
python
train
palantir/python-jsonrpc-server
pyls_jsonrpc/endpoint.py
https://github.com/palantir/python-jsonrpc-server/blob/7021d849901705ab53c141e483a71d0779aff3d2/pyls_jsonrpc/endpoint.py#L197-L222
def _request_callback(self, request_id): """Construct a request callback for the given request ID.""" def callback(future): # Remove the future from the client requests map self._client_request_futures.pop(request_id, None) if future.cancelled(): futu...
[ "def", "_request_callback", "(", "self", ",", "request_id", ")", ":", "def", "callback", "(", "future", ")", ":", "# Remove the future from the client requests map", "self", ".", "_client_request_futures", ".", "pop", "(", "request_id", ",", "None", ")", "if", "fu...
Construct a request callback for the given request ID.
[ "Construct", "a", "request", "callback", "for", "the", "given", "request", "ID", "." ]
python
train
frmdstryr/enamlx
enamlx/qt/qt_plot_area.py
https://github.com/frmdstryr/enamlx/blob/9582e29c88dc0c0340f912b49168b7307a47ed4f/enamlx/qt/qt_plot_area.py#L174-L204
def _refresh_multi_axis(self): """ If linked axis' are used, setup and link them """ d = self.declaration #: Create a separate viewbox self.viewbox = pg.ViewBox() #: If this is the first nested plot, use the parent right axis _plots = [c for c in self.pa...
[ "def", "_refresh_multi_axis", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "#: Create a separate viewbox", "self", ".", "viewbox", "=", "pg", ".", "ViewBox", "(", ")", "#: If this is the first nested plot, use the parent right axis", "_plots", "=", "["...
If linked axis' are used, setup and link them
[ "If", "linked", "axis", "are", "used", "setup", "and", "link", "them" ]
python
train
biocore/mustached-octo-ironman
moi/job.py
https://github.com/biocore/mustached-octo-ironman/blob/54128d8fdff327e1b7ffd9bb77bf38c3df9526d7/moi/job.py#L157-L188
def submit(ctx_name, parent_id, name, url, func, *args, **kwargs): """Submit through a context Parameters ---------- ctx_name : str The name of the context to submit through parent_id : str The ID of the group that the job is a part of. name : str The name of the job ...
[ "def", "submit", "(", "ctx_name", ",", "parent_id", ",", "name", ",", "url", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "ctx_name", ",", "Context", ")", ":", "ctx", "=", "ctx_name", "else", ":", "ctx"...
Submit through a context Parameters ---------- ctx_name : str The name of the context to submit through parent_id : str The ID of the group that the job is a part of. name : str The name of the job url : str The handler that can take the results (e.g., /beta_dive...
[ "Submit", "through", "a", "context" ]
python
train
rdobson/python-hwinfo
hwinfo/tools/inspector.py
https://github.com/rdobson/python-hwinfo/blob/ba93a112dac6863396a053636ea87df027daa5de/hwinfo/tools/inspector.py#L272-L278
def _load_from_file(self, filename): """Find filename in tar, and load it""" if filename in self.fdata: return self.fdata[filename] else: filepath = find_in_tarball(self.tarloc, filename) return read_from_tarball(self.tarloc, filepath)
[ "def", "_load_from_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "in", "self", ".", "fdata", ":", "return", "self", ".", "fdata", "[", "filename", "]", "else", ":", "filepath", "=", "find_in_tarball", "(", "self", ".", "tarloc", ",", ...
Find filename in tar, and load it
[ "Find", "filename", "in", "tar", "and", "load", "it" ]
python
train
apache/airflow
airflow/contrib/operators/spark_submit_operator.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/spark_submit_operator.py#L147-L176
def execute(self, context): """ Call the SparkSubmitHook to run the provided spark job """ self._hook = SparkSubmitHook( conf=self._conf, conn_id=self._conn_id, files=self._files, py_files=self._py_files, archives=self._archives...
[ "def", "execute", "(", "self", ",", "context", ")", ":", "self", ".", "_hook", "=", "SparkSubmitHook", "(", "conf", "=", "self", ".", "_conf", ",", "conn_id", "=", "self", ".", "_conn_id", ",", "files", "=", "self", ".", "_files", ",", "py_files", "=...
Call the SparkSubmitHook to run the provided spark job
[ "Call", "the", "SparkSubmitHook", "to", "run", "the", "provided", "spark", "job" ]
python
test
ev3dev/ev3dev-lang-python
ev3dev2/motor.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L750-L756
def run_forever(self, **kwargs): """ Run the motor until another command is sent. """ for key in kwargs: setattr(self, key, kwargs[key]) self.command = self.COMMAND_RUN_FOREVER
[ "def", "run_forever", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", "in", "kwargs", ":", "setattr", "(", "self", ",", "key", ",", "kwargs", "[", "key", "]", ")", "self", ".", "command", "=", "self", ".", "COMMAND_RUN_FOREVER" ]
Run the motor until another command is sent.
[ "Run", "the", "motor", "until", "another", "command", "is", "sent", "." ]
python
train
bokeh/bokeh
examples/howto/events_app.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/examples/howto/events_app.py#L16-L37
def display_event(div, attributes=[]): """ Function to build a suitable CustomJS to display the current event in the div model. """ style = 'float: left; clear: left; font-size: 10pt' return CustomJS(args=dict(div=div), code=""" var attrs = %s; var args = []; for (var i =...
[ "def", "display_event", "(", "div", ",", "attributes", "=", "[", "]", ")", ":", "style", "=", "'float: left; clear: left; font-size: 10pt'", "return", "CustomJS", "(", "args", "=", "dict", "(", "div", "=", "div", ")", ",", "code", "=", "\"\"\"\n var att...
Function to build a suitable CustomJS to display the current event in the div model.
[ "Function", "to", "build", "a", "suitable", "CustomJS", "to", "display", "the", "current", "event", "in", "the", "div", "model", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/abinit/launcher.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/launcher.py#L773-L781
def cleanup(self): """Cleanup routine: remove the pid file and save the pickle database""" try: os.remove(self.pid_file) except OSError as exc: logger.critical("Could not remove pid_file: %s", exc) # Save the final status of the flow. self.flow.pickle_dum...
[ "def", "cleanup", "(", "self", ")", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "pid_file", ")", "except", "OSError", "as", "exc", ":", "logger", ".", "critical", "(", "\"Could not remove pid_file: %s\"", ",", "exc", ")", "# Save the final status...
Cleanup routine: remove the pid file and save the pickle database
[ "Cleanup", "routine", ":", "remove", "the", "pid", "file", "and", "save", "the", "pickle", "database" ]
python
train
wummel/linkchecker
linkcheck/checker/httpurl.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/checker/httpurl.py#L187-L191
def _add_response_info(self): """Set info from established HTTP(S) connection.""" self.charset = httputil.get_charset(self.headers) self.set_content_type() self.add_size_info()
[ "def", "_add_response_info", "(", "self", ")", ":", "self", ".", "charset", "=", "httputil", ".", "get_charset", "(", "self", ".", "headers", ")", "self", ".", "set_content_type", "(", ")", "self", ".", "add_size_info", "(", ")" ]
Set info from established HTTP(S) connection.
[ "Set", "info", "from", "established", "HTTP", "(", "S", ")", "connection", "." ]
python
train
log2timeline/dfdatetime
dfdatetime/interface.py
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L235-L288
def _AdjustForTimeZoneOffset( self, year, month, day_of_month, hours, minutes, time_zone_offset): """Adjusts the date and time values for a time zone offset. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 r...
[ "def", "_AdjustForTimeZoneOffset", "(", "self", ",", "year", ",", "month", ",", "day_of_month", ",", "hours", ",", "minutes", ",", "time_zone_offset", ")", ":", "hours_from_utc", ",", "minutes_from_utc", "=", "divmod", "(", "time_zone_offset", ",", "60", ")", ...
Adjusts the date and time values for a time zone offset. Args: year (int): year e.g. 1970. month (int): month, where 1 represents January. day_of_month (int): day of the month, where 1 represents the first day. hours (int): hours. minutes (int): minutes. time_zone_offset (int): ...
[ "Adjusts", "the", "date", "and", "time", "values", "for", "a", "time", "zone", "offset", "." ]
python
train
dtmilano/AndroidViewClient
src/com/dtmilano/android/viewclient.py
https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L4325-L4333
def levenshteinDistance(self, tree): ''' Finds the Levenshtein distance between this tree and the one passed as argument. ''' s1 = ' '.join(map(View.__microStr__, self.views)) s2 = ' '.join(map(View.__microStr__, tree)) return ViewClient.__levenshteinDistance(s1, s2)
[ "def", "levenshteinDistance", "(", "self", ",", "tree", ")", ":", "s1", "=", "' '", ".", "join", "(", "map", "(", "View", ".", "__microStr__", ",", "self", ".", "views", ")", ")", "s2", "=", "' '", ".", "join", "(", "map", "(", "View", ".", "__mi...
Finds the Levenshtein distance between this tree and the one passed as argument.
[ "Finds", "the", "Levenshtein", "distance", "between", "this", "tree", "and", "the", "one", "passed", "as", "argument", "." ]
python
train
tensorforce/tensorforce
tensorforce/contrib/sanity_check_specs.py
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/contrib/sanity_check_specs.py#L55-L95
def sanity_check_actions(actions_spec): """ Sanity checks an actions dict, used to define the action space for an MDP. Throws an error or warns if mismatches are found. Args: actions_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the action space desc and 2...
[ "def", "sanity_check_actions", "(", "actions_spec", ")", ":", "# Leave incoming spec-dict intact.", "actions", "=", "copy", ".", "deepcopy", "(", "actions_spec", ")", "# Unique action shortform.", "is_unique", "=", "(", "'type'", "in", "actions", ")", "if", "is_unique...
Sanity checks an actions dict, used to define the action space for an MDP. Throws an error or warns if mismatches are found. Args: actions_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the action space desc and 2) whether there is only one component in the action ...
[ "Sanity", "checks", "an", "actions", "dict", "used", "to", "define", "the", "action", "space", "for", "an", "MDP", ".", "Throws", "an", "error", "or", "warns", "if", "mismatches", "are", "found", "." ]
python
valid
pantsbuild/pex
pex/vendor/_vendored/wheel/wheel/metadata.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/vendor/_vendored/wheel/wheel/metadata.py#L35-L43
def convert_requirements(requirements): """Yield Requires-Dist: strings for parsed requirements strings.""" for req in requirements: parsed_requirement = pkg_resources.Requirement.parse(req) spec = requires_to_requires_dist(parsed_requirement) extras = ",".join(parsed_requirement.extras)...
[ "def", "convert_requirements", "(", "requirements", ")", ":", "for", "req", "in", "requirements", ":", "parsed_requirement", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "req", ")", "spec", "=", "requires_to_requires_dist", "(", "parsed_requirement",...
Yield Requires-Dist: strings for parsed requirements strings.
[ "Yield", "Requires", "-", "Dist", ":", "strings", "for", "parsed", "requirements", "strings", "." ]
python
train
quantmind/pulsar
pulsar/apps/__init__.py
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L291-L309
def python_path(self, script): """Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application. """ if not scrip...
[ "def", "python_path", "(", "self", ",", "script", ")", ":", "if", "not", "script", ":", "try", ":", "import", "__main__", "script", "=", "getfile", "(", "__main__", ")", "except", "Exception", ":", "# pragma nocover", "return", "script", "=", "os", ".",...
Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application.
[ "Called", "during", "initialisation", "to", "obtain", "the", "script", "name", "." ]
python
train
WojciechMula/canvas2svg
canvasvg.py
https://github.com/WojciechMula/canvas2svg/blob/c05d73d88499e5c565386a1765f79d9417a14dac/canvasvg.py#L73-L315
def convert(document, canvas, items=None, tounicode=None): """ Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Ret...
[ "def", "convert", "(", "document", ",", "canvas", ",", "items", "=", "None", ",", "tounicode", "=", "None", ")", ":", "tk", "=", "canvas", ".", "tk", "global", "segment", "if", "items", "is", "None", ":", "# default: all items", "items", "=", "canvas", ...
Convert 'items' stored in 'canvas' to SVG 'document'. If 'items' is None, then all items are convered. tounicode is a function that get text and returns it's unicode representation. It should be used when national characters are used on canvas. Return list of XML elements
[ "Convert", "items", "stored", "in", "canvas", "to", "SVG", "document", ".", "If", "items", "is", "None", "then", "all", "items", "are", "convered", "." ]
python
train
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2016_05_31/file/fileservice.py
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2016_05_31/file/fileservice.py#L1741-L1794
def _get_file(self, share_name, directory_name, file_name, start_range=None, end_range=None, validate_content=False, timeout=None, _context=None): ''' Downloads a file's content, metadata, and properties. You can specify a range if you don't need to download th...
[ "def", "_get_file", "(", "self", ",", "share_name", ",", "directory_name", ",", "file_name", ",", "start_range", "=", "None", ",", "end_range", "=", "None", ",", "validate_content", "=", "False", ",", "timeout", "=", "None", ",", "_context", "=", "None", "...
Downloads a file's content, metadata, and properties. You can specify a range if you don't need to download the file in its entirety. If no range is specified, the full file will be downloaded. See get_file_to_* for high level functions that handle the download of large files with autom...
[ "Downloads", "a", "file", "s", "content", "metadata", "and", "properties", ".", "You", "can", "specify", "a", "range", "if", "you", "don", "t", "need", "to", "download", "the", "file", "in", "its", "entirety", ".", "If", "no", "range", "is", "specified",...
python
train
a1ezzz/wasp-general
wasp_general/cli/cli.py
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L171-L179
def row(self): """ Get row :return: str """ if not self.__history_mode: return self.__current_row else: return self.history().entry(self.history().position())
[ "def", "row", "(", "self", ")", ":", "if", "not", "self", ".", "__history_mode", ":", "return", "self", ".", "__current_row", "else", ":", "return", "self", ".", "history", "(", ")", ".", "entry", "(", "self", ".", "history", "(", ")", ".", "position...
Get row :return: str
[ "Get", "row" ]
python
train
jtwhite79/pyemu
pyemu/prototypes/ensemble_method.py
https://github.com/jtwhite79/pyemu/blob/c504d8e7a4097cec07655a6318d275739bd8148a/pyemu/prototypes/ensemble_method.py#L95-L106
def _calc_delta(self,ensemble,scaling_matrix=None): ''' calc the scaled ensemble differences from the mean ''' mean = np.array(ensemble.mean(axis=0)) delta = ensemble.as_pyemu_matrix() for i in range(ensemble.shape[0]): delta.x[i,:] -= mean if scaling...
[ "def", "_calc_delta", "(", "self", ",", "ensemble", ",", "scaling_matrix", "=", "None", ")", ":", "mean", "=", "np", ".", "array", "(", "ensemble", ".", "mean", "(", "axis", "=", "0", ")", ")", "delta", "=", "ensemble", ".", "as_pyemu_matrix", "(", "...
calc the scaled ensemble differences from the mean
[ "calc", "the", "scaled", "ensemble", "differences", "from", "the", "mean" ]
python
train
aparo/pyes
pyes/orm/queryset.py
https://github.com/aparo/pyes/blob/712eb6095961755067b2b5baa262008ade6584b3/pyes/orm/queryset.py#L437-L455
def get_or_create(self, **kwargs): """ Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created. """ assert kwargs, \ 'get_or_create() must be...
[ "def", "get_or_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "kwargs", ",", "'get_or_create() must be passed at least one keyword argument'", "defaults", "=", "kwargs", ".", "pop", "(", "'defaults'", ",", "{", "}", ")", "lookup", "=", "kwarg...
Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created.
[ "Looks", "up", "an", "object", "with", "the", "given", "kwargs", "creating", "one", "if", "necessary", ".", "Returns", "a", "tuple", "of", "(", "object", "created", ")", "where", "created", "is", "a", "boolean", "specifying", "whether", "an", "object", "wa...
python
train
konstantint/matplotlib-venn
matplotlib_venn/_arc.py
https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_arc.py#L44-L96
def length_degrees(self): '''Computes the length of the arc in degrees. The length computation corresponds to what you would expect if you would draw the arc using matplotlib taking direction into account. >>> Arc((0,0), 1, 0, 0, True).length_degrees() 0.0 >>> Arc((0,0),...
[ "def", "length_degrees", "(", "self", ")", ":", "d_angle", "=", "self", ".", "sign", "*", "(", "self", ".", "to_angle", "-", "self", ".", "from_angle", ")", "if", "(", "d_angle", ">", "360", ")", ":", "return", "360.0", "elif", "(", "d_angle", "<", ...
Computes the length of the arc in degrees. The length computation corresponds to what you would expect if you would draw the arc using matplotlib taking direction into account. >>> Arc((0,0), 1, 0, 0, True).length_degrees() 0.0 >>> Arc((0,0), 2, 0, 0, False).length_degrees() ...
[ "Computes", "the", "length", "of", "the", "arc", "in", "degrees", ".", "The", "length", "computation", "corresponds", "to", "what", "you", "would", "expect", "if", "you", "would", "draw", "the", "arc", "using", "matplotlib", "taking", "direction", "into", "a...
python
train
cloudsmith-io/cloudsmith-cli
cloudsmith_cli/core/api/rates.py
https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/rates.py#L19-L31
def get_rate_limits(): """Retrieve status (and optionally) version from the API.""" client = get_rates_api() with catch_raise_api_exception(): data, _, headers = client.rates_limits_list_with_http_info() ratelimits.maybe_rate_limit(client, headers) return { k: RateLimitsInfo.from_...
[ "def", "get_rate_limits", "(", ")", ":", "client", "=", "get_rates_api", "(", ")", "with", "catch_raise_api_exception", "(", ")", ":", "data", ",", "_", ",", "headers", "=", "client", ".", "rates_limits_list_with_http_info", "(", ")", "ratelimits", ".", "maybe...
Retrieve status (and optionally) version from the API.
[ "Retrieve", "status", "(", "and", "optionally", ")", "version", "from", "the", "API", "." ]
python
train
googleapis/google-cloud-python
bigtable/google/cloud/bigtable/policy.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigtable/google/cloud/bigtable/policy.py#L83-L95
def bigtable_admins(self): """Access to bigtable.admin role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_admins_policy] :end-before: [END bigtable_admins_policy] """ result = set() for member in self._bindin...
[ "def", "bigtable_admins", "(", "self", ")", ":", "result", "=", "set", "(", ")", "for", "member", "in", "self", ".", "_bindings", ".", "get", "(", "BIGTABLE_ADMIN_ROLE", ",", "(", ")", ")", ":", "result", ".", "add", "(", "member", ")", "return", "fr...
Access to bigtable.admin role memebers For example: .. literalinclude:: snippets.py :start-after: [START bigtable_admins_policy] :end-before: [END bigtable_admins_policy]
[ "Access", "to", "bigtable", ".", "admin", "role", "memebers" ]
python
train
michaelpb/omnic
omnic/utils/filesystem.py
https://github.com/michaelpb/omnic/blob/1111cfd73c9dc1955afe42d9cf2a468c46f83cd6/omnic/utils/filesystem.py#L71-L134
def flat_git_tree_to_nested(flat_tree, prefix=''): ''' Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { "path...
[ "def", "flat_git_tree_to_nested", "(", "flat_tree", ",", "prefix", "=", "''", ")", ":", "root", "=", "_make_empty_dir_dict", "(", "prefix", "if", "prefix", "else", "'/'", ")", "# Filter all descendents of this prefix", "descendent_files", "=", "[", "info", "for", ...
Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { "path": "/", "type": "directory", "children"...
[ "Given", "an", "array", "in", "format", ":", "[", "[", "100644", "blob", "ab3ce", "...", "748", ".", "gitignore", "]", "[", "100644", "blob", "ab3ce", "...", "748", "path", "/", "to", "/", "thing", "]", "...", "]" ]
python
train
astropy/astropy-healpix
astropy_healpix/core.py
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L561-L592
def neighbours(healpix_index, nside, order='ring'): """ Find all the HEALPix pixels that are the neighbours of a HEALPix pixel Parameters ---------- healpix_index : `~numpy.ndarray` Array of HEALPix pixels nside : int Number of pixels along the side of each of the 12 top-level H...
[ "def", "neighbours", "(", "healpix_index", ",", "nside", ",", "order", "=", "'ring'", ")", ":", "_validate_nside", "(", "nside", ")", "nside", "=", "np", ".", "asarray", "(", "nside", ",", "dtype", "=", "np", ".", "intc", ")", "if", "_validate_order", ...
Find all the HEALPix pixels that are the neighbours of a HEALPix pixel Parameters ---------- healpix_index : `~numpy.ndarray` Array of HEALPix pixels nside : int Number of pixels along the side of each of the 12 top-level HEALPix tiles order : { 'nested' | 'ring' } Order of ...
[ "Find", "all", "the", "HEALPix", "pixels", "that", "are", "the", "neighbours", "of", "a", "HEALPix", "pixel" ]
python
train
ActivisionGameScience/assertpy
assertpy/assertpy.py
https://github.com/ActivisionGameScience/assertpy/blob/08d799cdb01f9a25d3e20672efac991c7bc26d79/assertpy/assertpy.py#L944-L953
def is_child_of(self, parent): """Asserts that val is an existing path to a file and that file is a child of parent.""" self.is_file() if not isinstance(parent, str_types): raise TypeError('given parent directory arg must be a path') val_abspath = os.path.abspath(self.val) ...
[ "def", "is_child_of", "(", "self", ",", "parent", ")", ":", "self", ".", "is_file", "(", ")", "if", "not", "isinstance", "(", "parent", ",", "str_types", ")", ":", "raise", "TypeError", "(", "'given parent directory arg must be a path'", ")", "val_abspath", "=...
Asserts that val is an existing path to a file and that file is a child of parent.
[ "Asserts", "that", "val", "is", "an", "existing", "path", "to", "a", "file", "and", "that", "file", "is", "a", "child", "of", "parent", "." ]
python
valid
delfick/harpoon
harpoon/collector.py
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/collector.py#L118-L141
def setup_addon_register(self, harpoon): """Setup our addon register""" # Create the addon getter and register the crosshairs namespace self.addon_getter = AddonGetter() self.addon_getter.add_namespace("harpoon.crosshairs", Result.FieldSpec(), Addon.FieldSpec()) # Initiate the a...
[ "def", "setup_addon_register", "(", "self", ",", "harpoon", ")", ":", "# Create the addon getter and register the crosshairs namespace", "self", ".", "addon_getter", "=", "AddonGetter", "(", ")", "self", ".", "addon_getter", ".", "add_namespace", "(", "\"harpoon.crosshair...
Setup our addon register
[ "Setup", "our", "addon", "register" ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelmanager.py#L304-L321
def object_info(self, oname, detail_level=0): """Get metadata information about an object. Parameters ---------- oname : str A string specifying the object name. detail_level : int, optional The level of detail for the introspection (0-2) Returns...
[ "def", "object_info", "(", "self", ",", "oname", ",", "detail_level", "=", "0", ")", ":", "content", "=", "dict", "(", "oname", "=", "oname", ",", "detail_level", "=", "detail_level", ")", "msg", "=", "self", ".", "session", ".", "msg", "(", "'object_i...
Get metadata information about an object. Parameters ---------- oname : str A string specifying the object name. detail_level : int, optional The level of detail for the introspection (0-2) Returns ------- The msg_id of the message sent.
[ "Get", "metadata", "information", "about", "an", "object", "." ]
python
test
joshspeagle/dynesty
dynesty/utils.py
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/utils.py#L29-L42
def unitcheck(u, nonperiodic=None): """Check whether `u` is inside the unit cube. Given a masked array `nonperiodic`, also allows periodic boundaries conditions to exceed the unit cube.""" if nonperiodic is None: # No periodic boundary conditions provided. return np.all(u > 0.) and np.a...
[ "def", "unitcheck", "(", "u", ",", "nonperiodic", "=", "None", ")", ":", "if", "nonperiodic", "is", "None", ":", "# No periodic boundary conditions provided.", "return", "np", ".", "all", "(", "u", ">", "0.", ")", "and", "np", ".", "all", "(", "u", "<", ...
Check whether `u` is inside the unit cube. Given a masked array `nonperiodic`, also allows periodic boundaries conditions to exceed the unit cube.
[ "Check", "whether", "u", "is", "inside", "the", "unit", "cube", ".", "Given", "a", "masked", "array", "nonperiodic", "also", "allows", "periodic", "boundaries", "conditions", "to", "exceed", "the", "unit", "cube", "." ]
python
train
toumorokoshi/sprinter
sprinter/next/environment/injections.py
https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/environment/injections.py#L120-L127
def in_noninjected_file(self, file_path, content): """ Checks if a string exists in the file, sans the injected """ if os.path.exists(file_path): file_content = codecs.open(file_path, encoding="utf-8").read() file_content = self.wrapper_match.sub(u"", file_content) else: ...
[ "def", "in_noninjected_file", "(", "self", ",", "file_path", ",", "content", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "file_content", "=", "codecs", ".", "open", "(", "file_path", ",", "encoding", "=", "\"utf-8\"", ")...
Checks if a string exists in the file, sans the injected
[ "Checks", "if", "a", "string", "exists", "in", "the", "file", "sans", "the", "injected" ]
python
train
jcrist/skein
skein/core.py
https://github.com/jcrist/skein/blob/16f8b1d3b3d9f79f36e2f152e45893339a1793e8/skein/core.py#L855-L873
def shutdown(self, status='SUCCEEDED', diagnostics=None): """Shutdown the application. Stop all running containers and shutdown the application. Parameters ---------- status : FinalStatus, optional The final application status. Default is 'SUCCEEDED'. diagno...
[ "def", "shutdown", "(", "self", ",", "status", "=", "'SUCCEEDED'", ",", "diagnostics", "=", "None", ")", ":", "req", "=", "proto", ".", "ShutdownRequest", "(", "final_status", "=", "str", "(", "FinalStatus", "(", "status", ")", ")", ",", "diagnostics", "...
Shutdown the application. Stop all running containers and shutdown the application. Parameters ---------- status : FinalStatus, optional The final application status. Default is 'SUCCEEDED'. diagnostics : str, optional The application exit message, usual...
[ "Shutdown", "the", "application", "." ]
python
train
sigsep/sigsep-mus-eval
museval/__init__.py
https://github.com/sigsep/sigsep-mus-eval/blob/a7c9af3647f0c0bb9bbaeccec0b1a6a9e09d1e2d/museval/__init__.py#L507-L557
def evaluate( references, estimates, win=1*44100, hop=1*44100, mode='v4', padding=True ): """BSS_EVAL images evaluation using metrics module Parameters ---------- references : np.ndarray, shape=(nsrc, nsampl, nchan) array containing true reference sources estimates :...
[ "def", "evaluate", "(", "references", ",", "estimates", ",", "win", "=", "1", "*", "44100", ",", "hop", "=", "1", "*", "44100", ",", "mode", "=", "'v4'", ",", "padding", "=", "True", ")", ":", "estimates", "=", "np", ".", "array", "(", "estimates",...
BSS_EVAL images evaluation using metrics module Parameters ---------- references : np.ndarray, shape=(nsrc, nsampl, nchan) array containing true reference sources estimates : np.ndarray, shape=(nsrc, nsampl, nchan) array containing estimated sources window : int, defaults to 44100 ...
[ "BSS_EVAL", "images", "evaluation", "using", "metrics", "module" ]
python
train
evhub/coconut
coconut/terminal.py
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/terminal.py#L155-L164
def get_error(self): """Properly formats the current error.""" exc_info = sys.exc_info() if exc_info[0] is None: return None else: err_type, err_value, err_trace = exc_info[0], exc_info[1], None if self.verbose and len(exc_info) > 2: er...
[ "def", "get_error", "(", "self", ")", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "if", "exc_info", "[", "0", "]", "is", "None", ":", "return", "None", "else", ":", "err_type", ",", "err_value", ",", "err_trace", "=", "exc_info", "[", "0"...
Properly formats the current error.
[ "Properly", "formats", "the", "current", "error", "." ]
python
train
shexSpec/grammar
parsers/python/pyshexc/parser_impl/shex_doc_parser.py
https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_doc_parser.py#L55-L60
def visitPrefixDecl(self, ctx: ShExDocParser.PrefixDeclContext): """ prefixDecl: KW_PREFIX PNAME_NS IRIREF """ iri = self.context.iriref_to_shexj_iriref(ctx.IRIREF()) prefix = ctx.PNAME_NS().getText() if iri not in self.context.ld_prefixes: self.context.prefixes.setdefault(pr...
[ "def", "visitPrefixDecl", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "PrefixDeclContext", ")", ":", "iri", "=", "self", ".", "context", ".", "iriref_to_shexj_iriref", "(", "ctx", ".", "IRIREF", "(", ")", ")", "prefix", "=", "ctx", ".", "PNAME_NS",...
prefixDecl: KW_PREFIX PNAME_NS IRIREF
[ "prefixDecl", ":", "KW_PREFIX", "PNAME_NS", "IRIREF" ]
python
train
apple/turicreate
deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/char_stat.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/metaparse/tools/benchmark/char_stat.py#L34-L55
def main(): """The main function of the script""" desc = 'Generate character statistics from a source tree' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src', required=True, help='The root of the source tree' ) parser.add_...
[ "def", "main", "(", ")", ":", "desc", "=", "'Generate character statistics from a source tree'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "desc", ")", "parser", ".", "add_argument", "(", "'--src'", ",", "dest", "=", "'src'", ","...
The main function of the script
[ "The", "main", "function", "of", "the", "script" ]
python
train
digidotcom/python-devicecloud
devicecloud/devicecore.py
https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/devicecore.py#L419-L426
def get_tags(self, use_cached=True): """Get the list of tags for this device""" device_json = self.get_device_json(use_cached) potential_tags = device_json.get("dpTags") if potential_tags: return list(filter(None, potential_tags.split(","))) else: return [...
[ "def", "get_tags", "(", "self", ",", "use_cached", "=", "True", ")", ":", "device_json", "=", "self", ".", "get_device_json", "(", "use_cached", ")", "potential_tags", "=", "device_json", ".", "get", "(", "\"dpTags\"", ")", "if", "potential_tags", ":", "retu...
Get the list of tags for this device
[ "Get", "the", "list", "of", "tags", "for", "this", "device" ]
python
train
trailofbits/manticore
manticore/utils/event.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/utils/event.py#L65-L72
def all_events(cls): """ Return all events that all subclasses have so far registered to publish. """ all_evts = set() for cls, evts in cls.__all_events__.items(): all_evts.update(evts) return all_evts
[ "def", "all_events", "(", "cls", ")", ":", "all_evts", "=", "set", "(", ")", "for", "cls", ",", "evts", "in", "cls", ".", "__all_events__", ".", "items", "(", ")", ":", "all_evts", ".", "update", "(", "evts", ")", "return", "all_evts" ]
Return all events that all subclasses have so far registered to publish.
[ "Return", "all", "events", "that", "all", "subclasses", "have", "so", "far", "registered", "to", "publish", "." ]
python
valid
tensorflow/lucid
lucid/optvis/render.py
https://github.com/tensorflow/lucid/blob/d1a1e2e4fd4be61b89b8cba20dc425a5ae34576e/lucid/optvis/render.py#L44-L115
def render_vis(model, objective_f, param_f=None, optimizer=None, transforms=None, thresholds=(512,), print_objectives=None, verbose=True, relu_gradient_override=True, use_fixed_seed=False): """Flexible optimization-base feature vis. There's a lot of ways one might wish to customize ot...
[ "def", "render_vis", "(", "model", ",", "objective_f", ",", "param_f", "=", "None", ",", "optimizer", "=", "None", ",", "transforms", "=", "None", ",", "thresholds", "=", "(", "512", ",", ")", ",", "print_objectives", "=", "None", ",", "verbose", "=", ...
Flexible optimization-base feature vis. There's a lot of ways one might wish to customize otpimization-based feature visualization. It's hard to create an abstraction that stands up to all the things one might wish to try. This function probably can't do *everything* you want, but it's much more flexible th...
[ "Flexible", "optimization", "-", "base", "feature", "vis", "." ]
python
train
nickmilon/Hellas
Hellas/Delphi.py
https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Delphi.py#L54-L60
def color_code(cls, color): """ returns code for color :param tuple_or_code color: either a tuple as in colors.values or a string key to colors dictionary """ if not isinstance(color, tuple): color = cls.colors[color] return "{:d};{}".format(color[0], str(color[1]) i...
[ "def", "color_code", "(", "cls", ",", "color", ")", ":", "if", "not", "isinstance", "(", "color", ",", "tuple", ")", ":", "color", "=", "cls", ".", "colors", "[", "color", "]", "return", "\"{:d};{}\"", ".", "format", "(", "color", "[", "0", "]", ",...
returns code for color :param tuple_or_code color: either a tuple as in colors.values or a string key to colors dictionary
[ "returns", "code", "for", "color", ":", "param", "tuple_or_code", "color", ":", "either", "a", "tuple", "as", "in", "colors", ".", "values", "or", "a", "string", "key", "to", "colors", "dictionary" ]
python
train
jason-weirather/py-seq-tools
seqtools/range/multi.py
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/range/multi.py#L334-L345
def read_entry(self): """read the next bed entry from the stream""" line = self.fh.readline() if not line: return None m = re.match('([^\t]+)\t(\d+)\t(\d+)\t*(.*)',line.rstrip()) if not m: sys.stderr.write("ERROR: unknown line in bed format file\n"+line+"\n") sys.exit() g = GenomicRa...
[ "def", "read_entry", "(", "self", ")", ":", "line", "=", "self", ".", "fh", ".", "readline", "(", ")", "if", "not", "line", ":", "return", "None", "m", "=", "re", ".", "match", "(", "'([^\\t]+)\\t(\\d+)\\t(\\d+)\\t*(.*)'", ",", "line", ".", "rstrip", "...
read the next bed entry from the stream
[ "read", "the", "next", "bed", "entry", "from", "the", "stream" ]
python
train
crunchyroll/ef-open
efopen/ef_version.py
https://github.com/crunchyroll/ef-open/blob/59fff3761af07a59f8f1c1682f2be004bdac15f7/efopen/ef_version.py#L485-L503
def precheck(context): """ calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the p...
[ "def", "precheck", "(", "context", ")", ":", "if", "context", ".", "noprecheck", ":", "return", "True", "func_name", "=", "\"precheck_\"", "+", "context", ".", "key", ".", "replace", "(", "\"-\"", ",", "\"_\"", ")", "if", "func_name", "in", "globals", "(...
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the precheck passed, or if there was...
[ "calls", "a", "function", "named", "precheck_<key", ">", "where", "<key", ">", "is", "context_key", "with", "-", "changed", "to", "_", "(", "e", ".", "g", ".", "precheck_ami_id", ")", "Checking", "function", "should", "return", "True", "if", "OK", "or", ...
python
train
nschloe/meshplex
meshplex/helpers.py
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/helpers.py#L8-L17
def get_signed_simplex_volumes(cells, pts): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1) return ...
[ "def", "get_signed_simplex_volumes", "(", "cells", ",", "pts", ")", ":", "n", "=", "pts", ".", "shape", "[", "1", "]", "assert", "cells", ".", "shape", "[", "1", "]", "==", "n", "+", "1", "p", "=", "pts", "[", "cells", "]", "p", "=", "numpy", "...
Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n.
[ "Signed", "volume", "of", "a", "simplex", "in", "nD", ".", "Note", "that", "signing", "only", "makes", "sense", "for", "n", "-", "simplices", "in", "R^n", "." ]
python
train
stuaxo/vext
setup.py
https://github.com/stuaxo/vext/blob/fa98a21ecfbbc1c3d1b84085d69ec42defdd2f69/setup.py#L28-L49
def upgrade_setuptools(): """ setuptools 12.2 can trigger a really nasty bug that eats all memory, so upgrade it to 18.8, which is known to be good. """ # Note - I tried including the higher version in # setup_requires, but was still able to trigger # the bug. - stu.axon global MIN_S...
[ "def", "upgrade_setuptools", "(", ")", ":", "# Note - I tried including the higher version in", "# setup_requires, but was still able to trigger", "# the bug. - stu.axon", "global", "MIN_SETUPTOOLS", "r", "=", "None", "try", ":", "r", "=", "pkg_resources", ".", "require", "("...
setuptools 12.2 can trigger a really nasty bug that eats all memory, so upgrade it to 18.8, which is known to be good.
[ "setuptools", "12", ".", "2", "can", "trigger", "a", "really", "nasty", "bug", "that", "eats", "all", "memory", "so", "upgrade", "it", "to", "18", ".", "8", "which", "is", "known", "to", "be", "good", "." ]
python
train
diux-dev/ncluster
ncluster/local_backend.py
https://github.com/diux-dev/ncluster/blob/2fd359621896717197b479c7174d06d80df1529b/ncluster/local_backend.py#L185-L204
def switch_window(self, window_id: int): """ Switches currently active tmux window for given task. 0 is the default window Args: window_id: integer id of tmux window to use """ # windows are numbered sequentially 0, 1, 2, ... # create any missing windows and make them point to the same di...
[ "def", "switch_window", "(", "self", ",", "window_id", ":", "int", ")", ":", "# windows are numbered sequentially 0, 1, 2, ...", "# create any missing windows and make them point to the same directory", "if", "window_id", "not", "in", "self", ".", "tmux_available_window_ids", "...
Switches currently active tmux window for given task. 0 is the default window Args: window_id: integer id of tmux window to use
[ "Switches", "currently", "active", "tmux", "window", "for", "given", "task", ".", "0", "is", "the", "default", "window", "Args", ":", "window_id", ":", "integer", "id", "of", "tmux", "window", "to", "use" ]
python
train
googleapis/google-cloud-python
storage/google/cloud/storage/acl.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/storage/google/cloud/storage/acl.py#L215-L229
def validate_predefined(cls, predefined): """Ensures predefined is in list of predefined json values :type predefined: str :param predefined: name of a predefined acl :type predefined: str :param predefined: validated JSON name of predefined acl :raises: :exc: `ValueEr...
[ "def", "validate_predefined", "(", "cls", ",", "predefined", ")", ":", "predefined", "=", "cls", ".", "PREDEFINED_XML_ACLS", ".", "get", "(", "predefined", ",", "predefined", ")", "if", "predefined", "and", "predefined", "not", "in", "cls", ".", "PREDEFINED_JS...
Ensures predefined is in list of predefined json values :type predefined: str :param predefined: name of a predefined acl :type predefined: str :param predefined: validated JSON name of predefined acl :raises: :exc: `ValueError`: If predefined is not a valid acl
[ "Ensures", "predefined", "is", "in", "list", "of", "predefined", "json", "values" ]
python
train
fermiPy/fermipy
fermipy/jobs/job_archive.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L350-L354
def _fill_array_from_list(the_list, the_array): """Fill an `array` from a `list`""" for i, val in enumerate(the_list): the_array[i] = val return the_array
[ "def", "_fill_array_from_list", "(", "the_list", ",", "the_array", ")", ":", "for", "i", ",", "val", "in", "enumerate", "(", "the_list", ")", ":", "the_array", "[", "i", "]", "=", "val", "return", "the_array" ]
Fill an `array` from a `list`
[ "Fill", "an", "array", "from", "a", "list" ]
python
train
liftoff/pyminifier
pyminifier/analyze.py
https://github.com/liftoff/pyminifier/blob/087ea7b0c8c964f1f907c3f350f5ce281798db86/pyminifier/analyze.py#L179-L199
def enumerate_keyword_args(tokens): """ Iterates over *tokens* and returns a dictionary with function names as the keys and lists of keyword arguments as the values. """ keyword_args = {} inside_function = False for index, tok in enumerate(tokens): token_type = tok[0] token_s...
[ "def", "enumerate_keyword_args", "(", "tokens", ")", ":", "keyword_args", "=", "{", "}", "inside_function", "=", "False", "for", "index", ",", "tok", "in", "enumerate", "(", "tokens", ")", ":", "token_type", "=", "tok", "[", "0", "]", "token_string", "=", ...
Iterates over *tokens* and returns a dictionary with function names as the keys and lists of keyword arguments as the values.
[ "Iterates", "over", "*", "tokens", "*", "and", "returns", "a", "dictionary", "with", "function", "names", "as", "the", "keys", "and", "lists", "of", "keyword", "arguments", "as", "the", "values", "." ]
python
train
pyviz/holoviews
holoviews/util/transform.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/util/transform.py#L228-L240
def bin(self, bins, labels=None): """Bins continuous values. Bins continuous using the provided bins and assigns labels either computed from each bins center point or from the supplied labels. Args: bins: List or array containing the bin boundaries label...
[ "def", "bin", "(", "self", ",", "bins", ",", "labels", "=", "None", ")", ":", "return", "dim", "(", "self", ",", "bin", ",", "bins", ",", "labels", "=", "labels", ")" ]
Bins continuous values. Bins continuous using the provided bins and assigns labels either computed from each bins center point or from the supplied labels. Args: bins: List or array containing the bin boundaries labels: List of labels to assign to each bin ...
[ "Bins", "continuous", "values", "." ]
python
train
briandilley/ebs-deploy
ebs_deploy/__init__.py
https://github.com/briandilley/ebs-deploy/blob/4178c9c1282a9025fb987dab3470bea28c202e10/ebs_deploy/__init__.py#L302-L307
def application_exists(self): """ Returns whether or not the given app_name exists """ response = self.ebs.describe_applications(application_names=[self.app_name]) return len(response['DescribeApplicationsResponse']['DescribeApplicationsResult']['Applications']) > 0
[ "def", "application_exists", "(", "self", ")", ":", "response", "=", "self", ".", "ebs", ".", "describe_applications", "(", "application_names", "=", "[", "self", ".", "app_name", "]", ")", "return", "len", "(", "response", "[", "'DescribeApplicationsResponse'",...
Returns whether or not the given app_name exists
[ "Returns", "whether", "or", "not", "the", "given", "app_name", "exists" ]
python
valid
SoftwareDefinedBuildings/XBOS
apps/system_identification/rtu_energy.py
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/system_identification/rtu_energy.py#L94-L113
def call_cool(tstat): """ Adjusts the temperature setpoints in order to call for cooling. Returns a handler to call when you want to reset the thermostat """ current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint current_temp = tstat.temperature tstat.write({ 'heat...
[ "def", "call_cool", "(", "tstat", ")", ":", "current_hsp", ",", "current_csp", "=", "tstat", ".", "heating_setpoint", ",", "tstat", ".", "cooling_setpoint", "current_temp", "=", "tstat", ".", "temperature", "tstat", ".", "write", "(", "{", "'heating_setpoint'", ...
Adjusts the temperature setpoints in order to call for cooling. Returns a handler to call when you want to reset the thermostat
[ "Adjusts", "the", "temperature", "setpoints", "in", "order", "to", "call", "for", "cooling", ".", "Returns", "a", "handler", "to", "call", "when", "you", "want", "to", "reset", "the", "thermostat" ]
python
train
3ll3d00d/vibe
backend/src/analyser/common/measurementcontroller.py
https://github.com/3ll3d00d/vibe/blob/124b029f13ac746723e92cb47e9cb56edd2e54b5/backend/src/analyser/common/measurementcontroller.py#L109-L129
def updateDeviceStatus(self, deviceName, state, reason=None): """ Updates the current device status. :param deviceName: the device name. :param state: the state. :param reason: the reason for the change. :return: """ logger.info('Updating recording device ...
[ "def", "updateDeviceStatus", "(", "self", ",", "deviceName", ",", "state", ",", "reason", "=", "None", ")", ":", "logger", ".", "info", "(", "'Updating recording device state for '", "+", "deviceName", "+", "' to '", "+", "state", ".", "name", "+", "(", "''"...
Updates the current device status. :param deviceName: the device name. :param state: the state. :param reason: the reason for the change. :return:
[ "Updates", "the", "current", "device", "status", ".", ":", "param", "deviceName", ":", "the", "device", "name", ".", ":", "param", "state", ":", "the", "state", ".", ":", "param", "reason", ":", "the", "reason", "for", "the", "change", ".", ":", "retur...
python
train
rkhleics/wagtailmodeladmin
wagtailmodeladmin/options.py
https://github.com/rkhleics/wagtailmodeladmin/blob/7fddc853bab2ff3868b8c7a03329308c55f16358/wagtailmodeladmin/options.py#L589-L598
def get_permissions_for_registration(self): """ Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to be assigned to Groups in settings. """ qs = Permission.objects.none() for instance in self.modeladmin_i...
[ "def", "get_permissions_for_registration", "(", "self", ")", ":", "qs", "=", "Permission", ".", "objects", ".", "none", "(", ")", "for", "instance", "in", "self", ".", "modeladmin_instances", ":", "qs", "=", "qs", "|", "instance", ".", "get_permissions_for_reg...
Utilised by Wagtail's 'register_permissions' hook to allow permissions for a all models grouped by this class to be assigned to Groups in settings.
[ "Utilised", "by", "Wagtail", "s", "register_permissions", "hook", "to", "allow", "permissions", "for", "a", "all", "models", "grouped", "by", "this", "class", "to", "be", "assigned", "to", "Groups", "in", "settings", "." ]
python
train
memsql/memsql-python
memsql/common/sql_step_queue/task_handler.py
https://github.com/memsql/memsql-python/blob/aac223a1b937d5b348b42af3c601a6c685ca633a/memsql/common/sql_step_queue/task_handler.py#L129-L145
def stop_step(self, step_name): """ Stop a step. """ if self.finished is not None: raise AlreadyFinished() steps = copy.deepcopy(self.steps) step_data = self._get_step(step_name, steps=steps) if step_data is None: raise StepNotStarted() elif 'sto...
[ "def", "stop_step", "(", "self", ",", "step_name", ")", ":", "if", "self", ".", "finished", "is", "not", "None", ":", "raise", "AlreadyFinished", "(", ")", "steps", "=", "copy", ".", "deepcopy", "(", "self", ".", "steps", ")", "step_data", "=", "self",...
Stop a step.
[ "Stop", "a", "step", "." ]
python
test
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/breakpoint.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/breakpoint.py#L332-L355
def eval_condition(self, event): """ Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise. """ condition...
[ "def", "eval_condition", "(", "self", ",", "event", ")", ":", "condition", "=", "self", ".", "get_condition", "(", ")", "if", "condition", "is", "True", ":", "# shortcut for unconditional breakpoints", "return", "True", "if", "callable", "(", "condition", ")", ...
Evaluates the breakpoint condition, if any was set. @type event: L{Event} @param event: Debug event triggered by the breakpoint. @rtype: bool @return: C{True} to dispatch the event, C{False} otherwise.
[ "Evaluates", "the", "breakpoint", "condition", "if", "any", "was", "set", "." ]
python
train
materialsvirtuallab/monty
monty/json.py
https://github.com/materialsvirtuallab/monty/blob/d99d6f3c68372d83489d28ff515566c93cd569e2/monty/json.py#L266-L314
def jsanitize(obj, strict=False, allow_bson=False): """ This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty's...
[ "def", "jsanitize", "(", "obj", ",", "strict", "=", "False", ",", "allow_bson", "=", "False", ")", ":", "if", "allow_bson", "and", "(", "isinstance", "(", "obj", ",", "(", "datetime", ".", "datetime", ",", "bytes", ")", ")", "or", "(", "bson", "is", ...
This method cleans an input json-like object, either a list or a dict or some sequence, nested or otherwise, by converting all non-string dictionary keys (such as int and float) to strings, and also recursively encodes all objects using Monty's as_dict() protocol. Args: obj: input json-like obj...
[ "This", "method", "cleans", "an", "input", "json", "-", "like", "object", "either", "a", "list", "or", "a", "dict", "or", "some", "sequence", "nested", "or", "otherwise", "by", "converting", "all", "non", "-", "string", "dictionary", "keys", "(", "such", ...
python
train
python-openxml/python-docx
docx/oxml/table.py
https://github.com/python-openxml/python-docx/blob/6756f6cd145511d3eb6d1d188beea391b1ddfd53/docx/oxml/table.py#L648-L662
def _span_to_width(self, grid_width, top_tc, vMerge): """ Incorporate and then remove `w:tc` elements to the right of this one until this cell spans *grid_width*. Raises |ValueError| if *grid_width* cannot be exactly achieved, such as when a merged cell would drive the span width...
[ "def", "_span_to_width", "(", "self", ",", "grid_width", ",", "top_tc", ",", "vMerge", ")", ":", "self", ".", "_move_content_to", "(", "top_tc", ")", "while", "self", ".", "grid_span", "<", "grid_width", ":", "self", ".", "_swallow_next_tc", "(", "grid_width...
Incorporate and then remove `w:tc` elements to the right of this one until this cell spans *grid_width*. Raises |ValueError| if *grid_width* cannot be exactly achieved, such as when a merged cell would drive the span width greater than *grid_width* or if not enough grid columns are avail...
[ "Incorporate", "and", "then", "remove", "w", ":", "tc", "elements", "to", "the", "right", "of", "this", "one", "until", "this", "cell", "spans", "*", "grid_width", "*", ".", "Raises", "|ValueError|", "if", "*", "grid_width", "*", "cannot", "be", "exactly",...
python
train
elastic/elasticsearch-dsl-py
elasticsearch_dsl/search.py
https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L682-L701
def execute(self, ignore_cache=False): """ Execute the search and return an instance of ``Response`` wrapping all the data. :arg ignore_cache: if set to ``True``, consecutive calls will hit ES, while cached result will be ignored. Defaults to `False` """ if i...
[ "def", "execute", "(", "self", ",", "ignore_cache", "=", "False", ")", ":", "if", "ignore_cache", "or", "not", "hasattr", "(", "self", ",", "'_response'", ")", ":", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "self",...
Execute the search and return an instance of ``Response`` wrapping all the data. :arg ignore_cache: if set to ``True``, consecutive calls will hit ES, while cached result will be ignored. Defaults to `False`
[ "Execute", "the", "search", "and", "return", "an", "instance", "of", "Response", "wrapping", "all", "the", "data", "." ]
python
train
BlueBrain/NeuroM
neurom/io/hdf5.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/neurom/io/hdf5.py#L132-L136
def _unpack_v1(h5file): '''Unpack groups from HDF5 v1 file''' points = np.array(h5file['points']) groups = np.array(h5file['structure']) return points, groups
[ "def", "_unpack_v1", "(", "h5file", ")", ":", "points", "=", "np", ".", "array", "(", "h5file", "[", "'points'", "]", ")", "groups", "=", "np", ".", "array", "(", "h5file", "[", "'structure'", "]", ")", "return", "points", ",", "groups" ]
Unpack groups from HDF5 v1 file
[ "Unpack", "groups", "from", "HDF5", "v1", "file" ]
python
train
pyroscope/auvyon
pavement.py
https://github.com/pyroscope/auvyon/blob/5115c26f966df03df92a9934580b66c72e23d4e8/pavement.py#L131-L172
def docs(): """ Create documentation. """ from epydoc import cli path('build').exists() or path('build').makedirs() # get storage path docs_dir = options.docs.get('docs_dir', 'docs/apidocs') # clean up previous docs (path(docs_dir) / "epydoc.css").exists() and path(docs_dir).rmtree() ...
[ "def", "docs", "(", ")", ":", "from", "epydoc", "import", "cli", "path", "(", "'build'", ")", ".", "exists", "(", ")", "or", "path", "(", "'build'", ")", ".", "makedirs", "(", ")", "# get storage path", "docs_dir", "=", "options", ".", "docs", ".", "...
Create documentation.
[ "Create", "documentation", "." ]
python
train
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L30443-L30458
def get_bandwidth_group(self, name): """Get a bandwidth group by name. in name of type str Name of the bandwidth group to get. return bandwidth_group of type :class:`IBandwidthGroup` Where to store the bandwidth group on success. """ if not isinstance(n...
[ "def", "get_bandwidth_group", "(", "self", ",", "name", ")", ":", "if", "not", "isinstance", "(", "name", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"name can only be an instance of type basestring\"", ")", "bandwidth_group", "=", "self", ".", "_cal...
Get a bandwidth group by name. in name of type str Name of the bandwidth group to get. return bandwidth_group of type :class:`IBandwidthGroup` Where to store the bandwidth group on success.
[ "Get", "a", "bandwidth", "group", "by", "name", "." ]
python
train
sdispater/backpack
backpack/collections/base_collection.py
https://github.com/sdispater/backpack/blob/764e7f79fd2b1c1ac4883d8e5c9da5c65dfc875e/backpack/collections/base_collection.py#L720-L731
def transform(self, callback): """ Transform each item in the collection using a callback. :param callback: The callback :type callback: callable :rtype: Collection """ self._items = self.map(callback).all() return self
[ "def", "transform", "(", "self", ",", "callback", ")", ":", "self", ".", "_items", "=", "self", ".", "map", "(", "callback", ")", ".", "all", "(", ")", "return", "self" ]
Transform each item in the collection using a callback. :param callback: The callback :type callback: callable :rtype: Collection
[ "Transform", "each", "item", "in", "the", "collection", "using", "a", "callback", "." ]
python
train
LEMS/pylems
lems/model/dynamics.py
https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/dynamics.py#L43-L50
def toxml(self): """ Exports this object into a LEMS XML object """ return '<StateVariable name="{0}" dimension="{1}"'.format(self.name, self.dimension) +\ (' exposure="{0}"'.format(self.exposure) if self.exposure else '') +\ '/>'
[ "def", "toxml", "(", "self", ")", ":", "return", "'<StateVariable name=\"{0}\" dimension=\"{1}\"'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "dimension", ")", "+", "(", "' exposure=\"{0}\"'", ".", "format", "(", "self", ".", "exposure", ")", ...
Exports this object into a LEMS XML object
[ "Exports", "this", "object", "into", "a", "LEMS", "XML", "object" ]
python
train
dnephin/PyStaticConfiguration
staticconf/config.py
https://github.com/dnephin/PyStaticConfiguration/blob/229733270bc0dc0d9690ba850dbfb470e535c212/staticconf/config.py#L114-L124
def get_config_dict(self): """Reconstruct the nested structure of this object's configuration and return it as a dict. """ config_dict = {} for dotted_key, value in self.get_config_values().items(): subkeys = dotted_key.split('.') d = config_dict ...
[ "def", "get_config_dict", "(", "self", ")", ":", "config_dict", "=", "{", "}", "for", "dotted_key", ",", "value", "in", "self", ".", "get_config_values", "(", ")", ".", "items", "(", ")", ":", "subkeys", "=", "dotted_key", ".", "split", "(", "'.'", ")"...
Reconstruct the nested structure of this object's configuration and return it as a dict.
[ "Reconstruct", "the", "nested", "structure", "of", "this", "object", "s", "configuration", "and", "return", "it", "as", "a", "dict", "." ]
python
train
mozilla/configman
configman/__init__.py
https://github.com/mozilla/configman/blob/83159fed61cc4cbbe5a4a6a00d3acad8a0c39c96/configman/__init__.py#L38-L47
def configuration(*args, **kwargs): """this function just instantiates a ConfigurationManager and returns the configuration dictionary. It accepts all the same parameters as the constructor for the ConfigurationManager class.""" try: config_kwargs = {'mapping_class': kwargs.pop('mapping_class')...
[ "def", "configuration", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "config_kwargs", "=", "{", "'mapping_class'", ":", "kwargs", ".", "pop", "(", "'mapping_class'", ")", "}", "except", "KeyError", ":", "config_kwargs", "=", "{", "}",...
this function just instantiates a ConfigurationManager and returns the configuration dictionary. It accepts all the same parameters as the constructor for the ConfigurationManager class.
[ "this", "function", "just", "instantiates", "a", "ConfigurationManager", "and", "returns", "the", "configuration", "dictionary", ".", "It", "accepts", "all", "the", "same", "parameters", "as", "the", "constructor", "for", "the", "ConfigurationManager", "class", "." ...
python
train
tensorflow/mesh
examples/mnist.py
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/examples/mnist.py#L50-L118
def mnist_model(image, labels, mesh): """The model. Args: image: tf.Tensor with shape [batch, 28*28] labels: a tf.Tensor with shape [batch] and dtype tf.int32 mesh: a mtf.Mesh Returns: logits: a mtf.Tensor with shape [batch, 10] loss: a mtf.Tensor with shape [] """ batch_dim = mtf.Dimens...
[ "def", "mnist_model", "(", "image", ",", "labels", ",", "mesh", ")", ":", "batch_dim", "=", "mtf", ".", "Dimension", "(", "\"batch\"", ",", "FLAGS", ".", "batch_size", ")", "row_blocks_dim", "=", "mtf", ".", "Dimension", "(", "\"row_blocks\"", ",", "4", ...
The model. Args: image: tf.Tensor with shape [batch, 28*28] labels: a tf.Tensor with shape [batch] and dtype tf.int32 mesh: a mtf.Mesh Returns: logits: a mtf.Tensor with shape [batch, 10] loss: a mtf.Tensor with shape []
[ "The", "model", "." ]
python
train
bolt-project/bolt
bolt/spark/array.py
https://github.com/bolt-project/bolt/blob/9cd7104aa085498da3097b72696184b9d3651c51/bolt/spark/array.py#L351-L364
def var(self, axis=None, keepdims=False): """ Return the variance of the array over the given axis. Parameters ---------- axis : tuple or int, optional, default=None Axis to compute statistic over, if None will compute over all axes keepdims : bo...
[ "def", "var", "(", "self", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "return", "self", ".", "_stat", "(", "axis", ",", "name", "=", "'variance'", ",", "keepdims", "=", "keepdims", ")" ]
Return the variance of the array over the given axis. Parameters ---------- axis : tuple or int, optional, default=None Axis to compute statistic over, if None will compute over all axes keepdims : boolean, optional, default=False Keep axis remaining...
[ "Return", "the", "variance", "of", "the", "array", "over", "the", "given", "axis", "." ]
python
test
presslabs/django-payu-ro
payu/forms.py
https://github.com/presslabs/django-payu-ro/blob/fda9432c57cee7a78789873b6e6f439d912e4c7b/payu/forms.py#L226-L237
def _prepare_orders(self, orders): """ Each order needs to have all it's details filled with default value, or None, in case those are not already filled. """ for detail in PAYU_ORDER_DETAILS: if not any([detail in order for order in orders]): for ord...
[ "def", "_prepare_orders", "(", "self", ",", "orders", ")", ":", "for", "detail", "in", "PAYU_ORDER_DETAILS", ":", "if", "not", "any", "(", "[", "detail", "in", "order", "for", "order", "in", "orders", "]", ")", ":", "for", "order", "in", "orders", ":",...
Each order needs to have all it's details filled with default value, or None, in case those are not already filled.
[ "Each", "order", "needs", "to", "have", "all", "it", "s", "details", "filled", "with", "default", "value", "or", "None", "in", "case", "those", "are", "not", "already", "filled", "." ]
python
train
spacetelescope/drizzlepac
drizzlepac/hlautils/astrometric_utils.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/hlautils/astrometric_utils.py#L187-L209
def build_reference_wcs(inputs, sciname='sci'): """Create the reference WCS based on all the inputs for a field""" # start by creating a composite field-of-view for all inputs wcslist = [] for img in inputs: nsci = countExtn(img) for num in range(nsci): extname = (sciname, nu...
[ "def", "build_reference_wcs", "(", "inputs", ",", "sciname", "=", "'sci'", ")", ":", "# start by creating a composite field-of-view for all inputs", "wcslist", "=", "[", "]", "for", "img", "in", "inputs", ":", "nsci", "=", "countExtn", "(", "img", ")", "for", "n...
Create the reference WCS based on all the inputs for a field
[ "Create", "the", "reference", "WCS", "based", "on", "all", "the", "inputs", "for", "a", "field" ]
python
train
samirelanduk/quickplots
quickplots/charts.py
https://github.com/samirelanduk/quickplots/blob/59f5e6ff367b2c1c24ba7cf1805d03552034c6d8/quickplots/charts.py#L495-L513
def x_ticks(self, *ticks): """The points on the x-axis for which there are markers and grid lines. There are default ticks, but you can pass values to this method to override the defaults. Otherwise the method will return the ticks. :param \*ticks: if given, these will be chart's x-tic...
[ "def", "x_ticks", "(", "self", ",", "*", "ticks", ")", ":", "if", "ticks", ":", "for", "tick", "in", "ticks", ":", "if", "not", "is_numeric", "(", "tick", ")", ":", "raise", "TypeError", "(", "\"'%s' is not a numeric tick\"", "%", "str", "(", "tick", "...
The points on the x-axis for which there are markers and grid lines. There are default ticks, but you can pass values to this method to override the defaults. Otherwise the method will return the ticks. :param \*ticks: if given, these will be chart's x-ticks. :rtype: ``tuple``
[ "The", "points", "on", "the", "x", "-", "axis", "for", "which", "there", "are", "markers", "and", "grid", "lines", "." ]
python
train
tensorlayer/tensorlayer
tensorlayer/files/utils.py
https://github.com/tensorlayer/tensorlayer/blob/aa9e52e36c7058a7e6fd81d36563ca6850b21956/tensorlayer/files/utils.py#L2185-L2194
def load_folder_list(path=""): """Return a folder list in a folder by given a folder path. Parameters ---------- path : str A folder path. """ return [os.path.join(path, o) for o in os.listdir(path) if os.path.isdir(os.path.join(path, o))]
[ "def", "load_folder_list", "(", "path", "=", "\"\"", ")", ":", "return", "[", "os", ".", "path", ".", "join", "(", "path", ",", "o", ")", "for", "o", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os"...
Return a folder list in a folder by given a folder path. Parameters ---------- path : str A folder path.
[ "Return", "a", "folder", "list", "in", "a", "folder", "by", "given", "a", "folder", "path", "." ]
python
valid
materialsproject/pymatgen
pymatgen/io/abinit/tasks.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L2487-L2580
def get_graphviz(self, engine="automatic", graph_attr=None, node_attr=None, edge_attr=None): """ Generate task graph in the DOT language (only parents and children of this task). Args: engine: ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage'] graph_...
[ "def", "get_graphviz", "(", "self", ",", "engine", "=", "\"automatic\"", ",", "graph_attr", "=", "None", ",", "node_attr", "=", "None", ",", "edge_attr", "=", "None", ")", ":", "# https://www.graphviz.org/doc/info/", "from", "graphviz", "import", "Digraph", "fg"...
Generate task graph in the DOT language (only parents and children of this task). Args: engine: ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchwork', 'osage'] graph_attr: Mapping of (attribute, value) pairs for the graph. node_attr: Mapping of (attribute, value) pai...
[ "Generate", "task", "graph", "in", "the", "DOT", "language", "(", "only", "parents", "and", "children", "of", "this", "task", ")", "." ]
python
train
PlaidWeb/Publ
publ/queries.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/queries.py#L43-L60
def where_entry_category(query, category, recurse=False): """ Generate a where clause for a particular category """ category = str(category) if category and recurse: # We're recursing and aren't in /, so add the prefix clause return orm.select( e for e in query if e....
[ "def", "where_entry_category", "(", "query", ",", "category", ",", "recurse", "=", "False", ")", ":", "category", "=", "str", "(", "category", ")", "if", "category", "and", "recurse", ":", "# We're recursing and aren't in /, so add the prefix clause", "return", "orm...
Generate a where clause for a particular category
[ "Generate", "a", "where", "clause", "for", "a", "particular", "category" ]
python
train
batiste/django-page-cms
pages/checks.py
https://github.com/batiste/django-page-cms/blob/3c72111eb7c3997a63c462c1776ffd8ce8c50a5d/pages/checks.py#L9-L21
def page_templates_loading_check(app_configs, **kwargs): """ Check if any page template can't be loaded. """ errors = [] for page_template in settings.get_page_templates(): try: loader.get_template(page_template[0]) except template.TemplateDoesNotExist: errors.append...
[ "def", "page_templates_loading_check", "(", "app_configs", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "for", "page_template", "in", "settings", ".", "get_page_templates", "(", ")", ":", "try", ":", "loader", ".", "get_template", "(", "page_t...
Check if any page template can't be loaded.
[ "Check", "if", "any", "page", "template", "can", "t", "be", "loaded", "." ]
python
train
fabioz/PyDev.Debugger
_pydev_imps/_pydev_uuid_old.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_uuid_old.py#L530-L534
def uuid5(namespace, name): """Generate a UUID from the SHA-1 hash of a namespace UUID and a name.""" import sha hash = sha.sha(namespace.bytes + name).digest() return UUID(bytes=hash[:16], version=5)
[ "def", "uuid5", "(", "namespace", ",", "name", ")", ":", "import", "sha", "hash", "=", "sha", ".", "sha", "(", "namespace", ".", "bytes", "+", "name", ")", ".", "digest", "(", ")", "return", "UUID", "(", "bytes", "=", "hash", "[", ":", "16", "]",...
Generate a UUID from the SHA-1 hash of a namespace UUID and a name.
[ "Generate", "a", "UUID", "from", "the", "SHA", "-", "1", "hash", "of", "a", "namespace", "UUID", "and", "a", "name", "." ]
python
train
mdavidsaver/p4p
src/p4p/nt/__init__.py
https://github.com/mdavidsaver/p4p/blob/c5e45eac01edfdad9cc2857bc283c7f2695802b8/src/p4p/nt/__init__.py#L267-L292
def wrap(self, path, args=(), kws={}, scheme='', authority=''): """Wrap argument values (tuple/list with optional dict) into Value :param str path: The PV name to which this call is made :param tuple args: Ordered arguments :param dict kws: Keyword arguments :rtype: Value ...
[ "def", "wrap", "(", "self", ",", "path", ",", "args", "=", "(", ")", ",", "kws", "=", "{", "}", ",", "scheme", "=", "''", ",", "authority", "=", "''", ")", ":", "# build dict of argument name+value", "AV", "=", "{", "}", "AV", ".", "update", "(", ...
Wrap argument values (tuple/list with optional dict) into Value :param str path: The PV name to which this call is made :param tuple args: Ordered arguments :param dict kws: Keyword arguments :rtype: Value
[ "Wrap", "argument", "values", "(", "tuple", "/", "list", "with", "optional", "dict", ")", "into", "Value" ]
python
train
python-bugzilla/python-bugzilla
bugzilla/bug.py
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L346-L359
def updateflags(self, flags): """ Thin wrapper around build_update(flags=X). This only handles simple status changes, anything like needinfo requestee needs to call build_update + update_bugs directly :param flags: Dictionary of the form {"flagname": "status"}, example ...
[ "def", "updateflags", "(", "self", ",", "flags", ")", ":", "flaglist", "=", "[", "]", "for", "key", ",", "value", "in", "flags", ".", "items", "(", ")", ":", "flaglist", ".", "append", "(", "{", "\"name\"", ":", "key", ",", "\"status\"", ":", "valu...
Thin wrapper around build_update(flags=X). This only handles simple status changes, anything like needinfo requestee needs to call build_update + update_bugs directly :param flags: Dictionary of the form {"flagname": "status"}, example {"needinfo": "?", "devel_ack": "+"}
[ "Thin", "wrapper", "around", "build_update", "(", "flags", "=", "X", ")", ".", "This", "only", "handles", "simple", "status", "changes", "anything", "like", "needinfo", "requestee", "needs", "to", "call", "build_update", "+", "update_bugs", "directly" ]
python
train
erm0l0v/django-fake-model
django_fake_model/models.py
https://github.com/erm0l0v/django-fake-model/blob/42fb28ac3aa4db5f82b6cb97a7c2a92b83b36314/django_fake_model/models.py#L46-L64
def delete_table(cls): """ delete_table Manually delete a temporary table for model in test data base. :return: """ schema_editor = getattr(connection, 'schema_editor', None) if schema_editor: with connection.schema_editor() as schema_editor: ...
[ "def", "delete_table", "(", "cls", ")", ":", "schema_editor", "=", "getattr", "(", "connection", ",", "'schema_editor'", ",", "None", ")", "if", "schema_editor", ":", "with", "connection", ".", "schema_editor", "(", ")", "as", "schema_editor", ":", "schema_edi...
delete_table Manually delete a temporary table for model in test data base. :return:
[ "delete_table" ]
python
train