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
xu2243051/easyui-menu
easyui/mixins/easyui_mixins.py
https://github.com/xu2243051/easyui-menu/blob/4da0b50cf2d3ddb0f1ec7a4da65fd3c4339f8dfb/easyui/mixins/easyui_mixins.py#L160-L167
def get_slice_end(self): """ 返回queryset切片的尾巴 """ value = None if self.easyui_page: value = self.easyui_page * self.easyui_rows return value
[ "def", "get_slice_end", "(", "self", ")", ":", "value", "=", "None", "if", "self", ".", "easyui_page", ":", "value", "=", "self", ".", "easyui_page", "*", "self", ".", "easyui_rows", "return", "value" ]
返回queryset切片的尾巴
[ "返回queryset切片的尾巴" ]
python
valid
24.125
SmokinCaterpillar/pypet
pypet/storageservice.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/storageservice.py#L2632-L2645
def _tree_create_leaf(self, name, trajectory, hdf5_group): """ Creates a new pypet leaf instance. Returns the leaf and if it is an explored parameter the length of the range. """ class_name = self._all_get_from_attrs(hdf5_group, HDF5StorageService.CLASS_NAME) # Create the inst...
[ "def", "_tree_create_leaf", "(", "self", ",", "name", ",", "trajectory", ",", "hdf5_group", ")", ":", "class_name", "=", "self", ".", "_all_get_from_attrs", "(", "hdf5_group", ",", "HDF5StorageService", ".", "CLASS_NAME", ")", "# Create the instance with the appropria...
Creates a new pypet leaf instance. Returns the leaf and if it is an explored parameter the length of the range.
[ "Creates", "a", "new", "pypet", "leaf", "instance", "." ]
python
test
36.428571
controversial/livejson
livejson.py
https://github.com/controversial/livejson/blob/91021de60903d2d8b2cfb7d8d8910bcf27ec003b/livejson.py#L19-L40
def _initfile(path, data="dict"): """Initialize an empty JSON file.""" data = {} if data.lower() == "dict" else [] # The file will need to be created if it doesn't exist if not os.path.exists(path): # The file doesn't exist # Raise exception if the directory that should contain the file doesn't...
[ "def", "_initfile", "(", "path", ",", "data", "=", "\"dict\"", ")", ":", "data", "=", "{", "}", "if", "data", ".", "lower", "(", ")", "==", "\"dict\"", "else", "[", "]", "# The file will need to be created if it doesn't exist", "if", "not", "os", ".", "pat...
Initialize an empty JSON file.
[ "Initialize", "an", "empty", "JSON", "file", "." ]
python
valid
41.045455
twisted/mantissa
xmantissa/web.py
https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/web.py#L360-L373
def renderHTTP(self, context): """ Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS. """ if getattr(self.wrappedResource, 'needsSecure', False): ...
[ "def", "renderHTTP", "(", "self", ",", "context", ")", ":", "if", "getattr", "(", "self", ".", "wrappedResource", ",", "'needsSecure'", ",", "False", ")", ":", "request", "=", "IRequest", "(", "context", ")", "url", "=", "self", ".", "urlGenerator", ".",...
Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS.
[ "Check", "to", "see", "if", "the", "wrapped", "resource", "wants", "to", "be", "rendered", "over", "HTTPS", "and", "generate", "a", "redirect", "if", "this", "is", "so", "if", "HTTPS", "is", "available", "and", "if", "the", "request", "is", "not", "alrea...
python
train
42.714286
aliyun/aliyun-odps-python-sdk
odps/ml/expr/models/base.py
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/ml/expr/models/base.py#L254-L262
def persist(self, name, project=None, drop_model=False, **kwargs): """ Persist the execution into a new model. :param name: model name :param project: name of the project :param drop_model: drop model before creation """ return super(ODPSModelExpr, self).persist(...
[ "def", "persist", "(", "self", ",", "name", ",", "project", "=", "None", ",", "drop_model", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "ODPSModelExpr", ",", "self", ")", ".", "persist", "(", "name", ",", "project", "=", ...
Persist the execution into a new model. :param name: model name :param project: name of the project :param drop_model: drop model before creation
[ "Persist", "the", "execution", "into", "a", "new", "model", "." ]
python
train
40.777778
spdx/tools-python
spdx/parsers/rdf.py
https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/parsers/rdf.py#L876-L909
def parse_creation_info(self, ci_term): """ Parse creators, created and comment. """ for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)): try: ent = self.builder.create_entity(self.doc, six.text_type(o)) self.bu...
[ "def", "parse_creation_info", "(", "self", ",", "ci_term", ")", ":", "for", "_s", ",", "_p", ",", "o", "in", "self", ".", "graph", ".", "triples", "(", "(", "ci_term", ",", "self", ".", "spdx_namespace", "[", "'creator'", "]", ",", "None", ")", ")", ...
Parse creators, created and comment.
[ "Parse", "creators", "created", "and", "comment", "." ]
python
valid
43.823529
shexSpec/grammar
parsers/python/pyshexc/parser_impl/shex_node_expression_parser.py
https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_node_expression_parser.py#L64-L67
def visitNodeConstraintValueSet(self, ctx: ShExDocParser.NodeConstraintValueSetContext): """ nodeConstraint: valueSet xsFacet* #nodeConstraintValueSet """ self.nodeconstraint.values = [] self.visitChildren(ctx)
[ "def", "visitNodeConstraintValueSet", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "NodeConstraintValueSetContext", ")", ":", "self", ".", "nodeconstraint", ".", "values", "=", "[", "]", "self", ".", "visitChildren", "(", "ctx", ")" ]
nodeConstraint: valueSet xsFacet* #nodeConstraintValueSet
[ "nodeConstraint", ":", "valueSet", "xsFacet", "*", "#nodeConstraintValueSet" ]
python
train
57.75
SuLab/WikidataIntegrator
wikidataintegrator/wdi_helpers/__init__.py
https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_helpers/__init__.py#L58-L101
def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True): """ Write a PBB_core item. Log if item was created, updated, or skipped. Catch and log all errors. :param wd_item: A wikidata item that will be written :type wd_item: PBB_Core.WDItemEngine :param record_id: An e...
[ "def", "try_write", "(", "wd_item", ",", "record_id", ",", "record_prop", ",", "login", ",", "edit_summary", "=", "''", ",", "write", "=", "True", ")", ":", "if", "wd_item", ".", "require_write", ":", "if", "wd_item", ".", "create_new_item", ":", "msg", ...
Write a PBB_core item. Log if item was created, updated, or skipped. Catch and log all errors. :param wd_item: A wikidata item that will be written :type wd_item: PBB_Core.WDItemEngine :param record_id: An external identifier, to be used for logging :type record_id: str :param record_prop: Prop...
[ "Write", "a", "PBB_core", "item", ".", "Log", "if", "item", "was", "created", "updated", "or", "skipped", ".", "Catch", "and", "log", "all", "errors", "." ]
python
train
38.727273
ARMmbed/mbed-cloud-sdk-python
src/mbed_cloud/bootstrap/bootstrap.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/src/mbed_cloud/bootstrap/bootstrap.py#L44-L50
def add_psk(self, **kwargs): """Add""" api = self._get_api(bootstrap.PreSharedKeysApi) item = PreSharedKey._create_request_map(kwargs) item = models.PreSharedKey(**item) api.upload_pre_shared_key(item) return PreSharedKey(item)
[ "def", "add_psk", "(", "self", ",", "*", "*", "kwargs", ")", ":", "api", "=", "self", ".", "_get_api", "(", "bootstrap", ".", "PreSharedKeysApi", ")", "item", "=", "PreSharedKey", ".", "_create_request_map", "(", "kwargs", ")", "item", "=", "models", "."...
Add
[ "Add" ]
python
train
38.428571
samuelcolvin/pydantic
pydantic/json.py
https://github.com/samuelcolvin/pydantic/blob/bff8a1789dfde2c38928cced6640887b53615aa3/pydantic/json.py#L67-L73
def timedelta_isoformat(td: datetime.timedelta) -> str: """ ISO 8601 encoding for timedeltas. """ minutes, seconds = divmod(td.seconds, 60) hours, minutes = divmod(minutes, 60) return f'P{td.days}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S'
[ "def", "timedelta_isoformat", "(", "td", ":", "datetime", ".", "timedelta", ")", "->", "str", ":", "minutes", ",", "seconds", "=", "divmod", "(", "td", ".", "seconds", ",", "60", ")", "hours", ",", "minutes", "=", "divmod", "(", "minutes", ",", "60", ...
ISO 8601 encoding for timedeltas.
[ "ISO", "8601", "encoding", "for", "timedeltas", "." ]
python
train
39
apache/spark
python/pyspark/sql/functions.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L72-L77
def _wrap_deprecated_function(func, message): """ Wrap the deprecated function to print out deprecation warnings""" def _(col): warnings.warn(message, DeprecationWarning) return func(col) return functools.wraps(func)(_)
[ "def", "_wrap_deprecated_function", "(", "func", ",", "message", ")", ":", "def", "_", "(", "col", ")", ":", "warnings", ".", "warn", "(", "message", ",", "DeprecationWarning", ")", "return", "func", "(", "col", ")", "return", "functools", ".", "wraps", ...
Wrap the deprecated function to print out deprecation warnings
[ "Wrap", "the", "deprecated", "function", "to", "print", "out", "deprecation", "warnings" ]
python
train
40.333333
tradenity/python-sdk
tradenity/resources/countries_geo_zone.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/countries_geo_zone.py#L808-L829
def update_countries_geo_zone_by_id(cls, countries_geo_zone_id, countries_geo_zone, **kwargs): """Update CountriesGeoZone Update attributes of CountriesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >...
[ "def", "update_countries_geo_zone_by_id", "(", "cls", ",", "countries_geo_zone_id", ",", "countries_geo_zone", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", ...
Update CountriesGeoZone Update attributes of CountriesGeoZone This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.update_countries_geo_zone_by_id(countries_geo_zone_id, countries_geo_zone, async=True) ...
[ "Update", "CountriesGeoZone" ]
python
train
53.181818
google/grumpy
third_party/stdlib/textwrap.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/textwrap.py#L214-L239
def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long...
[ "def", "_handle_long_word", "(", "self", ",", "reversed_chunks", ",", "cur_line", ",", "cur_len", ",", "width", ")", ":", "# Figure out when indent is larger than the specified width, and make", "# sure at least one character is stripped off on every pass", "if", "width", "<", ...
_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line.
[ "_handle_long_word", "(", "chunks", ":", "[", "string", "]", "cur_line", ":", "[", "string", "]", "cur_len", ":", "int", "width", ":", "int", ")" ]
python
valid
44.769231
openego/eDisGo
edisgo/tools/pypsa_io.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/tools/pypsa_io.py#L1196-L1385
def process_pfa_results(network, pypsa, timesteps): """ Assing values from PyPSA to :meth:`results <edisgo.grid.network.Network.results>` Parameters ---------- network : Network The eDisGo grid topology model overall container pypsa : :pypsa:`pypsa.Network<network>` The PyPS...
[ "def", "process_pfa_results", "(", "network", ",", "pypsa", ",", "timesteps", ")", ":", "# get the absolute losses in the system", "# subtracting total generation (including slack) from total load", "grid_losses", "=", "{", "'p'", ":", "1e3", "*", "(", "pypsa", ".", "gene...
Assing values from PyPSA to :meth:`results <edisgo.grid.network.Network.results>` Parameters ---------- network : Network The eDisGo grid topology model overall container pypsa : :pypsa:`pypsa.Network<network>` The PyPSA `Network container <https://www.pypsa.org/doc/componen...
[ "Assing", "values", "from", "PyPSA", "to", ":", "meth", ":", "results", "<edisgo", ".", "grid", ".", "network", ".", "Network", ".", "results", ">" ]
python
train
42.947368
hanguokai/youku
youku/youku_schemas.py
https://github.com/hanguokai/youku/blob/b2df060c7dccfad990bcfa289fff68bb77d1e69b/youku/youku_schemas.py#L51-L57
def playlist_category(self): """doc: http://open.youku.com/docs/doc?id=94 """ url = 'https://openapi.youku.com/v2/schemas/playlist/category.json' r = requests.get(url) check_error(r) return r.json()
[ "def", "playlist_category", "(", "self", ")", ":", "url", "=", "'https://openapi.youku.com/v2/schemas/playlist/category.json'", "r", "=", "requests", ".", "get", "(", "url", ")", "check_error", "(", "r", ")", "return", "r", ".", "json", "(", ")" ]
doc: http://open.youku.com/docs/doc?id=94
[ "doc", ":", "http", ":", "//", "open", ".", "youku", ".", "com", "/", "docs", "/", "doc?id", "=", "94" ]
python
train
34.285714
softlayer/softlayer-python
SoftLayer/CLI/dedicatedhost/list_guests.py
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/CLI/dedicatedhost/list_guests.py#L57-L76
def cli(env, identifier, sortby, cpu, domain, hostname, memory, tag, columns): """List guests which are in a dedicated host server.""" mgr = SoftLayer.DedicatedHostManager(env.client) guests = mgr.list_guests(host_id=identifier, cpus=cpu, hostname=h...
[ "def", "cli", "(", "env", ",", "identifier", ",", "sortby", ",", "cpu", ",", "domain", ",", "hostname", ",", "memory", ",", "tag", ",", "columns", ")", ":", "mgr", "=", "SoftLayer", ".", "DedicatedHostManager", "(", "env", ".", "client", ")", "guests",...
List guests which are in a dedicated host server.
[ "List", "guests", "which", "are", "in", "a", "dedicated", "host", "server", "." ]
python
train
35.7
hayd/pep8radius
setup.py
https://github.com/hayd/pep8radius/blob/0c1d14835d390f7feeb602f35a768e52ce306a0a/setup.py#L13-L20
def version(): """Return version string.""" with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'pep8radius', 'main.py')) as input_file: for line in input_file: if line.startswith('__version__'): return pars...
[ "def", "version", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ",", "'pep8radius'", ",", "'main.py'", ")", ")", "as"...
Return version string.
[ "Return", "version", "string", "." ]
python
train
42
saltstack/salt
salt/modules/pip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pip.py#L259-L274
def _resolve_requirements_chain(requirements): ''' Return an array of requirements file paths that can be used to complete the no_chown==False && user != None conundrum ''' chain = [] if isinstance(requirements, six.string_types): requirements = [requirements] for req_file in requ...
[ "def", "_resolve_requirements_chain", "(", "requirements", ")", ":", "chain", "=", "[", "]", "if", "isinstance", "(", "requirements", ",", "six", ".", "string_types", ")", ":", "requirements", "=", "[", "requirements", "]", "for", "req_file", "in", "requiremen...
Return an array of requirements file paths that can be used to complete the no_chown==False && user != None conundrum
[ "Return", "an", "array", "of", "requirements", "file", "paths", "that", "can", "be", "used", "to", "complete", "the", "no_chown", "==", "False", "&&", "user", "!", "=", "None", "conundrum" ]
python
train
27.125
nerdvegas/rez
src/rez/rex.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L564-L571
def apply_environ(self): """Apply changes to target environ. """ if self.manager is None: raise RezSystemError("You must call 'set_manager' on a Python rex " "interpreter before using it.") self.target_environ.update(self.manager.environ)
[ "def", "apply_environ", "(", "self", ")", ":", "if", "self", ".", "manager", "is", "None", ":", "raise", "RezSystemError", "(", "\"You must call 'set_manager' on a Python rex \"", "\"interpreter before using it.\"", ")", "self", ".", "target_environ", ".", "update", "...
Apply changes to target environ.
[ "Apply", "changes", "to", "target", "environ", "." ]
python
train
38.625
saltstack/salt
salt/modules/pkgin.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgin.py#L663-L696
def file_dict(*packages, **kwargs): ''' .. versionchanged: 2016.3.0 List the files that belong to a package. CLI Examples: .. code-block:: bash salt '*' pkg.file_dict nginx salt '*' pkg.file_dict nginx varnish ''' errors = [] files = {} for package in packages: ...
[ "def", "file_dict", "(", "*", "packages", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "files", "=", "{", "}", "for", "package", "in", "packages", ":", "cmd", "=", "[", "'pkg_info'", ",", "'-qL'", ",", "package", "]", "ret", "=", "...
.. versionchanged: 2016.3.0 List the files that belong to a package. CLI Examples: .. code-block:: bash salt '*' pkg.file_dict nginx salt '*' pkg.file_dict nginx varnish
[ "..", "versionchanged", ":", "2016", ".", "3", ".", "0" ]
python
train
25.323529
sassoftware/saspy
saspy/sasets.py
https://github.com/sassoftware/saspy/blob/e433f71990f249d3a6c3db323ceb11cb2d462cf9/saspy/sasets.py#L291-L331
def x11(self, data: ['SASdata', str] = None, arima: str = None, by: [str, list] = None, id: [str, list] = None, macurves: str = None, monthly: str = None, output: [str, bool, 'SASdata'] = None, pdweights: str = None, quarter...
[ "def", "x11", "(", "self", ",", "data", ":", "[", "'SASdata'", ",", "str", "]", "=", "None", ",", "arima", ":", "str", "=", "None", ",", "by", ":", "[", "str", ",", "list", "]", "=", "None", ",", "id", ":", "[", "str", ",", "list", "]", "="...
Python method to call the X11 procedure Documentation link: https://go.documentation.sas.com/?cdcId=pgmsascdc&cdcVersion=9.4_3.4&docsetId=etsug&docsetTarget=etsug_x11_syntax.htm&locale=en Either the MONTHLY or QUARTERLY statement must be specified, depending on the type of time series data you...
[ "Python", "method", "to", "call", "the", "X11", "procedure" ]
python
train
55.97561
KartikTalwar/Duolingo
duolingo.py
https://github.com/KartikTalwar/Duolingo/blob/0f7e9a0d4bfa864ade82890fca3789679ef38bee/duolingo.py#L326-L338
def get_friends(self): """Get user's friends.""" for k, v in iter(self.user_data.language_data.items()): data = [] for friend in v['points_ranking_data']: temp = {'username': friend['username'], 'id': friend['id'], '...
[ "def", "get_friends", "(", "self", ")", ":", "for", "k", ",", "v", "in", "iter", "(", "self", ".", "user_data", ".", "language_data", ".", "items", "(", ")", ")", ":", "data", "=", "[", "]", "for", "friend", "in", "v", "[", "'points_ranking_data'", ...
Get user's friends.
[ "Get", "user", "s", "friends", "." ]
python
train
42.307692
vnmabus/dcor
dcor/_dcor.py
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L34-L44
def _distance_covariance_sqr_naive(x, y, exponent=1): """ Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _distance_matrix(x, exponent=exponent) b = _distance_matrix(y, e...
[ "def", "_distance_covariance_sqr_naive", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "a", "=", "_distance_matrix", "(", "x", ",", "exponent", "=", "exponent", ")", "b", "=", "_distance_matrix", "(", "y", ",", "exponent", "=", "exponent", ")"...
Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm.
[ "Naive", "biased", "estimator", "for", "distance", "covariance", "." ]
python
train
32.545455
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_web.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L149-L156
def cgi_method_is_post(environ: Dict[str, str]) -> bool: """ Determines if the CGI method was ``POST``, given the CGI environment. """ method = environ.get("REQUEST_METHOD", None) if not method: return False return method.upper() == "POST"
[ "def", "cgi_method_is_post", "(", "environ", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "bool", ":", "method", "=", "environ", ".", "get", "(", "\"REQUEST_METHOD\"", ",", "None", ")", "if", "not", "method", ":", "return", "False", "return", "...
Determines if the CGI method was ``POST``, given the CGI environment.
[ "Determines", "if", "the", "CGI", "method", "was", "POST", "given", "the", "CGI", "environment", "." ]
python
train
33
saltstack/salt
salt/states/boto_cognitoidentity.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cognitoidentity.py#L93-L131
def _role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params): ''' Helper function to set the Roles to the identity pool ''' r = __salt__['boto_cognitoidentity.get_identity_pool_roles'](IdentityPoolName='', Id...
[ "def", "_role_present", "(", "ret", ",", "IdentityPoolId", ",", "AuthenticatedRole", ",", "UnauthenticatedRole", ",", "conn_params", ")", ":", "r", "=", "__salt__", "[", "'boto_cognitoidentity.get_identity_pool_roles'", "]", "(", "IdentityPoolName", "=", "''", ",", ...
Helper function to set the Roles to the identity pool
[ "Helper", "function", "to", "set", "the", "Roles", "to", "the", "identity", "pool" ]
python
train
51.538462
har07/PySastrawi
src/Sastrawi/Dictionary/ArrayDictionary.py
https://github.com/har07/PySastrawi/blob/01afc81c579bde14dcb41c33686b26af8afab121/src/Sastrawi/Dictionary/ArrayDictionary.py#L19-L23
def add(self, word): """Add a word to the dictionary""" if not word or word.strip() == '': return self.words[word]=word
[ "def", "add", "(", "self", ",", "word", ")", ":", "if", "not", "word", "or", "word", ".", "strip", "(", ")", "==", "''", ":", "return", "self", ".", "words", "[", "word", "]", "=", "word" ]
Add a word to the dictionary
[ "Add", "a", "word", "to", "the", "dictionary" ]
python
train
30.2
apache/spark
python/pyspark/rdd.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/rdd.py#L1009-L1023
def max(self, key=None): """ Find the maximum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0]) >>> rdd.max() 43.0 >>> rdd.max(key=str) 5.0 """ if key is None: ...
[ "def", "max", "(", "self", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "return", "self", ".", "reduce", "(", "max", ")", "return", "self", ".", "reduce", "(", "lambda", "a", ",", "b", ":", "max", "(", "a", ",", "b", ","...
Find the maximum item in this RDD. :param key: A function used to generate key for comparing >>> rdd = sc.parallelize([1.0, 5.0, 43.0, 10.0]) >>> rdd.max() 43.0 >>> rdd.max(key=str) 5.0
[ "Find", "the", "maximum", "item", "in", "this", "RDD", "." ]
python
train
26.533333
pymc-devs/pymc
pymc/StepMethods.py
https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/StepMethods.py#L97-L130
def assign_method(stochastic, scale=None, verbose=-1): """ Returns a step method instance to handle a variable. If several methods have the same competence, it picks one arbitrarily (using set.pop()). """ # Retrieve set of best candidates best_candidates = pick_best_methods(stochastic) ...
[ "def", "assign_method", "(", "stochastic", ",", "scale", "=", "None", ",", "verbose", "=", "-", "1", ")", ":", "# Retrieve set of best candidates", "best_candidates", "=", "pick_best_methods", "(", "stochastic", ")", "# Randomly grab and appropriate method", "method", ...
Returns a step method instance to handle a variable. If several methods have the same competence, it picks one arbitrarily (using set.pop()).
[ "Returns", "a", "step", "method", "instance", "to", "handle", "a", "variable", ".", "If", "several", "methods", "have", "the", "same", "competence", "it", "picks", "one", "arbitrarily", "(", "using", "set", ".", "pop", "()", ")", "." ]
python
train
31.558824
mitsei/dlkit
dlkit/handcar/repository/objects.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/handcar/repository/objects.py#L1644-L1664
def set_url(self, url=None): """Sets the url. :param url: the new copyright :type url: ``string`` :raise: ``InvalidArgument`` -- ``url`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true`` :raise: ``NullArgument`` -- ``url`` is ``null`` *com...
[ "def", "set_url", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "raise", "NullArgument", "(", ")", "metadata", "=", "Metadata", "(", "*", "*", "settings", ".", "METADATA", "[", "'url'", "]", ")", "if", "metadata", ...
Sets the url. :param url: the new copyright :type url: ``string`` :raise: ``InvalidArgument`` -- ``url`` is invalid :raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true`` :raise: ``NullArgument`` -- ``url`` is ``null`` *compliance: mandatory -- This method must b...
[ "Sets", "the", "url", "." ]
python
train
33.095238
amicks/Speculator
speculator/market.py
https://github.com/amicks/Speculator/blob/f7d6590aded20b1e1b5df16a4b27228ee821c4ab/speculator/market.py#L80-L109
def set_long_features(self, features, columns_to_set=[], partition=2): """ Sets features of double the duration Example: Setting 14 day RSIs to longer will create add a feature column of a 28 day RSIs. Args: features: Pandas DataFrame instance with columns as numpy.floa...
[ "def", "set_long_features", "(", "self", ",", "features", ",", "columns_to_set", "=", "[", "]", ",", "partition", "=", "2", ")", ":", "# Create long features DataFrame", "features_long", "=", "self", ".", "set_features", "(", "partition", "=", "2", "*", "parti...
Sets features of double the duration Example: Setting 14 day RSIs to longer will create add a feature column of a 28 day RSIs. Args: features: Pandas DataFrame instance with columns as numpy.float32 features. columns_to_set: List of strings of feature names to make ...
[ "Sets", "features", "of", "double", "the", "duration" ]
python
train
43.166667
dddomodossola/remi
remi/gui.py
https://github.com/dddomodossola/remi/blob/85206f62220662bb7ecd471042268def71ccad28/remi/gui.py#L2251-L2267
def select_by_value(self, value): """Selects a DropDownItem by means of the contained text- Args: value (str): Textual content of the DropDownItem that have to be selected. """ self._selected_key = None self._selected_item = None for k in self.children: ...
[ "def", "select_by_value", "(", "self", ",", "value", ")", ":", "self", ".", "_selected_key", "=", "None", "self", ".", "_selected_item", "=", "None", "for", "k", "in", "self", ".", "children", ":", "item", "=", "self", ".", "children", "[", "k", "]", ...
Selects a DropDownItem by means of the contained text- Args: value (str): Textual content of the DropDownItem that have to be selected.
[ "Selects", "a", "DropDownItem", "by", "means", "of", "the", "contained", "text", "-" ]
python
train
37.294118
ionelmc/python-cogen
cogen/core/coroutines.py
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/coroutines.py#L159-L255
def run_op(self, op, sched): """ Handle the operation: * if coro is in STATE_RUNNING, send or throw the given op * if coro is in STATE_NEED_INIT, call the init function and if it doesn't return a generator, set STATE_COMPLETED and set the result to whatever t...
[ "def", "run_op", "(", "self", ",", "op", ",", "sched", ")", ":", "if", "op", "is", "self", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"Running coro %s with itself. Something is fishy.\"", "%", "op", ")", "assert", "self", ".", "state", "<", ...
Handle the operation: * if coro is in STATE_RUNNING, send or throw the given op * if coro is in STATE_NEED_INIT, call the init function and if it doesn't return a generator, set STATE_COMPLETED and set the result to whatever the function returned. * if StopIterati...
[ "Handle", "the", "operation", ":", "*", "if", "coro", "is", "in", "STATE_RUNNING", "send", "or", "throw", "the", "given", "op", "*", "if", "coro", "is", "in", "STATE_NEED_INIT", "call", "the", "init", "function", "and", "if", "it", "doesn", "t", "return"...
python
train
40.020619
MisterY/pydatum
pydatum/datum.py
https://github.com/MisterY/pydatum/blob/4b39f43040e31a95bcf219603b6429078a9ba3c2/pydatum/datum.py#L162-L165
def subtract_days(self, days: int) -> datetime: """ Subtracts dates from the given value """ self.value = self.value - relativedelta(days=days) return self.value
[ "def", "subtract_days", "(", "self", ",", "days", ":", "int", ")", "->", "datetime", ":", "self", ".", "value", "=", "self", ".", "value", "-", "relativedelta", "(", "days", "=", "days", ")", "return", "self", ".", "value" ]
Subtracts dates from the given value
[ "Subtracts", "dates", "from", "the", "given", "value" ]
python
train
45.5
taddeus/wspy
frame.py
https://github.com/taddeus/wspy/blob/13f054a72442bb8dcc37b0ac011cab6025830d66/frame.py#L198-L210
def unpack_close(self): """ Unpack a close message into a status code and a reason. If no payload is given, the code is None and the reason is an empty string. """ if self.payload: code = struct.unpack('!H', str(self.payload[:2]))[0] reason = str(self.payl...
[ "def", "unpack_close", "(", "self", ")", ":", "if", "self", ".", "payload", ":", "code", "=", "struct", ".", "unpack", "(", "'!H'", ",", "str", "(", "self", ".", "payload", "[", ":", "2", "]", ")", ")", "[", "0", "]", "reason", "=", "str", "(",...
Unpack a close message into a status code and a reason. If no payload is given, the code is None and the reason is an empty string.
[ "Unpack", "a", "close", "message", "into", "a", "status", "code", "and", "a", "reason", ".", "If", "no", "payload", "is", "given", "the", "code", "is", "None", "and", "the", "reason", "is", "an", "empty", "string", "." ]
python
train
31.307692
Microsoft/azure-devops-python-api
azure-devops/azure/devops/v5_0/git/git_client_base.py
https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/git/git_client_base.py#L431-L503
def get_commits(self, repository_id, search_criteria, project=None, skip=None, top=None): """GetCommits. Retrieve git commits for a project :param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified. :param :class:`<Git...
[ "def", "get_commits", "(", "self", ",", "repository_id", ",", "search_criteria", ",", "project", "=", "None", ",", "skip", "=", "None", ",", "top", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_...
GetCommits. Retrieve git commits for a project :param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified. :param :class:`<GitQueryCommitsCriteria> <azure.devops.v5_0.git.models.GitQueryCommitsCriteria>` search_criteria: ...
[ "GetCommits", ".", "Retrieve", "git", "commits", "for", "a", "project", ":", "param", "str", "repository_id", ":", "The", "id", "or", "friendly", "name", "of", "the", "repository", ".", "To", "use", "the", "friendly", "name", "projectId", "must", "also", "...
python
train
69.958904
cuducos/webassets-elm
webassets_elm/__init__.py
https://github.com/cuducos/webassets-elm/blob/86b24cd5def083bbd32b6a7a512937d762cac974/webassets_elm/__init__.py#L45-L70
def input(self, _in, out, **kw): """ Currently Elm does not write to stdout (https://github.com/elm-lang/elm-make/issues/39), so we need to write the compiled contents to a temporary file and then read it in order to output to stdout. """ # create a temp file ...
[ "def", "input", "(", "self", ",", "_in", ",", "out", ",", "*", "*", "kw", ")", ":", "# create a temp file", "tmp", "=", "NamedTemporaryFile", "(", "suffix", "=", "'.js'", ",", "delete", "=", "False", ")", "tmp", ".", "close", "(", ")", "# close it so w...
Currently Elm does not write to stdout (https://github.com/elm-lang/elm-make/issues/39), so we need to write the compiled contents to a temporary file and then read it in order to output to stdout.
[ "Currently", "Elm", "does", "not", "write", "to", "stdout", "(", "https", ":", "//", "github", ".", "com", "/", "elm", "-", "lang", "/", "elm", "-", "make", "/", "issues", "/", "39", ")", "so", "we", "need", "to", "write", "the", "compiled", "conte...
python
train
42.423077
bigchaindb/bigchaindb
bigchaindb/common/transaction.py
https://github.com/bigchaindb/bigchaindb/blob/835fdfcf598918f76139e3b88ee33dd157acaaa7/bigchaindb/common/transaction.py#L584-L592
def spent_outputs(self): """Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index. """ return ( input_.fulfills.to_dict() for input_ in self.inputs if input_.fulfills ...
[ "def", "spent_outputs", "(", "self", ")", ":", "return", "(", "input_", ".", "fulfills", ".", "to_dict", "(", ")", "for", "input_", "in", "self", ".", "inputs", "if", "input_", ".", "fulfills", ")" ]
Tuple of :obj:`dict`: Inputs of this transaction. Each input is represented as a dictionary containing a transaction id and output index.
[ "Tuple", "of", ":", "obj", ":", "dict", ":", "Inputs", "of", "this", "transaction", ".", "Each", "input", "is", "represented", "as", "a", "dictionary", "containing", "a", "transaction", "id", "and", "output", "index", "." ]
python
train
35
MisterY/gnucash-portfolio
gnucash_portfolio/accounts.py
https://github.com/MisterY/gnucash-portfolio/blob/bfaad8345a5479d1cd111acee1939e25c2a638c2/gnucash_portfolio/accounts.py#L244-L256
def find_by_name(self, term: str, include_placeholders: bool = False) -> List[Account]: """ Search for account by part of the name """ query = ( self.query .filter(Account.name.like('%' + term + '%')) .order_by(Account.name) ) # Exclude placeholder acc...
[ "def", "find_by_name", "(", "self", ",", "term", ":", "str", ",", "include_placeholders", ":", "bool", "=", "False", ")", "->", "List", "[", "Account", "]", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Account", ".", "name", "."...
Search for account by part of the name
[ "Search", "for", "account", "by", "part", "of", "the", "name" ]
python
train
36.769231
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/inputsplitter.py#L148-L160
def last_blank(src): """Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string. """ if not src: return False ll = src.splitlines()[-1] return (ll == '') or...
[ "def", "last_blank", "(", "src", ")", ":", "if", "not", "src", ":", "return", "False", "ll", "=", "src", ".", "splitlines", "(", ")", "[", "-", "1", "]", "return", "(", "ll", "==", "''", ")", "or", "ll", ".", "isspace", "(", ")" ]
Determine if the input source ends in a blank. A blank is either a newline or a line consisting of whitespace. Parameters ---------- src : string A single or multiline string.
[ "Determine", "if", "the", "input", "source", "ends", "in", "a", "blank", "." ]
python
test
24.692308
agoragames/haigha
haigha/connections/rabbit_connection.py
https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/connections/rabbit_connection.py#L338-L355
def select(self, nowait=True, cb=None): ''' Set this channel to use publisher confirmations. ''' nowait = nowait and self.allow_nowait() and not cb if not self._enabled: self._enabled = True self.channel.basic._msg_id = 0 self.channel.basic._l...
[ "def", "select", "(", "self", ",", "nowait", "=", "True", ",", "cb", "=", "None", ")", ":", "nowait", "=", "nowait", "and", "self", ".", "allow_nowait", "(", ")", "and", "not", "cb", "if", "not", "self", ".", "_enabled", ":", "self", ".", "_enabled...
Set this channel to use publisher confirmations.
[ "Set", "this", "channel", "to", "use", "publisher", "confirmations", "." ]
python
train
33
wummel/linkchecker
linkcheck/memoryutil.py
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/memoryutil.py#L31-L46
def write_memory_dump(): """Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string """ # first do a full garbage collection run gc.collect() if gc.garbage: log.warn(LOG_CHECK, "Unreachabe objects: %s", ...
[ "def", "write_memory_dump", "(", ")", ":", "# first do a full garbage collection run", "gc", ".", "collect", "(", ")", "if", "gc", ".", "garbage", ":", "log", ".", "warn", "(", "LOG_CHECK", ",", "\"Unreachabe objects: %s\"", ",", "pprint", ".", "pformat", "(", ...
Dump memory to a temporary filename with the meliae package. @return: JSON filename where memory dump has been written to @rtype: string
[ "Dump", "memory", "to", "a", "temporary", "filename", "with", "the", "meliae", "package", "." ]
python
train
33.6875
prompt-toolkit/pyvim
pyvim/window_arrangement.py
https://github.com/prompt-toolkit/pyvim/blob/5928b53b9d700863c1a06d2181a034a955f94594/pyvim/window_arrangement.py#L140-L145
def show_editor_buffer(self, editor_buffer): """ Open this `EditorBuffer` in the active window. """ assert isinstance(editor_buffer, EditorBuffer) self.active_window.editor_buffer = editor_buffer
[ "def", "show_editor_buffer", "(", "self", ",", "editor_buffer", ")", ":", "assert", "isinstance", "(", "editor_buffer", ",", "EditorBuffer", ")", "self", ".", "active_window", ".", "editor_buffer", "=", "editor_buffer" ]
Open this `EditorBuffer` in the active window.
[ "Open", "this", "EditorBuffer", "in", "the", "active", "window", "." ]
python
train
38.333333
bcbio/bcbio-nextgen
bcbio/structural/metasv.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/metasv.py#L18-L52
def run(items): """Run MetaSV if we have enough supported callers, adding output to the set of calls. """ assert len(items) == 1, "Expect one input to MetaSV ensemble calling" data = items[0] work_dir = _sv_workdir(data) out_file = os.path.join(work_dir, "variants.vcf.gz") cmd = _get_cmd() +...
[ "def", "run", "(", "items", ")", ":", "assert", "len", "(", "items", ")", "==", "1", ",", "\"Expect one input to MetaSV ensemble calling\"", "data", "=", "items", "[", "0", "]", "work_dir", "=", "_sv_workdir", "(", "data", ")", "out_file", "=", "os", ".", ...
Run MetaSV if we have enough supported callers, adding output to the set of calls.
[ "Run", "MetaSV", "if", "we", "have", "enough", "supported", "callers", "adding", "output", "to", "the", "set", "of", "calls", "." ]
python
train
63.742857
square/pylink
pylink/jlink.py
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3411-L3459
def num_available_breakpoints(self, arm=False, thumb=False, ram=False, flash=False, hw=False): """Returns the number of available breakpoints of the specified type. If ``arm`` is set, gets the number of available ARM breakpoint units. If ``thumb`` is set, gets the number of available THUMB brea...
[ "def", "num_available_breakpoints", "(", "self", ",", "arm", "=", "False", ",", "thumb", "=", "False", ",", "ram", "=", "False", ",", "flash", "=", "False", ",", "hw", "=", "False", ")", ":", "flags", "=", "[", "enums", ".", "JLinkBreakpoint", ".", "...
Returns the number of available breakpoints of the specified type. If ``arm`` is set, gets the number of available ARM breakpoint units. If ``thumb`` is set, gets the number of available THUMB breakpoint units. If ``ram`` is set, gets the number of available software RAM breakpoint uni...
[ "Returns", "the", "number", "of", "available", "breakpoints", "of", "the", "specified", "type", "." ]
python
train
40.979592
Alignak-monitoring/alignak
alignak/daemons/schedulerdaemon.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/daemons/schedulerdaemon.py#L553-L570
def get_monitoring_problems(self): """Get the current scheduler livesynthesis :return: live synthesis and problems dictionary :rtype: dict """ res = {} if not self.sched: return res # Get statistics from the scheduler scheduler_stats = self.s...
[ "def", "get_monitoring_problems", "(", "self", ")", ":", "res", "=", "{", "}", "if", "not", "self", ".", "sched", ":", "return", "res", "# Get statistics from the scheduler", "scheduler_stats", "=", "self", ".", "sched", ".", "get_scheduler_stats", "(", "details...
Get the current scheduler livesynthesis :return: live synthesis and problems dictionary :rtype: dict
[ "Get", "the", "current", "scheduler", "livesynthesis" ]
python
train
32
ellmetha/django-machina
machina/core/shortcuts.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/core/shortcuts.py#L4-L12
def get_object_or_none(klass, *args, **kwargs): """ Calls get() on a given model manager, but it returns None instead of the model’s DoesNotExist exception. """ queryset = _get_queryset(klass) try: return queryset.get(*args, **kwargs) except: # noqa: E722 return None
[ "def", "get_object_or_none", "(", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "_get_queryset", "(", "klass", ")", "try", ":", "return", "queryset", ".", "get", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except...
Calls get() on a given model manager, but it returns None instead of the model’s DoesNotExist exception.
[ "Calls", "get", "()", "on", "a", "given", "model", "manager", "but", "it", "returns", "None", "instead", "of", "the", "model’s", "DoesNotExist", "exception", "." ]
python
train
33.777778
LIVVkit/LIVVkit
livvkit/util/LIVVDict.py
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/LIVVDict.py#L49-L56
def nested_insert(self, item_list): """ Create a series of nested LIVVDicts given a list """ if len(item_list) == 1: self[item_list[0]] = LIVVDict() elif len(item_list) > 1: if item_list[0] not in self: self[item_list[0]] = LIVVDict() self[item...
[ "def", "nested_insert", "(", "self", ",", "item_list", ")", ":", "if", "len", "(", "item_list", ")", "==", "1", ":", "self", "[", "item_list", "[", "0", "]", "]", "=", "LIVVDict", "(", ")", "elif", "len", "(", "item_list", ")", ">", "1", ":", "if...
Create a series of nested LIVVDicts given a list
[ "Create", "a", "series", "of", "nested", "LIVVDicts", "given", "a", "list" ]
python
train
43.875
Kortemme-Lab/klab
klab/deprecated/rosettahelper.py
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/deprecated/rosettahelper.py#L132-L143
def get_files(dirname): '''recursion rockz''' all_files = [] os.chdir(dirname) for fn in os.listdir(os.path.abspath(dirname)): fn = os.path.abspath(fn) if os.path.isdir(fn): all_files += get_files(fn) else: all_files.append(fn) os.chdir('../') return all_files
[ "def", "get_files", "(", "dirname", ")", ":", "all_files", "=", "[", "]", "os", ".", "chdir", "(", "dirname", ")", "for", "fn", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "abspath", "(", "dirname", ")", ")", ":", "fn", "=", "os", ...
recursion rockz
[ "recursion", "rockz" ]
python
train
23.75
inveniosoftware-contrib/record-recommender
record_recommender/fetcher.py
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/fetcher.py#L105-L165
def _fetch_pageviews(self, storage, year, week, ip_users=False): """ Fetch PageViews from Elasticsearch. :param time_from: Staring at timestamp. :param time_to: To timestamp """ prefix = 'Pageviews' if ip_users: query_add = "AND !(bot:True) AND (id_us...
[ "def", "_fetch_pageviews", "(", "self", ",", "storage", ",", "year", ",", "week", ",", "ip_users", "=", "False", ")", ":", "prefix", "=", "'Pageviews'", "if", "ip_users", ":", "query_add", "=", "\"AND !(bot:True) AND (id_user:0)\"", "prefix", "+=", "'_IP'", "e...
Fetch PageViews from Elasticsearch. :param time_from: Staring at timestamp. :param time_to: To timestamp
[ "Fetch", "PageViews", "from", "Elasticsearch", "." ]
python
train
37.622951
silenc3r/dikicli
dikicli/core.py
https://github.com/silenc3r/dikicli/blob/53721cdf75db04e2edca5ed3f99beae7c079d980/dikicli/core.py#L367-L388
def _write_html_file(word, translations, data_dir, native=False): """Create html file of word translations. Parameters ---------- word : str Word that was translated. tralnslations : dict Dictionary of word translations. data_dir : pathlib.Path Location where html files ...
[ "def", "_write_html_file", "(", "word", ",", "translations", ",", "data_dir", ",", "native", "=", "False", ")", ":", "content_str", "=", "_create_html_file_content", "(", "translations", ")", "html_string", "=", "HTML_TEMPLATE", ".", "replace", "(", "\"{% word %}\...
Create html file of word translations. Parameters ---------- word : str Word that was translated. tralnslations : dict Dictionary of word translations. data_dir : pathlib.Path Location where html files are saved.
[ "Create", "html", "file", "of", "word", "translations", "." ]
python
train
34.318182
openpaperwork/paperwork-backend
paperwork_backend/docimport.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/docimport.py#L485-L495
def get_possible_importers(file_uris, current_doc=None): """ Return all the importer objects that can handle the specified files. Possible imports may vary depending on the currently active document """ importers = [] for importer in IMPORTERS: if importer.can_import(file_uris, current_...
[ "def", "get_possible_importers", "(", "file_uris", ",", "current_doc", "=", "None", ")", ":", "importers", "=", "[", "]", "for", "importer", "in", "IMPORTERS", ":", "if", "importer", ".", "can_import", "(", "file_uris", ",", "current_doc", ")", ":", "importe...
Return all the importer objects that can handle the specified files. Possible imports may vary depending on the currently active document
[ "Return", "all", "the", "importer", "objects", "that", "can", "handle", "the", "specified", "files", "." ]
python
train
34.090909
iotile/coretools
iotilebuild/iotile/build/dev/resolverchain.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/dev/resolverchain.py#L108-L176
def update_dependency(self, tile, depinfo, destdir=None): """Attempt to install or update a dependency to the latest version. Args: tile (IOTile): An IOTile object describing the tile that has the dependency depinfo (dict): a dictionary from tile.dependencies specifying the depe...
[ "def", "update_dependency", "(", "self", ",", "tile", ",", "depinfo", ",", "destdir", "=", "None", ")", ":", "if", "destdir", "is", "None", ":", "destdir", "=", "os", ".", "path", ".", "join", "(", "tile", ".", "folder", ",", "'build'", ",", "'deps'"...
Attempt to install or update a dependency to the latest version. Args: tile (IOTile): An IOTile object describing the tile that has the dependency depinfo (dict): a dictionary from tile.dependencies specifying the dependency destdir (string): An optional folder into which to...
[ "Attempt", "to", "install", "or", "update", "a", "dependency", "to", "the", "latest", "version", "." ]
python
train
31.362319
basho/riak-python-client
riak/multidict.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/multidict.py#L63-L71
def getall(self, key): """ Return a list of all values matching the key (may be an empty list) """ result = [] for k, v in self._items: if key == k: result.append(v) return result
[ "def", "getall", "(", "self", ",", "key", ")", ":", "result", "=", "[", "]", "for", "k", ",", "v", "in", "self", ".", "_items", ":", "if", "key", "==", "k", ":", "result", ".", "append", "(", "v", ")", "return", "result" ]
Return a list of all values matching the key (may be an empty list)
[ "Return", "a", "list", "of", "all", "values", "matching", "the", "key", "(", "may", "be", "an", "empty", "list", ")" ]
python
train
27.444444
celliern/triflow
triflow/core/simulation.py
https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L422-L432
def remove_post_process(self, name): """remove a post-process Parameters ---------- name : str name of the post-process to remove. """ self._pprocesses = [post_process for post_process in self._pprocesses ...
[ "def", "remove_post_process", "(", "self", ",", "name", ")", ":", "self", ".", "_pprocesses", "=", "[", "post_process", "for", "post_process", "in", "self", ".", "_pprocesses", "if", "post_process", ".", "name", "!=", "name", "]" ]
remove a post-process Parameters ---------- name : str name of the post-process to remove.
[ "remove", "a", "post", "-", "process" ]
python
train
31
zeroSteiner/smoke-zephyr
smoke_zephyr/utilities.py
https://github.com/zeroSteiner/smoke-zephyr/blob/a6d2498aeacc72ee52e7806f783a4d83d537ffb2/smoke_zephyr/utilities.py#L420-L454
def configure_stream_logger(logger='', level=None, formatter='%(levelname)-8s %(message)s'): """ Configure the default stream handler for logging messages to the console, remove other logging handlers, and enable capturing warnings. .. versionadded:: 1.3.0 :param str logger: The logger to add the stream handler ...
[ "def", "configure_stream_logger", "(", "logger", "=", "''", ",", "level", "=", "None", ",", "formatter", "=", "'%(levelname)-8s %(message)s'", ")", ":", "level", "=", "level", "or", "logging", ".", "WARNING", "if", "isinstance", "(", "level", ",", "str", ")"...
Configure the default stream handler for logging messages to the console, remove other logging handlers, and enable capturing warnings. .. versionadded:: 1.3.0 :param str logger: The logger to add the stream handler for. :param level: The level to set the logger to, will default to WARNING if no level is specifie...
[ "Configure", "the", "default", "stream", "handler", "for", "logging", "messages", "to", "the", "console", "remove", "other", "logging", "handlers", "and", "enable", "capturing", "warnings", "." ]
python
train
40.542857
yakupadakli/python-unsplash
unsplash/collection.py
https://github.com/yakupadakli/python-unsplash/blob/6e43dce3225237e1b8111fd475fb98b1ea33972c/unsplash/collection.py#L145-L163
def update(self, collection_id, title=None, description=None, private=False): """ Update an existing collection belonging to the logged-in user. This requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param title [string]: The ...
[ "def", "update", "(", "self", ",", "collection_id", ",", "title", "=", "None", ",", "description", "=", "None", ",", "private", "=", "False", ")", ":", "url", "=", "\"/collections/%s\"", "%", "collection_id", "data", "=", "{", "\"title\"", ":", "title", ...
Update an existing collection belonging to the logged-in user. This requires the 'write_collections' scope. :param collection_id [string]: The collection’s ID. Required. :param title [string]: The title of the collection. (Required.) :param description [string]: The collection’s descrip...
[ "Update", "an", "existing", "collection", "belonging", "to", "the", "logged", "-", "in", "user", ".", "This", "requires", "the", "write_collections", "scope", "." ]
python
train
44.684211
NateFerrero/oauth2lib
oauth2lib/provider.py
https://github.com/NateFerrero/oauth2lib/blob/d161b010f8a596826050a09e5e94d59443cc12d9/oauth2lib/provider.py#L61-L80
def _make_json_response(self, data, headers=None, status_code=200): """Return a response object from the given JSON data. :param data: Data to JSON-encode. :type data: mixed :param headers: Dict of headers to include in the requests. :type headers: dict :param status_cod...
[ "def", "_make_json_response", "(", "self", ",", "data", ",", "headers", "=", "None", ",", "status_code", "=", "200", ")", ":", "response_headers", "=", "{", "}", "if", "headers", "is", "not", "None", ":", "response_headers", ".", "update", "(", "headers", ...
Return a response object from the given JSON data. :param data: Data to JSON-encode. :type data: mixed :param headers: Dict of headers to include in the requests. :type headers: dict :param status_code: HTTP status code. :type status_code: int :rtype: requests.Re...
[ "Return", "a", "response", "object", "from", "the", "given", "JSON", "data", "." ]
python
test
41.9
reiinakano/scikit-plot
scikitplot/cluster.py
https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/cluster.py#L110-L132
def _clone_and_score_clusterer(clf, X, n_clusters): """Clones and scores clusterer instance. Args: clf: Clusterer instance that implements ``fit``,``fit_predict``, and ``score`` methods, and an ``n_clusters`` hyperparameter. e.g. :class:`sklearn.cluster.KMeans` instance ...
[ "def", "_clone_and_score_clusterer", "(", "clf", ",", "X", ",", "n_clusters", ")", ":", "start", "=", "time", ".", "time", "(", ")", "clf", "=", "clone", "(", "clf", ")", "setattr", "(", "clf", ",", "'n_clusters'", ",", "n_clusters", ")", "return", "cl...
Clones and scores clusterer instance. Args: clf: Clusterer instance that implements ``fit``,``fit_predict``, and ``score`` methods, and an ``n_clusters`` hyperparameter. e.g. :class:`sklearn.cluster.KMeans` instance X (array-like, shape (n_samples, n_features)): ...
[ "Clones", "and", "scores", "clusterer", "instance", "." ]
python
train
33.304348
callowayproject/django-categories
categories/editor/templatetags/admin_tree_list_tags.py
https://github.com/callowayproject/django-categories/blob/3765851320a79b12c6d3306f3784a2302ea64812/categories/editor/templatetags/admin_tree_list_tags.py#L153-L166
def result_tree_list(cl): """ Displays the headers and data list together """ import django result = { 'cl': cl, 'result_headers': list(result_headers(cl)), 'results': list(tree_results(cl)) } if django.VERSION[0] == 1 and django.VERSION[1] > 2: from django.co...
[ "def", "result_tree_list", "(", "cl", ")", ":", "import", "django", "result", "=", "{", "'cl'", ":", "cl", ",", "'result_headers'", ":", "list", "(", "result_headers", "(", "cl", ")", ")", ",", "'results'", ":", "list", "(", "tree_results", "(", "cl", ...
Displays the headers and data list together
[ "Displays", "the", "headers", "and", "data", "list", "together" ]
python
train
32.857143
d0c-s4vage/pfp
pfp/interp.py
https://github.com/d0c-s4vage/pfp/blob/32f2d34fdec1c70019fa83c7006d5e3be0f92fcd/pfp/interp.py#L1191-L1210
def _handle_metadata(self, node, scope, ctxt, stream): """Handle metadata for the node """ self._dlog("handling node metadata {}".format(node.metadata.keyvals)) keyvals = node.metadata.keyvals metadata_info = [] if "watch" in node.metadata.keyvals or "update" in keyval...
[ "def", "_handle_metadata", "(", "self", ",", "node", ",", "scope", ",", "ctxt", ",", "stream", ")", ":", "self", ".", "_dlog", "(", "\"handling node metadata {}\"", ".", "format", "(", "node", ".", "metadata", ".", "keyvals", ")", ")", "keyvals", "=", "n...
Handle metadata for the node
[ "Handle", "metadata", "for", "the", "node" ]
python
train
32.2
allenai/allennlp
allennlp/modules/elmo.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/modules/elmo.py#L561-L625
def forward(self, # pylint: disable=arguments-differ inputs: torch.Tensor, word_inputs: torch.Tensor = None) -> Dict[str, Union[torch.Tensor, List[torch.Tensor]]]: """ Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_si...
[ "def", "forward", "(", "self", ",", "# pylint: disable=arguments-differ", "inputs", ":", "torch", ".", "Tensor", ",", "word_inputs", ":", "torch", ".", "Tensor", "=", "None", ")", "->", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", ...
Parameters ---------- inputs: ``torch.Tensor``, required. Shape ``(batch_size, timesteps, 50)`` of character ids representing the current batch. word_inputs : ``torch.Tensor``, required. If you passed a cached vocab, you can in addition pass a tensor of shape ``(batch_siz...
[ "Parameters", "----------", "inputs", ":", "torch", ".", "Tensor", "required", ".", "Shape", "(", "batch_size", "timesteps", "50", ")", "of", "character", "ids", "representing", "the", "current", "batch", ".", "word_inputs", ":", "torch", ".", "Tensor", "requi...
python
train
47.676923
Ex-Mente/auxi.0
auxi/tools/materialphysicalproperties/polynomial.py
https://github.com/Ex-Mente/auxi.0/blob/2dcdae74154f136f8ca58289fe5b20772f215046/auxi/tools/materialphysicalproperties/polynomial.py#L79-L89
def calculate(self, **state): """ Calculate the material physical property at the specified temperature in the units specified by the object's 'property_units' property. :param T: [K] temperature :returns: physical property value """ super().calculate(**state) ...
[ "def", "calculate", "(", "self", ",", "*", "*", "state", ")", ":", "super", "(", ")", ".", "calculate", "(", "*", "*", "state", ")", "return", "np", ".", "polyval", "(", "self", ".", "_coeffs", ",", "state", "[", "'T'", "]", ")" ]
Calculate the material physical property at the specified temperature in the units specified by the object's 'property_units' property. :param T: [K] temperature :returns: physical property value
[ "Calculate", "the", "material", "physical", "property", "at", "the", "specified", "temperature", "in", "the", "units", "specified", "by", "the", "object", "s", "property_units", "property", "." ]
python
valid
32.727273
minhhoit/yacms
yacms/blog/views.py
https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/views.py#L84-L91
def blog_post_feed(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request) except KeyError: raise Http404()
[ "def", "blog_post_feed", "(", "request", ",", "format", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "{", "\"rss\"", ":", "PostsRSS", ",", "\"atom\"", ":", "PostsAtom", "}", "[", "format", "]", "(", "*", "*", "kwargs", ")", "(", "request"...
Blog posts feeds - maps format to the correct feed view.
[ "Blog", "posts", "feeds", "-", "maps", "format", "to", "the", "correct", "feed", "view", "." ]
python
train
31.125
CityOfZion/neo-python
neo/Settings.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Settings.py#L311-L319
def set_loglevel(self, level): """ Set the minimum loglevel for all components Args: level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels """ self.log_level = level log_manager.config_stdio(de...
[ "def", "set_loglevel", "(", "self", ",", "level", ")", ":", "self", ".", "log_level", "=", "level", "log_manager", ".", "config_stdio", "(", "default_level", "=", "level", ")" ]
Set the minimum loglevel for all components Args: level (int): eg. logging.DEBUG or logging.ERROR. See also https://docs.python.org/2/library/logging.html#logging-levels
[ "Set", "the", "minimum", "loglevel", "for", "all", "components" ]
python
train
36.666667
saltstack/salt
salt/modules/svn.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/svn.py#L133-L174
def checkout(cwd, remote, target=None, user=None, username=None, password=None, *opts): ''' Download a working copy of the remote Subversion repository directory or file cwd The path to the Subversion repository ...
[ "def", "checkout", "(", "cwd", ",", "remote", ",", "target", "=", "None", ",", "user", "=", "None", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "opts", ")", ":", "opts", "+=", "(", "remote", ",", ")", "if", "target", ":"...
Download a working copy of the remote Subversion repository directory or file cwd The path to the Subversion repository remote : None URL to checkout target : None The name to give the file or directory working copy Default: svn uses the remote basename user : Non...
[ "Download", "a", "working", "copy", "of", "the", "remote", "Subversion", "repository", "directory", "or", "file" ]
python
train
22.833333
alexcepoi/cake
cake/color.py
https://github.com/alexcepoi/cake/blob/0fde58dfea1fdbfd632816d5850b47cb0f9ece64/cake/color.py#L52-L64
def ansi(string, *args): """ Convenience function to chain multiple ColorWrappers to a string """ ansi = '' for arg in args: arg = str(arg) if not re.match(ANSI_PATTERN, arg): raise ValueError('Additional arguments must be ansi strings') ansi += arg return ansi + string + colorama.Style.RESET_ALL
[ "def", "ansi", "(", "string", ",", "*", "args", ")", ":", "ansi", "=", "''", "for", "arg", "in", "args", ":", "arg", "=", "str", "(", "arg", ")", "if", "not", "re", ".", "match", "(", "ANSI_PATTERN", ",", "arg", ")", ":", "raise", "ValueError", ...
Convenience function to chain multiple ColorWrappers to a string
[ "Convenience", "function", "to", "chain", "multiple", "ColorWrappers", "to", "a", "string" ]
python
train
23.307692
wandb/client
wandb/vendor/prompt_toolkit/layout/containers.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/layout/containers.py#L733-L741
def center_visible_line(self, before_scroll_offset=False, after_scroll_offset=False): """ Like `first_visible_line`, but for the center visible line. """ return (self.first_visible_line(after_scroll_offset) + (self.last_visible_line(before_scro...
[ "def", "center_visible_line", "(", "self", ",", "before_scroll_offset", "=", "False", ",", "after_scroll_offset", "=", "False", ")", ":", "return", "(", "self", ".", "first_visible_line", "(", "after_scroll_offset", ")", "+", "(", "self", ".", "last_visible_line",...
Like `first_visible_line`, but for the center visible line.
[ "Like", "first_visible_line", "but", "for", "the", "center", "visible", "line", "." ]
python
train
45.444444
fprimex/zdesk
zdesk/zdesk_api.py
https://github.com/fprimex/zdesk/blob/851611c13b4d530e9df31390b3ec709baf0a0188/zdesk/zdesk_api.py#L1266-L1270
def group_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/groups#delete-group" api_path = "/api/v2/groups/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "group_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/groups/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", ",",...
https://developer.zendesk.com/rest_api/docs/core/groups#delete-group
[ "https", ":", "//", "developer", ".", "zendesk", ".", "com", "/", "rest_api", "/", "docs", "/", "core", "/", "groups#delete", "-", "group" ]
python
train
52.4
satellogic/telluric
telluric/georaster.py
https://github.com/satellogic/telluric/blob/e752cd3ee71e339f79717e526fde362e80055d9e/telluric/georaster.py#L1506-L1522
def from_bytes(cls, image_bytes, affine, crs, band_names=None): """Create GeoRaster from image BytesIo object. :param image_bytes: io.BytesIO object :param affine: rasters affine :param crs: rasters crs :param band_names: e.g. ['red', 'blue'] or 'red' """ b = io....
[ "def", "from_bytes", "(", "cls", ",", "image_bytes", ",", "affine", ",", "crs", ",", "band_names", "=", "None", ")", ":", "b", "=", "io", ".", "BytesIO", "(", "image_bytes", ")", "image", "=", "imageio", ".", "imread", "(", "b", ")", "roll", "=", "...
Create GeoRaster from image BytesIo object. :param image_bytes: io.BytesIO object :param affine: rasters affine :param crs: rasters crs :param band_names: e.g. ['red', 'blue'] or 'red'
[ "Create", "GeoRaster", "from", "image", "BytesIo", "object", "." ]
python
train
37.470588
quodlibet/mutagen
mutagen/asf/_util.py
https://github.com/quodlibet/mutagen/blob/e393df5971ba41ba5a50de9c2c9e7e5484d82c4e/mutagen/asf/_util.py#L27-L38
def guid2bytes(s): """Converts a GUID to the serialized bytes representation""" assert isinstance(s, str) assert len(s) == 36 p = struct.pack return b"".join([ p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)), p(">H", int(s[19:23], 16)), p(">Q", int(s[24:], 16...
[ "def", "guid2bytes", "(", "s", ")", ":", "assert", "isinstance", "(", "s", ",", "str", ")", "assert", "len", "(", "s", ")", "==", "36", "p", "=", "struct", ".", "pack", "return", "b\"\"", ".", "join", "(", "[", "p", "(", "\"<IHH\"", ",", "int", ...
Converts a GUID to the serialized bytes representation
[ "Converts", "a", "GUID", "to", "the", "serialized", "bytes", "representation" ]
python
train
26.916667
booktype/python-ooxml
ooxml/serialize.py
https://github.com/booktype/python-ooxml/blob/b56990a5bee2e1bc46839cec5161ff3726dc4d87/ooxml/serialize.py#L342-L355
def has_style(node): """Tells us if node element has defined styling. :Args: - node (:class:`ooxml.doc.Element`): Element :Returns: True or False """ elements = ['b', 'i', 'u', 'strike', 'color', 'jc', 'sz', 'ind', 'superscript', 'subscript', 'small_caps'] return any([True f...
[ "def", "has_style", "(", "node", ")", ":", "elements", "=", "[", "'b'", ",", "'i'", ",", "'u'", ",", "'strike'", ",", "'color'", ",", "'jc'", ",", "'sz'", ",", "'ind'", ",", "'superscript'", ",", "'subscript'", ",", "'small_caps'", "]", "return", "any"...
Tells us if node element has defined styling. :Args: - node (:class:`ooxml.doc.Element`): Element :Returns: True or False
[ "Tells", "us", "if", "node", "element", "has", "defined", "styling", "." ]
python
train
24.857143
matousc89/padasip
padasip/ann/mlp.py
https://github.com/matousc89/padasip/blob/c969eadd7fa181a84da0554d737fc13c6450d16f/padasip/ann/mlp.py#L413-L436
def predict(self, x): """ This function make forward pass through MLP (no update). **Args:** * `x` : input vector (1-dimensional array) **Returns:** * `y` : output of MLP (float or 1-diemnsional array). Size depends on number of MLP outputs. ...
[ "def", "predict", "(", "self", ",", "x", ")", ":", "# forward pass to hidden layers", "for", "l", "in", "self", ".", "layers", ":", "x", "=", "l", ".", "predict", "(", "x", ")", "self", ".", "x", "[", "1", ":", "]", "=", "x", "# forward pass to outpu...
This function make forward pass through MLP (no update). **Args:** * `x` : input vector (1-dimensional array) **Returns:** * `y` : output of MLP (float or 1-diemnsional array). Size depends on number of MLP outputs.
[ "This", "function", "make", "forward", "pass", "through", "MLP", "(", "no", "update", ")", "." ]
python
train
26.583333
jealous/stockstats
stockstats.py
https://github.com/jealous/stockstats/blob/a479a504ea1906955feeb8519c34ef40eb48ec9b/stockstats.py#L534-L546
def _get_pdi(cls, df, windows): """ +DI, positive directional moving index :param df: data :param windows: range :return: """ window = cls.get_only_one_positive_int(windows) pdm_column = 'pdm_{}'.format(window) tr_column = 'atr_{}'.format(window)...
[ "def", "_get_pdi", "(", "cls", ",", "df", ",", "windows", ")", ":", "window", "=", "cls", ".", "get_only_one_positive_int", "(", "windows", ")", "pdm_column", "=", "'pdm_{}'", ".", "format", "(", "window", ")", "tr_column", "=", "'atr_{}'", ".", "format", ...
+DI, positive directional moving index :param df: data :param windows: range :return:
[ "+", "DI", "positive", "directional", "moving", "index", ":", "param", "df", ":", "data", ":", "param", "windows", ":", "range", ":", "return", ":" ]
python
train
34.461538
abhinav/reversible
reversible/generator.py
https://github.com/abhinav/reversible/blob/7e28aaf0390f7d4b889c6ac14d7b340f8f314e89/reversible/generator.py#L64-L153
def gen(function): """ Allows using a generator to chain together reversible actions. This decorator may be added to a generator that yields reversible actions (any object with a ``.forwards()`` and ``.backwards()`` method). These may be constructed manually or via :py:func:`reversible.action`. The...
[ "def", "gen", "(", "function", ")", ":", "@", "functools", ".", "wraps", "(", "function", ")", "# TODO: use wrapt instead?", "def", "new_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "value", "=", "function", "(", "*", "ar...
Allows using a generator to chain together reversible actions. This decorator may be added to a generator that yields reversible actions (any object with a ``.forwards()`` and ``.backwards()`` method). These may be constructed manually or via :py:func:`reversible.action`. The decorated function, when c...
[ "Allows", "using", "a", "generator", "to", "chain", "together", "reversible", "actions", "." ]
python
train
38.277778
hydraplatform/hydra-base
hydra_base/lib/network.py
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/lib/network.py#L1994-L2043
def add_group(network_id, group,**kwargs): """ Add a resourcegroup to a network """ user_id = kwargs.get('user_id') try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() net_i.check_write_permission(user_id=user_id) except NoResultFound: rai...
[ "def", "add_group", "(", "network_id", ",", "group", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "try", ":", "net_i", "=", "db", ".", "DBSession", ".", "query", "(", "Network", ")", ".", "filter", ...
Add a resourcegroup to a network
[ "Add", "a", "resourcegroup", "to", "a", "network" ]
python
train
35.98
osrg/ryu
ryu/lib/ovs/bridge.py
https://github.com/osrg/ryu/blob/6f906e72c92e10bd0264c9b91a2f7bb85b97780c/ryu/lib/ovs/bridge.py#L235-L250
def get_db_attribute(self, table, record, column, key=None): """ Gets values of 'column' in 'record' in 'table'. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl get TBL REC COL[:KEY] """ if key is not None: column = '%s:%s' ...
[ "def", "get_db_attribute", "(", "self", ",", "table", ",", "record", ",", "column", ",", "key", "=", "None", ")", ":", "if", "key", "is", "not", "None", ":", "column", "=", "'%s:%s'", "%", "(", "column", ",", "key", ")", "command", "=", "ovs_vsctl", ...
Gets values of 'column' in 'record' in 'table'. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl get TBL REC COL[:KEY]
[ "Gets", "values", "of", "column", "in", "record", "in", "table", "." ]
python
train
32.875
bokeh/bokeh
bokeh/colors/rgb.py
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/colors/rgb.py#L110-L120
def to_css(self): ''' Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"`` ''' if self.a == 1.0: return "rgb(%d, %d, %d)" % (self.r, self.g, self.b) else: return "rgba(%d, %d, %d, %s)" % (self.r, ...
[ "def", "to_css", "(", "self", ")", ":", "if", "self", ".", "a", "==", "1.0", ":", "return", "\"rgb(%d, %d, %d)\"", "%", "(", "self", ".", "r", ",", "self", ".", "g", ",", "self", ".", "b", ")", "else", ":", "return", "\"rgba(%d, %d, %d, %s)\"", "%", ...
Generate the CSS representation of this RGB color. Returns: str, ``"rgb(...)"`` or ``"rgba(...)"``
[ "Generate", "the", "CSS", "representation", "of", "this", "RGB", "color", "." ]
python
train
30.272727
jhuapl-boss/intern
intern/remote/boss/remote.py
https://github.com/jhuapl-boss/intern/blob/d8fc6df011d8f212c87e6a1fd4cc21cfb5d103ed/intern/remote/boss/remote.py#L952-L970
def get_neuroglancer_link(self, resource, resolution, x_range, y_range, z_range, **kwargs): """ Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible w...
[ "def", "get_neuroglancer_link", "(", "self", ",", "resource", ",", "resolution", ",", "x_range", ",", "y_range", ",", "z_range", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_volume", ".", "get_neuroglancer_link", "(", "resource", ",", "resolut...
Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step. Args: resource (intern.resource.Resource): Resource compatible with cutout operations. resolution (int): 0 indicates native resolution. x_range (list[in...
[ "Get", "a", "neuroglancer", "link", "of", "the", "cutout", "specified", "from", "the", "host", "specified", "in", "the", "remote", "configuration", "step", "." ]
python
train
54.631579
acorg/dark-matter
dark/filter.py
https://github.com/acorg/dark-matter/blob/c78a1bf262667fa5db3548fa7066c4ec14d0551d/dark/filter.py#L129-L157
def accept(self, title, titleAlignments): """ Return C{True} if the read id set in C{titleAlignments} is sufficiently different from all previously seen read sets. @param title: A C{str} sequence title. @param titleAlignments: An instance of L{TitleAlignment}. @return: A...
[ "def", "accept", "(", "self", ",", "title", ",", "titleAlignments", ")", ":", "# Sanity check: titles can only be passed once.", "assert", "title", "not", "in", "self", ".", "_titles", ",", "(", "'Title %r seen multiple times.'", "%", "title", ")", "readIds", "=", ...
Return C{True} if the read id set in C{titleAlignments} is sufficiently different from all previously seen read sets. @param title: A C{str} sequence title. @param titleAlignments: An instance of L{TitleAlignment}. @return: A C{bool} indicating whether a title has an acceptably novel ...
[ "Return", "C", "{", "True", "}", "if", "the", "read", "id", "set", "in", "C", "{", "titleAlignments", "}", "is", "sufficiently", "different", "from", "all", "previously", "seen", "read", "sets", "." ]
python
train
38.413793
ungarj/tilematrix
tilematrix/_tilepyramid.py
https://github.com/ungarj/tilematrix/blob/6f8cd3b85f61434a7ce5d7b635c3ad8f18ccb268/tilematrix/_tilepyramid.py#L173-L194
def tiles_from_bounds(self, bounds, zoom): """ Return all tiles intersecting with bounds. Bounds values will be cleaned if they cross the antimeridian or are outside of the Northern or Southern tile pyramid bounds. - bounds: tuple of (left, bottom, right, top) bounding values i...
[ "def", "tiles_from_bounds", "(", "self", ",", "bounds", ",", "zoom", ")", ":", "validate_zoom", "(", "zoom", ")", "if", "not", "isinstance", "(", "bounds", ",", "tuple", ")", "or", "len", "(", "bounds", ")", "!=", "4", ":", "raise", "ValueError", "(", ...
Return all tiles intersecting with bounds. Bounds values will be cleaned if they cross the antimeridian or are outside of the Northern or Southern tile pyramid bounds. - bounds: tuple of (left, bottom, right, top) bounding values in tile pyramid CRS - zoom: zoom level
[ "Return", "all", "tiles", "intersecting", "with", "bounds", "." ]
python
train
39.363636
tisimst/mcerp
mcerp/__init__.py
https://github.com/tisimst/mcerp/blob/2bb8260c9ad2d58a806847f1b627b6451e407de1/mcerp/__init__.py#L1191-L1234
def Hypergeometric(N, n, K, tag=None): """ A Hypergeometric random variate Parameters ---------- N : int The total population size n : int The number of individuals of interest in the population K : int The number of individuals that will be chosen from the popul...
[ "def", "Hypergeometric", "(", "N", ",", "n", ",", "K", ",", "tag", "=", "None", ")", ":", "assert", "(", "int", "(", "N", ")", "==", "N", "and", "N", ">", "0", ")", ",", "'Hypergeometric total population size \"N\" must be an integer greater than zero.'", "a...
A Hypergeometric random variate Parameters ---------- N : int The total population size n : int The number of individuals of interest in the population K : int The number of individuals that will be chosen from the population Example ------- (Taken f...
[ "A", "Hypergeometric", "random", "variate", "Parameters", "----------", "N", ":", "int", "The", "total", "population", "size", "n", ":", "int", "The", "number", "of", "individuals", "of", "interest", "in", "the", "population", "K", ":", "int", "The", "number...
python
train
35
totalgood/nlpia
src/nlpia/plots.py
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L226-L239
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): """Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""...
[ "def", "normalize_etpinard_df", "(", "df", "=", "'https://plot.ly/~etpinard/191.csv'", ",", "columns", "=", "'x y size text'", ".", "split", "(", ")", ",", "category_col", "=", "'category'", ",", "possible_categories", "=", "[", "'Africa'", ",", "'Americas'", ",", ...
Reformat a dataframe in etpinard's format for use in plot functions and sklearn models
[ "Reformat", "a", "dataframe", "in", "etpinard", "s", "format", "for", "use", "in", "plot", "functions", "and", "sklearn", "models" ]
python
train
72.285714
manns/pyspread
pyspread/src/lib/__csv.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/lib/__csv.py#L434-L459
def write(self, iterable): """Writes values from iterable into CSV file""" io_error_text = _("Error writing to file {filepath}.") io_error_text = io_error_text.format(filepath=self.path) try: with open(self.path, "wb") as csvfile: csv_writer = csv.writer(cs...
[ "def", "write", "(", "self", ",", "iterable", ")", ":", "io_error_text", "=", "_", "(", "\"Error writing to file {filepath}.\"", ")", "io_error_text", "=", "io_error_text", ".", "format", "(", "filepath", "=", "self", ".", "path", ")", "try", ":", "with", "o...
Writes values from iterable into CSV file
[ "Writes", "values", "from", "iterable", "into", "CSV", "file" ]
python
train
33.076923
datastore/datastore
datastore/core/serialize.py
https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/serialize.py#L84-L88
def loads(cls, value): '''Returns mapping type deserialized `value`.''' if len(value) == 1 and cls.sentinel in value: value = value[cls.sentinel] return value
[ "def", "loads", "(", "cls", ",", "value", ")", ":", "if", "len", "(", "value", ")", "==", "1", "and", "cls", ".", "sentinel", "in", "value", ":", "value", "=", "value", "[", "cls", ".", "sentinel", "]", "return", "value" ]
Returns mapping type deserialized `value`.
[ "Returns", "mapping", "type", "deserialized", "value", "." ]
python
train
34.4
saltstack/salt
salt/modules/splunk_search.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L82-L89
def _get_splunk_search_props(search): ''' Get splunk search properties from an object ''' props = search.content props["app"] = search.access.app props["sharing"] = search.access.sharing return props
[ "def", "_get_splunk_search_props", "(", "search", ")", ":", "props", "=", "search", ".", "content", "props", "[", "\"app\"", "]", "=", "search", ".", "access", ".", "app", "props", "[", "\"sharing\"", "]", "=", "search", ".", "access", ".", "sharing", "r...
Get splunk search properties from an object
[ "Get", "splunk", "search", "properties", "from", "an", "object" ]
python
train
27.5
c0fec0de/anytree
anytree/exporter/dotexporter.py
https://github.com/c0fec0de/anytree/blob/775477e206a75e697983e70dae6372b5a7e42dcf/anytree/exporter/dotexporter.py#L190-L215
def to_dotfile(self, filename): """ Write graph to `filename`. >>> from anytree import Node >>> root = Node("root") >>> s0 = Node("sub0", parent=root) >>> s0b = Node("sub0B", parent=s0) >>> s0a = Node("sub0A", parent=s0) >>> s1 = Node("sub1", parent=root)...
[ "def", "to_dotfile", "(", "self", ",", "filename", ")", ":", "with", "codecs", ".", "open", "(", "filename", ",", "\"w\"", ",", "\"utf-8\"", ")", "as", "file", ":", "for", "line", "in", "self", ":", "file", ".", "write", "(", "\"%s\\n\"", "%", "line"...
Write graph to `filename`. >>> from anytree import Node >>> root = Node("root") >>> s0 = Node("sub0", parent=root) >>> s0b = Node("sub0B", parent=s0) >>> s0a = Node("sub0A", parent=s0) >>> s1 = Node("sub1", parent=root) >>> s1a = Node("sub1A", parent=s1) ...
[ "Write", "graph", "to", "filename", "." ]
python
train
34.076923
thiagopbueno/pyrddl
pyrddl/parser.py
https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/parser.py#L463-L470
def p_state_invariant_section(self, p): '''state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI | STATE_INVARIANTS LCURLY RCURLY SEMI''' if len(p) == 6: p[0] = ('invariants', p[3]) elif len(p) == 5: p[0] = (...
[ "def", "p_state_invariant_section", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "6", ":", "p", "[", "0", "]", "=", "(", "'invariants'", ",", "p", "[", "3", "]", ")", "elif", "len", "(", "p", ")", "==", "5", ":", "p", ...
state_invariant_section : STATE_INVARIANTS LCURLY state_invariant_list RCURLY SEMI | STATE_INVARIANTS LCURLY RCURLY SEMI
[ "state_invariant_section", ":", "STATE_INVARIANTS", "LCURLY", "state_invariant_list", "RCURLY", "SEMI", "|", "STATE_INVARIANTS", "LCURLY", "RCURLY", "SEMI" ]
python
train
46.5
limix/glimix-core
glimix_core/lmm/_kron2sum.py
https://github.com/limix/glimix-core/blob/cddd0994591d100499cc41c1f480ddd575e7a980/glimix_core/lmm/_kron2sum.py#L140-L150
def get_fast_scanner(self): """ Return :class:`.FastScanner` for association scan. Returns ------- :class:`.FastScanner` Instance of a class designed to perform very fast association scan. """ terms = self._terms return KronFastScanner(self._Y...
[ "def", "get_fast_scanner", "(", "self", ")", ":", "terms", "=", "self", ".", "_terms", "return", "KronFastScanner", "(", "self", ".", "_Y", ",", "self", ".", "_mean", ".", "A", ",", "self", ".", "_mean", ".", "X", ",", "self", ".", "_cov", ".", "Ge...
Return :class:`.FastScanner` for association scan. Returns ------- :class:`.FastScanner` Instance of a class designed to perform very fast association scan.
[ "Return", ":", "class", ":", ".", "FastScanner", "for", "association", "scan", "." ]
python
valid
32.727273
tensorpack/tensorpack
tensorpack/utils/argtools.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/argtools.py#L75-L86
def memoized_ignoreargs(func): """ A decorator. It performs memoization ignoring the arguments used to call the function. """ def wrapper(*args, **kwargs): if func not in _MEMOIZED_NOARGS: res = func(*args, **kwargs) _MEMOIZED_NOARGS[func] = res return res...
[ "def", "memoized_ignoreargs", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "func", "not", "in", "_MEMOIZED_NOARGS", ":", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_ME...
A decorator. It performs memoization ignoring the arguments used to call the function.
[ "A", "decorator", ".", "It", "performs", "memoization", "ignoring", "the", "arguments", "used", "to", "call", "the", "function", "." ]
python
train
30.5
dhhagan/py-opc
opc/__init__.py
https://github.com/dhhagan/py-opc/blob/2c8f19530fb64bf5fd4ee0d694a47850161ed8a7/opc/__init__.py#L1041-L1103
def read_histogram(self): """Read and reset the histogram. The expected return is a dictionary containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature, pressure, the sampling period, the checksum, PM1, PM2.5, and PM10. **NOTE:** The sampling period for the OPCN1 seems t...
[ "def", "read_histogram", "(", "self", ")", ":", "resp", "=", "[", "]", "data", "=", "{", "}", "# command byte", "command", "=", "0x30", "# Send the command byte", "self", ".", "cnxn", ".", "xfer", "(", "[", "command", "]", ")", "# Wait 10 ms", "sleep", "...
Read and reset the histogram. The expected return is a dictionary containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature, pressure, the sampling period, the checksum, PM1, PM2.5, and PM10. **NOTE:** The sampling period for the OPCN1 seems to be incorrect. :returns: di...
[ "Read", "and", "reset", "the", "histogram", ".", "The", "expected", "return", "is", "a", "dictionary", "containing", "the", "counts", "per", "bin", "MToF", "for", "bins", "1", "3", "5", "and", "7", "temperature", "pressure", "the", "sampling", "period", "t...
python
valid
48.68254
Hackerfleet/hfos
hfos/database.py
https://github.com/Hackerfleet/hfos/blob/b6df14eacaffb6be5c844108873ff8763ec7f0c9/hfos/database.py#L558-L577
def _check_collections(self): """Checks node local collection storage sizes""" self.collection_sizes = {} self.collection_total = 0 for col in self.db.collection_names(include_system_collections=False): self.collection_sizes[col] = self.db.command('collstats', col).get( ...
[ "def", "_check_collections", "(", "self", ")", ":", "self", ".", "collection_sizes", "=", "{", "}", "self", ".", "collection_total", "=", "0", "for", "col", "in", "self", ".", "db", ".", "collection_names", "(", "include_system_collections", "=", "False", ")...
Checks node local collection storage sizes
[ "Checks", "node", "local", "collection", "storage", "sizes" ]
python
train
41.4
Gandi/gandi.cli
gandi/cli/commands/vm.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/vm.py#L364-L389
def update(gandi, resource, memory, cores, console, password, background, reboot): """Update a virtual machine. Resource can be a Hostname or an ID """ pwd = None if password: pwd = click.prompt('password', hide_input=True, confirmation_prompt=True) ...
[ "def", "update", "(", "gandi", ",", "resource", ",", "memory", ",", "cores", ",", "console", ",", "password", ",", "background", ",", "reboot", ")", ":", "pwd", "=", "None", "if", "password", ":", "pwd", "=", "click", ".", "prompt", "(", "'password'", ...
Update a virtual machine. Resource can be a Hostname or an ID
[ "Update", "a", "virtual", "machine", "." ]
python
train
29.692308
timothydmorton/VESPA
vespa/populations.py
https://github.com/timothydmorton/VESPA/blob/0446b54d48009f3655cfd1a3957ceea21d3adcaa/vespa/populations.py#L2261-L2268
def add_population(self,pop): """Adds population to PopulationSet """ if pop.model in self.modelnames: raise ValueError('%s model already in PopulationSet.' % pop.model) self.modelnames.append(pop.model) self.shortmodelnames.append(pop.modelshort) self.poplist...
[ "def", "add_population", "(", "self", ",", "pop", ")", ":", "if", "pop", ".", "model", "in", "self", ".", "modelnames", ":", "raise", "ValueError", "(", "'%s model already in PopulationSet.'", "%", "pop", ".", "model", ")", "self", ".", "modelnames", ".", ...
Adds population to PopulationSet
[ "Adds", "population", "to", "PopulationSet" ]
python
train
40.625
PyCQA/pylint
pylint/config.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/config.py#L827-L831
def option_attrname(self, opt, optdict=None): """get the config attribute corresponding to opt""" if optdict is None: optdict = self.get_option_def(opt) return optdict.get("dest", opt.replace("-", "_"))
[ "def", "option_attrname", "(", "self", ",", "opt", ",", "optdict", "=", "None", ")", ":", "if", "optdict", "is", "None", ":", "optdict", "=", "self", ".", "get_option_def", "(", "opt", ")", "return", "optdict", ".", "get", "(", "\"dest\"", ",", "opt", ...
get the config attribute corresponding to opt
[ "get", "the", "config", "attribute", "corresponding", "to", "opt" ]
python
test
46.8
google/grumpy
third_party/stdlib/textwrap.py
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/textwrap.py#L322-L335
def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characte...
[ "def", "wrap", "(", "self", ",", "text", ")", ":", "text", "=", "self", ".", "_munge_whitespace", "(", "text", ")", "chunks", "=", "self", ".", "_split", "(", "text", ")", "if", "self", ".", "fix_sentence_endings", ":", "self", ".", "_fix_sentence_ending...
wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are ...
[ "wrap", "(", "text", ":", "string", ")", "-", ">", "[", "string", "]" ]
python
valid
41.285714
Clinical-Genomics/scout
scout/commands/serve.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/commands/serve.py#L22-L53
def serve(context, config, host, port, debug, livereload): """Start the web server.""" pymongo_config = dict( MONGO_HOST=context.obj['host'], MONGO_PORT=context.obj['port'], MONGO_DBNAME=context.obj['mongodb'], MONGO_USERNAME=context.obj['username'], MONGO_PASSWORD=contex...
[ "def", "serve", "(", "context", ",", "config", ",", "host", ",", "port", ",", "debug", ",", "livereload", ")", ":", "pymongo_config", "=", "dict", "(", "MONGO_HOST", "=", "context", ".", "obj", "[", "'host'", "]", ",", "MONGO_PORT", "=", "context", "."...
Start the web server.
[ "Start", "the", "web", "server", "." ]
python
test
34.15625
ND-CSE-30151/tock
tock/machines.py
https://github.com/ND-CSE-30151/tock/blob/b8d21901aaf0e6ac913c2afa855f5b5a882a16c6/tock/machines.py#L389-L406
def is_deterministic(self): """Tests whether machine is deterministic.""" # naive quadratic algorithm patterns = [t.lhs for t in self.transitions] + list(self.accept_configs) for i, t1 in enumerate(patterns): for t2 in patterns[:i]: match = True ...
[ "def", "is_deterministic", "(", "self", ")", ":", "# naive quadratic algorithm", "patterns", "=", "[", "t", ".", "lhs", "for", "t", "in", "self", ".", "transitions", "]", "+", "list", "(", "self", ".", "accept_configs", ")", "for", "i", ",", "t1", "in", ...
Tests whether machine is deterministic.
[ "Tests", "whether", "machine", "is", "deterministic", "." ]
python
train
43.055556
volfpeter/graphscraper
src/graphscraper/spotifyartist.py
https://github.com/volfpeter/graphscraper/blob/11d407509956a282ee25190ed6491a162fc0fe7f/src/graphscraper/spotifyartist.py#L222-L239
def _create_node(self, index: int, name: str, external_id: Optional[str] = None) -> SpotifyArtistNode: """ Returns a new `SpotifyArtistNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node ...
[ "def", "_create_node", "(", "self", ",", "index", ":", "int", ",", "name", ":", "str", ",", "external_id", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "SpotifyArtistNode", ":", "if", "external_id", "is", "None", ":", "graph", ":", "Spotif...
Returns a new `SpotifyArtistNode` instance with the given index and name. Arguments: index (int): The index of the node to create. name (str): The name of the node to create. external_id (Optional[str]): The external ID of the node.
[ "Returns", "a", "new", "SpotifyArtistNode", "instance", "with", "the", "given", "index", "and", "name", "." ]
python
train
45.277778
wdm0006/git-pandas
gitpandas/repository.py
https://github.com/wdm0006/git-pandas/blob/e56b817b1d66b8296d1d5e703d5db0e181d25899/gitpandas/repository.py#L945-L997
def punchcard(self, branch='master', limit=None, days=None, by=None, normalize=None, ignore_globs=None, include_globs=None): """ Returns a pandas DataFrame containing all of the data for a punchcard. * day_of_week * hour_of_day * author / committer ...
[ "def", "punchcard", "(", "self", ",", "branch", "=", "'master'", ",", "limit", "=", "None", ",", "days", "=", "None", ",", "by", "=", "None", ",", "normalize", "=", "None", ",", "ignore_globs", "=", "None", ",", "include_globs", "=", "None", ")", ":"...
Returns a pandas DataFrame containing all of the data for a punchcard. * day_of_week * hour_of_day * author / committer * lines * insertions * deletions * net :param branch: the branch to return commits for :param limit: (optional, default...
[ "Returns", "a", "pandas", "DataFrame", "containing", "all", "of", "the", "data", "for", "a", "punchcard", "." ]
python
train
38.679245
tensorflow/tensor2tensor
tensor2tensor/data_generators/ice_parsing.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/ice_parsing.py#L37-L50
def tabbed_parsing_token_generator(data_dir, tmp_dir, train, prefix, source_vocab_size, target_vocab_size): """Generate source and target data from a single file.""" filename = "parsing_{0}.pairs".format("train" if train else "dev") source_vocab = generator_utils.get_or_generate...
[ "def", "tabbed_parsing_token_generator", "(", "data_dir", ",", "tmp_dir", ",", "train", ",", "prefix", ",", "source_vocab_size", ",", "target_vocab_size", ")", ":", "filename", "=", "\"parsing_{0}.pairs\"", ".", "format", "(", "\"train\"", "if", "train", "else", "...
Generate source and target data from a single file.
[ "Generate", "source", "and", "target", "data", "from", "a", "single", "file", "." ]
python
train
58.571429