repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
google/grr
grr/server/grr_response_server/databases/mem_clients.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_clients.py#L87-L104
def WriteClientSnapshot(self, snapshot): """Writes new client snapshot.""" client_id = snapshot.client_id if client_id not in self.metadatas: raise db.UnknownClientError(client_id) startup_info = snapshot.startup_info snapshot.startup_info = None ts = rdfvalue.RDFDatetime.Now() hist...
[ "def", "WriteClientSnapshot", "(", "self", ",", "snapshot", ")", ":", "client_id", "=", "snapshot", ".", "client_id", "if", "client_id", "not", "in", "self", ".", "metadatas", ":", "raise", "db", ".", "UnknownClientError", "(", "client_id", ")", "startup_info"...
Writes new client snapshot.
[ "Writes", "new", "client", "snapshot", "." ]
python
train
30.5
influxdata/influxdb-python
influxdb/client.py
https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/client.py#L690-L737
def alter_retention_policy(self, name, database=None, duration=None, replication=None, default=None, shard_duration=None): """Modify an existing retention policy for a database. :param name: the name of the retention policy to modify ...
[ "def", "alter_retention_policy", "(", "self", ",", "name", ",", "database", "=", "None", ",", "duration", "=", "None", ",", "replication", "=", "None", ",", "default", "=", "None", ",", "shard_duration", "=", "None", ")", ":", "query_string", "=", "(", "...
Modify an existing retention policy for a database. :param name: the name of the retention policy to modify :type name: str :param database: the database for which the retention policy is modified. Defaults to current client's database :type database: str :param dura...
[ "Modify", "an", "existing", "retention", "policy", "for", "a", "database", "." ]
python
train
48.270833
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/moments.py
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/moments.py#L386-L401
def _M2_dense(X, Y, weights=None, diag_only=False): """ 2nd moment matrix using dense matrix computations. This function is encapsulated such that we can make easy modifications of the basic algorithms """ if weights is not None: if diag_only: return np.sum(weights[:, None] * X * Y...
[ "def", "_M2_dense", "(", "X", ",", "Y", ",", "weights", "=", "None", ",", "diag_only", "=", "False", ")", ":", "if", "weights", "is", "not", "None", ":", "if", "diag_only", ":", "return", "np", ".", "sum", "(", "weights", "[", ":", ",", "None", "...
2nd moment matrix using dense matrix computations. This function is encapsulated such that we can make easy modifications of the basic algorithms
[ "2nd", "moment", "matrix", "using", "dense", "matrix", "computations", "." ]
python
train
31.5
rackerlabs/lambda-uploader
lambda_uploader/package.py
https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L168-L189
def _build_new_virtualenv(self): '''Build a new virtualenvironment if self._virtualenv is set to None''' if self._virtualenv is None: # virtualenv was "None" which means "do default" self._pkg_venv = os.path.join(self._temp_workspace, 'venv') self._venv_pip = 'bin/pip...
[ "def", "_build_new_virtualenv", "(", "self", ")", ":", "if", "self", ".", "_virtualenv", "is", "None", ":", "# virtualenv was \"None\" which means \"do default\"", "self", ".", "_pkg_venv", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_temp_workspace", ...
Build a new virtualenvironment if self._virtualenv is set to None
[ "Build", "a", "new", "virtualenvironment", "if", "self", ".", "_virtualenv", "is", "set", "to", "None" ]
python
train
43.909091
wavycloud/pyboto3
pyboto3/iam.py
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/iam.py#L4244-L4413
def simulate_custom_policy(PolicyInputList=None, ActionNames=None, ResourceArns=None, ResourcePolicy=None, ResourceOwner=None, CallerArn=None, ContextEntries=None, ResourceHandlingOption=None, MaxItems=None, Marker=None): """ Simulate how a set of IAM policies and optionally a resource-based policy works with a...
[ "def", "simulate_custom_policy", "(", "PolicyInputList", "=", "None", ",", "ActionNames", "=", "None", ",", "ResourceArns", "=", "None", ",", "ResourcePolicy", "=", "None", ",", "ResourceOwner", "=", "None", ",", "CallerArn", "=", "None", ",", "ContextEntries", ...
Simulate how a set of IAM policies and optionally a resource-based policy works with a list of API actions and AWS resources to determine the policies' effective permissions. The policies are provided as strings. The simulation does not perform the API actions; it only checks the authorization to determine if the s...
[ "Simulate", "how", "a", "set", "of", "IAM", "policies", "and", "optionally", "a", "resource", "-", "based", "policy", "works", "with", "a", "list", "of", "API", "actions", "and", "AWS", "resources", "to", "determine", "the", "policies", "effective", "permiss...
python
train
71.570588
dade-ai/snipy
snipy/img/imageutil.py
https://github.com/dade-ai/snipy/blob/408520867179f99b3158b57520e2619f3fecd69b/snipy/img/imageutil.py#L461-L476
def canny(img, threshold1=255/3, threshold2=255, **kwargs): """ canny edge """ import cv2 # edges=None, apertureSize=None, L2gradient=None if img.ndim <= 3: edge = cv2.Canny(img, threshold1, threshold2, **kwargs) if edge.ndim == 2: edge = np.expand_dims(edge, 2) elif img....
[ "def", "canny", "(", "img", ",", "threshold1", "=", "255", "/", "3", ",", "threshold2", "=", "255", ",", "*", "*", "kwargs", ")", ":", "import", "cv2", "# edges=None, apertureSize=None, L2gradient=None", "if", "img", ".", "ndim", "<=", "3", ":", "edge", ...
canny edge
[ "canny", "edge" ]
python
valid
34.625
burnash/gspread
gspread/client.py
https://github.com/burnash/gspread/blob/0e8debe208095aeed3e3e7136c2fa5cd74090946/gspread/client.py#L423-L437
def remove_permission(self, file_id, permission_id): """Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str """ url = '{0}/{1}/permissions/{2...
[ "def", "remove_permission", "(", "self", ",", "file_id", ",", "permission_id", ")", ":", "url", "=", "'{0}/{1}/permissions/{2}'", ".", "format", "(", "DRIVE_FILES_API_V2_URL", ",", "file_id", ",", "permission_id", ")", "self", ".", "request", "(", "'delete'", ",...
Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str
[ "Deletes", "a", "permission", "from", "a", "file", "." ]
python
train
29.733333
pyrocat101/moo
moo/__init__.py
https://github.com/pyrocat101/moo/blob/39e86d4ecb329309260bc30876c77aa3a7a2cfb1/moo/__init__.py#L209-L229
def main(port, export, css, files): """ \b Examples: $ moo README.md # live preview README.md $ moo -e *.md # export all markdown files $ moo --no-css -e README.md # export README.md without CSS $ cat README.md | moo -e - | less # export ST...
[ "def", "main", "(", "port", ",", "export", ",", "css", ",", "files", ")", ":", "options", "=", "{", "'css'", ":", "css", ",", "'port'", ":", "port", "}", "try", ":", "if", "not", "export", ":", "if", "len", "(", "files", ")", "!=", "1", ":", ...
\b Examples: $ moo README.md # live preview README.md $ moo -e *.md # export all markdown files $ moo --no-css -e README.md # export README.md without CSS $ cat README.md | moo -e - | less # export STDIN to STDOUT
[ "\\", "b", "Examples", ":", "$", "moo", "README", ".", "md", "#", "live", "preview", "README", ".", "md", "$", "moo", "-", "e", "*", ".", "md", "#", "export", "all", "markdown", "files", "$", "moo", "--", "no", "-", "css", "-", "e", "README", "...
python
test
32.380952
bykof/billomapy
billomapy/billomapy.py
https://github.com/bykof/billomapy/blob/a28ba69fd37654fa145d0411d52c200e7f8984ab/billomapy/billomapy.py#L3876-L3888
def update_letter(self, letter_id, letter_dict): """ Updates a letter :param letter_id: the letter id :param letter_dict: dict :return: dict """ return self._create_put_request( resource=LETTERS, billomat_id=letter_id, send_dat...
[ "def", "update_letter", "(", "self", ",", "letter_id", ",", "letter_dict", ")", ":", "return", "self", ".", "_create_put_request", "(", "resource", "=", "LETTERS", ",", "billomat_id", "=", "letter_id", ",", "send_data", "=", "letter_dict", ")" ]
Updates a letter :param letter_id: the letter id :param letter_dict: dict :return: dict
[ "Updates", "a", "letter" ]
python
train
25.461538
google/grr
grr/server/grr_response_server/aff4.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4.py#L2373-L2376
def Compile(self, filter_implemention): """Returns the data_store filter implementation from the attribute.""" return self.operator_method(self.attribute_obj, filter_implemention, *self.args)
[ "def", "Compile", "(", "self", ",", "filter_implemention", ")", ":", "return", "self", ".", "operator_method", "(", "self", ".", "attribute_obj", ",", "filter_implemention", ",", "*", "self", ".", "args", ")" ]
Returns the data_store filter implementation from the attribute.
[ "Returns", "the", "data_store", "filter", "implementation", "from", "the", "attribute", "." ]
python
train
57
aliyun/aliyun-log-python-sdk
aliyun/log/consumer/shard_worker.py
https://github.com/aliyun/aliyun-log-python-sdk/blob/ac383db0a16abf1e5ef7df36074374184b43516e/aliyun/log/consumer/shard_worker.py#L188-L216
def _generate_next_task(self): """ submit consumer framework defined task :return: """ if self.consumer_status == ConsumerStatus.INITIALIZING: self.current_task_exist = True self.task_future = self.executor.submit(consumer_initialize_task, self.processor, ...
[ "def", "_generate_next_task", "(", "self", ")", ":", "if", "self", ".", "consumer_status", "==", "ConsumerStatus", ".", "INITIALIZING", ":", "self", ".", "current_task_exist", "=", "True", "self", ".", "task_future", "=", "self", ".", "executor", ".", "submit"...
submit consumer framework defined task :return:
[ "submit", "consumer", "framework", "defined", "task", ":", "return", ":" ]
python
train
53.62069
influxdata/influxdb-python
influxdb/influxdb08/client.py
https://github.com/influxdata/influxdb-python/blob/d5d12499f3755199d5eedd8b363450f1cf4073bd/influxdb/influxdb08/client.py#L839-L843
def send_packet(self, packet): """Send a UDP packet along the wire.""" data = json.dumps(packet) byte = data.encode('utf-8') self.udp_socket.sendto(byte, (self._host, self._udp_port))
[ "def", "send_packet", "(", "self", ",", "packet", ")", ":", "data", "=", "json", ".", "dumps", "(", "packet", ")", "byte", "=", "data", ".", "encode", "(", "'utf-8'", ")", "self", ".", "udp_socket", ".", "sendto", "(", "byte", ",", "(", "self", "."...
Send a UDP packet along the wire.
[ "Send", "a", "UDP", "packet", "along", "the", "wire", "." ]
python
train
42.2
spyder-ide/qtawesome
qtawesome/iconic_font.py
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L192-L250
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when acce...
[ "def", "load_font", "(", "self", ",", "prefix", ",", "ttf_filename", ",", "charmap_filename", ",", "directory", "=", "None", ")", ":", "def", "hook", "(", "obj", ")", ":", "result", "=", "{", "}", "for", "key", "in", "obj", ":", "result", "[", "key",...
Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename c...
[ "Loads", "a", "font", "file", "and", "the", "associated", "charmap", "." ]
python
train
43.915254
saltstack/salt
salt/utils/stringutils.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/stringutils.py#L513-L537
def print_cli(msg, retries=10, step=0.01): ''' Wrapper around print() that suppresses tracebacks on broken pipes (i.e. when salt output is piped to less and less is stopped prematurely). ''' while retries: try: try: print(msg) except UnicodeEncodeError...
[ "def", "print_cli", "(", "msg", ",", "retries", "=", "10", ",", "step", "=", "0.01", ")", ":", "while", "retries", ":", "try", ":", "try", ":", "print", "(", "msg", ")", "except", "UnicodeEncodeError", ":", "print", "(", "msg", ".", "encode", "(", ...
Wrapper around print() that suppresses tracebacks on broken pipes (i.e. when salt output is piped to less and less is stopped prematurely).
[ "Wrapper", "around", "print", "()", "that", "suppresses", "tracebacks", "on", "broken", "pipes", "(", "i", ".", "e", ".", "when", "salt", "output", "is", "piped", "to", "less", "and", "less", "is", "stopped", "prematurely", ")", "." ]
python
train
31.56
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_common_def.py#L447-L458
def ip_hide_ext_community_list_holder_extcommunity_list_extcommunity_list_num(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") hide_ext_community_list_holder = ET.SubElement...
[ "def", "ip_hide_ext_community_list_holder_extcommunity_list_extcommunity_list_num", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ip", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ip\"", ","...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
62
9seconds/pep3134
pep3134/py3.py
https://github.com/9seconds/pep3134/blob/6b6fae903bb63cb2ac24004bb2c18ebc6a7d41d0/pep3134/py3.py#L22-L35
def raise_(type_, value=None, traceback=None): # pylint: disable=W0613 """ Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is...
[ "def", "raise_", "(", "type_", ",", "value", "=", "None", ",", "traceback", "=", "None", ")", ":", "# pylint: disable=W0613", "if", "type_", ".", "__traceback__", "is", "not", "traceback", ":", "raise", "type_", ".", "with_traceback", "(", "traceback", ")", ...
Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty carefull with tracebacks. If it is possible, use sys.exc_info...
[ "Does", "the", "same", "as", "ordinary", "raise", "with", "arguments", "do", "in", "Python", "2", ".", "But", "works", "in", "Python", "3", "(", ">", "=", "3", ".", "3", ")", "also!" ]
python
train
40.428571
O365/python-o365
O365/excel.py
https://github.com/O365/python-o365/blob/02a71cf3775cc6a3c042e003365d6a07c8c75a73/O365/excel.py#L1605-L1611
def get_cell(self, row, column): """ Gets the range object containing the single cell based on row and column numbers. """ url = self.build_url(self._endpoints.get('get_cell').format(row=row, column=column)) response = self.session.get(url) if not response: return None ...
[ "def", "get_cell", "(", "self", ",", "row", ",", "column", ")", ":", "url", "=", "self", ".", "build_url", "(", "self", ".", "_endpoints", ".", "get", "(", "'get_cell'", ")", ".", "format", "(", "row", "=", "row", ",", "column", "=", "column", ")",...
Gets the range object containing the single cell based on row and column numbers.
[ "Gets", "the", "range", "object", "containing", "the", "single", "cell", "based", "on", "row", "and", "column", "numbers", "." ]
python
train
57.285714
hyperledger/sawtooth-core
validator/sawtooth_validator/gossip/permission_verifier.py
https://github.com/hyperledger/sawtooth-core/blob/8cf473bc2207e51f02bd182d825158a57d72b098/validator/sawtooth_validator/gossip/permission_verifier.py#L465-L489
def get_role(self, item, state_root, from_state=False): """ Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value shoul...
[ "def", "get_role", "(", "self", ",", "item", ",", "state_root", ",", "from_state", "=", "False", ")", ":", "if", "from_state", ":", "# if from state use identity_view and do not add to cache", "if", "self", ".", "_identity_view", "is", "None", ":", "self", ".", ...
Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value should be read directly from state, instead of using the cached v...
[ "Used", "to", "retrieve", "an", "identity", "role", ".", "Args", ":", "item", "(", "string", ")", ":", "the", "name", "of", "the", "role", "to", "be", "fetched", "state_root", "(", "string", ")", ":", "The", "state", "root", "of", "the", "previous", ...
python
train
41.4
Chilipp/psyplot
psyplot/data.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/data.py#L416-L524
def get_filename_ds(ds, dump=True, paths=None, **kwargs): """ Return the filename of the corresponding to a dataset This method returns the path to the `ds` or saves the dataset if there exists no filename Parameters ---------- ds: xarray.Dataset The dataset you want the path infor...
[ "def", "get_filename_ds", "(", "ds", ",", "dump", "=", "True", ",", "paths", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "tempfile", "import", "NamedTemporaryFile", "# if already specified, return that filename", "if", "ds", ".", "psy", ".", "_file...
Return the filename of the corresponding to a dataset This method returns the path to the `ds` or saves the dataset if there exists no filename Parameters ---------- ds: xarray.Dataset The dataset you want the path information for dump: bool If True and the dataset has not been...
[ "Return", "the", "filename", "of", "the", "corresponding", "to", "a", "dataset" ]
python
train
34.366972
juju/charm-helpers
charmhelpers/core/hookenv.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L692-L705
def role_and_interface_to_relations(role, interface_name): """ Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A list of relation names. """ ...
[ "def", "role_and_interface_to_relations", "(", "role", ",", "interface_name", ")", ":", "_metadata", "=", "metadata", "(", ")", "results", "=", "[", "]", "for", "relation_name", ",", "relation", "in", "_metadata", ".", "get", "(", "role", ",", "{", "}", ")...
Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A list of relation names.
[ "Given", "a", "role", "and", "interface", "name", "return", "a", "list", "of", "relation", "names", "for", "the", "current", "charm", "that", "use", "that", "interface", "under", "that", "role", "(", "where", "role", "is", "one", "of", "provides", "require...
python
train
37.928571
hackthefed/govtrack2csv
govtrack2csv/__init__.py
https://github.com/hackthefed/govtrack2csv/blob/db991f5fcd3dfda6e6d51fadd286cba983f493e5/govtrack2csv/__init__.py#L580-L594
def lis_to_bio_map(folder): """ Senators have a lis_id that is used in some places. That's dumb. Build a dict from lis_id to bioguide_id which every member of congress has. """ logger.info("Opening legislator csv for lis_dct creation") lis_dic = {} leg_path = "{0}/legislators.csv".format(fol...
[ "def", "lis_to_bio_map", "(", "folder", ")", ":", "logger", ".", "info", "(", "\"Opening legislator csv for lis_dct creation\"", ")", "lis_dic", "=", "{", "}", "leg_path", "=", "\"{0}/legislators.csv\"", ".", "format", "(", "folder", ")", "logger", ".", "info", ...
Senators have a lis_id that is used in some places. That's dumb. Build a dict from lis_id to bioguide_id which every member of congress has.
[ "Senators", "have", "a", "lis_id", "that", "is", "used", "in", "some", "places", ".", "That", "s", "dumb", ".", "Build", "a", "dict", "from", "lis_id", "to", "bioguide_id", "which", "every", "member", "of", "congress", "has", "." ]
python
train
35.666667
pypa/pipenv
pipenv/vendor/vistir/spin.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/vistir/spin.py#L227-L234
def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # Do not display spin text for ok state self._text = None _text = to_text(text) if text else u"OK" err = err or not self.write_to_stdout self._freeze(_text, err=err)
[ "def", "ok", "(", "self", ",", "text", "=", "u\"OK\"", ",", "err", "=", "False", ")", ":", "# Do not display spin text for ok state", "self", ".", "_text", "=", "None", "_text", "=", "to_text", "(", "text", ")", "if", "text", "else", "u\"OK\"", "err", "=...
Set Ok (success) finalizer to a spinner.
[ "Set", "Ok", "(", "success", ")", "finalizer", "to", "a", "spinner", "." ]
python
train
36.375
datadesk/python-documentcloud
documentcloud/MultipartPostHandler.py
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/MultipartPostHandler.py#L201-L210
def getsize(o_file): """ get the size, either by seeeking to the end. """ startpos = o_file.tell() o_file.seek(0) o_file.seek(0, SEEK_END) size = o_file.tell() o_file.seek(startpos) return size
[ "def", "getsize", "(", "o_file", ")", ":", "startpos", "=", "o_file", ".", "tell", "(", ")", "o_file", ".", "seek", "(", "0", ")", "o_file", ".", "seek", "(", "0", ",", "SEEK_END", ")", "size", "=", "o_file", ".", "tell", "(", ")", "o_file", ".",...
get the size, either by seeeking to the end.
[ "get", "the", "size", "either", "by", "seeeking", "to", "the", "end", "." ]
python
train
22
ihabunek/toot
toot/wcstring.py
https://github.com/ihabunek/toot/blob/d13fa8685b300f96621fa325774913ec0f413a7f/toot/wcstring.py#L33-L66
def wc_wrap(text, length): """ Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation. """ line_words = [] line_len = 0 words = re....
[ "def", "wc_wrap", "(", "text", ",", "length", ")", ":", "line_words", "=", "[", "]", "line_len", "=", "0", "words", "=", "re", ".", "split", "(", "r\"\\s+\"", ",", "text", ".", "strip", "(", ")", ")", "for", "word", "in", "words", ":", "word_len", ...
Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation.
[ "Wrap", "text", "to", "given", "length", "breaking", "on", "whitespace", "and", "taking", "into", "account", "character", "width", "." ]
python
train
27.705882
pandas-dev/pandas
pandas/core/missing.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/missing.py#L631-L657
def dispatch_missing(op, left, right, result): """ Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) ...
[ "def", "dispatch_missing", "(", "op", ",", "left", ",", "right", ",", "result", ")", ":", "opstr", "=", "'__{opname}__'", ".", "format", "(", "opname", "=", "op", ".", "__name__", ")", ".", "replace", "(", "'____'", ",", "'__'", ")", "if", "op", "in"...
Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) result : ndarray Returns ------- result : ...
[ "Fill", "nulls", "caused", "by", "division", "by", "zero", "casting", "to", "a", "diffferent", "dtype", "if", "necessary", "." ]
python
train
32.814815
Becksteinlab/GromacsWrapper
gromacs/fileformats/xvg.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/xvg.py#L469-L537
def parse(self, stride=None): """Read and cache the file as a numpy array. Store every *stride* line of data; if ``None`` then the class default is used. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1...
[ "def", "parse", "(", "self", ",", "stride", "=", "None", ")", ":", "if", "stride", "is", "None", ":", "stride", "=", "self", ".", "stride", "self", ".", "corrupted_lineno", "=", "[", "]", "irow", "=", "0", "# count rows of data", "# cannot use numpy.loadtx...
Read and cache the file as a numpy array. Store every *stride* line of data; if ``None`` then the class default is used. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .
[ "Read", "and", "cache", "the", "file", "as", "a", "numpy", "array", "." ]
python
valid
51.275362
bprinty/gems
gems/decorators.py
https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/decorators.py#L19-L67
def require(method): """ Decorator for managing chained dependencies of different class properties. The @require decorator allows developers to specify that a function call must be operated on before another property or function call is accessed, so that data and processing for an entire class c...
[ "def", "require", "(", "method", ")", ":", "def", "decorator", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# throw exception if input class doesn't have requirement", "if", ...
Decorator for managing chained dependencies of different class properties. The @require decorator allows developers to specify that a function call must be operated on before another property or function call is accessed, so that data and processing for an entire class can be evaluated in a lazy way (i....
[ "Decorator", "for", "managing", "chained", "dependencies", "of", "different", "class", "properties", ".", "The", "@require", "decorator", "allows", "developers", "to", "specify", "that", "a", "function", "call", "must", "be", "operated", "on", "before", "another",...
python
valid
32.061224
Calysto/calysto
calysto/ai/conx.py
https://github.com/Calysto/calysto/blob/20813c0f48096317aa775d03a5c6b20f12fafc93/calysto/ai/conx.py#L2833-L2837
def saveNetwork(self, filename, makeWrapper = 1, mode = "pickle", counter = None): """ Saves network to file using pickle. """ self.saveNetworkToFile(filename, makeWrapper, mode, counter)
[ "def", "saveNetwork", "(", "self", ",", "filename", ",", "makeWrapper", "=", "1", ",", "mode", "=", "\"pickle\"", ",", "counter", "=", "None", ")", ":", "self", ".", "saveNetworkToFile", "(", "filename", ",", "makeWrapper", ",", "mode", ",", "counter", "...
Saves network to file using pickle.
[ "Saves", "network", "to", "file", "using", "pickle", "." ]
python
train
43
thomasjiangcy/django-rest-mock
rest_mock_server/builder.py
https://github.com/thomasjiangcy/django-rest-mock/blob/09e91de20d1a5efd5c47c6e3d7fe979443012e2c/rest_mock_server/builder.py#L177-L245
def build(port=8000, fixtures=None): """ Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file """ extractor = Extractor() parser = Par...
[ "def", "build", "(", "port", "=", "8000", ",", "fixtures", "=", "None", ")", ":", "extractor", "=", "Extractor", "(", ")", "parser", "=", "Parser", "(", "extractor", ".", "url_details", ",", "fixtures", ")", "parser", ".", "parse", "(", ")", "url_detai...
Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file
[ "Builds", "a", "server", "file", "." ]
python
train
43.681159
flukso/tmpo-py
tmpo/__init__.py
https://github.com/flukso/tmpo-py/blob/3c99e3d123bc985a6fba2558922b29430d2a0a94/tmpo/__init__.py#L142-L175
def dbcon(func): """Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.""" @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.dbcon is None: # set up connection self.dbco...
[ "def", "dbcon", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "if", "self", ".", "dbcon", "is", "None", ":", "# set up connection"...
Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.
[ "Set", "up", "connection", "before", "executing", "function", "commit", "and", "close", "connection", "afterwards", ".", "Unless", "a", "connection", "already", "has", "been", "created", "." ]
python
train
34.411765
pyblish/pyblish-qml
pyblish_qml/control.py
https://github.com/pyblish/pyblish-qml/blob/6095d18b2ec0afd0409a9b1a17e53b0658887283/pyblish_qml/control.py#L141-L290
def setup_statemachine(self): """Setup and start state machine""" machine = QtCore.QStateMachine() # _______________ # | | # | | # | | # |_______________| # group = util.QState("group", QtCore.QState.Par...
[ "def", "setup_statemachine", "(", "self", ")", ":", "machine", "=", "QtCore", ".", "QStateMachine", "(", ")", "# _______________", "# | |", "# | |", "# | |", "# |_______________|", "#", "group", "=", "util", ".", "QState", "(...
Setup and start state machine
[ "Setup", "and", "start", "state", "machine" ]
python
train
33.013333
cloudera/impyla
impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py
https://github.com/cloudera/impyla/blob/547fa2ba3b6151e2a98b3544301471a643212dc3/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L4758-L4766
def delete_table_column_statistics(self, db_name, tbl_name, col_name): """ Parameters: - db_name - tbl_name - col_name """ self.send_delete_table_column_statistics(db_name, tbl_name, col_name) return self.recv_delete_table_column_statistics()
[ "def", "delete_table_column_statistics", "(", "self", ",", "db_name", ",", "tbl_name", ",", "col_name", ")", ":", "self", ".", "send_delete_table_column_statistics", "(", "db_name", ",", "tbl_name", ",", "col_name", ")", "return", "self", ".", "recv_delete_table_col...
Parameters: - db_name - tbl_name - col_name
[ "Parameters", ":", "-", "db_name", "-", "tbl_name", "-", "col_name" ]
python
train
29.888889
bsolomon1124/pyfinance
pyfinance/returns.py
https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/returns.py#L1065-L1104
def up_capture(self, benchmark, threshold=0.0, compare_op="ge"): """Upside capture ratio. Measures the performance of `self` relative to benchmark conditioned on periods where `benchmark` is gt or ge to `threshold`. Upside capture ratios are calculated by taking the fund's ...
[ "def", "up_capture", "(", "self", ",", "benchmark", ",", "threshold", "=", "0.0", ",", "compare_op", "=", "\"ge\"", ")", ":", "slf", ",", "bm", "=", "self", ".", "upmarket_filter", "(", "benchmark", "=", "benchmark", ",", "threshold", "=", "threshold", "...
Upside capture ratio. Measures the performance of `self` relative to benchmark conditioned on periods where `benchmark` is gt or ge to `threshold`. Upside capture ratios are calculated by taking the fund's monthly return during the periods of positive benchmark performa...
[ "Upside", "capture", "ratio", "." ]
python
train
33.875
b3j0f/annotation
b3j0f/annotation/core.py
https://github.com/b3j0f/annotation/blob/738035a974e4092696d9dc1bbd149faa21c8c51f/b3j0f/annotation/core.py#L624-L651
def get_annotated_fields(cls, instance, select=lambda *p: True): """Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict """ result = {} for _, member in getmembers(instance): ...
[ "def", "get_annotated_fields", "(", "cls", ",", "instance", ",", "select", "=", "lambda", "*", "p", ":", "True", ")", ":", "result", "=", "{", "}", "for", "_", ",", "member", "in", "getmembers", "(", "instance", ")", ":", "try", ":", "annotations", "...
Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict
[ "Get", "dict", "of", "{", "annotated", "fields", ":", "annotations", "}", "by", "cls", "of", "input", "instance", "." ]
python
train
26.142857
ambitioninc/django-entity
entity/models.py
https://github.com/ambitioninc/django-entity/blob/ebc61f34313c52f4ef5819eb1da25b2ad837e80c/entity/models.py#L108-L126
def is_sub_to_all_kinds(self, *super_entity_kinds): """ Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds """ if super_entity_kinds: if len(super_entity_kinds) == 1: # Optimize for the case of just one ...
[ "def", "is_sub_to_all_kinds", "(", "self", ",", "*", "super_entity_kinds", ")", ":", "if", "super_entity_kinds", ":", "if", "len", "(", "super_entity_kinds", ")", "==", "1", ":", "# Optimize for the case of just one", "has_subset", "=", "EntityRelationship", ".", "o...
Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds
[ "Each", "returned", "entity", "will", "have", "superentites", "whos", "combined", "entity_kinds", "included", "*", "super_entity_kinds" ]
python
train
51.263158
jaraco/jaraco.mongodb
jaraco/mongodb/helper.py
https://github.com/jaraco/jaraco.mongodb/blob/280f17894941f4babf2e97db033dbb1fd2b9f705/jaraco/mongodb/helper.py#L18-L24
def connect(uri, factory=pymongo.MongoClient): """ Use the factory to establish a connection to uri. """ warnings.warn( "do not use. Just call MongoClient directly.", DeprecationWarning) return factory(uri)
[ "def", "connect", "(", "uri", ",", "factory", "=", "pymongo", ".", "MongoClient", ")", ":", "warnings", ".", "warn", "(", "\"do not use. Just call MongoClient directly.\"", ",", "DeprecationWarning", ")", "return", "factory", "(", "uri", ")" ]
Use the factory to establish a connection to uri.
[ "Use", "the", "factory", "to", "establish", "a", "connection", "to", "uri", "." ]
python
train
32.571429
CivicSpleen/ambry
ambry/util/__init__.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/util/__init__.py#L1347-L1379
def delete_module(modname, paranoid=None): """ Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return: """ from sys import modules try: thismod = modules[modname] except KeyError: raise ValueError(modname) these_symbols = dir(thism...
[ "def", "delete_module", "(", "modname", ",", "paranoid", "=", "None", ")", ":", "from", "sys", "import", "modules", "try", ":", "thismod", "=", "modules", "[", "modname", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "modname", ")", "these_sy...
Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return:
[ "Delete", "a", "module", ".", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "1668289", ":", "param", "modname", ":", ":", "param", "paranoid", ":", ":", "return", ":" ]
python
train
28.515152
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/io/image.py
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/io/image.py#L17-L98
def _make_png(data, level=6): """Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 control...
[ "def", "_make_png", "(", "data", ",", "level", "=", "6", ")", ":", "# Eventually we might want to use ext/png.py for this, but this", "# routine *should* be faster b/c it's speacialized for our use case", "def", "mkchunk", "(", "data", ",", "name", ")", ":", "if", "isinstan...
Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 controlling the level of compression: ...
[ "Convert", "numpy", "array", "to", "PNG", "byte", "array", "." ]
python
train
30.914634
mcs07/ChemDataExtractor
chemdataextractor/scrape/entity.py
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/entity.py#L102-L118
def serialize(self): """Convert Entity to python dictionary.""" # Serialize fields to a dict data = {} for field_name in self: value = self._values.get(field_name) field = self.fields.get(field_name) if value is not None: if field.all: ...
[ "def", "serialize", "(", "self", ")", ":", "# Serialize fields to a dict", "data", "=", "{", "}", "for", "field_name", "in", "self", ":", "value", "=", "self", ".", "_values", ".", "get", "(", "field_name", ")", "field", "=", "self", ".", "fields", ".", ...
Convert Entity to python dictionary.
[ "Convert", "Entity", "to", "python", "dictionary", "." ]
python
train
40
welbornprod/colr
colr/colr.py
https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/colr.py#L408-L427
def get_code_num(s: str) -> Optional[int]: """ Get code number from an escape code. Raises InvalidEscapeCode if an invalid number is found. """ if ';' in s: # Extended fore/back codes. numberstr = s.rpartition(';')[-1][:-1] else: # Fore, back, style, codes. number...
[ "def", "get_code_num", "(", "s", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "if", "';'", "in", "s", ":", "# Extended fore/back codes.", "numberstr", "=", "s", ".", "rpartition", "(", "';'", ")", "[", "-", "1", "]", "[", ":", "-", "1",...
Get code number from an escape code. Raises InvalidEscapeCode if an invalid number is found.
[ "Get", "code", "number", "from", "an", "escape", "code", ".", "Raises", "InvalidEscapeCode", "if", "an", "invalid", "number", "is", "found", "." ]
python
train
26.15
vistoyn/python-foruse
foruse/lib.py
https://github.com/vistoyn/python-foruse/blob/312588d25ac391aa7b3325b7cb4c8f8188b559c7/foruse/lib.py#L427-L438
def var_dump(*obs): """ shows structured information of a object, list, tuple etc """ i = 0 for x in obs: str = var_dump_output(x, 0, ' ', '\n', True) print (str.strip()) #dump(x, 0, i, '', object) i += 1
[ "def", "var_dump", "(", "*", "obs", ")", ":", "i", "=", "0", "for", "x", "in", "obs", ":", "str", "=", "var_dump_output", "(", "x", ",", "0", ",", "' '", ",", "'\\n'", ",", "True", ")", "print", "(", "str", ".", "strip", "(", ")", ")", "#dum...
shows structured information of a object, list, tuple etc
[ "shows", "structured", "information", "of", "a", "object", "list", "tuple", "etc" ]
python
train
17.916667
quantopian/zipline
zipline/utils/range.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/range.py#L179-L212
def maybe_from_tuple(tup_or_range): """Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range...
[ "def", "maybe_from_tuple", "(", "tup_or_range", ")", ":", "if", "isinstance", "(", "tup_or_range", ",", "tuple", ")", ":", "return", "from_tuple", "(", "tup_or_range", ")", "elif", "isinstance", "(", "tup_or_range", ",", "range", ")", ":", "return", "tup_or_ra...
Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range : tuple or range A tuple to pass t...
[ "Convert", "a", "tuple", "into", "a", "range", "but", "pass", "ranges", "through", "silently", "." ]
python
train
28.294118
keenlabs/KeenClient-Python
keen/Padding.py
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/Padding.py#L186-L192
def appendSpacePadding(str, blocksize=AES_blocksize): 'Pad with spaces' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
[ "def", "appendSpacePadding", "(", "str", ",", "blocksize", "=", "AES_blocksize", ")", ":", "pad_len", "=", "paddingLength", "(", "len", "(", "str", ")", ",", "blocksize", ")", "padding", "=", "'\\0'", "*", "pad_len", "return", "str", "+", "padding" ]
Pad with spaces
[ "Pad", "with", "spaces" ]
python
train
24.571429
gawel/irc3
irc3/base.py
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/base.py#L373-L392
def from_config(cls, cfg, **kwargs): """return an instance configured with the ``cfg`` dict""" cfg = dict(cfg, **kwargs) pythonpath = cfg.get('pythonpath', []) if 'here' in cfg: pythonpath.append(cfg['here']) for path in pythonpath: sys.path.append(os.path...
[ "def", "from_config", "(", "cls", ",", "cfg", ",", "*", "*", "kwargs", ")", ":", "cfg", "=", "dict", "(", "cfg", ",", "*", "*", "kwargs", ")", "pythonpath", "=", "cfg", ".", "get", "(", "'pythonpath'", ",", "[", "]", ")", "if", "'here'", "in", ...
return an instance configured with the ``cfg`` dict
[ "return", "an", "instance", "configured", "with", "the", "cfg", "dict" ]
python
train
41
mikicz/arca
arca/_arca.py
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/_arca.py#L442-L457
def validate_depth(self, depth: DepthDefinitionType) -> Optional[int]: """ Converts the depth to int and validates that the value can be used. :raise ValueError: If the provided depth is not valid """ if depth is not None: try: depth = int(depth) ...
[ "def", "validate_depth", "(", "self", ",", "depth", ":", "DepthDefinitionType", ")", "->", "Optional", "[", "int", "]", ":", "if", "depth", "is", "not", "None", ":", "try", ":", "depth", "=", "int", "(", "depth", ")", "except", "ValueError", ":", "rais...
Converts the depth to int and validates that the value can be used. :raise ValueError: If the provided depth is not valid
[ "Converts", "the", "depth", "to", "int", "and", "validates", "that", "the", "value", "can", "be", "used", "." ]
python
train
34.5625
pyvisa/pyvisa-sim
pyvisa-sim/devices.py
https://github.com/pyvisa/pyvisa-sim/blob/9836166b6b57c165fc63a276f87fe81f106a4e26/pyvisa-sim/devices.py#L252-L260
def read(self): """Return a single byte from the output buffer """ if self._output_buffer: b, self._output_buffer = (self._output_buffer[0:1], self._output_buffer[1:]) return b return b''
[ "def", "read", "(", "self", ")", ":", "if", "self", ".", "_output_buffer", ":", "b", ",", "self", ".", "_output_buffer", "=", "(", "self", ".", "_output_buffer", "[", "0", ":", "1", "]", ",", "self", ".", "_output_buffer", "[", "1", ":", "]", ")", ...
Return a single byte from the output buffer
[ "Return", "a", "single", "byte", "from", "the", "output", "buffer" ]
python
train
30.444444
matgrioni/betacode
betacode/conv.py
https://github.com/matgrioni/betacode/blob/2f8b439c0de9cdf451b0b390161752cac9879137/betacode/conv.py#L97-L147
def beta_to_uni(text, strict=False): """ Converts the given text from betacode to unicode. Args: text: The beta code text to convert. All of this text must be betacode. strict: Flag to allow for flexible diacritic order on input. Returns: The converted text. """ # Check if the requ...
[ "def", "beta_to_uni", "(", "text", ",", "strict", "=", "False", ")", ":", "# Check if the requested configuration for conversion already has a trie", "# stored otherwise convert it.", "param_key", "=", "(", "strict", ",", ")", "try", ":", "t", "=", "_BETA_CONVERSION_TRIES...
Converts the given text from betacode to unicode. Args: text: The beta code text to convert. All of this text must be betacode. strict: Flag to allow for flexible diacritic order on input. Returns: The converted text.
[ "Converts", "the", "given", "text", "from", "betacode", "to", "unicode", "." ]
python
train
30.529412
caspervg/pylex
src/pylex/user.py
https://github.com/caspervg/pylex/blob/bae00c705b5331b0f784d42b27e19dc3541e1b5a/src/pylex/user.py#L59-L68
def activate(self, key): """ Activates a new registree on the LEX with given activation key :rtype: None """ url = self._base + 'user/activate' r = requests.get(url, params={ 'activation_key': key }) r.raise_for_status()
[ "def", "activate", "(", "self", ",", "key", ")", ":", "url", "=", "self", ".", "_base", "+", "'user/activate'", "r", "=", "requests", ".", "get", "(", "url", ",", "params", "=", "{", "'activation_key'", ":", "key", "}", ")", "r", ".", "raise_for_stat...
Activates a new registree on the LEX with given activation key :rtype: None
[ "Activates", "a", "new", "registree", "on", "the", "LEX", "with", "given", "activation", "key", ":", "rtype", ":", "None" ]
python
train
28.7
google/gin-config
gin/config_parser.py
https://github.com/google/gin-config/blob/17a170e0a6711005d1c78e67cf493dc44674d44f/gin/config_parser.py#L388-L415
def _maybe_parse_basic_type(self): """Try to parse a basic type (str, bool, number).""" token_value = '' # Allow a leading dash to handle negative numbers. if self._current_token.value == '-': token_value += self._current_token.value self._advance() basic_type_tokens = [tokenize.NAME, t...
[ "def", "_maybe_parse_basic_type", "(", "self", ")", ":", "token_value", "=", "''", "# Allow a leading dash to handle negative numbers.", "if", "self", ".", "_current_token", ".", "value", "==", "'-'", ":", "token_value", "+=", "self", ".", "_current_token", ".", "va...
Try to parse a basic type (str, bool, number).
[ "Try", "to", "parse", "a", "basic", "type", "(", "str", "bool", "number", ")", "." ]
python
test
35.178571
google/tangent
tangent/annotate.py
https://github.com/google/tangent/blob/6533e83af09de7345d1b438512679992f080dcc9/tangent/annotate.py#L83-L111
def resolve_calls(func): """Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarly, functions defined inside of the func...
[ "def", "resolve_calls", "(", "func", ")", ":", "node", "=", "quoting", ".", "parse_function", "(", "func", ")", "ResolveCalls", "(", "func", ")", ".", "visit", "(", "node", ")", "return", "node" ]
Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarly, functions defined inside of the function that we are trying to r...
[ "Parse", "a", "function", "into", "an", "AST", "with", "function", "calls", "resolved", "." ]
python
train
35.103448
what-studio/gauge
recipes/namedgauge.py
https://github.com/what-studio/gauge/blob/4624602c87c9287de1a8a0bcb2a68f827af49ccb/recipes/namedgauge.py#L67-L85
def update_momentum_by_name(self, name, **kwargs): """Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new value ...
[ "def", "update_momentum_by_name", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "momentum", "=", "self", ".", "pop_momentum_by_name", "(", "name", ")", "velocity", ",", "since", ",", "until", "=", "momentum", "[", ":", "3", "]", "velocity"...
Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new value for `until`. :returns: a momentum updated. :...
[ "Updates", "a", "momentum", "by", "the", "given", "name", "." ]
python
train
40.894737
saltstack/salt
salt/modules/boto3_route53.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto3_route53.py#L465-L567
def associate_vpc_with_hosted_zone(HostedZoneId=None, Name=None, VPCId=None, VPCName=None, VPCRegion=None, Comment=None, region=None, key=None, keyid=None, profile=None): ''' Associates an Amazon VPC with a private hosted zone. To perfor...
[ "def", "associate_vpc_with_hosted_zone", "(", "HostedZoneId", "=", "None", ",", "Name", "=", "None", ",", "VPCId", "=", "None", ",", "VPCName", "=", "None", ",", "VPCRegion", "=", "None", ",", "Comment", "=", "None", ",", "region", "=", "None", ",", "key...
Associates an Amazon VPC with a private hosted zone. To perform the association, the VPC and the private hosted zone must already exist. You can't convert a public hosted zone into a private hosted zone. If you want to associate a VPC from one AWS account with a zone from a another, the AWS account owning...
[ "Associates", "an", "Amazon", "VPC", "with", "a", "private", "hosted", "zone", "." ]
python
train
46.669903
sethmlarson/virtualbox-python
virtualbox/library.py
https://github.com/sethmlarson/virtualbox-python/blob/706c8e3f6e3aee17eb06458e73cbb4bc2d37878b/virtualbox/library.py#L13880-L13892
def get_usb_controller_count_by_type(self, type_p): """Returns the number of USB controllers of the given type attached to the VM. in type_p of type :class:`USBControllerType` return controllers of type int """ if not isinstance(type_p, USBControllerType): raise Ty...
[ "def", "get_usb_controller_count_by_type", "(", "self", ",", "type_p", ")", ":", "if", "not", "isinstance", "(", "type_p", ",", "USBControllerType", ")", ":", "raise", "TypeError", "(", "\"type_p can only be an instance of type USBControllerType\"", ")", "controllers", ...
Returns the number of USB controllers of the given type attached to the VM. in type_p of type :class:`USBControllerType` return controllers of type int
[ "Returns", "the", "number", "of", "USB", "controllers", "of", "the", "given", "type", "attached", "to", "the", "VM", "." ]
python
train
38.615385
Azure/azure-cli-extensions
src/interactive/azext_interactive/azclishell/app.py
https://github.com/Azure/azure-cli-extensions/blob/3d4854205b0f0d882f688cfa12383d14506c2e35/src/interactive/azext_interactive/azclishell/app.py#L157-L166
def handle_cd(self, cmd): """changes dir """ if len(cmd) != 2: print("Invalid syntax: cd path", file=self.output) return path = os.path.expandvars(os.path.expanduser(cmd[1])) try: os.chdir(path) except OSError as ex: print("cd: %s\n...
[ "def", "handle_cd", "(", "self", ",", "cmd", ")", ":", "if", "len", "(", "cmd", ")", "!=", "2", ":", "print", "(", "\"Invalid syntax: cd path\"", ",", "file", "=", "self", ".", "output", ")", "return", "path", "=", "os", ".", "path", ".", "expandvars...
changes dir
[ "changes", "dir" ]
python
train
33.6
lreis2415/PyGeoC
pygeoc/postTauDEM.py
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/postTauDEM.py#L167-L182
def downstream_index_dinf(dinfdir_value, i, j): """find downslope coordinate for Dinf of TauDEM Args: dinfdir_value: dinf direction value i: current row j: current col Returns: downstream (row, col)s """ down_dirs = DinfUtil.dinf_d...
[ "def", "downstream_index_dinf", "(", "dinfdir_value", ",", "i", ",", "j", ")", ":", "down_dirs", "=", "DinfUtil", ".", "dinf_downslope_direction", "(", "dinfdir_value", ")", "down_coors", "=", "[", "]", "for", "dir_code", "in", "down_dirs", ":", "row", ",", ...
find downslope coordinate for Dinf of TauDEM Args: dinfdir_value: dinf direction value i: current row j: current col Returns: downstream (row, col)s
[ "find", "downslope", "coordinate", "for", "Dinf", "of", "TauDEM", "Args", ":", "dinfdir_value", ":", "dinf", "direction", "value", "i", ":", "current", "row", "j", ":", "current", "col" ]
python
train
33
intel-analytics/BigDL
pyspark/bigdl/nn/layer.py
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L80-L115
def of(jvalue, bigdl_type="float"): """ Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer """ def get_py_name(jclass_name): if jclass_name == "StaticGraph" or jclass_name == ...
[ "def", "of", "(", "jvalue", ",", "bigdl_type", "=", "\"float\"", ")", ":", "def", "get_py_name", "(", "jclass_name", ")", ":", "if", "jclass_name", "==", "\"StaticGraph\"", "or", "jclass_name", "==", "\"DynamicGraph\"", ":", "return", "\"Model\"", "elif", "jcl...
Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer
[ "Create", "a", "Python", "Layer", "base", "on", "the", "given", "java", "value", "and", "the", "real", "type", ".", ":", "param", "jvalue", ":", "Java", "object", "create", "by", "Py4j", ":", "return", ":", "A", "Python", "Layer" ]
python
test
41.527778
sqlalchemy-redshift/sqlalchemy-redshift
sqlalchemy_redshift/commands.py
https://github.com/sqlalchemy-redshift/sqlalchemy-redshift/blob/b1a24872da0c8151aa60da4524605b6243d8d765/sqlalchemy_redshift/commands.py#L807-L842
def visit_create_library_command(element, compiler, **kw): """ Returns the actual sql query for the CreateLibraryCommand class. """ query = """ CREATE {or_replace} LIBRARY {name} LANGUAGE pythonplu FROM :location WITH CREDENTIALS AS :credentials {region} """ ...
[ "def", "visit_create_library_command", "(", "element", ",", "compiler", ",", "*", "*", "kw", ")", ":", "query", "=", "\"\"\"\n CREATE {or_replace} LIBRARY {name}\n LANGUAGE pythonplu\n FROM :location\n WITH CREDENTIALS AS :credentials\n {region}\n \"...
Returns the actual sql query for the CreateLibraryCommand class.
[ "Returns", "the", "actual", "sql", "query", "for", "the", "CreateLibraryCommand", "class", "." ]
python
train
30.111111
elehcimd/pynb
fabfile.py
https://github.com/elehcimd/pynb/blob/a32af1f0e574f880eccda4a46aede6d65151f8c9/fabfile.py#L50-L65
def git_check(): """ Check that all changes , besides versioning files, are committed :return: """ # check that changes staged for commit are pushed to origin output = local('git diff --name-only | egrep -v "^(pynb/version.py)|(version.py)$" | tr "\\n" " "', capture=True).str...
[ "def", "git_check", "(", ")", ":", "# check that changes staged for commit are pushed to origin", "output", "=", "local", "(", "'git diff --name-only | egrep -v \"^(pynb/version.py)|(version.py)$\" | tr \"\\\\n\" \" \"'", ",", "capture", "=", "True", ")", ".", "strip", "(", ")"...
Check that all changes , besides versioning files, are committed :return:
[ "Check", "that", "all", "changes", "besides", "versioning", "files", "are", "committed", ":", "return", ":" ]
python
train
39.8125
jamieleshaw/lurklib
lurklib/connection.py
https://github.com/jamieleshaw/lurklib/blob/a861f35d880140422103dd78ec3239814e85fd7e/lurklib/connection.py#L95-L188
def _init(self, server, nick, user, real_name, password, port=None, tls=True, tls_verify=True, proxy=False, proxy_type='SOCKS5', proxy_server=None, proxy_port=None, proxy_username=None, proxy_password=None): """ Connect and register with the IRC server and - ...
[ "def", "_init", "(", "self", ",", "server", ",", "nick", ",", "user", ",", "real_name", ",", "password", ",", "port", "=", "None", ",", "tls", "=", "True", ",", "tls_verify", "=", "True", ",", "proxy", "=", "False", ",", "proxy_type", "=", "'SOCKS5'"...
Connect and register with the IRC server and - set server-related information variables. Required arguments: * server - Server to connect to. * nick - Nick to use. If a tuple/list is specified it will try to use the first, and if the first is already used - ...
[ "Connect", "and", "register", "with", "the", "IRC", "server", "and", "-", "set", "server", "-", "related", "information", "variables", ".", "Required", "arguments", ":", "*", "server", "-", "Server", "to", "connect", "to", ".", "*", "nick", "-", "Nick", ...
python
train
42.744681
CityOfZion/neo-python
neo/Core/Helper.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L72-L90
def ToArray(value): """ Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: hex formatted bytes """ ms = StreamManager.GetStream() writer =...
[ "def", "ToArray", "(", "value", ")", ":", "ms", "=", "StreamManager", ".", "GetStream", "(", ")", "writer", "=", "BinaryWriter", "(", "ms", ")", "value", ".", "Serialize", "(", "writer", ")", "retVal", "=", "ms", ".", "ToArray", "(", ")", "StreamManage...
Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: hex formatted bytes
[ "Serialize", "the", "given", "value", "to", "a", "an", "array", "of", "bytes", "." ]
python
train
23.473684
Neurita/boyle
boyle/nifti/read.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/read.py#L190-L244
def _crop_img_to(image, slices, copy=True): """Crops image to a smaller size Crop img to size indicated by slices and modify the affine accordingly. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data(...
[ "def", "_crop_img_to", "(", "image", ",", "slices", ",", "copy", "=", "True", ")", ":", "img", "=", "check_img", "(", "image", ")", "data", "=", "img", ".", "get_data", "(", ")", "affine", "=", "img", ".", "get_affine", "(", ")", "cropped_data", "=",...
Crops image to a smaller size Crop img to size indicated by slices and modify the affine accordingly. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Ima...
[ "Crops", "image", "to", "a", "smaller", "size" ]
python
valid
29.981818
prawn-cake/vk-requests
vk_requests/session.py
https://github.com/prawn-cake/vk-requests/blob/dde01c1ed06f13de912506163a35d8c7e06a8f62/vk_requests/session.py#L398-L442
def make_request(self, request, captcha_response=None): """Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response """ logger.debug...
[ "def", "make_request", "(", "self", ",", "request", ",", "captcha_response", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Prepare API Method request %r'", ",", "request", ")", "response", "=", "self", ".", "_send_api_request", "(", "request", "=", "re...
Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response
[ "Make", "api", "request", "helper", "function" ]
python
train
41.755556
CitrineInformatics/pif-dft
dfttopif/parsers/vasp.py
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/vasp.py#L331-L336
def _get_bandgap_from_bands(energies, nelec): """Compute difference in conduction band min and valence band max""" nelec = int(nelec) valence = [x[nelec-1] for x in energies] conduction = [x[nelec] for x in energies] return max(min(conduction) - max(valence), 0.0)
[ "def", "_get_bandgap_from_bands", "(", "energies", ",", "nelec", ")", ":", "nelec", "=", "int", "(", "nelec", ")", "valence", "=", "[", "x", "[", "nelec", "-", "1", "]", "for", "x", "in", "energies", "]", "conduction", "=", "[", "x", "[", "nelec", ...
Compute difference in conduction band min and valence band max
[ "Compute", "difference", "in", "conduction", "band", "min", "and", "valence", "band", "max" ]
python
train
49.833333
konstantint/matplotlib-venn
matplotlib_venn/_math.py
https://github.com/konstantint/matplotlib-venn/blob/c26796c9925bdac512edf48387452fbd1848c791/matplotlib_venn/_math.py#L202-L223
def normalize_by_center_of_mass(coords, radii): ''' Given coordinates of circle centers and radii, as two arrays, returns new coordinates array, computed such that the center of mass of the three circles is (0, 0). >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 3.0]]), np.a...
[ "def", "normalize_by_center_of_mass", "(", "coords", ",", "radii", ")", ":", "# Now find the center of mass.", "radii", "=", "radii", "**", "2", "sum_r", "=", "np", ".", "sum", "(", "radii", ")", "if", "sum_r", "<", "tol", ":", "return", "coords", "else", ...
Given coordinates of circle centers and radii, as two arrays, returns new coordinates array, computed such that the center of mass of the three circles is (0, 0). >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 3.0]]), np.array([1.0, 1.0, 1.0])) array([[-1., -1.], [ 1...
[ "Given", "coordinates", "of", "circle", "centers", "and", "radii", "as", "two", "arrays", "returns", "new", "coordinates", "array", "computed", "such", "that", "the", "center", "of", "mass", "of", "the", "three", "circles", "is", "(", "0", "0", ")", "." ]
python
train
35.681818
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_netconf_ext.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_netconf_ext.py#L12-L23
def get_netconf_client_capabilities_input_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities") config = get_netconf_client_capabilities input = ET.SubElement(ge...
[ "def", "get_netconf_client_capabilities_input_session_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_netconf_client_capabilities", "=", "ET", ".", "Element", "(", "\"get_netconf_client_capabilitie...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
45.5
DataONEorg/d1_python
lib_common/src/d1_common/cert/subjects.py
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/cert/subjects.py#L32-L59
def extract_subjects(cert_pem): """Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate. Args: cert_pem: str or bytes PEM (Base64) encoded X.509 v3 certificate Returns: 2-tuple: - The primary subject string, extracted from the certificate DN. - A se...
[ "def", "extract_subjects", "(", "cert_pem", ")", ":", "primary_str", ",", "subject_info_xml", "=", "d1_common", ".", "cert", ".", "x509", ".", "extract_subjects", "(", "cert_pem", ")", "equivalent_set", "=", "{", "primary_str", ",", "d1_common", ".", "const", ...
Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate. Args: cert_pem: str or bytes PEM (Base64) encoded X.509 v3 certificate Returns: 2-tuple: - The primary subject string, extracted from the certificate DN. - A set of equivalent identities, group membe...
[ "Extract", "subjects", "from", "a", "DataONE", "PEM", "(", "Base64", ")", "encoded", "X", ".", "509", "v3", "certificate", "." ]
python
train
36.75
nkavaldj/myhdl_lib
myhdl_lib/mem.py
https://github.com/nkavaldj/myhdl_lib/blob/9902afd2031e7847373f692821b2135fd0810aa8/myhdl_lib/mem.py#L186-L190
def convert_rom(ADDR_WIDTH=8, DATA_WIDTH=8, CONTENT=(4,5,6,7)): ''' Convert ROM''' addr = Signal(intbv(0)[ADDR_WIDTH:]) dout = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(rom, addr, dout, CONTENT)
[ "def", "convert_rom", "(", "ADDR_WIDTH", "=", "8", ",", "DATA_WIDTH", "=", "8", ",", "CONTENT", "=", "(", "4", ",", "5", ",", "6", ",", "7", ")", ")", ":", "addr", "=", "Signal", "(", "intbv", "(", "0", ")", "[", "ADDR_WIDTH", ":", "]", ")", ...
Convert ROM
[ "Convert", "ROM" ]
python
train
40.8
wbond/oscrypto
oscrypto/_win/tls.py
https://github.com/wbond/oscrypto/blob/af778bf1c88bf6c4a7342f5353b130686a5bbe1c/oscrypto/_win/tls.py#L1320-L1334
def select_write(self, timeout=None): """ Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boole...
[ "def", "select_write", "(", "self", ",", "timeout", "=", "None", ")", ":", "_", ",", "write_ready", ",", "_", "=", "select", ".", "select", "(", "[", "]", ",", "[", "self", ".", "_socket", "]", ",", "[", "]", ",", "timeout", ")", "return", "len",...
Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boolean - if the socket is ready for writing. Will only be Fals...
[ "Blocks", "until", "the", "socket", "is", "ready", "to", "be", "written", "to", "or", "the", "timeout", "is", "hit" ]
python
valid
35
bokeh/bokeh
scripts/issues.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/scripts/issues.py#L92-L106
def issue_section(issue): """Returns the section heading for the issue, or None if this issue should be ignored.""" labels = issue.get('labels', []) for label in labels: if not label['name'].startswith('type: '): continue if label['name'] in LOG_SECTION: return LOG_S...
[ "def", "issue_section", "(", "issue", ")", ":", "labels", "=", "issue", ".", "get", "(", "'labels'", ",", "[", "]", ")", "for", "label", "in", "labels", ":", "if", "not", "label", "[", "'name'", "]", ".", "startswith", "(", "'type: '", ")", ":", "c...
Returns the section heading for the issue, or None if this issue should be ignored.
[ "Returns", "the", "section", "heading", "for", "the", "issue", "or", "None", "if", "this", "issue", "should", "be", "ignored", "." ]
python
train
35.733333
googleapis/google-auth-library-python
google/oauth2/service_account.py
https://github.com/googleapis/google-auth-library-python/blob/2c6ad78917e936f38f87c946209c8031166dc96e/google/oauth2/service_account.py#L285-L316
def _make_authorization_grant_assertion(self): """Create the OAuth 2.0 assertion. This assertion is used during the OAuth 2.0 grant to acquire an access token. Returns: bytes: The authorization grant assertion. """ now = _helpers.utcnow() lifetime = ...
[ "def", "_make_authorization_grant_assertion", "(", "self", ")", ":", "now", "=", "_helpers", ".", "utcnow", "(", ")", "lifetime", "=", "datetime", ".", "timedelta", "(", "seconds", "=", "_DEFAULT_TOKEN_LIFETIME_SECS", ")", "expiry", "=", "now", "+", "lifetime", ...
Create the OAuth 2.0 assertion. This assertion is used during the OAuth 2.0 grant to acquire an access token. Returns: bytes: The authorization grant assertion.
[ "Create", "the", "OAuth", "2", ".", "0", "assertion", "." ]
python
train
33.15625
neuropsychology/NeuroKit.py
neurokit/signal/complexity.py
https://github.com/neuropsychology/NeuroKit.py/blob/c9589348fbbde0fa7e986048c48f38e6b488adfe/neurokit/signal/complexity.py#L454-L528
def complexity_fd_higushi(signal, k_max): """ Computes Higuchi Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. k_max : int The maximal val...
[ "def", "complexity_fd_higushi", "(", "signal", ",", "k_max", ")", ":", "signal", "=", "np", ".", "array", "(", "signal", ")", "L", "=", "[", "]", "x", "=", "[", "]", "N", "=", "signal", ".", "size", "km_idxs", "=", "np", ".", "triu_indices", "(", ...
Computes Higuchi Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. k_max : int The maximal value of k. The point at which the FD plateaus is conside...
[ "Computes", "Higuchi", "Fractal", "Dimension", "of", "a", "signal", ".", "Based", "on", "the", "pyrem", "<https", ":", "//", "github", ".", "com", "/", "gilestrolab", "/", "pyrem", ">", "_", "repo", "by", "Quentin", "Geissmann", "." ]
python
train
34.893333
splunk/splunk-sdk-python
splunklib/binding.py
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L78-L95
def _parse_cookies(cookie_str, dictionary): """Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictiona...
[ "def", "_parse_cookies", "(", "cookie_str", ",", "dictionary", ")", ":", "parsed_cookie", "=", "six", ".", "moves", ".", "http_cookies", ".", "SimpleCookie", "(", "cookie_str", ")", "for", "cookie", "in", "parsed_cookie", ".", "values", "(", ")", ":", "dicti...
Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictionary['my'] == 'value' :param cookie_str: A strin...
[ "Tries", "to", "parse", "any", "key", "-", "value", "pairs", "of", "cookies", "in", "a", "string", "then", "updates", "the", "the", "dictionary", "with", "any", "key", "-", "value", "pairs", "found", "." ]
python
train
40.388889
googlefonts/fontbakery
Lib/fontbakery/profiles/head.py
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/head.py#L76-L100
def parse_version_string(name: str) -> Tuple[str, str]: """Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The parsed version numbers will therefore mat...
[ "def", "parse_version_string", "(", "name", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "import", "re", "# We assume \";\" is the universal delimiter here.", "version_entry", "=", "name", ".", "split", "(", "\";\"", ")", "[", "0", "]", ...
Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The parsed version numbers will therefore match in spirit, but not necessarily in string form.
[ "Parse", "a", "version", "string", "(", "name", "ID", "5", ")", "and", "return", "(", "major", "minor", ")", "strings", "." ]
python
train
39.04
tjcsl/cslbot
cslbot/commands/vote.py
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/vote.py#L25-L41
def start_poll(args): """Starts a poll.""" if args.type == 'privmsg': return "We don't have secret ballots in this benevolent dictatorship!" if not args.msg: return "Polls need a question." ctrlchan = args.config['core']['ctrlchan'] poll = Polls(question=args.msg, submitter=args.nick...
[ "def", "start_poll", "(", "args", ")", ":", "if", "args", ".", "type", "==", "'privmsg'", ":", "return", "\"We don't have secret ballots in this benevolent dictatorship!\"", "if", "not", "args", ".", "msg", ":", "return", "\"Polls need a question.\"", "ctrlchan", "=",...
Starts a poll.
[ "Starts", "a", "poll", "." ]
python
train
41.647059
DataBiosphere/dsub
dsub/lib/providers_util.py
https://github.com/DataBiosphere/dsub/blob/443ce31daa6023dc2fd65ef2051796e19d18d5a7/dsub/lib/providers_util.py#L94-L133
def build_recursive_localize_command(destination, inputs, file_provider): """Return a multi-line string with a shell script to copy recursively. Arguments: destination: Folder where to put the data. For example /mnt/data inputs: a list of InputFileParam file_provider: file provider str...
[ "def", "build_recursive_localize_command", "(", "destination", ",", "inputs", ",", "file_provider", ")", ":", "command", "=", "_LOCALIZE_COMMAND_MAP", "[", "file_provider", "]", "filtered_inputs", "=", "[", "var", "for", "var", "in", "inputs", "if", "var", ".", ...
Return a multi-line string with a shell script to copy recursively. Arguments: destination: Folder where to put the data. For example /mnt/data inputs: a list of InputFileParam file_provider: file provider string used to filter the output params; the returned command wil...
[ "Return", "a", "multi", "-", "line", "string", "with", "a", "shell", "script", "to", "copy", "recursively", "." ]
python
valid
33.125
calmjs/calmjs.parse
src/calmjs/parse/handlers/core.py
https://github.com/calmjs/calmjs.parse/blob/369f0ee346c5a84c4d5c35a7733a0e63b02eac59/src/calmjs/parse/handlers/core.py#L55-L66
def token_handler_str_default( token, dispatcher, node, subnode, sourcepath_stack=(None,)): """ Standard token handler that will return the value, ignoring any tokens or strings that have been remapped. """ if isinstance(token.pos, int): _, lineno, colno = node.getpos(subnode, token...
[ "def", "token_handler_str_default", "(", "token", ",", "dispatcher", ",", "node", ",", "subnode", ",", "sourcepath_stack", "=", "(", "None", ",", ")", ")", ":", "if", "isinstance", "(", "token", ".", "pos", ",", "int", ")", ":", "_", ",", "lineno", ","...
Standard token handler that will return the value, ignoring any tokens or strings that have been remapped.
[ "Standard", "token", "handler", "that", "will", "return", "the", "value", "ignoring", "any", "tokens", "or", "strings", "that", "have", "been", "remapped", "." ]
python
train
36.333333
cggh/scikit-allel
allel/model/ndarray.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L3632-L3663
def intersect_range(self, start=None, stop=None): """Intersect with range defined by `start` and `stop` values **inclusive**. Parameters ---------- start : int, optional Start value. stop : int, optional Stop value. Returns ------...
[ "def", "intersect_range", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "try", ":", "loc", "=", "self", ".", "locate_range", "(", "start", "=", "start", ",", "stop", "=", "stop", ")", "except", "KeyError", ":", "return",...
Intersect with range defined by `start` and `stop` values **inclusive**. Parameters ---------- start : int, optional Start value. stop : int, optional Stop value. Returns ------- idx : SortedIndex Examples -------...
[ "Intersect", "with", "range", "defined", "by", "start", "and", "stop", "values", "**", "inclusive", "**", "." ]
python
train
22.75
PMEAL/OpenPNM
openpnm/models/misc/misc.py
https://github.com/PMEAL/OpenPNM/blob/0547b5724ffedc0a593aae48639d36fe10e0baed/openpnm/models/misc/misc.py#L155-L176
def linear(target, m, b, prop): r""" Calculates a property as a linear function of a given property Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides acce...
[ "def", "linear", "(", "target", ",", "m", ",", "b", ",", "prop", ")", ":", "x", "=", "target", "[", "prop", "]", "value", "=", "m", "*", "x", "+", "b", "return", "value" ]
r""" Calculates a property as a linear function of a given property Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid pr...
[ "r", "Calculates", "a", "property", "as", "a", "linear", "function", "of", "a", "given", "property" ]
python
train
28.272727
quaddra/provision
provision/config.py
https://github.com/quaddra/provision/blob/d84dca80abb34ed93381aae4d5b8005bd08a5681/provision/config.py#L289-L296
def parser(): """Return a parser for setting one or more configuration paths""" parser = argparse.ArgumentParser() parser.add_argument('-c', '--config_paths', default=[], action='append', help='path to a configuration directory') return parser
[ "def", "parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--config_paths'", ",", "default", "=", "[", "]", ",", "action", "=", "'append'", ",", "help", "=", "'path to a ...
Return a parser for setting one or more configuration paths
[ "Return", "a", "parser", "for", "setting", "one", "or", "more", "configuration", "paths" ]
python
train
34.75
cytoscape/py2cytoscape
py2cytoscape/cyrest/layout.py
https://github.com/cytoscape/py2cytoscape/blob/dd34de8d028f512314d0057168df7fef7c5d5195/py2cytoscape/cyrest/layout.py#L64-L104
def attributes_layout(self, EdgeAttribute=None, maxwidth=None, minrad=None, \ network=None, NodeAttribute=None,nodeList=None, radmult=None, \ spacingx=None, spacingy=None, verbose=False): """ Execute the Group Attributes Layout on a network :param EdgeAttribute (string, optional): The name of the edge column ...
[ "def", "attributes_layout", "(", "self", ",", "EdgeAttribute", "=", "None", ",", "maxwidth", "=", "None", ",", "minrad", "=", "None", ",", "network", "=", "None", ",", "NodeAttribute", "=", "None", ",", "nodeList", "=", "None", ",", "radmult", "=", "None...
Execute the Group Attributes Layout on a network :param EdgeAttribute (string, optional): The name of the edge column containing numeric values that will be used as weights in the layout algorithm. Only columns containing numeric values are shown :param maxwidth (string, optional): Maximum width of a row, i...
[ "Execute", "the", "Group", "Attributes", "Layout", "on", "a", "network" ]
python
train
53.268293
cloudant/python-cloudant
src/cloudant/client.py
https://github.com/cloudant/python-cloudant/blob/e0ba190f6ba07fe3522a668747128214ad573c7e/src/cloudant/client.py#L607-L636
def _usage_endpoint(self, endpoint, year=None, month=None): """ Common helper for getting usage and billing reports with optional year and month URL elements. :param str endpoint: Cloudant usage endpoint. :param int year: Year to query against. Optional parameter. D...
[ "def", "_usage_endpoint", "(", "self", ",", "endpoint", ",", "year", "=", "None", ",", "month", "=", "None", ")", ":", "err", "=", "False", "if", "year", "is", "None", "and", "month", "is", "None", ":", "resp", "=", "self", ".", "r_session", ".", "...
Common helper for getting usage and billing reports with optional year and month URL elements. :param str endpoint: Cloudant usage endpoint. :param int year: Year to query against. Optional parameter. Defaults to None. If used, it must be accompanied by ``month``. :param i...
[ "Common", "helper", "for", "getting", "usage", "and", "billing", "reports", "with", "optional", "year", "and", "month", "URL", "elements", "." ]
python
train
39.066667
shendo/websnort
websnort/ids/snort.py
https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L47-L61
def _snort_cmd(self, pcap): """ Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :returns: list of snort command args to scan supplied pcap file """ cmdline = "'{0}' -A console -N -y -c '{1}' {2} -r '{3}'" \ .format(self.c...
[ "def", "_snort_cmd", "(", "self", ",", "pcap", ")", ":", "cmdline", "=", "\"'{0}' -A console -N -y -c '{1}' {2} -r '{3}'\"", ".", "format", "(", "self", ".", "conf", "[", "'path'", "]", ",", "self", ".", "conf", "[", "'config'", "]", ",", "self", ".", "con...
Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :returns: list of snort command args to scan supplied pcap file
[ "Given", "a", "pcap", "filename", "get", "the", "commandline", "to", "run", "." ]
python
train
40.466667
annoviko/pyclustering
pyclustering/utils/__init__.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/utils/__init__.py#L611-L647
def extract_number_oscillations(osc_dyn, index = 0, amplitude_threshold = 1.0): """! @brief Extracts number of oscillations of specified oscillator. @param[in] osc_dyn (list): Dynamic of oscillators. @param[in] index (uint): Index of oscillator in dynamic. @param[in] amplitude_threshold (...
[ "def", "extract_number_oscillations", "(", "osc_dyn", ",", "index", "=", "0", ",", "amplitude_threshold", "=", "1.0", ")", ":", "number_oscillations", "=", "0", "waiting_differential", "=", "False", "threshold_passed", "=", "False", "high_level_trigger", "=", "True"...
! @brief Extracts number of oscillations of specified oscillator. @param[in] osc_dyn (list): Dynamic of oscillators. @param[in] index (uint): Index of oscillator in dynamic. @param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example, ...
[ "!" ]
python
valid
40.432432
vaexio/vaex
packages/vaex-astro/vaex/astro/transformations.py
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-astro/vaex/astro/transformations.py#L189-L202
def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_lat="pm_b", pm_long_out="pm_ra", pm_lat_out="pm_dec", name_prefix="__proper_motion_gal2eq", right_ascension_galactic_pole=192.85, ...
[ "def", "add_virtual_columns_proper_motion_gal2eq", "(", "self", ",", "long_in", "=", "\"ra\"", ",", "lat_in", "=", "\"dec\"", ",", "pm_long", "=", "\"pm_l\"", ",", "pm_lat", "=", "\"pm_b\"", ",", "pm_long_out", "=", "\"pm_ra\"", ",", "pm_lat_out", "=", "\"pm_dec...
Transform/rotate proper motions from galactic to equatorial coordinates. Inverse of :py:`add_virtual_columns_proper_motion_eq2gal`
[ "Transform", "/", "rotate", "proper", "motions", "from", "galactic", "to", "equatorial", "coordinates", "." ]
python
test
57.642857
GetmeUK/MongoFrames
mongoframes/factory/blueprints.py
https://github.com/GetmeUK/MongoFrames/blob/7d2bd792235dfa77a9deecab5366f5f73480823d/mongoframes/factory/blueprints.py#L75-L81
def assemble(cls): """Assemble a single document using the blueprint""" document = {} for field_name, maker in cls._instructions.items(): with maker.target(document): document[field_name] = maker() return document
[ "def", "assemble", "(", "cls", ")", ":", "document", "=", "{", "}", "for", "field_name", ",", "maker", "in", "cls", ".", "_instructions", ".", "items", "(", ")", ":", "with", "maker", ".", "target", "(", "document", ")", ":", "document", "[", "field_...
Assemble a single document using the blueprint
[ "Assemble", "a", "single", "document", "using", "the", "blueprint" ]
python
train
38.142857
SuperCowPowers/workbench
workbench/clients/help_client.py
https://github.com/SuperCowPowers/workbench/blob/710232756dd717f734253315e3d0b33c9628dafb/workbench/clients/help_client.py#L5-L24
def run(): ''' This client calls a bunch of help commands from workbench ''' # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # C...
[ "def", "run", "(", ")", ":", "# Grab server args", "args", "=", "client_helper", ".", "grab_server_args", "(", ")", "# Start up workbench connection", "workbench", "=", "zerorpc", ".", "Client", "(", "timeout", "=", "300", ",", "heartbeat", "=", "60", ")", "wo...
This client calls a bunch of help commands from workbench
[ "This", "client", "calls", "a", "bunch", "of", "help", "commands", "from", "workbench" ]
python
train
29.55
StanfordVL/robosuite
robosuite/environments/base.py
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/environments/base.py#L14-L22
def make(env_name, *args, **kwargs): """Try to get the equivalent functionality of gym.make in a sloppy way.""" if env_name not in REGISTERED_ENVS: raise Exception( "Environment {} not found. Make sure it is a registered environment among: {}".format( env_name, ", ".join(REGI...
[ "def", "make", "(", "env_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "env_name", "not", "in", "REGISTERED_ENVS", ":", "raise", "Exception", "(", "\"Environment {} not found. Make sure it is a registered environment among: {}\"", ".", "format", ...
Try to get the equivalent functionality of gym.make in a sloppy way.
[ "Try", "to", "get", "the", "equivalent", "functionality", "of", "gym", ".", "make", "in", "a", "sloppy", "way", "." ]
python
train
44.666667
CalebBell/fluids
fluids/fittings.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L1589-L1630
def spiral(Di, rmax, rmin, pitch, fd): r'''Returns loss coefficient for any size constant-pitch spiral as shown in [1]_. Has applications in immersed coils in tanks. .. math:: K = \frac{r_{max} - r_{min}}{p} \left[ f\pi\left(\frac{r_{max} +r_{min}}{d}\right) + 0.20 + 4.8f\right] + \...
[ "def", "spiral", "(", "Di", ",", "rmax", ",", "rmin", ",", "pitch", ",", "fd", ")", ":", "return", "(", "rmax", "-", "rmin", ")", "/", "pitch", "*", "(", "fd", "*", "pi", "*", "(", "rmax", "+", "rmin", ")", "/", "Di", "+", "0.20", "+", "4.8...
r'''Returns loss coefficient for any size constant-pitch spiral as shown in [1]_. Has applications in immersed coils in tanks. .. math:: K = \frac{r_{max} - r_{min}}{p} \left[ f\pi\left(\frac{r_{max} +r_{min}}{d}\right) + 0.20 + 4.8f\right] + \frac{13.2f}{(r_{min}/d)^2} Parameters ...
[ "r", "Returns", "loss", "coefficient", "for", "any", "size", "constant", "-", "pitch", "spiral", "as", "shown", "in", "[", "1", "]", "_", ".", "Has", "applications", "in", "immersed", "coils", "in", "tanks", "." ]
python
train
27.619048
PyGithub/PyGithub
github/PullRequest.py
https://github.com/PyGithub/PyGithub/blob/f716df86bbe7dc276c6596699fa9712b61ef974c/github/PullRequest.py#L367-L376
def create_comment(self, body, commit_id, path, position): """ :calls: `POST /repos/:owner/:repo/pulls/:number/comments <http://developer.github.com/v3/pulls/comments>`_ :param body: string :param commit_id: :class:`github.Commit.Commit` :param path: string :param positio...
[ "def", "create_comment", "(", "self", ",", "body", ",", "commit_id", ",", "path", ",", "position", ")", ":", "return", "self", ".", "create_review_comment", "(", "body", ",", "commit_id", ",", "path", ",", "position", ")" ]
:calls: `POST /repos/:owner/:repo/pulls/:number/comments <http://developer.github.com/v3/pulls/comments>`_ :param body: string :param commit_id: :class:`github.Commit.Commit` :param path: string :param position: integer :rtype: :class:`github.PullRequestComment.PullRequestComment...
[ ":", "calls", ":", "POST", "/", "repos", "/", ":", "owner", "/", ":", "repo", "/", "pulls", "/", ":", "number", "/", "comments", "<http", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "pulls", "/", "comments", ">", "_", ":", ...
python
train
47.8
nerdvegas/rez
src/rez/packages_.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L358-L376
def get_requires(self, build_requires=False, private_build_requires=False): """Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. ...
[ "def", "get_requires", "(", "self", ",", "build_requires", "=", "False", ",", "private_build_requires", "=", "False", ")", ":", "requires", "=", "self", ".", "requires", "or", "[", "]", "if", "build_requires", ":", "requires", "=", "requires", "+", "(", "s...
Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. Returns: List of `Requirement` objects.
[ "Get", "the", "requirements", "of", "the", "variant", "." ]
python
train
33.052632
opinkerfi/nago
nago/extensions/nodes.py
https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/nodes.py#L130-L151
def connect(remote_host): """ Connect to remote host and show our status """ if remote_host in ('master', 'server'): remote_host = nago.settings.get_option('server') node = nago.core.get_node(remote_host) if not node: try: address = socket.gethostbyname(remote_host) ...
[ "def", "connect", "(", "remote_host", ")", ":", "if", "remote_host", "in", "(", "'master'", ",", "'server'", ")", ":", "remote_host", "=", "nago", ".", "settings", ".", "get_option", "(", "'server'", ")", "node", "=", "nago", ".", "core", ".", "get_node"...
Connect to remote host and show our status
[ "Connect", "to", "remote", "host", "and", "show", "our", "status" ]
python
train
43.318182
sosy-lab/benchexec
benchexec/container.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/container.py#L415-L421
def is_container_system_config_file(file): """Determine whether a given file is one of the files created by setup_container_system_config(). @param file: Absolute file path as string. """ if not file.startswith("/etc/"): return False return file in [os.path.join("/etc", f.decode()) for f in ...
[ "def", "is_container_system_config_file", "(", "file", ")", ":", "if", "not", "file", ".", "startswith", "(", "\"/etc/\"", ")", ":", "return", "False", "return", "file", "in", "[", "os", ".", "path", ".", "join", "(", "\"/etc\"", ",", "f", ".", "decode",...
Determine whether a given file is one of the files created by setup_container_system_config(). @param file: Absolute file path as string.
[ "Determine", "whether", "a", "given", "file", "is", "one", "of", "the", "files", "created", "by", "setup_container_system_config", "()", "." ]
python
train
48.857143
redcanari/canari3
src/canari/easygui.py
https://github.com/redcanari/canari3/blob/322d2bae4b49ac728229f418b786b51fcc227352/src/canari/easygui.py#L350-L447
def buttonbox(msg="",title=" " ,choices=("Button1", "Button2", "Button3") , image=None , root=None ): """ Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg...
[ "def", "buttonbox", "(", "msg", "=", "\"\"", ",", "title", "=", "\" \"", ",", "choices", "=", "(", "\"Button1\"", ",", "\"Button2\"", ",", "\"Button3\"", ")", ",", "image", "=", "None", ",", "root", "=", "None", ")", ":", "if", "sys", ".", "platform"...
Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a list or tuple of the choices to be displayed
[ "Display", "a", "msg", "a", "title", "and", "a", "set", "of", "buttons", ".", "The", "buttons", "are", "defined", "by", "the", "members", "of", "the", "choices", "list", ".", "Return", "the", "text", "of", "the", "button", "that", "the", "user", "selec...
python
train
36.408163
Yelp/kafka-utils
kafka_utils/kafka_consumer_manager/commands/offset_restore.py
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_consumer_manager/commands/offset_restore.py#L79-L137
def build_new_offsets(cls, client, topics_offset_data, topic_partitions, current_offsets): """Build complete consumer offsets from parsed current consumer-offsets and lowmarks and highmarks from current-offsets for. """ new_offsets = defaultdict(dict) try: for topic, ...
[ "def", "build_new_offsets", "(", "cls", ",", "client", ",", "topics_offset_data", ",", "topic_partitions", ",", "current_offsets", ")", ":", "new_offsets", "=", "defaultdict", "(", "dict", ")", "try", ":", "for", "topic", ",", "partitions", "in", "six", ".", ...
Build complete consumer offsets from parsed current consumer-offsets and lowmarks and highmarks from current-offsets for.
[ "Build", "complete", "consumer", "offsets", "from", "parsed", "current", "consumer", "-", "offsets", "and", "lowmarks", "and", "highmarks", "from", "current", "-", "offsets", "for", "." ]
python
train
50.576271
emre/lightsteem
lightsteem/broadcast/key_objects.py
https://github.com/emre/lightsteem/blob/0fc29a517c20d881cbdbb15b43add4bcf3af242e/lightsteem/broadcast/key_objects.py#L174-L189
def compressedpubkey(self): """ Derive uncompressed public key """ secret = unhexlify(repr(self._wif)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1).curve.generator.order() p = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1).ver...
[ "def", "compressedpubkey", "(", "self", ")", ":", "secret", "=", "unhexlify", "(", "repr", "(", "self", ".", "_wif", ")", ")", "order", "=", "ecdsa", ".", "SigningKey", ".", "from_string", "(", "secret", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")...
Derive uncompressed public key
[ "Derive", "uncompressed", "public", "key" ]
python
train
44.5
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/lxml/html/diff.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/lxml/html/diff.py#L309-L347
def split_unbalanced(chunks): """Return (unbalanced_start, balanced, unbalanced_end), where each is a list of text and tag chunks. unbalanced_start is a list of all the tags that are opened, but not closed in this span. Similarly, unbalanced_end is a list of tags that are closed but were not opene...
[ "def", "split_unbalanced", "(", "chunks", ")", ":", "start", "=", "[", "]", "end", "=", "[", "]", "tag_stack", "=", "[", "]", "balanced", "=", "[", "]", "for", "chunk", "in", "chunks", ":", "if", "not", "chunk", ".", "startswith", "(", "'<'", ")", ...
Return (unbalanced_start, balanced, unbalanced_end), where each is a list of text and tag chunks. unbalanced_start is a list of all the tags that are opened, but not closed in this span. Similarly, unbalanced_end is a list of tags that are closed but were not opened. Extracting these might mean s...
[ "Return", "(", "unbalanced_start", "balanced", "unbalanced_end", ")", "where", "each", "is", "a", "list", "of", "text", "and", "tag", "chunks", "." ]
python
test
35.512821
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/registry.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/registry.py#L429-L454
def _split_path(self, path): """ Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the ...
[ "def", "_split_path", "(", "self", ",", "path", ")", ":", "if", "'\\\\'", "in", "path", ":", "p", "=", "path", ".", "find", "(", "'\\\\'", ")", "hive", "=", "path", "[", ":", "p", "]", "path", "=", "path", "[", "p", "+", "1", ":", "]", "else"...
Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the following integer constants: - L{win...
[ "Splits", "a", "Registry", "path", "and", "returns", "the", "hive", "and", "key", "." ]
python
train
32.5
pkgw/pwkit
pwkit/dulk_models.py
https://github.com/pkgw/pwkit/blob/d40957a1c3d2ea34e7ceac2267ee9635135f2793/pwkit/dulk_models.py#L86-L89
def calc_freefree_eta(ne, t, hz): """Dulk (1985) equations 7 and 20, assuming pure hydrogen.""" kappa = calc_freefree_kappa(ne, t, hz) return kappa * cgs.k * t * hz**2 / cgs.c**2
[ "def", "calc_freefree_eta", "(", "ne", ",", "t", ",", "hz", ")", ":", "kappa", "=", "calc_freefree_kappa", "(", "ne", ",", "t", ",", "hz", ")", "return", "kappa", "*", "cgs", ".", "k", "*", "t", "*", "hz", "**", "2", "/", "cgs", ".", "c", "**",...
Dulk (1985) equations 7 and 20, assuming pure hydrogen.
[ "Dulk", "(", "1985", ")", "equations", "7", "and", "20", "assuming", "pure", "hydrogen", "." ]
python
train
46.75
spacetelescope/drizzlepac
drizzlepac/imageObject.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/imageObject.py#L929-L939
def _averageFromHeader(self, header, keyword): """ Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list. """ _list = '' for _kw in keyword.split(','): if _kw in header: _list = _list + '...
[ "def", "_averageFromHeader", "(", "self", ",", "header", ",", "keyword", ")", ":", "_list", "=", "''", "for", "_kw", "in", "keyword", ".", "split", "(", "','", ")", ":", "if", "_kw", "in", "header", ":", "_list", "=", "_list", "+", "','", "+", "str...
Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list.
[ "Averages", "out", "values", "taken", "from", "header", ".", "The", "keywords", "where", "to", "read", "values", "from", "are", "passed", "as", "a", "comma", "-", "separated", "list", "." ]
python
train
38.272727
treycucco/pyebnf
pyebnf/_hand_written_parser.py
https://github.com/treycucco/pyebnf/blob/3634ddabbe5d73508bcc20f4a591f86a46634e1d/pyebnf/_hand_written_parser.py#L76-L91
def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ alternation([ self.alpha_character, "_" ]), zero_or_more( alternation([ self.alpha_character, "...
[ "def", "identifier", "(", "self", ",", "text", ")", ":", "self", ".", "_attempting", "(", "text", ")", "return", "concatenation", "(", "[", "alternation", "(", "[", "self", ".", "alpha_character", ",", "\"_\"", "]", ")", ",", "zero_or_more", "(", "altern...
identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;
[ "identifier", "=", "alpha_character", "|", "_", ".", "{", "alpha_character", "|", "_", "|", "digit", "}", ";" ]
python
test
26.1875