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
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/submissions.py#L121-L134
def init_from_storage_write_to_datastore(self): """Init list of sumibssions from Storage and saves them to Datastore. Should be called only once (typically by master) during evaluation of the competition. """ # Load submissions self._attacks = self._load_submissions_from_datastore_dir( ...
[ "def", "init_from_storage_write_to_datastore", "(", "self", ")", ":", "# Load submissions", "self", ".", "_attacks", "=", "self", ".", "_load_submissions_from_datastore_dir", "(", "ATTACK_SUBDIR", ",", "ATTACK_ID_PATTERN", ")", "self", ".", "_targeted_attacks", "=", "se...
Init list of sumibssions from Storage and saves them to Datastore. Should be called only once (typically by master) during evaluation of the competition.
[ "Init", "list", "of", "sumibssions", "from", "Storage", "and", "saves", "them", "to", "Datastore", "." ]
python
train
cmutel/constructive_geometries
constructive_geometries/geomatcher.py
https://github.com/cmutel/constructive_geometries/blob/d38d7e8d5bf943a6499f3000004f1953af5970de/constructive_geometries/geomatcher.py#L104-L132
def _finish_filter(self, lst, key, include_self, exclusive, biggest_first): """Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.""" key = self._actual_key(key) locations = [x[0] ...
[ "def", "_finish_filter", "(", "self", ",", "lst", ",", "key", ",", "include_self", ",", "exclusive", ",", "biggest_first", ")", ":", "key", "=", "self", ".", "_actual_key", "(", "key", ")", "locations", "=", "[", "x", "[", "0", "]", "for", "x", "in",...
Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.
[ "Finish", "filtering", "a", "GIS", "operation", ".", "Can", "optionally", "exclude", "the", "input", "key", "sort", "results", "and", "exclude", "overlapping", "results", ".", "Internal", "function", "not", "normally", "called", "directly", "." ]
python
train
mattloper/chumpy
chumpy/utils.py
https://github.com/mattloper/chumpy/blob/a3cfdb1be3c8265c369c507b22f6f3f89414c772/chumpy/utils.py#L44-L78
def sparse_is_desireable(lhs, rhs): ''' Examines a pair of matrices and determines if the result of their multiplication should be sparse or not. ''' return False if len(lhs.shape) == 1: return False else: lhs_rows, lhs_cols = lhs.shape if len(rhs.shape) == 1: rhs_ro...
[ "def", "sparse_is_desireable", "(", "lhs", ",", "rhs", ")", ":", "return", "False", "if", "len", "(", "lhs", ".", "shape", ")", "==", "1", ":", "return", "False", "else", ":", "lhs_rows", ",", "lhs_cols", "=", "lhs", ".", "shape", "if", "len", "(", ...
Examines a pair of matrices and determines if the result of their multiplication should be sparse or not.
[ "Examines", "a", "pair", "of", "matrices", "and", "determines", "if", "the", "result", "of", "their", "multiplication", "should", "be", "sparse", "or", "not", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/script.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/script.py#L107-L117
def _load_script(self): """Loads the script from the filesystem :raises exceptions.IOError: if the script file could not be opened """ script_text = filesystem.read_file(self.path, self.filename) if not script_text: raise IOError("Script file could not be opened or ...
[ "def", "_load_script", "(", "self", ")", ":", "script_text", "=", "filesystem", ".", "read_file", "(", "self", ".", "path", ",", "self", ".", "filename", ")", "if", "not", "script_text", ":", "raise", "IOError", "(", "\"Script file could not be opened or was emp...
Loads the script from the filesystem :raises exceptions.IOError: if the script file could not be opened
[ "Loads", "the", "script", "from", "the", "filesystem" ]
python
train
paramiko/paramiko
paramiko/kex_gss.py
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L91-L115
def start_kex(self): """ Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange. """ self._generate_x() if self.transport.server_mode: # compute f = g^x mod p, but don't send it yet self.f = pow(self.G, self.x, self.P) self.transpor...
[ "def", "start_kex", "(", "self", ")", ":", "self", ".", "_generate_x", "(", ")", "if", "self", ".", "transport", ".", "server_mode", ":", "# compute f = g^x mod p, but don't send it yet", "self", ".", "f", "=", "pow", "(", "self", ".", "G", ",", "self", "....
Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange.
[ "Start", "the", "GSS", "-", "API", "/", "SSPI", "Authenticated", "Diffie", "-", "Hellman", "Key", "Exchange", "." ]
python
train
estnltk/estnltk
estnltk/database/elastic/__init__.py
https://github.com/estnltk/estnltk/blob/28ae334a68a0673072febc318635f04da0dcc54a/estnltk/database/elastic/__init__.py#L16-L32
def create_index(index_name, **kwargs): """ Parameters ---------- index_name : str Name of the index to be created **kwargs Arguments to pass to Elasticsearch instance. Returns ------- Index """ es = elasticsearch.Elasticsearch(**kwargs) es.indices.create(in...
[ "def", "create_index", "(", "index_name", ",", "*", "*", "kwargs", ")", ":", "es", "=", "elasticsearch", ".", "Elasticsearch", "(", "*", "*", "kwargs", ")", "es", ".", "indices", ".", "create", "(", "index", "=", "index_name", ",", "body", "=", "mappin...
Parameters ---------- index_name : str Name of the index to be created **kwargs Arguments to pass to Elasticsearch instance. Returns ------- Index
[ "Parameters", "----------", "index_name", ":", "str", "Name", "of", "the", "index", "to", "be", "created", "**", "kwargs", "Arguments", "to", "pass", "to", "Elasticsearch", "instance", "." ]
python
train
OSSOS/MOP
src/ossos/core/ossos/gui/errorhandling.py
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/gui/errorhandling.py#L19-L32
def handle_error(self, error, download_request): """ Checks what error occured and looks for an appropriate solution. Args: error: Exception The error that has occured. download_request: The request which resulted in the error. """ if ...
[ "def", "handle_error", "(", "self", ",", "error", ",", "download_request", ")", ":", "if", "hasattr", "(", "error", ",", "\"errno\"", ")", "and", "error", ".", "errno", "==", "errno", ".", "EACCES", ":", "self", ".", "handle_certificate_problem", "(", "str...
Checks what error occured and looks for an appropriate solution. Args: error: Exception The error that has occured. download_request: The request which resulted in the error.
[ "Checks", "what", "error", "occured", "and", "looks", "for", "an", "appropriate", "solution", "." ]
python
train
apache/incubator-mxnet
example/gluon/house_prices/kaggle_k_fold_cross_validation.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/example/gluon/house_prices/kaggle_k_fold_cross_validation.py#L82-L102
def train(net, X_train, y_train, epochs, verbose_epoch, learning_rate, weight_decay, batch_size): """Trains the model.""" dataset_train = gluon.data.ArrayDataset(X_train, y_train) data_iter_train = gluon.data.DataLoader(dataset_train, batch_size, shuffle...
[ "def", "train", "(", "net", ",", "X_train", ",", "y_train", ",", "epochs", ",", "verbose_epoch", ",", "learning_rate", ",", "weight_decay", ",", "batch_size", ")", ":", "dataset_train", "=", "gluon", ".", "data", ".", "ArrayDataset", "(", "X_train", ",", "...
Trains the model.
[ "Trains", "the", "model", "." ]
python
train
wummel/linkchecker
linkcheck/ansicolor.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/ansicolor.py#L195-L211
def has_colors (fp): """Test if given file is an ANSI color enabled tty.""" # The is_tty() function ensures that we do not colorize # redirected streams, as this is almost never what we want if not is_tty(fp): return False if os.name == 'nt': return True elif has_curses: ...
[ "def", "has_colors", "(", "fp", ")", ":", "# The is_tty() function ensures that we do not colorize", "# redirected streams, as this is almost never what we want", "if", "not", "is_tty", "(", "fp", ")", ":", "return", "False", "if", "os", ".", "name", "==", "'nt'", ":", ...
Test if given file is an ANSI color enabled tty.
[ "Test", "if", "given", "file", "is", "an", "ANSI", "color", "enabled", "tty", "." ]
python
train
gtalarico/airtable-python-wrapper
airtable/airtable.py
https://github.com/gtalarico/airtable-python-wrapper/blob/48b2d806178085b52a31817571e5a1fc3dce4045/airtable/airtable.py#L217-L256
def get_iter(self, **options): """ Record Retriever Iterator Returns iterator with lists in batches according to pageSize. To get all records at once use :any:`get_all` >>> for page in airtable.get_iter(): ... for record in page: ... print(r...
[ "def", "get_iter", "(", "self", ",", "*", "*", "options", ")", ":", "offset", "=", "None", "while", "True", ":", "data", "=", "self", ".", "_get", "(", "self", ".", "url_table", ",", "offset", "=", "offset", ",", "*", "*", "options", ")", "records"...
Record Retriever Iterator Returns iterator with lists in batches according to pageSize. To get all records at once use :any:`get_all` >>> for page in airtable.get_iter(): ... for record in page: ... print(record) [{'fields': ... }, ...] Ke...
[ "Record", "Retriever", "Iterator", "Returns", "iterator", "with", "lists", "in", "batches", "according", "to", "pageSize", ".", "To", "get", "all", "records", "at", "once", "use", ":", "any", ":", "get_all", ">>>", "for", "page", "in", "airtable", ".", "ge...
python
train
geophysics-ubonn/crtomo_tools
src/td_correct_temperature.py
https://github.com/geophysics-ubonn/crtomo_tools/blob/27c3e21a557f8df1c12455b96c4c2e00e08a5b4a/src/td_correct_temperature.py#L176-L210
def save_mag_to_file(mag, filename, rhofile): """Save the values in rho- or mag-format. """ if rhofile: # bring data in shape null = np.zeros(len(mag)) if mag.shape[1] == 3: null = np.column_stack((null, null, null, null)) result = np.column_stack((mag, null)) ...
[ "def", "save_mag_to_file", "(", "mag", ",", "filename", ",", "rhofile", ")", ":", "if", "rhofile", ":", "# bring data in shape", "null", "=", "np", ".", "zeros", "(", "len", "(", "mag", ")", ")", "if", "mag", ".", "shape", "[", "1", "]", "==", "3", ...
Save the values in rho- or mag-format.
[ "Save", "the", "values", "in", "rho", "-", "or", "mag", "-", "format", "." ]
python
train
psss/did
did/plugins/bugzilla.py
https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L148-L156
def summary(self): """ Bug summary including resolution if enabled """ if not self.bug.resolution: return self.bug.summary if (self.bug.resolution.lower() in self.parent.resolutions or "all" in self.parent.resolutions): return "{0} [{1}]".format( ...
[ "def", "summary", "(", "self", ")", ":", "if", "not", "self", ".", "bug", ".", "resolution", ":", "return", "self", ".", "bug", ".", "summary", "if", "(", "self", ".", "bug", ".", "resolution", ".", "lower", "(", ")", "in", "self", ".", "parent", ...
Bug summary including resolution if enabled
[ "Bug", "summary", "including", "resolution", "if", "enabled" ]
python
train
Yubico/python-yubico
yubico/yubikey_config.py
https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_config.py#L550-L557
def _get_flag(which, flags): """ Find 'which' entry in 'flags'. """ res = [this for this in flags if this.is_equal(which)] if len(res) == 0: return None if len(res) == 1: return res[0] assert()
[ "def", "_get_flag", "(", "which", ",", "flags", ")", ":", "res", "=", "[", "this", "for", "this", "in", "flags", "if", "this", ".", "is_equal", "(", "which", ")", "]", "if", "len", "(", "res", ")", "==", "0", ":", "return", "None", "if", "len", ...
Find 'which' entry in 'flags'.
[ "Find", "which", "entry", "in", "flags", "." ]
python
train
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_db.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2334-L2343
def fetch_fieldnames(self, sql: str, *args) -> List[str]: """Executes SQL; returns just the output fieldnames.""" self.ensure_db_open() cursor = self.db.cursor() self.db_exec_with_cursor(cursor, sql, *args) try: return [i[0] for i in cursor.description] except...
[ "def", "fetch_fieldnames", "(", "self", ",", "sql", ":", "str", ",", "*", "args", ")", "->", "List", "[", "str", "]", ":", "self", ".", "ensure_db_open", "(", ")", "cursor", "=", "self", ".", "db", ".", "cursor", "(", ")", "self", ".", "db_exec_wit...
Executes SQL; returns just the output fieldnames.
[ "Executes", "SQL", ";", "returns", "just", "the", "output", "fieldnames", "." ]
python
train
ssato/python-anytemplate
anytemplate/utils.py
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/utils.py#L195-L205
def _write_to_filepath(content, output): """ :param content: Content string to write to :param output: Output file path """ outdir = os.path.dirname(output) if outdir and not os.path.exists(outdir): os.makedirs(outdir) with anytemplate.compat.copen(output, 'w') as out: out.w...
[ "def", "_write_to_filepath", "(", "content", ",", "output", ")", ":", "outdir", "=", "os", ".", "path", ".", "dirname", "(", "output", ")", "if", "outdir", "and", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs"...
:param content: Content string to write to :param output: Output file path
[ ":", "param", "content", ":", "Content", "string", "to", "write", "to", ":", "param", "output", ":", "Output", "file", "path" ]
python
train
pkkid/python-plexapi
plexapi/myplex.py
https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L401-L418
def syncItems(self, client=None, clientId=None): """ Returns an instance of :class:`plexapi.sync.SyncList` for specified client. Parameters: client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for. clientId (str): an identifier of a client to ...
[ "def", "syncItems", "(", "self", ",", "client", "=", "None", ",", "clientId", "=", "None", ")", ":", "if", "client", ":", "clientId", "=", "client", ".", "clientIdentifier", "elif", "clientId", "is", "None", ":", "clientId", "=", "X_PLEX_IDENTIFIER", "data...
Returns an instance of :class:`plexapi.sync.SyncList` for specified client. Parameters: client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for. clientId (str): an identifier of a client to query SyncItems for. If both `client` and `clien...
[ "Returns", "an", "instance", "of", ":", "class", ":", "plexapi", ".", "sync", ".", "SyncList", "for", "specified", "client", "." ]
python
train
nwilming/ocupy
ocupy/saccade_geometry.py
https://github.com/nwilming/ocupy/blob/a0bd64f822576feaa502939d6bafd1183b237d16/ocupy/saccade_geometry.py#L93-L122
def predict_fixation_duration( durations, angles, length_diffs, dataset=None, params=None): """ Fits a non-linear piecewise regression to fixtaion durations for a fixmat. Returns corrected fixation durations. """ if dataset is None: dataset = np.ones(durations.shape) corrected_d...
[ "def", "predict_fixation_duration", "(", "durations", ",", "angles", ",", "length_diffs", ",", "dataset", "=", "None", ",", "params", "=", "None", ")", ":", "if", "dataset", "is", "None", ":", "dataset", "=", "np", ".", "ones", "(", "durations", ".", "sh...
Fits a non-linear piecewise regression to fixtaion durations for a fixmat. Returns corrected fixation durations.
[ "Fits", "a", "non", "-", "linear", "piecewise", "regression", "to", "fixtaion", "durations", "for", "a", "fixmat", "." ]
python
train
Archived-Object/ligament
ligament/buildcontext.py
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/buildcontext.py#L94-L110
def verify_valid_dependencies(self): """ Checks if the assigned dependencies are valid valid dependency graphs are: - noncyclic (i.e. no `A -> B -> ... -> A`) - Contain no undefined dependencies (dependencies referencing undefined tasks) """ un...
[ "def", "verify_valid_dependencies", "(", "self", ")", ":", "unobserved_dependencies", "=", "set", "(", "self", ".", "tasks", ".", "keys", "(", ")", ")", "target_queue", "=", "[", "]", "while", "len", "(", "unobserved_dependencies", ")", ">", "0", ":", "tar...
Checks if the assigned dependencies are valid valid dependency graphs are: - noncyclic (i.e. no `A -> B -> ... -> A`) - Contain no undefined dependencies (dependencies referencing undefined tasks)
[ "Checks", "if", "the", "assigned", "dependencies", "are", "valid", "valid", "dependency", "graphs", "are", ":" ]
python
train
treethought/flask-assistant
flask_assistant/response.py
https://github.com/treethought/flask-assistant/blob/9331b9796644dfa987bcd97a13e78e9ab62923d3/flask_assistant/response.py#L99-L121
def suggest(self, *replies): """Use suggestion chips to hint at responses to continue or pivot the conversation""" chips = [] for r in replies: chips.append({"title": r}) # NOTE: both of these formats work in the dialogflow console, # but only the first (suggestions)...
[ "def", "suggest", "(", "self", ",", "*", "replies", ")", ":", "chips", "=", "[", "]", "for", "r", "in", "replies", ":", "chips", ".", "append", "(", "{", "\"title\"", ":", "r", "}", ")", "# NOTE: both of these formats work in the dialogflow console,", "# but...
Use suggestion chips to hint at responses to continue or pivot the conversation
[ "Use", "suggestion", "chips", "to", "hint", "at", "responses", "to", "continue", "or", "pivot", "the", "conversation" ]
python
train
raiden-network/raiden
raiden/transfer/views.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L427-L438
def get_channelstate_settled( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of settled channels in a token network.""" return get_channelstate_filter( chain_state, payment_ne...
[ "def", "get_channelstate_settled", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", ...
Return the state of settled channels in a token network.
[ "Return", "the", "state", "of", "settled", "channels", "in", "a", "token", "network", "." ]
python
train
deepmind/pysc2
pysc2/lib/actions.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/actions.py#L96-L101
def select_unit(action, action_space, select_unit_act, select_unit_id): """Select a specific unit from the multi-unit selection.""" del action_space select = action.action_ui.multi_panel select.type = select_unit_act select.unit_index = select_unit_id
[ "def", "select_unit", "(", "action", ",", "action_space", ",", "select_unit_act", ",", "select_unit_id", ")", ":", "del", "action_space", "select", "=", "action", ".", "action_ui", ".", "multi_panel", "select", ".", "type", "=", "select_unit_act", "select", ".",...
Select a specific unit from the multi-unit selection.
[ "Select", "a", "specific", "unit", "from", "the", "multi", "-", "unit", "selection", "." ]
python
train
fermiPy/fermipy
fermipy/jobs/job_archive.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/jobs/job_archive.py#L433-L439
def update_table_row(self, table, row_idx): """Add this instance as a row on a `astropy.table.Table` """ try: table[row_idx]['timestamp'] = self.timestamp table[row_idx]['status'] = self.status except IndexError: print("Index error", len(table), row_idx)
[ "def", "update_table_row", "(", "self", ",", "table", ",", "row_idx", ")", ":", "try", ":", "table", "[", "row_idx", "]", "[", "'timestamp'", "]", "=", "self", ".", "timestamp", "table", "[", "row_idx", "]", "[", "'status'", "]", "=", "self", ".", "s...
Add this instance as a row on a `astropy.table.Table`
[ "Add", "this", "instance", "as", "a", "row", "on", "a", "astropy", ".", "table", ".", "Table" ]
python
train
proycon/clam
clam/clamservice.py
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/clamservice.py#L869-L879
def inputindexbytemplate(project, user, inputtemplate): """Retrieve sorted index for the specified input template""" index = [] #pylint: disable=redefined-outer-name prefix = Project.path(project, user) + 'input/' for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate....
[ "def", "inputindexbytemplate", "(", "project", ",", "user", ",", "inputtemplate", ")", ":", "index", "=", "[", "]", "#pylint: disable=redefined-outer-name", "prefix", "=", "Project", ".", "path", "(", "project", ",", "user", ")", "+", "'input/'", "for", "linkf...
Retrieve sorted index for the specified input template
[ "Retrieve", "sorted", "index", "for", "the", "specified", "input", "template" ]
python
train
4Kaylum/Brickfront
brickfront/client.py
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L30-L39
def checkResponse(request): ''' Returns if a request has an okay error code, otherwise raises InvalidRequest. ''' # Check the status code of the returned request if str(request.status_code)[0] not in ['2', '3']: w = str(request.text).split('\\r')[0][2:] r...
[ "def", "checkResponse", "(", "request", ")", ":", "# Check the status code of the returned request", "if", "str", "(", "request", ".", "status_code", ")", "[", "0", "]", "not", "in", "[", "'2'", ",", "'3'", "]", ":", "w", "=", "str", "(", "request", ".", ...
Returns if a request has an okay error code, otherwise raises InvalidRequest.
[ "Returns", "if", "a", "request", "has", "an", "okay", "error", "code", "otherwise", "raises", "InvalidRequest", "." ]
python
train
Bogdanp/anom-py
anom/transaction.py
https://github.com/Bogdanp/anom-py/blob/519078b6d1570fa63c5f17cf98817c7bb5588136/anom/transaction.py#L82-L131
def transactional(*, adapter=None, retries=3, propagation=Transaction.Propagation.Nested): """Decorates functions so that all of their operations (except for queries) run inside a Datastore transaction. Parameters: adapter(Adapter, optional): The Adapter to use when running the transaction. ...
[ "def", "transactional", "(", "*", ",", "adapter", "=", "None", ",", "retries", "=", "3", ",", "propagation", "=", "Transaction", ".", "Propagation", ".", "Nested", ")", ":", "def", "decorator", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def"...
Decorates functions so that all of their operations (except for queries) run inside a Datastore transaction. Parameters: adapter(Adapter, optional): The Adapter to use when running the transaction. Defaults to the current adapter. retries(int, optional): The number of times to retry the ...
[ "Decorates", "functions", "so", "that", "all", "of", "their", "operations", "(", "except", "for", "queries", ")", "run", "inside", "a", "Datastore", "transaction", "." ]
python
train
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAFetch/QAQuery.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QAQuery.py#L291-L334
def QA_fetch_index_min( code, start, end, format='numpy', frequence='1min', collections=DATABASE.index_min): '获取股票分钟线' if frequence in ['1min', '1m']: frequence = '1min' elif frequence in ['5min', '5m']: frequence = '5min' elif frequence in ['15min...
[ "def", "QA_fetch_index_min", "(", "code", ",", "start", ",", "end", ",", "format", "=", "'numpy'", ",", "frequence", "=", "'1min'", ",", "collections", "=", "DATABASE", ".", "index_min", ")", ":", "if", "frequence", "in", "[", "'1min'", ",", "'1m'", "]",...
获取股票分钟线
[ "获取股票分钟线" ]
python
train
tensorflow/mesh
mesh_tensorflow/layers.py
https://github.com/tensorflow/mesh/blob/3921196e5e43302e820da0a87329f25d7e2a3016/mesh_tensorflow/layers.py#L27-L82
def dense(x, output_dim, reduced_dims=None, expert_dims=None, use_bias=True, activation=None, master_dtype=tf.float32, slice_dtype=tf.float32, variable_dtype=None, name=None): """Dense layer doing (kernel*x + bias) computation. Args: x: a mtf.Tensor of shape [....
[ "def", "dense", "(", "x", ",", "output_dim", ",", "reduced_dims", "=", "None", ",", "expert_dims", "=", "None", ",", "use_bias", "=", "True", ",", "activation", "=", "None", ",", "master_dtype", "=", "tf", ".", "float32", ",", "slice_dtype", "=", "tf", ...
Dense layer doing (kernel*x + bias) computation. Args: x: a mtf.Tensor of shape [..., reduced_dims]. output_dim: a mtf.Dimension reduced_dims: an optional list of mtf.Dimensions of x to be reduced. If omitted, we reduce the last dimension. expert_dims: an optional list of mtf.Dimension which re...
[ "Dense", "layer", "doing", "(", "kernel", "*", "x", "+", "bias", ")", "computation", "." ]
python
train
pyopenapi/pyswagger
pyswagger/core.py
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L194-L232
def prepare_obj(self, obj, jref): """ basic preparation of an object(those in sepc._version_.objects), and cache the 'prepared' object. """ if not obj: raise Exception('unexpected, passing {0}:{1} to prepare'.format(obj, jref)) s = Scanner(self) if self.versi...
[ "def", "prepare_obj", "(", "self", ",", "obj", ",", "jref", ")", ":", "if", "not", "obj", ":", "raise", "Exception", "(", "'unexpected, passing {0}:{1} to prepare'", ".", "format", "(", "obj", ",", "jref", ")", ")", "s", "=", "Scanner", "(", "self", ")",...
basic preparation of an object(those in sepc._version_.objects), and cache the 'prepared' object.
[ "basic", "preparation", "of", "an", "object", "(", "those", "in", "sepc", ".", "_version_", ".", "objects", ")", "and", "cache", "the", "prepared", "object", "." ]
python
train
Cognexa/cxflow
cxflow/cli/resume.py
https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/resume.py#L11-L35
def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None: """ Load config from the directory specified and start the training. :param config_path: path to the config file or the directory in which it is stored :param restore_from: backend-specific...
[ "def", "resume", "(", "config_path", ":", "str", ",", "restore_from", ":", "Optional", "[", "str", "]", ",", "cl_arguments", ":", "Iterable", "[", "str", "]", ",", "output_root", ":", "str", ")", "->", "None", ":", "config", "=", "None", "try", ":", ...
Load config from the directory specified and start the training. :param config_path: path to the config file or the directory in which it is stored :param restore_from: backend-specific path to the already trained model to be restored from. If ``None`` is passed, it is inferred from th...
[ "Load", "config", "from", "the", "directory", "specified", "and", "start", "the", "training", "." ]
python
train
obriencj/python-javatools
javatools/opcodes.py
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/opcodes.py#L162-L168
def _unpack(struct, bc, offset=0): """ returns the unpacked data tuple, and the next offset past the unpacked data """ return struct.unpack_from(bc, offset), offset + struct.size
[ "def", "_unpack", "(", "struct", ",", "bc", ",", "offset", "=", "0", ")", ":", "return", "struct", ".", "unpack_from", "(", "bc", ",", "offset", ")", ",", "offset", "+", "struct", ".", "size" ]
returns the unpacked data tuple, and the next offset past the unpacked data
[ "returns", "the", "unpacked", "data", "tuple", "and", "the", "next", "offset", "past", "the", "unpacked", "data" ]
python
train
hawkular/hawkular-client-python
hawkular/metrics.py
https://github.com/hawkular/hawkular-client-python/blob/52371f9ebabbe310efee2a8ff8eb735ccc0654bb/hawkular/metrics.py#L244-L253
def query_tag_values(self, metric_type=None, **tags): """ Query for possible tag values. :param metric_type: A MetricType to be queried. If left to None, matches all the MetricTypes :param tags: A dict of tag key/value pairs. Uses Hawkular-Metrics tag query language for syntax "...
[ "def", "query_tag_values", "(", "self", ",", "metric_type", "=", "None", ",", "*", "*", "tags", ")", ":", "tagql", "=", "self", ".", "_transform_tags", "(", "*", "*", "tags", ")", "return", "self", ".", "_get", "(", "self", ".", "_get_metrics_tags_url", ...
Query for possible tag values. :param metric_type: A MetricType to be queried. If left to None, matches all the MetricTypes :param tags: A dict of tag key/value pairs. Uses Hawkular-Metrics tag query language for syntax
[ "Query", "for", "possible", "tag", "values", "." ]
python
train
saltstack/salt
salt/output/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/__init__.py#L69-L79
def update_progress(opts, progress, progress_iter, out): ''' Update the progress iterator for the given outputter ''' # Look up the outputter try: progress_outputter = salt.loader.outputters(opts)[out] except KeyError: # Outputter is not loaded log.warning('Progress outputter no...
[ "def", "update_progress", "(", "opts", ",", "progress", ",", "progress_iter", ",", "out", ")", ":", "# Look up the outputter", "try", ":", "progress_outputter", "=", "salt", ".", "loader", ".", "outputters", "(", "opts", ")", "[", "out", "]", "except", "KeyE...
Update the progress iterator for the given outputter
[ "Update", "the", "progress", "iterator", "for", "the", "given", "outputter" ]
python
train
Shapeways/coyote_framework
coyote_framework/drivers/coyote_driver.py
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/drivers/coyote_driver.py#L8-L16
def visit(self, url=''): """Visit the url, checking for rr errors in the response @param url: URL @return: Visit result """ result = super(CoyoteDriver, self).visit(url) source = self.page_source() return result
[ "def", "visit", "(", "self", ",", "url", "=", "''", ")", ":", "result", "=", "super", "(", "CoyoteDriver", ",", "self", ")", ".", "visit", "(", "url", ")", "source", "=", "self", ".", "page_source", "(", ")", "return", "result" ]
Visit the url, checking for rr errors in the response @param url: URL @return: Visit result
[ "Visit", "the", "url", "checking", "for", "rr", "errors", "in", "the", "response" ]
python
train
ngmiller/mipsy
mipsy/util.py
https://github.com/ngmiller/mipsy/blob/78c058f44685765193acd386e81fada3b4187b95/mipsy/util.py#L51-L60
def query(self, label): """ Returns (hit, index) tuple. hit is a boolean, signifying label presence in the cache index is an integer, the instruction index for the label entry """ try: return True, self.cache[label] except KeyError, e: retu...
[ "def", "query", "(", "self", ",", "label", ")", ":", "try", ":", "return", "True", ",", "self", ".", "cache", "[", "label", "]", "except", "KeyError", ",", "e", ":", "return", "False", ",", "0" ]
Returns (hit, index) tuple. hit is a boolean, signifying label presence in the cache index is an integer, the instruction index for the label entry
[ "Returns", "(", "hit", "index", ")", "tuple", ".", "hit", "is", "a", "boolean", "signifying", "label", "presence", "in", "the", "cache", "index", "is", "an", "integer", "the", "instruction", "index", "for", "the", "label", "entry" ]
python
train
wavefrontHQ/python-client
wavefront_api_client/api/search_api.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/search_api.py#L424-L445
def search_alert_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's non-deleted alerts # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_r...
[ "def", "search_alert_for_facet", "(", "self", ",", "facet", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "se...
Lists the values of a specific facet over the customer's non-deleted alerts # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_alert_for_facet(facet, async_req=Tru...
[ "Lists", "the", "values", "of", "a", "specific", "facet", "over", "the", "customer", "s", "non", "-", "deleted", "alerts", "#", "noqa", ":", "E501" ]
python
train
bkosciow/python_iot-1
iot_message/message.py
https://github.com/bkosciow/python_iot-1/blob/32880760e0d218a686ebdb0b6ee3ce07e5cbf018/iot_message/message.py#L44-L65
def prepare_message(self, data=None): """ Return message as dict :return dict """ message = { 'protocol': self.protocol, 'node': self._node, 'chip_id': self._chip_id, 'event': '', 'parameters': {}, 'response'...
[ "def", "prepare_message", "(", "self", ",", "data", "=", "None", ")", ":", "message", "=", "{", "'protocol'", ":", "self", ".", "protocol", ",", "'node'", ":", "self", ".", "_node", ",", "'chip_id'", ":", "self", ".", "_chip_id", ",", "'event'", ":", ...
Return message as dict :return dict
[ "Return", "message", "as", "dict", ":", "return", "dict" ]
python
test
oauthlib/oauthlib
oauthlib/oauth1/rfc5849/signature.py
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/oauth1/rfc5849/signature.py#L109-L205
def base_string_uri(uri, host=None): """**Base String URI** Per `section 3.4.1.2`_ of RFC 5849. For example, the HTTP request:: GET /r%20v/X?id=123 HTTP/1.1 Host: EXAMPLE.COM:80 is represented by the base string URI: "http://example.com/r%20v/X". In another example, the HTTPS req...
[ "def", "base_string_uri", "(", "uri", ",", "host", "=", "None", ")", ":", "if", "not", "isinstance", "(", "uri", ",", "unicode_type", ")", ":", "raise", "ValueError", "(", "'uri must be a unicode object.'", ")", "# FIXME: urlparse does not support unicode", "scheme"...
**Base String URI** Per `section 3.4.1.2`_ of RFC 5849. For example, the HTTP request:: GET /r%20v/X?id=123 HTTP/1.1 Host: EXAMPLE.COM:80 is represented by the base string URI: "http://example.com/r%20v/X". In another example, the HTTPS request:: GET /?q=1 HTTP/1.1 H...
[ "**", "Base", "String", "URI", "**", "Per", "section", "3", ".", "4", ".", "1", ".", "2", "_", "of", "RFC", "5849", "." ]
python
train
sosy-lab/benchexec
benchexec/runexecutor.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/runexecutor.py#L434-L450
def _kill_process0(self, pid, sig=signal.SIGKILL): """ Send signal to given process, either directly or with sudo. If the target is the sudo process itself, the signal will be lost, because we do not have the rights to send signals to sudo. Use _kill_process() because of this. ...
[ "def", "_kill_process0", "(", "self", ",", "pid", ",", "sig", "=", "signal", ".", "SIGKILL", ")", ":", "if", "self", ".", "_user", "is", "None", ":", "super", "(", "RunExecutor", ",", "self", ")", ".", "_kill_process", "(", "pid", ",", "sig", ")", ...
Send signal to given process, either directly or with sudo. If the target is the sudo process itself, the signal will be lost, because we do not have the rights to send signals to sudo. Use _kill_process() because of this.
[ "Send", "signal", "to", "given", "process", "either", "directly", "or", "with", "sudo", ".", "If", "the", "target", "is", "the", "sudo", "process", "itself", "the", "signal", "will", "be", "lost", "because", "we", "do", "not", "have", "the", "rights", "t...
python
train
HDI-Project/ballet
ballet/project.py
https://github.com/HDI-Project/ballet/blob/6f4d4b87b8234cb6bb38b9e9484a58ef8fe8fdb2/ballet/project.py#L103-L115
def relative_to_contrib(diff, project): """Compute relative path of changed file to contrib dir Args: diff (git.diff.Diff): file diff project (Project): project Returns: Path """ path = pathlib.Path(diff.b_path) contrib_path = project.contrib_module_path return path...
[ "def", "relative_to_contrib", "(", "diff", ",", "project", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "diff", ".", "b_path", ")", "contrib_path", "=", "project", ".", "contrib_module_path", "return", "path", ".", "relative_to", "(", "contrib_path", ...
Compute relative path of changed file to contrib dir Args: diff (git.diff.Diff): file diff project (Project): project Returns: Path
[ "Compute", "relative", "path", "of", "changed", "file", "to", "contrib", "dir" ]
python
train
desbma/sacad
sacad/cover.py
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L510-L525
async def guessImageMetadataFromHttpData(response): """ Identify an image format and size from the beginning of its HTTP data. """ metadata = None img_data = bytearray() while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE: new_img_data = await response.content.read(__class__.METAD...
[ "async", "def", "guessImageMetadataFromHttpData", "(", "response", ")", ":", "metadata", "=", "None", "img_data", "=", "bytearray", "(", ")", "while", "len", "(", "img_data", ")", "<", "CoverSourceResult", ".", "MAX_FILE_METADATA_PEEK_SIZE", ":", "new_img_data", "...
Identify an image format and size from the beginning of its HTTP data.
[ "Identify", "an", "image", "format", "and", "size", "from", "the", "beginning", "of", "its", "HTTP", "data", "." ]
python
train
tensorflow/probability
tensorflow_probability/python/distributions/wishart.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L416-L423
def _multi_gamma_sequence(self, a, p, name="multi_gamma_sequence"): """Creates sequence used in multivariate (di)gamma; shape = shape(a)+[p].""" with self._name_scope(name): # Linspace only takes scalars, so we'll add in the offset afterwards. seq = tf.linspace( tf.constant(0., dtype=self....
[ "def", "_multi_gamma_sequence", "(", "self", ",", "a", ",", "p", ",", "name", "=", "\"multi_gamma_sequence\"", ")", ":", "with", "self", ".", "_name_scope", "(", "name", ")", ":", "# Linspace only takes scalars, so we'll add in the offset afterwards.", "seq", "=", "...
Creates sequence used in multivariate (di)gamma; shape = shape(a)+[p].
[ "Creates", "sequence", "used", "in", "multivariate", "(", "di", ")", "gamma", ";", "shape", "=", "shape", "(", "a", ")", "+", "[", "p", "]", "." ]
python
test
SiLab-Bonn/pyBAR
pybar/analysis/analysis_utils.py
https://github.com/SiLab-Bonn/pyBAR/blob/5ad95bbcd41cd358825823fb78f396cfce23593e/pybar/analysis/analysis_utils.py#L1323-L1353
def select_good_pixel_region(hits, col_span, row_span, min_cut_threshold=0.2, max_cut_threshold=2.0): '''Takes the hit array and masks all pixels with a certain occupancy. Parameters ---------- hits : array like If dim > 2 the additional dimensions are summed up. min_cut_threshold : float ...
[ "def", "select_good_pixel_region", "(", "hits", ",", "col_span", ",", "row_span", ",", "min_cut_threshold", "=", "0.2", ",", "max_cut_threshold", "=", "2.0", ")", ":", "hits", "=", "np", ".", "sum", "(", "hits", ",", "axis", "=", "(", "-", "1", ")", ")...
Takes the hit array and masks all pixels with a certain occupancy. Parameters ---------- hits : array like If dim > 2 the additional dimensions are summed up. min_cut_threshold : float A number to specify the minimum threshold, which pixel to take. Pixels are masked if occupancy...
[ "Takes", "the", "hit", "array", "and", "masks", "all", "pixels", "with", "a", "certain", "occupancy", "." ]
python
train
log2timeline/plaso
plaso/output/shared_elastic.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/shared_elastic.py#L198-L220
def _InsertEvent(self, event, force_flush=False): """Inserts an event. Events are buffered in the form of documents and inserted to Elasticsearch when either forced to flush or when the flush interval (threshold) has been reached. Args: event (EventObject): event. force_flush (bool): T...
[ "def", "_InsertEvent", "(", "self", ",", "event", ",", "force_flush", "=", "False", ")", ":", "if", "event", ":", "event_document", "=", "{", "'index'", ":", "{", "'_index'", ":", "self", ".", "_index_name", ",", "'_type'", ":", "self", ".", "_document_t...
Inserts an event. Events are buffered in the form of documents and inserted to Elasticsearch when either forced to flush or when the flush interval (threshold) has been reached. Args: event (EventObject): event. force_flush (bool): True if buffered event documents should be inserted ...
[ "Inserts", "an", "event", "." ]
python
train
maaku/python-bitcoin
bitcoin/hash.py
https://github.com/maaku/python-bitcoin/blob/1b80c284170fd3f547cc45f4700ce169f3f99641/bitcoin/hash.py#L146-L156
def new(self, string=None, *args, **kwargs): """Returns a `_ChainedHashAlgorithm` if the underlying tuple (specifying the list of algorithms) is not empty, otherwise a `_NopHashAlgorithm` instance is returned.""" if len(self): hobj = _ChainedHashAlgorithm(self, *args, **kwarg...
[ "def", "new", "(", "self", ",", "string", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "self", ")", ":", "hobj", "=", "_ChainedHashAlgorithm", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "...
Returns a `_ChainedHashAlgorithm` if the underlying tuple (specifying the list of algorithms) is not empty, otherwise a `_NopHashAlgorithm` instance is returned.
[ "Returns", "a", "_ChainedHashAlgorithm", "if", "the", "underlying", "tuple", "(", "specifying", "the", "list", "of", "algorithms", ")", "is", "not", "empty", "otherwise", "a", "_NopHashAlgorithm", "instance", "is", "returned", "." ]
python
train
kgori/treeCl
treeCl/bootstrap.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/bootstrap.py#L143-L160
def optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001): """ Optimise value of x using levenberg-marquardt """ x_new = x x_old = x-1 # dummy value f_old = f(x_new, a, c) while np.abs(x_new - x_old).sum() > tolerance: x_old = x_new x_tmp = levenberg_marquardt...
[ "def", "optimise_levenberg_marquardt", "(", "x", ",", "a", ",", "c", ",", "damping", "=", "0.001", ",", "tolerance", "=", "0.001", ")", ":", "x_new", "=", "x", "x_old", "=", "x", "-", "1", "# dummy value", "f_old", "=", "f", "(", "x_new", ",", "a", ...
Optimise value of x using levenberg-marquardt
[ "Optimise", "value", "of", "x", "using", "levenberg", "-", "marquardt" ]
python
train
quantmind/dynts
dynts/api/timeseries.py
https://github.com/quantmind/dynts/blob/21ac57c648bfec402fa6b1fe569496cf098fb5e8/dynts/api/timeseries.py#L512-L518
def rollapply(self, func, window=20, **kwargs): '''A generic :ref:`rolling function <rolling-function>` for function *func*. Same construct as :meth:`dynts.TimeSeries.apply` but with default ``window`` set to ``20``. ''' return self.apply(func, window=window, **kwar...
[ "def", "rollapply", "(", "self", ",", "func", ",", "window", "=", "20", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "apply", "(", "func", ",", "window", "=", "window", ",", "*", "*", "kwargs", ")" ]
A generic :ref:`rolling function <rolling-function>` for function *func*. Same construct as :meth:`dynts.TimeSeries.apply` but with default ``window`` set to ``20``.
[ "A", "generic", ":", "ref", ":", "rolling", "function", "<rolling", "-", "function", ">", "for", "function", "*", "func", "*", ".", "Same", "construct", "as", ":", "meth", ":", "dynts", ".", "TimeSeries", ".", "apply", "but", "with", "default", "window",...
python
train
mpenning/polymer
polymer/Polymer.py
https://github.com/mpenning/polymer/blob/1cdf4ed2573c894bde9d398fa173816b6b47e9f3/polymer/Polymer.py#L380-L515
def supervise(self): """If not in a hot_loop, call supervise() to start the tasks""" self.retval = set([]) stats = TaskMgrStats( worker_count=self.worker_count, log_interval=self.log_interval, hot_loop=self.hot_loop, ) hot_loop = self.hot_loop...
[ "def", "supervise", "(", "self", ")", ":", "self", ".", "retval", "=", "set", "(", "[", "]", ")", "stats", "=", "TaskMgrStats", "(", "worker_count", "=", "self", ".", "worker_count", ",", "log_interval", "=", "self", ".", "log_interval", ",", "hot_loop",...
If not in a hot_loop, call supervise() to start the tasks
[ "If", "not", "in", "a", "hot_loop", "call", "supervise", "()", "to", "start", "the", "tasks" ]
python
test
bokeh/bokeh
bokeh/plotting/helpers.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/plotting/helpers.py#L286-L315
def _pop_colors_and_alpha(glyphclass, kwargs, prefix="", default_alpha=1.0): """ Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist. """ result = dict() # TODO: The need to do...
[ "def", "_pop_colors_and_alpha", "(", "glyphclass", ",", "kwargs", ",", "prefix", "=", "\"\"", ",", "default_alpha", "=", "1.0", ")", ":", "result", "=", "dict", "(", ")", "# TODO: The need to do this and the complexity of managing this kind of", "# thing throughout the co...
Given a kwargs dict, a prefix, and a default value, looks for different color and alpha fields of the given prefix, and fills in the default value if it doesn't exist.
[ "Given", "a", "kwargs", "dict", "a", "prefix", "and", "a", "default", "value", "looks", "for", "different", "color", "and", "alpha", "fields", "of", "the", "given", "prefix", "and", "fills", "in", "the", "default", "value", "if", "it", "doesn", "t", "exi...
python
train
hozn/coilmq
coilmq/config/__init__.py
https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/config/__init__.py#L69-L110
def init_logging(logfile=None, loglevel=logging.INFO, configfile=None): """ Configures the logging using either basic filename + loglevel or passed config file path. This is performed separately from L{init_config()} in order to support the case where logging should happen independent of (usu. *after*...
[ "def", "init_logging", "(", "logfile", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ",", "configfile", "=", "None", ")", ":", "# If a config file was specified, we will use that in place of the", "# explicitly", "use_configfile", "=", "False", "if", "con...
Configures the logging using either basic filename + loglevel or passed config file path. This is performed separately from L{init_config()} in order to support the case where logging should happen independent of (usu. *after*) other aspects of the configuration initialization. For example, if logging ma...
[ "Configures", "the", "logging", "using", "either", "basic", "filename", "+", "loglevel", "or", "passed", "config", "file", "path", "." ]
python
train
aewallin/allantools
allantools/ci.py
https://github.com/aewallin/allantools/blob/b5c695a5af4379fcea4d4ce93a066cb902e7ee0a/allantools/ci.py#L693-L708
def edf_totdev(N, m, alpha): """ Equivalent degrees of freedom for Total Deviation FIXME: what is the right behavior for alpha outside 0,-1,-2? NIST SP1065 page 41, Table 7 """ alpha = int(alpha) if alpha in [0, -1, -2]: # alpha 0 WFM # alpha -1 FFM # al...
[ "def", "edf_totdev", "(", "N", ",", "m", ",", "alpha", ")", ":", "alpha", "=", "int", "(", "alpha", ")", "if", "alpha", "in", "[", "0", ",", "-", "1", ",", "-", "2", "]", ":", "# alpha 0 WFM", "# alpha -1 FFM", "# alpha -2 RWFM", "NIST_SP1065_table7",...
Equivalent degrees of freedom for Total Deviation FIXME: what is the right behavior for alpha outside 0,-1,-2? NIST SP1065 page 41, Table 7
[ "Equivalent", "degrees", "of", "freedom", "for", "Total", "Deviation", "FIXME", ":", "what", "is", "the", "right", "behavior", "for", "alpha", "outside", "0", "-", "1", "-", "2?", "NIST", "SP1065", "page", "41", "Table", "7" ]
python
train
molmod/molmod
molmod/graphs.py
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/graphs.py#L1339-L1381
def get_closed_cycles(self): """Return the closed cycles corresponding to this permutation The cycle will be normalized to facilitate the elimination of duplicates. The following is guaranteed: 1) If this permutation is represented by disconnected cycles, the cyc...
[ "def", "get_closed_cycles", "(", "self", ")", ":", "# A) construct all the cycles", "closed_cycles", "=", "[", "]", "todo", "=", "set", "(", "self", ".", "forward", ".", "keys", "(", ")", ")", "if", "todo", "!=", "set", "(", "self", ".", "forward", ".", ...
Return the closed cycles corresponding to this permutation The cycle will be normalized to facilitate the elimination of duplicates. The following is guaranteed: 1) If this permutation is represented by disconnected cycles, the cycles will be sorted by the lowest index t...
[ "Return", "the", "closed", "cycles", "corresponding", "to", "this", "permutation" ]
python
train
ros-infrastructure/ros_buildfarm
ros_buildfarm/doc_job.py
https://github.com/ros-infrastructure/ros_buildfarm/blob/c63ad85b21470f3262086fcd987528a0efc0cf6d/ros_buildfarm/doc_job.py#L159-L249
def configure_doc_job( config_url, rosdistro_name, doc_build_name, repo_name, os_name, os_code_name, arch, config=None, build_file=None, index=None, dist_file=None, dist_cache=None, jenkins=None, views=None, is_disabled=False, groovy_script=None, doc_repos...
[ "def", "configure_doc_job", "(", "config_url", ",", "rosdistro_name", ",", "doc_build_name", ",", "repo_name", ",", "os_name", ",", "os_code_name", ",", "arch", ",", "config", "=", "None", ",", "build_file", "=", "None", ",", "index", "=", "None", ",", "dist...
Configure a single Jenkins doc job. This includes the following steps: - clone the doc repository to use - clone the ros_buildfarm repository - write the distribution repository keys into files - invoke the run_doc_job.py script
[ "Configure", "a", "single", "Jenkins", "doc", "job", "." ]
python
valid
rsalmei/clearly
clearly/server.py
https://github.com/rsalmei/clearly/blob/fd784843d13f0fed28fc192565bec3668f1363f4/clearly/server.py#L169-L178
def get_stats(self, request, context): """Returns the server statistics.""" _log_request(request, context) m = self.listener.memory return clearly_pb2.StatsMessage( task_count=m.task_count, event_count=m.event_count, len_tasks=len(m.tasks), ...
[ "def", "get_stats", "(", "self", ",", "request", ",", "context", ")", ":", "_log_request", "(", "request", ",", "context", ")", "m", "=", "self", ".", "listener", ".", "memory", "return", "clearly_pb2", ".", "StatsMessage", "(", "task_count", "=", "m", "...
Returns the server statistics.
[ "Returns", "the", "server", "statistics", "." ]
python
train
asphalt-framework/asphalt
asphalt/core/utils.py
https://github.com/asphalt-framework/asphalt/blob/4114b3ac9743cbd9facb374a3f53e19d3afef22d/asphalt/core/utils.py#L62-L67
def callable_name(func: Callable) -> str: """Return the qualified name (e.g. package.module.func) for the given callable.""" if func.__module__ == 'builtins': return func.__name__ else: return '{}.{}'.format(func.__module__, func.__qualname__)
[ "def", "callable_name", "(", "func", ":", "Callable", ")", "->", "str", ":", "if", "func", ".", "__module__", "==", "'builtins'", ":", "return", "func", ".", "__name__", "else", ":", "return", "'{}.{}'", ".", "format", "(", "func", ".", "__module__", ","...
Return the qualified name (e.g. package.module.func) for the given callable.
[ "Return", "the", "qualified", "name", "(", "e", ".", "g", ".", "package", ".", "module", ".", "func", ")", "for", "the", "given", "callable", "." ]
python
train
david-caro/python-autosemver
autosemver/packaging.py
https://github.com/david-caro/python-autosemver/blob/3bc0adb70c33e4bd3623ae4c1944d5ee37f4303d/autosemver/packaging.py#L118-L146
def get_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False): """ Retrieves the changelog, from the CHANGELOG file (if in a package) or generates it from the git history. Optionally in rpm-compatible format. :param project_dir: Path to the git repo of the project. :type project_dir...
[ "def", "get_changelog", "(", "project_dir", "=", "os", ".", "curdir", ",", "bugtracker_url", "=", "''", ",", "rpm_format", "=", "False", ")", ":", "changelog", "=", "''", "pkg_info_file", "=", "os", ".", "path", ".", "join", "(", "project_dir", ",", "'PK...
Retrieves the changelog, from the CHANGELOG file (if in a package) or generates it from the git history. Optionally in rpm-compatible format. :param project_dir: Path to the git repo of the project. :type project_dir: str :param bugtracker_url: Url to the bug tracker for the issues. :type bugtracke...
[ "Retrieves", "the", "changelog", "from", "the", "CHANGELOG", "file", "(", "if", "in", "a", "package", ")", "or", "generates", "it", "from", "the", "git", "history", ".", "Optionally", "in", "rpm", "-", "compatible", "format", "." ]
python
train
django-danceschool/django-danceschool
danceschool/core/templatetags/danceschool_tags.py
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/templatetags/danceschool_tags.py#L164-L172
def getReturnPage(context, prior=False): ''' This tag makes it easy to get return links from within a template without requiring custom logic inside the view. Just include {% getReturnPage as returnPage %} and then reference {{ returnPage.url }} and {{ returnPage.title }} as needed. ''' ...
[ "def", "getReturnPage", "(", "context", ",", "prior", "=", "False", ")", ":", "siteHistory", "=", "getattr", "(", "context", ".", "get", "(", "'request'", ",", "None", ")", ",", "'session'", ",", "{", "}", ")", ".", "get", "(", "'SITE_HISTORY'", ",", ...
This tag makes it easy to get return links from within a template without requiring custom logic inside the view. Just include {% getReturnPage as returnPage %} and then reference {{ returnPage.url }} and {{ returnPage.title }} as needed.
[ "This", "tag", "makes", "it", "easy", "to", "get", "return", "links", "from", "within", "a", "template", "without", "requiring", "custom", "logic", "inside", "the", "view", ".", "Just", "include", "{", "%", "getReturnPage", "as", "returnPage", "%", "}", "a...
python
train
iKevinY/EulerPy
EulerPy/euler.py
https://github.com/iKevinY/EulerPy/blob/739c1c67fa7b32af9140ca51e4b4a07733e057a6/EulerPy/euler.py#L25-L57
def generate(num, prompt_default=True): """Generates Python file for a problem.""" p = Problem(num) problem_text = p.text msg = "Generate file for problem %i?" % num click.confirm(msg, default=prompt_default, abort=True) # Allow skipped problem files to be recreated if p.glob: fil...
[ "def", "generate", "(", "num", ",", "prompt_default", "=", "True", ")", ":", "p", "=", "Problem", "(", "num", ")", "problem_text", "=", "p", ".", "text", "msg", "=", "\"Generate file for problem %i?\"", "%", "num", "click", ".", "confirm", "(", "msg", ",...
Generates Python file for a problem.
[ "Generates", "Python", "file", "for", "a", "problem", "." ]
python
train
jordanncg/Bison
bison/cli.py
https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/cli.py#L31-L50
def main(): """A""" parser = argparse.ArgumentParser(description='A site preprocessor based \ on Jinja2, a templating engine for Python') subparsers = parser.add_subparsers(description='The following options \ are available:') # 'create' command parser_create = subparsers.add_parser...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'A site preprocessor based \\\n on Jinja2, a templating engine for Python'", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", "description", "=", ...
A
[ "A" ]
python
train
SwissDataScienceCenter/renku-python
renku/models/cwl/_ascwl.py
https://github.com/SwissDataScienceCenter/renku-python/blob/691644d695b055a01e0ca22b2620e55bbd928c0d/renku/models/cwl/_ascwl.py#L111-L197
def ascwl( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, basedir=None, ): """Return the ``attrs`` attribute values of *inst* as a dict. Support ``jsonldPredicate`` in a field metadata for generating mappings from lists. Adapted from ``attr._...
[ "def", "ascwl", "(", "inst", ",", "recurse", "=", "True", ",", "filter", "=", "None", ",", "dict_factory", "=", "dict", ",", "retain_collection_types", "=", "False", ",", "basedir", "=", "None", ",", ")", ":", "attrs", "=", "fields", "(", "inst", ".", ...
Return the ``attrs`` attribute values of *inst* as a dict. Support ``jsonldPredicate`` in a field metadata for generating mappings from lists. Adapted from ``attr._funcs``.
[ "Return", "the", "attrs", "attribute", "values", "of", "*", "inst", "*", "as", "a", "dict", "." ]
python
train
lsst-sqre/documenteer
documenteer/sphinxconfig/stackconf.py
https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxconfig/stackconf.py#L220-L254
def _insert_automodapi_configs(c): """Add configurations related to automodapi, autodoc, and numpydoc to the state. """ # Don't show summaries of the members in each class along with the # class' docstring c['numpydoc_show_class_members'] = False c['autosummary_generate'] = True c['aut...
[ "def", "_insert_automodapi_configs", "(", "c", ")", ":", "# Don't show summaries of the members in each class along with the", "# class' docstring", "c", "[", "'numpydoc_show_class_members'", "]", "=", "False", "c", "[", "'autosummary_generate'", "]", "=", "True", "c", "[",...
Add configurations related to automodapi, autodoc, and numpydoc to the state.
[ "Add", "configurations", "related", "to", "automodapi", "autodoc", "and", "numpydoc", "to", "the", "state", "." ]
python
train
benhoff/pluginmanager
pluginmanager/plugin_interface.py
https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/plugin_interface.py#L244-L256
def set_plugin_filepaths(self, filepaths, except_blacklisted=True): """ Sets internal state to `filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. ...
[ "def", "set_plugin_filepaths", "(", "self", ",", "filepaths", ",", "except_blacklisted", "=", "True", ")", ":", "self", ".", "file_manager", ".", "set_plugin_filepaths", "(", "filepaths", ",", "except_blacklisted", ")" ]
Sets internal state to `filepaths`. Recommend passing in absolute filepaths. Method will attempt to convert to absolute paths if they are not already. `filepaths` can be a single object or an iterable. If `except_blacklisted` is `True`, all `filepaths` that have been blackliste...
[ "Sets", "internal", "state", "to", "filepaths", ".", "Recommend", "passing", "in", "absolute", "filepaths", ".", "Method", "will", "attempt", "to", "convert", "to", "absolute", "paths", "if", "they", "are", "not", "already", "." ]
python
train
ARMmbed/yotta
yotta/lib/target.py
https://github.com/ARMmbed/yotta/blob/56bc1e56c602fa20307b23fe27518e9cd6c11af1/yotta/lib/target.py#L311-L325
def _loadConfig(self): ''' load the configuration information from the target hierarchy ''' config_dicts = [self.additional_config, self.app_config] + [t.getConfig() for t in self.hierarchy] # create an identical set of dictionaries, but with the names of the # sources in place of the va...
[ "def", "_loadConfig", "(", "self", ")", ":", "config_dicts", "=", "[", "self", ".", "additional_config", ",", "self", ".", "app_config", "]", "+", "[", "t", ".", "getConfig", "(", ")", "for", "t", "in", "self", ".", "hierarchy", "]", "# create an identic...
load the configuration information from the target hierarchy
[ "load", "the", "configuration", "information", "from", "the", "target", "hierarchy" ]
python
valid
nickmckay/LiPD-utilities
Python/lipd/timeseries.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/timeseries.py#L252-L295
def _extract_special(current, table_data): """ Extract year, age, and depth column from table data :param dict table_data: Data at the table level :param dict current: Current data :return dict current: """ logger_ts.info("enter extract_special") try: # Add age, year, and depth c...
[ "def", "_extract_special", "(", "current", ",", "table_data", ")", ":", "logger_ts", ".", "info", "(", "\"enter extract_special\"", ")", "try", ":", "# Add age, year, and depth columns to ts_root where possible", "for", "k", ",", "v", "in", "table_data", "[", "'column...
Extract year, age, and depth column from table data :param dict table_data: Data at the table level :param dict current: Current data :return dict current:
[ "Extract", "year", "age", "and", "depth", "column", "from", "table", "data", ":", "param", "dict", "table_data", ":", "Data", "at", "the", "table", "level", ":", "param", "dict", "current", ":", "Current", "data", ":", "return", "dict", "current", ":" ]
python
train
apache/incubator-heron
third_party/python/cpplint/cpplint.py
https://github.com/apache/incubator-heron/blob/ad10325a0febe89ad337e561ebcbe37ec5d9a5ac/third_party/python/cpplint/cpplint.py#L4607-L4669
def _ClassifyInclude(fileinfo, include, is_system): """Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _...
[ "def", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ":", "# This is a list of all standard c++ header files, except", "# those already checked for above.", "is_cpp_h", "=", "include", "in", "_CPP_HEADERS", "# Headers with C++ extensions shouldn't be c...
Figures out what kind of header 'include' is. Args: fileinfo: The current file cpplint is running over. A FileInfo instance. include: The path to a #included file. is_system: True if the #include used <> rather than "". Returns: One of the _XXX_HEADER constants. For example: >>> _ClassifyIn...
[ "Figures", "out", "what", "kind", "of", "header", "include", "is", "." ]
python
valid
openxc/openxc-python
openxc/sources/trace.py
https://github.com/openxc/openxc-python/blob/4becb4a6310bd658c125195ef6ffea4deaf7d7e7/openxc/sources/trace.py#L45-L52
def _store_timestamp(self, timestamp): """If not already saved, cache the first timestamp in the active trace file on the instance. """ if getattr(self, 'first_timestamp', None) is None: self.first_timestamp = timestamp LOG.debug("Storing %d as the first timestamp...
[ "def", "_store_timestamp", "(", "self", ",", "timestamp", ")", ":", "if", "getattr", "(", "self", ",", "'first_timestamp'", ",", "None", ")", "is", "None", ":", "self", ".", "first_timestamp", "=", "timestamp", "LOG", ".", "debug", "(", "\"Storing %d as the ...
If not already saved, cache the first timestamp in the active trace file on the instance.
[ "If", "not", "already", "saved", "cache", "the", "first", "timestamp", "in", "the", "active", "trace", "file", "on", "the", "instance", "." ]
python
train
mikedh/trimesh
trimesh/path/exchange/svg_io.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/path/exchange/svg_io.py#L25-L76
def svg_to_path(file_obj, file_type=None): """ Load an SVG file into a Path2D object. Parameters ----------- file_obj : open file object Contains SVG data file_type: None Not used Returns ----------- loaded : dict With kwargs for Path2D constructor """ de...
[ "def", "svg_to_path", "(", "file_obj", ",", "file_type", "=", "None", ")", ":", "def", "element_transform", "(", "e", ",", "max_depth", "=", "100", ")", ":", "\"\"\"\n Find a transformation matrix for an XML element.\n \"\"\"", "matrices", "=", "[", "]",...
Load an SVG file into a Path2D object. Parameters ----------- file_obj : open file object Contains SVG data file_type: None Not used Returns ----------- loaded : dict With kwargs for Path2D constructor
[ "Load", "an", "SVG", "file", "into", "a", "Path2D", "object", "." ]
python
train
opencobra/cobrapy
cobra/core/dictlist.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/dictlist.py#L334-L343
def insert(self, index, object): """insert object before index""" self._check(object.id) list.insert(self, index, object) # all subsequent entries now have been shifted up by 1 _dict = self._dict for i, j in iteritems(_dict): if j >= index: _di...
[ "def", "insert", "(", "self", ",", "index", ",", "object", ")", ":", "self", ".", "_check", "(", "object", ".", "id", ")", "list", ".", "insert", "(", "self", ",", "index", ",", "object", ")", "# all subsequent entries now have been shifted up by 1", "_dict"...
insert object before index
[ "insert", "object", "before", "index" ]
python
valid
Yelp/kafka-utils
kafka_utils/kafka_check/commands/replication_factor.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_check/commands/replication_factor.py#L42-L55
def run_command(self): """Replication factor command, checks replication factor settings and compare it with min.isr in the cluster.""" topics = get_topic_partition_metadata(self.cluster_config.broker_list) topics_with_wrong_rf = _find_topics_with_wrong_rp( topics, ...
[ "def", "run_command", "(", "self", ")", ":", "topics", "=", "get_topic_partition_metadata", "(", "self", ".", "cluster_config", ".", "broker_list", ")", "topics_with_wrong_rf", "=", "_find_topics_with_wrong_rp", "(", "topics", ",", "self", ".", "zk", ",", "self", ...
Replication factor command, checks replication factor settings and compare it with min.isr in the cluster.
[ "Replication", "factor", "command", "checks", "replication", "factor", "settings", "and", "compare", "it", "with", "min", ".", "isr", "in", "the", "cluster", "." ]
python
train
gwastro/pycbc
pycbc/tmpltbank/bank_output_utils.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/tmpltbank/bank_output_utils.py#L50-L100
def return_search_summary(start_time=0, end_time=0, nevents=0, ifos=None, **kwargs): """ Function to create a SearchSummary object where all columns are populated but all are set to values that test False (ie. strings to '', floats/ints to 0, ...). This avoids errors when you t...
[ "def", "return_search_summary", "(", "start_time", "=", "0", ",", "end_time", "=", "0", ",", "nevents", "=", "0", ",", "ifos", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "ifos", "is", "None", ":", "ifos", "=", "[", "]", "# create an empty ...
Function to create a SearchSummary object where all columns are populated but all are set to values that test False (ie. strings to '', floats/ints to 0, ...). This avoids errors when you try to create a table containing columns you don't care about, but which still need populating. NOTE: This will also...
[ "Function", "to", "create", "a", "SearchSummary", "object", "where", "all", "columns", "are", "populated", "but", "all", "are", "set", "to", "values", "that", "test", "False", "(", "ie", ".", "strings", "to", "floats", "/", "ints", "to", "0", "...", ")",...
python
train
tensorflow/probability
tensorflow_probability/python/layers/initializers.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/initializers.py#L106-L116
def get_config(self): """Returns initializer configuration as a JSON-serializable dict.""" return { 'initializers': [ tf.compat.v2.initializers.serialize( tf.keras.initializers.get(init)) for init in self.initializers ], 'sizes': self.sizes, ...
[ "def", "get_config", "(", "self", ")", ":", "return", "{", "'initializers'", ":", "[", "tf", ".", "compat", ".", "v2", ".", "initializers", ".", "serialize", "(", "tf", ".", "keras", ".", "initializers", ".", "get", "(", "init", ")", ")", "for", "ini...
Returns initializer configuration as a JSON-serializable dict.
[ "Returns", "initializer", "configuration", "as", "a", "JSON", "-", "serializable", "dict", "." ]
python
test
elastic/elasticsearch-py
elasticsearch/client/cluster.py
https://github.com/elastic/elasticsearch-py/blob/2aab285c8f506f3863cbdaba3c90a685c510ba00/elasticsearch/client/cluster.py#L101-L121
def reroute(self, body=None, params=None): """ Explicitly execute a cluster reroute allocation command including specific commands. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-reroute.html>`_ :arg body: The definition of `commands` to perform (`move`, `cance...
[ "def", "reroute", "(", "self", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "'POST'", ",", "'/_cluster/reroute'", ",", "params", "=", "params", ",", "body", "=", "body", ...
Explicitly execute a cluster reroute allocation command including specific commands. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-reroute.html>`_ :arg body: The definition of `commands` to perform (`move`, `cancel`, `allocate`) :arg dry_run: Simulate the ...
[ "Explicitly", "execute", "a", "cluster", "reroute", "allocation", "command", "including", "specific", "commands", ".", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/",...
python
train
nickmckay/LiPD-utilities
Python/lipd/lpd_noaa.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L421-L465
def __reorganize(self): """ Reorganize the keys into their proper section order for the NOAA output file DO NOT parse data tables (paleoData or chronData). We will do those separately. :param str key: :param any value: :return none: """ logger_lpd_noaa.inf...
[ "def", "__reorganize", "(", "self", ")", ":", "logger_lpd_noaa", ".", "info", "(", "\"enter reorganize\"", ")", "# NOAA files are organized in sections differently than NOAA. try to translate these sections.", "for", "key", ",", "value", "in", "self", ".", "lipd_data", ".",...
Reorganize the keys into their proper section order for the NOAA output file DO NOT parse data tables (paleoData or chronData). We will do those separately. :param str key: :param any value: :return none:
[ "Reorganize", "the", "keys", "into", "their", "proper", "section", "order", "for", "the", "NOAA", "output", "file", "DO", "NOT", "parse", "data", "tables", "(", "paleoData", "or", "chronData", ")", ".", "We", "will", "do", "those", "separately", ".", ":", ...
python
train
googleapis/google-cloud-python
logging/google/cloud/logging/_gapic.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/logging/google/cloud/logging/_gapic.py#L499-L515
def _item_to_sink(iterator, log_sink_pb): """Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Si...
[ "def", "_item_to_sink", "(", "iterator", ",", "log_sink_pb", ")", ":", "# NOTE: LogSink message type does not have an ``Any`` field", "# so `MessageToDict`` can safely be used.", "resource", "=", "MessageToDict", "(", "log_sink_pb", ")", "return", "Sink", ".", "from_api_r...
Convert a sink protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type log_sink_pb: :class:`.logging_config_pb2.LogSink` :param log_sink_pb: Sink protobuf returned from the API. :rtype: :...
[ "Convert", "a", "sink", "protobuf", "to", "the", "native", "object", "." ]
python
train
moonlitesolutions/SolrClient
SolrClient/helpers/reindexer.py
https://github.com/moonlitesolutions/SolrClient/blob/19c5280c9f8e97ee104d22ae883c4ccfd7c4f43b/SolrClient/helpers/reindexer.py#L153-L165
def _get_query(self, cursor): ''' Query tempalte for source Solr, sorts by id by default. ''' query = {'q':'*:*', 'sort':'id desc', 'rows':self._rows, 'cursorMark':cursor} if self._date_field: query['sort'] = "{...
[ "def", "_get_query", "(", "self", ",", "cursor", ")", ":", "query", "=", "{", "'q'", ":", "'*:*'", ",", "'sort'", ":", "'id desc'", ",", "'rows'", ":", "self", ".", "_rows", ",", "'cursorMark'", ":", "cursor", "}", "if", "self", ".", "_date_field", "...
Query tempalte for source Solr, sorts by id by default.
[ "Query", "tempalte", "for", "source", "Solr", "sorts", "by", "id", "by", "default", "." ]
python
train
Shopify/shopify_python_api
shopify/base.py
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/base.py#L33-L50
def connection(cls): """HTTP connection for the current thread""" local = cls._threadlocal if not getattr(local, 'connection', None): # Make sure these variables are no longer affected by other threads. local.user = cls.user local.password = cls.password ...
[ "def", "connection", "(", "cls", ")", ":", "local", "=", "cls", ".", "_threadlocal", "if", "not", "getattr", "(", "local", ",", "'connection'", ",", "None", ")", ":", "# Make sure these variables are no longer affected by other threads.", "local", ".", "user", "="...
HTTP connection for the current thread
[ "HTTP", "connection", "for", "the", "current", "thread" ]
python
train
datastax/python-driver
cassandra/query.py
https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/query.py#L972-L1026
def populate(self, max_wait=2.0, wait_for_complete=True, query_cl=None): """ Retrieves the actual tracing details from Cassandra and populates the attributes of this instance. Because tracing details are stored asynchronously by Cassandra, this may need to retry the session deta...
[ "def", "populate", "(", "self", ",", "max_wait", "=", "2.0", ",", "wait_for_complete", "=", "True", ",", "query_cl", "=", "None", ")", ":", "attempt", "=", "0", "start", "=", "time", ".", "time", "(", ")", "while", "True", ":", "time_spent", "=", "ti...
Retrieves the actual tracing details from Cassandra and populates the attributes of this instance. Because tracing details are stored asynchronously by Cassandra, this may need to retry the session detail fetch. If the trace is still not available after `max_wait` seconds, :exc:`.Trace...
[ "Retrieves", "the", "actual", "tracing", "details", "from", "Cassandra", "and", "populates", "the", "attributes", "of", "this", "instance", ".", "Because", "tracing", "details", "are", "stored", "asynchronously", "by", "Cassandra", "this", "may", "need", "to", "...
python
train
ff0000/scarlet
scarlet/cms/sites.py
https://github.com/ff0000/scarlet/blob/6c37befd810916a2d7ffff2cdb2dab57bcb6d12e/scarlet/cms/sites.py#L205-L219
def password_change(self, request): """ Handles the "change password" task -- both form display and validation. Uses the default auth views. """ from django.contrib.auth.views import password_change url = reverse('admin:cms_password_change_done') defaults = { ...
[ "def", "password_change", "(", "self", ",", "request", ")", ":", "from", "django", ".", "contrib", ".", "auth", ".", "views", "import", "password_change", "url", "=", "reverse", "(", "'admin:cms_password_change_done'", ")", "defaults", "=", "{", "'post_change_re...
Handles the "change password" task -- both form display and validation. Uses the default auth views.
[ "Handles", "the", "change", "password", "task", "--", "both", "form", "display", "and", "validation", "." ]
python
train
arne-cl/discoursegraphs
src/discoursegraphs/readwrite/salt/nodes.py
https://github.com/arne-cl/discoursegraphs/blob/842f0068a3190be2c75905754521b176b25a54fb/src/discoursegraphs/readwrite/salt/nodes.py#L107-L117
def from_etree(cls, etree_element): """ creates a ``PrimaryTextNode`` instance from the etree representation of a <nodes> element from a SaltXMI file. """ ins = SaltNode.from_etree(etree_element) # TODO: this looks dangerous, ask Stackoverflow about it! # convert ...
[ "def", "from_etree", "(", "cls", ",", "etree_element", ")", ":", "ins", "=", "SaltNode", ".", "from_etree", "(", "etree_element", ")", "# TODO: this looks dangerous, ask Stackoverflow about it!", "# convert SaltNode into PrimaryTextNode", "ins", ".", "__class__", "=", "Pr...
creates a ``PrimaryTextNode`` instance from the etree representation of a <nodes> element from a SaltXMI file.
[ "creates", "a", "PrimaryTextNode", "instance", "from", "the", "etree", "representation", "of", "a", "<nodes", ">", "element", "from", "a", "SaltXMI", "file", "." ]
python
train
mathandy/svgpathtools
svgpathtools/path.py
https://github.com/mathandy/svgpathtools/blob/fd7348a1dfd88b65ea61da02325c6605aedf8c4f/svgpathtools/path.py#L285-L320
def bezier_unit_tangent(seg, t): """Returns the unit tangent of the segment at t. Notes ----- If you receive a RuntimeWarning, try the following: >>> import numpy >>> old_numpy_error_settings = numpy.seterr(invalid='raise') This can be undone with: >>> numpy.seterr(**old_numpy_error_set...
[ "def", "bezier_unit_tangent", "(", "seg", ",", "t", ")", ":", "assert", "0", "<=", "t", "<=", "1", "dseg", "=", "seg", ".", "derivative", "(", "t", ")", "# Note: dseg might be numpy value, use np.seterr(invalid='raise')", "try", ":", "unit_tangent", "=", "dseg",...
Returns the unit tangent of the segment at t. Notes ----- If you receive a RuntimeWarning, try the following: >>> import numpy >>> old_numpy_error_settings = numpy.seterr(invalid='raise') This can be undone with: >>> numpy.seterr(**old_numpy_error_settings)
[ "Returns", "the", "unit", "tangent", "of", "the", "segment", "at", "t", "." ]
python
train
refinery29/chassis
chassis/services/dependency_injection/__init__.py
https://github.com/refinery29/chassis/blob/1238d5214cbb8f3e1fe7c0dc2fa72f45bf085192/chassis/services/dependency_injection/__init__.py#L27-L32
def _check_type(name, obj, expected_type): """ Raise a TypeError if object is not of expected type """ if not isinstance(obj, expected_type): raise TypeError( '"%s" must be an a %s' % (name, expected_type.__name__) )
[ "def", "_check_type", "(", "name", ",", "obj", ",", "expected_type", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "expected_type", ")", ":", "raise", "TypeError", "(", "'\"%s\" must be an a %s'", "%", "(", "name", ",", "expected_type", ".", "__name_...
Raise a TypeError if object is not of expected type
[ "Raise", "a", "TypeError", "if", "object", "is", "not", "of", "expected", "type" ]
python
train
PMEAL/OpenPNM
openpnm/topotools/topotools.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/topotools/topotools.py#L1471-L1498
def find_pore_to_pore_distance(network, pores1=None, pores2=None): r''' Find the distance between all pores on set one to each pore in set 2 Parameters ---------- network : OpenPNM Network Object The network object containing the pore coordinates pores1 : array_like The pore in...
[ "def", "find_pore_to_pore_distance", "(", "network", ",", "pores1", "=", "None", ",", "pores2", "=", "None", ")", ":", "from", "scipy", ".", "spatial", ".", "distance", "import", "cdist", "p1", "=", "sp", ".", "array", "(", "pores1", ",", "ndmin", "=", ...
r''' Find the distance between all pores on set one to each pore in set 2 Parameters ---------- network : OpenPNM Network Object The network object containing the pore coordinates pores1 : array_like The pore indices of the first set pores2 : array_Like The pore indice...
[ "r", "Find", "the", "distance", "between", "all", "pores", "on", "set", "one", "to", "each", "pore", "in", "set", "2" ]
python
train
aichaos/rivescript-python
rivescript/rivescript.py
https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L771-L787
def get_uservar(self, user, name): """Get a variable about a user. :param str user: The user ID to look up a variable for. :param str name: The name of the variable to get. :return: The user variable, or ``None`` or ``"undefined"``: * If the user has no data at all, this r...
[ "def", "get_uservar", "(", "self", ",", "user", ",", "name", ")", ":", "if", "name", "==", "'__lastmatch__'", ":", "# Treat var `__lastmatch__` since it can't receive \"undefined\" value", "return", "self", ".", "last_match", "(", "user", ")", "else", ":", "return",...
Get a variable about a user. :param str user: The user ID to look up a variable for. :param str name: The name of the variable to get. :return: The user variable, or ``None`` or ``"undefined"``: * If the user has no data at all, this returns ``None``. * If the user doe...
[ "Get", "a", "variable", "about", "a", "user", "." ]
python
train
pyviz/holoviews
holoviews/core/dimension.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/dimension.py#L51-L68
def asdim(dimension): """Convert the input to a Dimension. Args: dimension: tuple, dict or string type to convert to Dimension Returns: A Dimension object constructed from the dimension spec. No copy is performed if the input is already a Dimension. """ if isinstance(dimens...
[ "def", "asdim", "(", "dimension", ")", ":", "if", "isinstance", "(", "dimension", ",", "Dimension", ")", ":", "return", "dimension", "elif", "isinstance", "(", "dimension", ",", "(", "tuple", ",", "dict", ",", "basestring", ")", ")", ":", "return", "Dime...
Convert the input to a Dimension. Args: dimension: tuple, dict or string type to convert to Dimension Returns: A Dimension object constructed from the dimension spec. No copy is performed if the input is already a Dimension.
[ "Convert", "the", "input", "to", "a", "Dimension", "." ]
python
train
mezz64/pyEight
pyeight/user.py
https://github.com/mezz64/pyEight/blob/e557e4e6876f490d0964298e9475d68b64222d4f/pyeight/user.py#L581-L594
async def update_trend_data(self, startdate, enddate): """Update trends data json for specified time period.""" url = '{}/users/{}/trends'.format(API_URL, self.userid) params = { 'tz': self.device.tzone, 'from': startdate, 'to': enddate } ...
[ "async", "def", "update_trend_data", "(", "self", ",", "startdate", ",", "enddate", ")", ":", "url", "=", "'{}/users/{}/trends'", ".", "format", "(", "API_URL", ",", "self", ".", "userid", ")", "params", "=", "{", "'tz'", ":", "self", ".", "device", ".",...
Update trends data json for specified time period.
[ "Update", "trends", "data", "json", "for", "specified", "time", "period", "." ]
python
train
programa-stic/barf-project
barf/core/reil/emulator/tainter.py
https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/emulator/tainter.py#L195-L202
def __taint_move(self, instr): """Taint registers move instruction. """ # Get taint information. op0_taint = self.get_operand_taint(instr.operands[0]) # Propagate taint. self.set_operand_taint(instr.operands[2], op0_taint)
[ "def", "__taint_move", "(", "self", ",", "instr", ")", ":", "# Get taint information.", "op0_taint", "=", "self", ".", "get_operand_taint", "(", "instr", ".", "operands", "[", "0", "]", ")", "# Propagate taint.", "self", ".", "set_operand_taint", "(", "instr", ...
Taint registers move instruction.
[ "Taint", "registers", "move", "instruction", "." ]
python
train
senaite/senaite.core
bika/lims/browser/dashboard/dashboard.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/dashboard/dashboard.py#L205-L228
def check_dashboard_cookie(self): """ Check if the dashboard cookie should exist through bikasetup configuration. If it should exist but doesn't exist yet, the function creates it with all values as default. If it should exist and already exists, it returns the value. ...
[ "def", "check_dashboard_cookie", "(", "self", ")", ":", "# Getting cookie", "cookie_raw", "=", "self", ".", "request", ".", "get", "(", "DASHBOARD_FILTER_COOKIE", ",", "None", ")", "# If it doesn't exist, create it with default values", "if", "cookie_raw", "is", "None",...
Check if the dashboard cookie should exist through bikasetup configuration. If it should exist but doesn't exist yet, the function creates it with all values as default. If it should exist and already exists, it returns the value. Otherwise, the function returns None. :...
[ "Check", "if", "the", "dashboard", "cookie", "should", "exist", "through", "bikasetup", "configuration", "." ]
python
train
openstax/cnx-epub
cnxepub/models.py
https://github.com/openstax/cnx-epub/blob/f648a309eff551b0a68a115a98ddf7858149a2ea/cnxepub/models.py#L263-L270
def bind(self, model, template="{}"): """Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed. """ self._bound_model = model self._uri_template = template self._set_uri_fr...
[ "def", "bind", "(", "self", ",", "model", ",", "template", "=", "\"{}\"", ")", ":", "self", ".", "_bound_model", "=", "model", "self", ".", "_uri_template", "=", "template", "self", ".", "_set_uri_from_bound_model", "(", ")" ]
Bind the ``model`` to the reference. This uses the model's ``id`` attribute and the given ``template`` to dynamically produce a uri when accessed.
[ "Bind", "the", "model", "to", "the", "reference", ".", "This", "uses", "the", "model", "s", "id", "attribute", "and", "the", "given", "template", "to", "dynamically", "produce", "a", "uri", "when", "accessed", "." ]
python
train
labstreaminglayer/liblsl-Python
pylsl/pylsl.py
https://github.com/labstreaminglayer/liblsl-Python/blob/1ff6fe2794f8dba286b7491d1f7a4c915b8a0605/pylsl/pylsl.py#L457-L495
def push_chunk(self, x, timestamp=0.0, pushthrough=True): """Push a list of samples into the outlet. samples -- A list of samples, either as a list of lists or a list of multiplexed values. timestamp -- Optionally the capture time of the most recent sample, in ...
[ "def", "push_chunk", "(", "self", ",", "x", ",", "timestamp", "=", "0.0", ",", "pushthrough", "=", "True", ")", ":", "try", ":", "n_values", "=", "self", ".", "channel_count", "*", "len", "(", "x", ")", "data_buff", "=", "(", "self", ".", "value_type...
Push a list of samples into the outlet. samples -- A list of samples, either as a list of lists or a list of multiplexed values. timestamp -- Optionally the capture time of the most recent sample, in agreement with local_clock(); if omitted, the current ...
[ "Push", "a", "list", "of", "samples", "into", "the", "outlet", "." ]
python
test
econ-ark/HARK
HARK/ConsumptionSaving/ConsMarkovModel.py
https://github.com/econ-ark/HARK/blob/3d184153a189e618a87c9540df1cd12044039cc5/HARK/ConsumptionSaving/ConsMarkovModel.py#L502-L519
def makeLinearcFunc(self,mNrm,cNrm): ''' Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolat...
[ "def", "makeLinearcFunc", "(", "self", ",", "mNrm", ",", "cNrm", ")", ":", "cFuncUnc", "=", "LinearInterp", "(", "mNrm", ",", "cNrm", ",", "self", ".", "MPCminNow_j", "*", "self", ".", "hNrmNow_j", ",", "self", ".", "MPCminNow_j", ")", "return", "cFuncUn...
Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normali...
[ "Make", "a", "linear", "interpolation", "to", "represent", "the", "(", "unconstrained", ")", "consumption", "function", "conditional", "on", "the", "current", "period", "state", "." ]
python
train
kennethreitz/records
records.py
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L207-L226
def first(self, default=None, as_dict=False, as_ordereddict=False): """Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.""" # Try to get a record, or return/raise default. ...
[ "def", "first", "(", "self", ",", "default", "=", "None", ",", "as_dict", "=", "False", ",", "as_ordereddict", "=", "False", ")", ":", "# Try to get a record, or return/raise default.", "try", ":", "record", "=", "self", "[", "0", "]", "except", "IndexError", ...
Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
[ "Returns", "a", "single", "record", "for", "the", "RecordCollection", "or", "default", ".", "If", "default", "is", "an", "instance", "or", "subclass", "of", "Exception", "then", "raise", "it", "instead", "of", "returning", "it", "." ]
python
train
alfred82santa/dirty-models
dirty_models/models.py
https://github.com/alfred82santa/dirty-models/blob/354becdb751b21f673515eae928c256c7e923c50/dirty_models/models.py#L650-L666
def delete_attr_by_path(self, field_path): """ It deletes fields looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: str """ fields, next_fie...
[ "def", "delete_attr_by_path", "(", "self", ",", "field_path", ")", ":", "fields", ",", "next_field", "=", "self", ".", "_get_fields_by_path", "(", "field_path", ")", "for", "field", "in", "fields", ":", "if", "next_field", ":", "try", ":", "self", ".", "ge...
It deletes fields looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: str
[ "It", "deletes", "fields", "looked", "up", "by", "field", "path", ".", "Field", "path", "is", "dot", "-", "formatted", "string", "path", ":", "parent_field", ".", "child_field", "." ]
python
train
artefactual-labs/agentarchives
agentarchives/archivesspace/client.py
https://github.com/artefactual-labs/agentarchives/blob/af19ade56a90c64069cf46b50972fe72b6f10a45/agentarchives/archivesspace/client.py#L287-L352
def edit_record(self, new_record): """ Update a record in ArchivesSpace using the provided new_record. The format of new_record is identical to the format returned by get_resource_component_and_children and related methods; consult the documentation for that method in ArchivistsToolkitClient to...
[ "def", "edit_record", "(", "self", ",", "new_record", ")", ":", "try", ":", "record_id", "=", "new_record", "[", "\"id\"", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "\"No record ID provided!\"", ")", "record", "=", "self", ".", "get_record", ...
Update a record in ArchivesSpace using the provided new_record. The format of new_record is identical to the format returned by get_resource_component_and_children and related methods; consult the documentation for that method in ArchivistsToolkitClient to see the format. This means it's possible, for ...
[ "Update", "a", "record", "in", "ArchivesSpace", "using", "the", "provided", "new_record", "." ]
python
train
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/tailf_webui.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/tailf_webui.py#L420-L431
def webui_data_stores_data_store_key(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") webui = ET.SubElement(config, "webui", xmlns="http://tail-f.com/ns/webui") data_stores = ET.SubElement(webui, "data-stores") data_store = ET.SubElement(data_stor...
[ "def", "webui_data_stores_data_store_key", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "webui", "=", "ET", ".", "SubElement", "(", "config", ",", "\"webui\"", ",", "xmlns", "=", "\"http://tai...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
night-crawler/django-docker-helpers
django_docker_helpers/config/__init__.py
https://github.com/night-crawler/django-docker-helpers/blob/b64f8009101a8eb61d3841124ba19e3ab881aa2f/django_docker_helpers/config/__init__.py#L118-L169
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, required: bool = False, **kwargs): """ Tries to read a ``variable_path`` from each ...
[ "def", "get", "(", "self", ",", "variable_path", ":", "str", ",", "default", ":", "t", ".", "Optional", "[", "t", ".", "Any", "]", "=", "None", ",", "coerce_type", ":", "t", ".", "Optional", "[", "t", ".", "Type", "]", "=", "None", ",", "coercer"...
Tries to read a ``variable_path`` from each of the passed parsers. It stops if read was successful and returns a retrieved value. If none of the parsers contain a value for the specified path it returns ``default``. :param variable_path: a path to variable in config :param default: a de...
[ "Tries", "to", "read", "a", "variable_path", "from", "each", "of", "the", "passed", "parsers", ".", "It", "stops", "if", "read", "was", "successful", "and", "returns", "a", "retrieved", "value", ".", "If", "none", "of", "the", "parsers", "contain", "a", ...
python
train
vtraag/louvain-igraph
src/functions.py
https://github.com/vtraag/louvain-igraph/blob/8de2c3bad736a9deea90b80f104d8444769d331f/src/functions.py#L81-L136
def find_partition_multiplex(graphs, partition_type, **kwargs): """ Detect communities for multiplex graphs. Each graph should be defined on the same set of vertices, only the edges may differ for different graphs. See :func:`Optimiser.optimise_partition_multiplex` for a more detailed explanation. Paramet...
[ "def", "find_partition_multiplex", "(", "graphs", ",", "partition_type", ",", "*", "*", "kwargs", ")", ":", "n_layers", "=", "len", "(", "graphs", ")", "partitions", "=", "[", "]", "layer_weights", "=", "[", "1", "]", "*", "n_layers", "for", "graph", "in...
Detect communities for multiplex graphs. Each graph should be defined on the same set of vertices, only the edges may differ for different graphs. See :func:`Optimiser.optimise_partition_multiplex` for a more detailed explanation. Parameters ---------- graphs : list of :class:`ig.Graph` List of :cla...
[ "Detect", "communities", "for", "multiplex", "graphs", "." ]
python
train
glitchassassin/lackey
lackey/RegionMatching.py
https://github.com/glitchassassin/lackey/blob/7adadfacd7f45d81186710be992f5668b15399fe/lackey/RegionMatching.py#L222-L231
def setLocation(self, location): """ Change the upper left-hand corner to a new ``Location`` Doesn't change width or height """ if not location or not isinstance(location, Location): raise ValueError("setLocation expected a Location object") self.x = location.x ...
[ "def", "setLocation", "(", "self", ",", "location", ")", ":", "if", "not", "location", "or", "not", "isinstance", "(", "location", ",", "Location", ")", ":", "raise", "ValueError", "(", "\"setLocation expected a Location object\"", ")", "self", ".", "x", "=", ...
Change the upper left-hand corner to a new ``Location`` Doesn't change width or height
[ "Change", "the", "upper", "left", "-", "hand", "corner", "to", "a", "new", "Location" ]
python
train
adamrehn/slidingwindow
slidingwindow/SlidingWindow.py
https://github.com/adamrehn/slidingwindow/blob/17ea9395b48671e8cb7321b9510c6b25fec5e45f/slidingwindow/SlidingWindow.py#L40-L44
def setRect(self, rect): """ Sets the window bounds from a tuple of (x,y,w,h) """ self.x, self.y, self.w, self.h = rect
[ "def", "setRect", "(", "self", ",", "rect", ")", ":", "self", ".", "x", ",", "self", ".", "y", ",", "self", ".", "w", ",", "self", ".", "h", "=", "rect" ]
Sets the window bounds from a tuple of (x,y,w,h)
[ "Sets", "the", "window", "bounds", "from", "a", "tuple", "of", "(", "x", "y", "w", "h", ")" ]
python
train
Ezhil-Language-Foundation/open-tamil
tamil/utf8.py
https://github.com/Ezhil-Language-Foundation/open-tamil/blob/b7556e88878d29bbc6c944ee17cdd3f75b8ea9f0/tamil/utf8.py#L265-L270
def uyirmei_constructed( mei_idx, uyir_idx): """ construct uyirmei letter give mei index and uyir index """ idx,idy = mei_idx,uyir_idx assert ( idy >= 0 and idy < uyir_len() ) assert ( idx >= 0 and idx < 6+mei_len() ) return grantha_agaram_letters[mei_idx]+accent_symbols[uyir_idx]
[ "def", "uyirmei_constructed", "(", "mei_idx", ",", "uyir_idx", ")", ":", "idx", ",", "idy", "=", "mei_idx", ",", "uyir_idx", "assert", "(", "idy", ">=", "0", "and", "idy", "<", "uyir_len", "(", ")", ")", "assert", "(", "idx", ">=", "0", "and", "idx",...
construct uyirmei letter give mei index and uyir index
[ "construct", "uyirmei", "letter", "give", "mei", "index", "and", "uyir", "index" ]
python
train
tensorflow/probability
tensorflow_probability/python/sts/semilocal_linear_trend.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/semilocal_linear_trend.py#L266-L296
def semilocal_linear_trend_transition_noise(level_scale, slope_mean, slope_scale, autoregressive_coef): """Build the transition noise model for a semi-local linear trend model.""" # A...
[ "def", "semilocal_linear_trend_transition_noise", "(", "level_scale", ",", "slope_mean", ",", "slope_scale", ",", "autoregressive_coef", ")", ":", "# At each timestep, the stochasticity of `level` and `slope` are given", "# by `level_scale` and `slope_scale` respectively.", "broadcast_ba...
Build the transition noise model for a semi-local linear trend model.
[ "Build", "the", "transition", "noise", "model", "for", "a", "semi", "-", "local", "linear", "trend", "model", "." ]
python
test
aetros/aetros-cli
aetros/utils/__init__.py
https://github.com/aetros/aetros-cli/blob/a2a1f38d6af1660e1e2680c7d413ec2aef45faab/aetros/utils/__init__.py#L877-L900
def human_size(size_bytes, precision=0): """ Format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc """ if size_bytes == ...
[ "def", "human_size", "(", "size_bytes", ",", "precision", "=", "0", ")", ":", "if", "size_bytes", "==", "1", ":", "# because I really hate unnecessary plurals", "return", "\"1 byte\"", "suffixes_table", "=", "[", "(", "'bytes'", ",", "0", ")", ",", "(", "'KB'"...
Format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc
[ "Format", "a", "size", "in", "bytes", "into", "a", "human", "file", "size", "e", ".", "g", ".", "bytes", "KB", "MB", "GB", "TB", "PB", "Note", "that", "bytes", "/", "KB", "will", "be", "reported", "in", "whole", "numbers", "but", "MB", "and", "abov...
python
train