repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
quadrismegistus/prosodic
prosodic/entity.py
https://github.com/quadrismegistus/prosodic/blob/8af66ed9be40c922d03a0b09bc11c87d2061b618/prosodic/entity.py#L972-L1115
def genfsms(self,meter=None): """Generate FSM images. Requires networkx and GraphViz.""" if (hasattr(self,'allParses')): name=self.getName() import networkx as nx m2int={'w':'0','s':'1'} gs={} gs['weight']=['str_weight'] gs['stress']=['str_stress'] gs['stressweight']=['str_stress','str_weigh...
[ "def", "genfsms", "(", "self", ",", "meter", "=", "None", ")", ":", "if", "(", "hasattr", "(", "self", ",", "'allParses'", ")", ")", ":", "name", "=", "self", ".", "getName", "(", ")", "import", "networkx", "as", "nx", "m2int", "=", "{", "'w'", "...
Generate FSM images. Requires networkx and GraphViz.
[ "Generate", "FSM", "images", ".", "Requires", "networkx", "and", "GraphViz", "." ]
python
train
openai/universe
universe/vncdriver/vnc_client.py
https://github.com/openai/universe/blob/cc9ce6ec241821bfb0f3b85dd455bd36e4ee7a8c/universe/vncdriver/vnc_client.py#L398-L402
def send_ClientCutText(self, message): """The client has new text in its clipboard. """ self.sendMessage(struct.pack("!BxxxI", 6, len(message))) self.sendMessage(message)
[ "def", "send_ClientCutText", "(", "self", ",", "message", ")", ":", "self", ".", "sendMessage", "(", "struct", ".", "pack", "(", "\"!BxxxI\"", ",", "6", ",", "len", "(", "message", ")", ")", ")", "self", ".", "sendMessage", "(", "message", ")" ]
The client has new text in its clipboard.
[ "The", "client", "has", "new", "text", "in", "its", "clipboard", "." ]
python
train
spotify/luigi
luigi/execution_summary.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/execution_summary.py#L257-L268
def _ranging_attributes(attributes, param_class): """ Checks if there is a continuous range """ next_attributes = {param_class.next_in_enumeration(attribute) for attribute in attributes} in_first = attributes.difference(next_attributes) in_second = next_attributes.difference(attributes) if l...
[ "def", "_ranging_attributes", "(", "attributes", ",", "param_class", ")", ":", "next_attributes", "=", "{", "param_class", ".", "next_in_enumeration", "(", "attribute", ")", "for", "attribute", "in", "attributes", "}", "in_first", "=", "attributes", ".", "differen...
Checks if there is a continuous range
[ "Checks", "if", "there", "is", "a", "continuous", "range" ]
python
train
fabioz/PyDev.Debugger
_pydev_bundle/pydev_umd.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_umd.py#L102-L123
def _get_globals(): """Return current Python interpreter globals namespace""" if _get_globals_callback is not None: return _get_globals_callback() else: try: from __main__ import __dict__ as namespace except ImportError: try: # The import fails...
[ "def", "_get_globals", "(", ")", ":", "if", "_get_globals_callback", "is", "not", "None", ":", "return", "_get_globals_callback", "(", ")", "else", ":", "try", ":", "from", "__main__", "import", "__dict__", "as", "namespace", "except", "ImportError", ":", "try...
Return current Python interpreter globals namespace
[ "Return", "current", "Python", "interpreter", "globals", "namespace" ]
python
train
google/grr
grr/server/grr_response_server/databases/mysql_clients.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_clients.py#L542-L562
def ListClientsForKeywords(self, keywords, start_time=None, cursor=None): """Lists the clients associated with keywords.""" keywords = set(keywords) hash_to_kw = {mysql_utils.Hash(kw): kw for kw in keywords} result = {kw: [] for kw in keywords} query = """ SELECT keyword_hash, client_id ...
[ "def", "ListClientsForKeywords", "(", "self", ",", "keywords", ",", "start_time", "=", "None", ",", "cursor", "=", "None", ")", ":", "keywords", "=", "set", "(", "keywords", ")", "hash_to_kw", "=", "{", "mysql_utils", ".", "Hash", "(", "kw", ")", ":", ...
Lists the clients associated with keywords.
[ "Lists", "the", "clients", "associated", "with", "keywords", "." ]
python
train
stanfordnlp/stanza
stanza/nlp/corenlp.py
https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/nlp/corenlp.py#L51-L77
def _request(self, text, properties, retries=0): """Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :return: request result """ text = to_unicode(text)...
[ "def", "_request", "(", "self", ",", "text", ",", "properties", ",", "retries", "=", "0", ")", ":", "text", "=", "to_unicode", "(", "text", ")", "# ensures unicode", "try", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "server", ",", "par...
Send a request to the CoreNLP server. :param (str | unicode) text: raw text for the CoreNLPServer to parse :param (dict) properties: properties that the server expects :return: request result
[ "Send", "a", "request", "to", "the", "CoreNLP", "server", "." ]
python
train
google/openhtf
examples/phase_groups.py
https://github.com/google/openhtf/blob/655e85df7134db7bdf8f8fdd6ff9a6bf932e7b09/examples/phase_groups.py#L97-L117
def run_nested_groups(): """Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase """ test = htf.Test( htf.PhaseGroup( main=[ ...
[ "def", "run_nested_groups", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "main", "=", "[", "main_phase", ",", "htf", ".", "PhaseGroup", ".", "with_teardown", "(", "inner_teardown_phase", ")", "(", "inner_main_phase", ...
Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase
[ "Run", "the", "nested", "groups", "example", "." ]
python
train
callowayproject/django-staff
staff/views.py
https://github.com/callowayproject/django-staff/blob/248e2b69be36ee9f702ff5ba92cd1fb58597cd41/staff/views.py#L24-L46
def userinfo_json(request, user_id): """ Return the user's information in a json object """ data = {'first_name': '', 'last_name': '', 'email': '', 'slug': '', 'bio': '', 'phone': '', 'is_active': False} try: member = S...
[ "def", "userinfo_json", "(", "request", ",", "user_id", ")", ":", "data", "=", "{", "'first_name'", ":", "''", ",", "'last_name'", ":", "''", ",", "'email'", ":", "''", ",", "'slug'", ":", "''", ",", "'bio'", ":", "''", ",", "'phone'", ":", "''", "...
Return the user's information in a json object
[ "Return", "the", "user", "s", "information", "in", "a", "json", "object" ]
python
train
jjgomera/iapws
iapws/_iapws.py
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/_iapws.py#L1027-L1077
def _Kw(rho, T): """Equation for the ionization constant of ordinary water Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] Returns ------- pKw : float Ionization constant in -log10(kw), [-] Notes ------ Raise :class:`No...
[ "def", "_Kw", "(", "rho", ",", "T", ")", ":", "# Check input parameters", "if", "rho", "<", "0", "or", "rho", ">", "1250", "or", "T", "<", "273.15", "or", "T", ">", "1073.15", ":", "raise", "NotImplementedError", "(", "\"Incoming out of bound\"", ")", "#...
Equation for the ionization constant of ordinary water Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] Returns ------- pKw : float Ionization constant in -log10(kw), [-] Notes ------ Raise :class:`NotImplementedError` if in...
[ "Equation", "for", "the", "ionization", "constant", "of", "ordinary", "water" ]
python
train
roclark/sportsreference
sportsreference/nba/boxscore.py
https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nba/boxscore.py#L1115-L1124
def home_wins(self): """ Returns an ``int`` of the number of games the home team won after the conclusion of the game. """ try: wins, losses = re.findall(r'\d+', self._home_record) return wins except ValueError: return 0
[ "def", "home_wins", "(", "self", ")", ":", "try", ":", "wins", ",", "losses", "=", "re", ".", "findall", "(", "r'\\d+'", ",", "self", ".", "_home_record", ")", "return", "wins", "except", "ValueError", ":", "return", "0" ]
Returns an ``int`` of the number of games the home team won after the conclusion of the game.
[ "Returns", "an", "int", "of", "the", "number", "of", "games", "the", "home", "team", "won", "after", "the", "conclusion", "of", "the", "game", "." ]
python
train
psd-tools/psd-tools
src/psd_tools/api/psd_image.py
https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/psd_image.py#L294-L300
def viewbox(self): """ Return bounding box of the viewport. :return: (left, top, right, bottom) `tuple`. """ return self.left, self.top, self.right, self.bottom
[ "def", "viewbox", "(", "self", ")", ":", "return", "self", ".", "left", ",", "self", ".", "top", ",", "self", ".", "right", ",", "self", ".", "bottom" ]
Return bounding box of the viewport. :return: (left, top, right, bottom) `tuple`.
[ "Return", "bounding", "box", "of", "the", "viewport", "." ]
python
train
singularityhub/sregistry-cli
sregistry/client/build.py
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/client/build.py#L173-L186
def list_logs(args, container_name=None): '''list a specific log for a builder, or the latest log if none provided Parameters ========== args: the argparse object to look for a container name container_name: a default container name set to be None (show latest log) ''' from sre...
[ "def", "list_logs", "(", "args", ",", "container_name", "=", "None", ")", ":", "from", "sregistry", ".", "main", "import", "Client", "as", "cli", "if", "len", "(", "args", ".", "commands", ")", ">", "0", ":", "container_name", "=", "args", ".", "comman...
list a specific log for a builder, or the latest log if none provided Parameters ========== args: the argparse object to look for a container name container_name: a default container name set to be None (show latest log)
[ "list", "a", "specific", "log", "for", "a", "builder", "or", "the", "latest", "log", "if", "none", "provided" ]
python
test
brocade/pynos
pynos/versions/ver_6/ver_6_0_1/yang/brocade_qos.py
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/ver_6/ver_6_0_1/yang/brocade_qos.py#L886-L897
def nas_auto_qos_set_dscp(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nas = ET.SubElement(config, "nas", xmlns="urn:brocade.com:mgmt:brocade-qos") auto_qos = ET.SubElement(nas, "auto-qos") set = ET.SubElement(auto_qos, "set") dscp = E...
[ "def", "nas_auto_qos_set_dscp", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "nas", "=", "ET", ".", "SubElement", "(", "config", ",", "\"nas\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:broc...
Auto Generated Code
[ "Auto", "Generated", "Code" ]
python
train
tensorflow/tensor2tensor
tensor2tensor/models/research/autoencoders.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/autoencoders.py#L1157-L1164
def autoencoder_residual_discrete_big(): """Residual discrete autoencoder model, big version.""" hparams = autoencoder_residual_discrete() hparams.hidden_size = 128 hparams.max_hidden_size = 4096 hparams.bottleneck_noise = 0.1 hparams.residual_dropout = 0.4 return hparams
[ "def", "autoencoder_residual_discrete_big", "(", ")", ":", "hparams", "=", "autoencoder_residual_discrete", "(", ")", "hparams", ".", "hidden_size", "=", "128", "hparams", ".", "max_hidden_size", "=", "4096", "hparams", ".", "bottleneck_noise", "=", "0.1", "hparams"...
Residual discrete autoencoder model, big version.
[ "Residual", "discrete", "autoencoder", "model", "big", "version", "." ]
python
train
CartoDB/cartoframes
cartoframes/datasets.py
https://github.com/CartoDB/cartoframes/blob/c94238a545f3dec45963dac3892540942b6f0df8/cartoframes/datasets.py#L213-L219
def get_columns(context, query): """Get list of cartoframes.columns.Column""" table_info = context.sql_client.send(query) if 'fields' in table_info: return Column.from_sql_api_fields(table_info['fields']) return None
[ "def", "get_columns", "(", "context", ",", "query", ")", ":", "table_info", "=", "context", ".", "sql_client", ".", "send", "(", "query", ")", "if", "'fields'", "in", "table_info", ":", "return", "Column", ".", "from_sql_api_fields", "(", "table_info", "[", ...
Get list of cartoframes.columns.Column
[ "Get", "list", "of", "cartoframes", ".", "columns", ".", "Column" ]
python
train
Azure/azure-cosmos-python
azure/cosmos/cosmos_client.py
https://github.com/Azure/azure-cosmos-python/blob/dd01b3c5d308c6da83cfcaa0ab7083351a476353/azure/cosmos/cosmos_client.py#L639-L662
def ReadPermission(self, permission_link, options=None): """Reads a permission. :param str permission_link: The link to the permission. :param dict options: The request options for the request. :return: The read permission. :rtype: ...
[ "def", "ReadPermission", "(", "self", ",", "permission_link", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "{", "}", "path", "=", "base", ".", "GetPathFromLink", "(", "permission_link", ")", "permission_id", "=...
Reads a permission. :param str permission_link: The link to the permission. :param dict options: The request options for the request. :return: The read permission. :rtype: dict
[ "Reads", "a", "permission", "." ]
python
train
zimeon/iiif
iiif/manipulator_gen.py
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/manipulator_gen.py#L62-L73
def do_region(self, x, y, w, h): """Record region.""" if (x is None): self.rx = 0 self.ry = 0 self.rw = self.width self.rh = self.height else: self.rx = x self.ry = y self.rw = w self.rh = h
[ "def", "do_region", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "if", "(", "x", "is", "None", ")", ":", "self", ".", "rx", "=", "0", "self", ".", "ry", "=", "0", "self", ".", "rw", "=", "self", ".", "width", "self", "."...
Record region.
[ "Record", "region", "." ]
python
train
Qiskit/qiskit-terra
qiskit/pulse/ops.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/pulse/ops.py#L22-L36
def union(*schedules: List[Union[ScheduleComponent, Tuple[int, ScheduleComponent]]], name: str = None) -> Schedule: """Create a union (and also shift if desired) of all input `Schedule`s. Args: *schedules: Schedules to take the union of name: Name of the new schedule. Defaults to firs...
[ "def", "union", "(", "*", "schedules", ":", "List", "[", "Union", "[", "ScheduleComponent", ",", "Tuple", "[", "int", ",", "ScheduleComponent", "]", "]", "]", ",", "name", ":", "str", "=", "None", ")", "->", "Schedule", ":", "if", "name", "is", "None...
Create a union (and also shift if desired) of all input `Schedule`s. Args: *schedules: Schedules to take the union of name: Name of the new schedule. Defaults to first element of `schedules`
[ "Create", "a", "union", "(", "and", "also", "shift", "if", "desired", ")", "of", "all", "input", "Schedule", "s", "." ]
python
test
Crunch-io/crunch-cube
src/cr/cube/crunch_cube.py
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/crunch_cube.py#L1361-L1378
def is_weighted(self): """True if weights have been applied to the measure(s) for this cube. Unweighted counts are available for all cubes. Weighting applies to any other measures provided by the cube. """ cube_dict = self._cube_dict if cube_dict.get("query", {}).get("we...
[ "def", "is_weighted", "(", "self", ")", ":", "cube_dict", "=", "self", ".", "_cube_dict", "if", "cube_dict", ".", "get", "(", "\"query\"", ",", "{", "}", ")", ".", "get", "(", "\"weight\"", ")", "is", "not", "None", ":", "return", "True", "if", "cube...
True if weights have been applied to the measure(s) for this cube. Unweighted counts are available for all cubes. Weighting applies to any other measures provided by the cube.
[ "True", "if", "weights", "have", "been", "applied", "to", "the", "measure", "(", "s", ")", "for", "this", "cube", "." ]
python
train
nathforge/validatesns
src/validatesns/__init__.py
https://github.com/nathforge/validatesns/blob/39f7f7d1fae215746bb9763856045b501fae05f4/src/validatesns/__init__.py#L28-L69
def validate( message, get_certificate=lambda url: urlopen(url).read(), certificate_url_regex=DEFAULT_CERTIFICATE_URL_REGEX, max_age=DEFAULT_MAX_AGE ): """ Validate a decoded SNS message. Parameters: message: Decoded SNS message. get_certificate: Fun...
[ "def", "validate", "(", "message", ",", "get_certificate", "=", "lambda", "url", ":", "urlopen", "(", "url", ")", ".", "read", "(", ")", ",", "certificate_url_regex", "=", "DEFAULT_CERTIFICATE_URL_REGEX", ",", "max_age", "=", "DEFAULT_MAX_AGE", ")", ":", "# Ch...
Validate a decoded SNS message. Parameters: message: Decoded SNS message. get_certificate: Function that receives a URL, and returns the certificate from that URL as a string. The default doesn't implement caching. certificate_url_regex: Reg...
[ "Validate", "a", "decoded", "SNS", "message", "." ]
python
test
LogicalDash/LiSE
ELiDE/ELiDE/board/board.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L147-L201
def on_touch_down(self, touch): """Check for collisions and select an appropriate entity.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if not self.collide_point(*touch.pos): return touch.push() touch.apply_transform_2d(self.to_loc...
[ "def", "on_touch_down", "(", "self", ",", "touch", ")", ":", "if", "hasattr", "(", "self", ",", "'_lasttouch'", ")", "and", "self", ".", "_lasttouch", "==", "touch", ":", "return", "if", "not", "self", ".", "collide_point", "(", "*", "touch", ".", "pos...
Check for collisions and select an appropriate entity.
[ "Check", "for", "collisions", "and", "select", "an", "appropriate", "entity", "." ]
python
train
sirfoga/pyhal
hal/charts/plotter.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/charts/plotter.py#L159-L301
def plot_type(self, func, mins, maxs, precision, kind): """Plots function :param func: function to plot :param mins: minimum of values (x, y ...) :param maxs: maximum of values (x, y ...) :param precision: precision to plot :param kind: kind of plot, "slice", "countour" ...
[ "def", "plot_type", "(", "self", ",", "func", ",", "mins", ",", "maxs", ",", "precision", ",", "kind", ")", ":", "min_x", ",", "min_y", ",", "min_z", "=", "mins", "[", "0", "]", ",", "mins", "[", "1", "]", ",", "mins", "[", "2", "]", "max_x", ...
Plots function :param func: function to plot :param mins: minimum of values (x, y ...) :param maxs: maximum of values (x, y ...) :param precision: precision to plot :param kind: kind of plot, "slice", "countour"
[ "Plots", "function" ]
python
train
CGATOxford/UMI-tools
umi_tools/Utilities.py
https://github.com/CGATOxford/UMI-tools/blob/c4b5d84aac391d59916d294f8f4f8f5378abcfbe/umi_tools/Utilities.py#L530-L543
def getHeader(): """return a header string with command line options and timestamp """ system, host, release, version, machine = os.uname() return "# UMI-tools version: %s\n# output generated by %s\n# job started at %s on %s -- %s\n# pid: %i, system: %s %s %s %s" %\ (__version__, ...
[ "def", "getHeader", "(", ")", ":", "system", ",", "host", ",", "release", ",", "version", ",", "machine", "=", "os", ".", "uname", "(", ")", "return", "\"# UMI-tools version: %s\\n# output generated by %s\\n# job started at %s on %s -- %s\\n# pid: %i, system: %s %s %s %s\""...
return a header string with command line options and timestamp
[ "return", "a", "header", "string", "with", "command", "line", "options", "and", "timestamp" ]
python
train
deepmind/pysc2
pysc2/lib/remote_controller.py
https://github.com/deepmind/pysc2/blob/df4cc4b00f07a2242be9ba153d4a7f4ad2017897/pysc2/lib/remote_controller.py#L148-L174
def _connect(self, host, port, proc, timeout_seconds): """Connect to the websocket, retrying as needed. Returns the socket.""" if ":" in host and not host.startswith("["): # Support ipv6 addresses. host = "[%s]" % host url = "ws://%s:%s/sc2api" % (host, port) was_running = False for i in ran...
[ "def", "_connect", "(", "self", ",", "host", ",", "port", ",", "proc", ",", "timeout_seconds", ")", ":", "if", "\":\"", "in", "host", "and", "not", "host", ".", "startswith", "(", "\"[\"", ")", ":", "# Support ipv6 addresses.", "host", "=", "\"[%s]\"", "...
Connect to the websocket, retrying as needed. Returns the socket.
[ "Connect", "to", "the", "websocket", "retrying", "as", "needed", ".", "Returns", "the", "socket", "." ]
python
train
saltstack/salt
salt/log/setup.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L742-L824
def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a referenc...
[ "def", "setup_extended_logging", "(", "opts", ")", ":", "if", "is_extended_logging_configured", "(", ")", "is", "True", ":", "# Don't re-configure external loggers", "return", "# Explicit late import of salt's loader", "import", "salt", ".", "loader", "# Let's keep a referenc...
Setup any additional logging handlers, internal or external
[ "Setup", "any", "additional", "logging", "handlers", "internal", "or", "external" ]
python
train
MostAwesomeDude/gentleman
gentleman/base.py
https://github.com/MostAwesomeDude/gentleman/blob/17fb8ffb922aa4af9d8bcab85e452c9311d41805/gentleman/base.py#L1256-L1273
def RenameGroup(r, group, new_name): """ Changes the name of a node group. @type group: string @param group: Node group name @type new_name: string @param new_name: New node group name @rtype: int @return: job id """ body = { "new_name": new_name, } return r.r...
[ "def", "RenameGroup", "(", "r", ",", "group", ",", "new_name", ")", ":", "body", "=", "{", "\"new_name\"", ":", "new_name", ",", "}", "return", "r", ".", "request", "(", "\"put\"", ",", "\"/2/groups/%s/rename\"", "%", "group", ",", "content", "=", "body"...
Changes the name of a node group. @type group: string @param group: Node group name @type new_name: string @param new_name: New node group name @rtype: int @return: job id
[ "Changes", "the", "name", "of", "a", "node", "group", "." ]
python
train
PyCQA/pylint
pylint/message/message_handler_mix_in.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/message/message_handler_mix_in.py#L187-L196
def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED): """Returns the scope at which a message was enabled/disabled.""" if self.config.confidence and confidence.name not in self.config.confidence: return MSG_STATE_CONFIDENCE try: if line in self.file_s...
[ "def", "get_message_state_scope", "(", "self", ",", "msgid", ",", "line", "=", "None", ",", "confidence", "=", "UNDEFINED", ")", ":", "if", "self", ".", "config", ".", "confidence", "and", "confidence", ".", "name", "not", "in", "self", ".", "config", "....
Returns the scope at which a message was enabled/disabled.
[ "Returns", "the", "scope", "at", "which", "a", "message", "was", "enabled", "/", "disabled", "." ]
python
test
intake/intake
intake/gui/base.py
https://github.com/intake/intake/blob/277b96bfdee39d8a3048ea5408c6d6716d568336/intake/gui/base.py#L268-L273
def source(self, source): """When the source gets updated, update the select widget""" if isinstance(source, list): # if source is a list, get first item or None source = source[0] if len(source) > 0 else None self._source = source
[ "def", "source", "(", "self", ",", "source", ")", ":", "if", "isinstance", "(", "source", ",", "list", ")", ":", "# if source is a list, get first item or None", "source", "=", "source", "[", "0", "]", "if", "len", "(", "source", ")", ">", "0", "else", "...
When the source gets updated, update the select widget
[ "When", "the", "source", "gets", "updated", "update", "the", "select", "widget" ]
python
train
aiidateam/aiida-ase
aiida_ase/calculations/ase.py
https://github.com/aiidateam/aiida-ase/blob/688a01fa872717ee3babdb1f10405b306371cf44/aiida_ase/calculations/ase.py#L64-L365
def _prepare_for_submission(self,tempfolder, inputdict): """ This is the routine to be called when you want to create the input files and related stuff with a plugin. :param tempfolder: a aiida.common.folders.Folder subclass where the plugin sh...
[ "def", "_prepare_for_submission", "(", "self", ",", "tempfolder", ",", "inputdict", ")", ":", "try", ":", "code", "=", "inputdict", ".", "pop", "(", "self", ".", "get_linkname", "(", "'code'", ")", ")", "except", "KeyError", ":", "raise", "InputValidationErr...
This is the routine to be called when you want to create the input files and related stuff with a plugin. :param tempfolder: a aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: a dictionary with the input nodes, ...
[ "This", "is", "the", "routine", "to", "be", "called", "when", "you", "want", "to", "create", "the", "input", "files", "and", "related", "stuff", "with", "a", "plugin", ".", ":", "param", "tempfolder", ":", "a", "aiida", ".", "common", ".", "folders", "...
python
train
yjzhang/uncurl_python
uncurl/ensemble.py
https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/ensemble.py#L235-L247
def poisson_consensus_se(data, k, n_runs=10, **se_params): """ Initializes Poisson State Estimation using a consensus Poisson clustering. """ clusters = [] for i in range(n_runs): assignments, means = poisson_cluster(data, k) clusters.append(assignments) clusterings = np.vstack(...
[ "def", "poisson_consensus_se", "(", "data", ",", "k", ",", "n_runs", "=", "10", ",", "*", "*", "se_params", ")", ":", "clusters", "=", "[", "]", "for", "i", "in", "range", "(", "n_runs", ")", ":", "assignments", ",", "means", "=", "poisson_cluster", ...
Initializes Poisson State Estimation using a consensus Poisson clustering.
[ "Initializes", "Poisson", "State", "Estimation", "using", "a", "consensus", "Poisson", "clustering", "." ]
python
train
AkihikoITOH/capybara
capybara/virtualenv/lib/python2.7/site-packages/flask/config.py
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/flask/config.py#L138-L165
def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually e...
[ "def", "from_object", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "string_types", ")", ":", "obj", "=", "import_string", "(", "obj", ")", "for", "key", "in", "dir", "(", "obj", ")", ":", "if", "key", ".", "isupper", "(",...
Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. Just...
[ "Updates", "the", "values", "from", "the", "given", "object", ".", "An", "object", "can", "be", "of", "one", "of", "the", "following", "two", "types", ":" ]
python
test
Esri/ArcREST
src/arcrest/manageorg/_content.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_content.py#L1977-L2043
def __init(self, folder='/'): """loads the property data into the class""" params = { "f" : "json" } if folder is None or folder == "/": folder = 'root' result_template = { "username": "", "total": 0, "start": 1, ...
[ "def", "__init", "(", "self", ",", "folder", "=", "'/'", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "if", "folder", "is", "None", "or", "folder", "==", "\"/\"", ":", "folder", "=", "'root'", "result_template", "=", "{", "\"username\""...
loads the property data into the class
[ "loads", "the", "property", "data", "into", "the", "class" ]
python
train
liip/taxi
taxi/aliases.py
https://github.com/liip/taxi/blob/269423c1f1ab571bd01a522819afe3e325bfbff6/taxi/aliases.py#L94-L117
def filter_from_mapping(self, mapping, backend=None): """ Return mappings that either exactly correspond to the given `mapping` tuple, or, if the second item of `mapping` is `None`, include mappings that only match the first item of `mapping` (useful to show all mappings for a gi...
[ "def", "filter_from_mapping", "(", "self", ",", "mapping", ",", "backend", "=", "None", ")", ":", "def", "mapping_filter", "(", "key_item", ")", ":", "key", ",", "item", "=", "key_item", "return", "(", "(", "mapping", "is", "None", "or", "item", ".", "...
Return mappings that either exactly correspond to the given `mapping` tuple, or, if the second item of `mapping` is `None`, include mappings that only match the first item of `mapping` (useful to show all mappings for a given project).
[ "Return", "mappings", "that", "either", "exactly", "correspond", "to", "the", "given", "mapping", "tuple", "or", "if", "the", "second", "item", "of", "mapping", "is", "None", "include", "mappings", "that", "only", "match", "the", "first", "item", "of", "mapp...
python
train
kivy/python-for-android
pythonforandroid/bootstrap.py
https://github.com/kivy/python-for-android/blob/8e0e8056bc22e4d5bd3398a6b0301f38ff167933/pythonforandroid/bootstrap.py#L224-L229
def distribute_javaclasses(self, javaclass_dir, dest_dir="src"): '''Copy existing javaclasses from build dir to current dist dir.''' info('Copying java files') ensure_dir(dest_dir) for filename in glob.glob(javaclass_dir): shprint(sh.cp, '-a', filename, dest_dir)
[ "def", "distribute_javaclasses", "(", "self", ",", "javaclass_dir", ",", "dest_dir", "=", "\"src\"", ")", ":", "info", "(", "'Copying java files'", ")", "ensure_dir", "(", "dest_dir", ")", "for", "filename", "in", "glob", ".", "glob", "(", "javaclass_dir", ")"...
Copy existing javaclasses from build dir to current dist dir.
[ "Copy", "existing", "javaclasses", "from", "build", "dir", "to", "current", "dist", "dir", "." ]
python
train
dwkim78/upsilon
upsilon/extract_features/extract_features.py
https://github.com/dwkim78/upsilon/blob/5f381453f26582ef56e62fb8fed7317ce67861af/upsilon/extract_features/extract_features.py#L564-L600
def get_features2(self): """ Return all features with its names. Returns ------- names : list Feature names. values : list Feature values """ feature_names = [] feature_values = [] # Get all the names of features....
[ "def", "get_features2", "(", "self", ")", ":", "feature_names", "=", "[", "]", "feature_values", "=", "[", "]", "# Get all the names of features.", "all_vars", "=", "vars", "(", "self", ")", "for", "name", "in", "all_vars", ".", "keys", "(", ")", ":", "# O...
Return all features with its names. Returns ------- names : list Feature names. values : list Feature values
[ "Return", "all", "features", "with", "its", "names", "." ]
python
train
Qiskit/qiskit-terra
qiskit/quantum_info/operators/operator.py
https://github.com/Qiskit/qiskit-terra/blob/d4f58d903bc96341b816f7c35df936d6421267d1/qiskit/quantum_info/operators/operator.py#L402-L416
def _format_state(self, state): """Format input state so it is statevector or density matrix""" state = np.array(state) shape = state.shape ndim = state.ndim if ndim > 2: raise QiskitError('Input state is not a vector or matrix.') # Flatten column-vector to ve...
[ "def", "_format_state", "(", "self", ",", "state", ")", ":", "state", "=", "np", ".", "array", "(", "state", ")", "shape", "=", "state", ".", "shape", "ndim", "=", "state", ".", "ndim", "if", "ndim", ">", "2", ":", "raise", "QiskitError", "(", "'In...
Format input state so it is statevector or density matrix
[ "Format", "input", "state", "so", "it", "is", "statevector", "or", "density", "matrix" ]
python
test
ArduPilot/MAVProxy
MAVProxy/modules/mavproxy_example.py
https://github.com/ArduPilot/MAVProxy/blob/f50bdeff33064876f7dc8dc4683d278ff47f75d5/MAVProxy/modules/mavproxy_example.py#L59-L67
def status(self): '''returns information about module''' self.status_callcount += 1 self.last_bored = time.time() # status entertains us return("status called %(status_callcount)d times. My target positions=%(packets_mytarget)u Other target positions=%(packets_mytarget)u" % ...
[ "def", "status", "(", "self", ")", ":", "self", ".", "status_callcount", "+=", "1", "self", ".", "last_bored", "=", "time", ".", "time", "(", ")", "# status entertains us", "return", "(", "\"status called %(status_callcount)d times. My target positions=%(packets_mytarg...
returns information about module
[ "returns", "information", "about", "module" ]
python
train
Sanji-IO/sanji
sanji/core.py
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/core.py#L271-L292
def stop(self, *args, **kwargs): """ exit """ _logger.debug("Bundle [%s] has been shutting down" % self.bundle.profile["name"]) if hasattr(self, 'before_stop') and \ hasattr(self.before_stop, '__call__'): _logger.debug("Invoking befor...
[ "def", "stop", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_logger", ".", "debug", "(", "\"Bundle [%s] has been shutting down\"", "%", "self", ".", "bundle", ".", "profile", "[", "\"name\"", "]", ")", "if", "hasattr", "(", "self", ...
exit
[ "exit" ]
python
train
NoneGG/aredis
aredis/connection.py
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L651-L663
async def on_connect(self): """ Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization. """ if self.db: warnings.warn('SELECT DB is not allowed in cluster mode') self.db = '' await ...
[ "async", "def", "on_connect", "(", "self", ")", ":", "if", "self", ".", "db", ":", "warnings", ".", "warn", "(", "'SELECT DB is not allowed in cluster mode'", ")", "self", ".", "db", "=", "''", "await", "super", "(", "ClusterConnection", ",", "self", ")", ...
Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization.
[ "Initialize", "the", "connection", "authenticate", "and", "select", "a", "database", "and", "send", "READONLY", "if", "it", "is", "set", "during", "object", "initialization", "." ]
python
train
fredrike/pypoint
pypoint/__init__.py
https://github.com/fredrike/pypoint/blob/b5c9a701d2b7e24d796aa7f8c410360b61d8ec8a/pypoint/__init__.py#L295-L302
def device_status(self): """Status of device.""" return { 'active': self.device['active'], 'offline': self.device['offline'], 'last_update': self.last_update, 'battery_level': self.battery_level, }
[ "def", "device_status", "(", "self", ")", ":", "return", "{", "'active'", ":", "self", ".", "device", "[", "'active'", "]", ",", "'offline'", ":", "self", ".", "device", "[", "'offline'", "]", ",", "'last_update'", ":", "self", ".", "last_update", ",", ...
Status of device.
[ "Status", "of", "device", "." ]
python
train
internetarchive/doublethink
doublethink/rethinker.py
https://github.com/internetarchive/doublethink/blob/f7fc7da725c9b572d473c717b3dad9af98a7a2b4/doublethink/rethinker.py#L141-L155
def _server_whitelist(self): ''' Returns list of servers that have not errored in the last five minutes. If all servers have errored in the last five minutes, returns list with one item, the server that errored least recently. ''' whitelist = [] for server in self...
[ "def", "_server_whitelist", "(", "self", ")", ":", "whitelist", "=", "[", "]", "for", "server", "in", "self", ".", "servers", ":", "if", "(", "server", "not", "in", "self", ".", "last_error", "or", "self", ".", "last_error", "[", "server", "]", "<", ...
Returns list of servers that have not errored in the last five minutes. If all servers have errored in the last five minutes, returns list with one item, the server that errored least recently.
[ "Returns", "list", "of", "servers", "that", "have", "not", "errored", "in", "the", "last", "five", "minutes", ".", "If", "all", "servers", "have", "errored", "in", "the", "last", "five", "minutes", "returns", "list", "with", "one", "item", "the", "server",...
python
train
dtmilano/AndroidViewClient
src/com/dtmilano/android/adb/adbclient.py
https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/adb/adbclient.py#L994-L1011
def isLocked(self): ''' Checks if the device screen is locked. @return True if the device screen is locked ''' self.__checkTransport() lockScreenRE = re.compile('mShowingLockscreen=(true|false)') dwp = self.shell('dumpsys window policy') m = lockScreenRE...
[ "def", "isLocked", "(", "self", ")", ":", "self", ".", "__checkTransport", "(", ")", "lockScreenRE", "=", "re", ".", "compile", "(", "'mShowingLockscreen=(true|false)'", ")", "dwp", "=", "self", ".", "shell", "(", "'dumpsys window policy'", ")", "m", "=", "l...
Checks if the device screen is locked. @return True if the device screen is locked
[ "Checks", "if", "the", "device", "screen", "is", "locked", "." ]
python
train
soasme/dogeon
dson/decoder.py
https://github.com/soasme/dogeon/blob/496b9a5b099946d14434ed0cd7a94a270f607207/dson/decoder.py#L357-L370
def raw_decode(self, s, idx=0): r"""Decode a DSON document from ``s`` (a ``str`` or ``unicode`` beginning with a DSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a DSON document from a string tha...
[ "def", "raw_decode", "(", "self", ",", "s", ",", "idx", "=", "0", ")", ":", "try", ":", "obj", ",", "end", "=", "self", ".", "scan_once", "(", "s", ",", "idx", ")", "except", "StopIteration", ":", "raise", "ValueError", "(", "\"No DSON object could be ...
r"""Decode a DSON document from ``s`` (a ``str`` or ``unicode`` beginning with a DSON document) and return a 2-tuple of the Python representation and the index in ``s`` where the document ended. This can be used to decode a DSON document from a string that may have extraneous data at th...
[ "r", "Decode", "a", "DSON", "document", "from", "s", "(", "a", "str", "or", "unicode", "beginning", "with", "a", "DSON", "document", ")", "and", "return", "a", "2", "-", "tuple", "of", "the", "Python", "representation", "and", "the", "index", "in", "s"...
python
train
Kunstmord/datalib
src/dataset.py
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L408-L427
def return_single_features_base(dbpath, set_object, object_id): """ Generic function which returns the features of an object specified by the object_id Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the dat...
[ "def", "return_single_features_base", "(", "dbpath", ",", "set_object", ",", "object_id", ")", ":", "engine", "=", "create_engine", "(", "'sqlite:////'", "+", "dbpath", ")", "session_cl", "=", "sessionmaker", "(", "bind", "=", "engine", ")", "session", "=", "s...
Generic function which returns the features of an object specified by the object_id Parameters ---------- dbpath : string, path to SQLite database file set_object : object (either TestSet or TrainSet) which is stored in the database object_id : int, id of object in database Returns -------...
[ "Generic", "function", "which", "returns", "the", "features", "of", "an", "object", "specified", "by", "the", "object_id" ]
python
train
google/apitools
apitools/base/py/encoding_helper.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/encoding_helper.py#L464-L485
def _EncodeUnknownFields(message): """Remap unknown fields in message out of message.source.""" source = _UNRECOGNIZED_FIELD_MAPPINGS.get(type(message)) if source is None: return message # CopyProtoMessage uses _ProtoJsonApiTools, which uses this message. Use # the vanilla protojson-based co...
[ "def", "_EncodeUnknownFields", "(", "message", ")", ":", "source", "=", "_UNRECOGNIZED_FIELD_MAPPINGS", ".", "get", "(", "type", "(", "message", ")", ")", "if", "source", "is", "None", ":", "return", "message", "# CopyProtoMessage uses _ProtoJsonApiTools, which uses t...
Remap unknown fields in message out of message.source.
[ "Remap", "unknown", "fields", "in", "message", "out", "of", "message", ".", "source", "." ]
python
train
jldantas/libmft
libmft/attribute.py
https://github.com/jldantas/libmft/blob/65a988605fe7663b788bd81dcb52c0a4eaad1549/libmft/attribute.py#L756-L792
def _from_binary_stdinfo(cls, binary_stream): """See base class.""" ''' TIMESTAMPS(32) Creation time - 8 File altered time - 8 MFT/Metadata altered time - 8 Accessed time - 8 Flags - 4 (FileInfoFlags) Maximum number of versions - 4 ...
[ "def", "_from_binary_stdinfo", "(", "cls", ",", "binary_stream", ")", ":", "'''\n TIMESTAMPS(32)\n Creation time - 8\n File altered time - 8\n MFT/Metadata altered time - 8\n Accessed time - 8\n Flags - 4 (FileInfoFlags)\n Maximum numb...
See base class.
[ "See", "base", "class", "." ]
python
train
coldfix/udiskie
udiskie/mount.py
https://github.com/coldfix/udiskie/blob/804c9d27df6f7361fec3097c432398f2d702f911/udiskie/mount.py#L576-L608
async def losetup(self, image, read_only=True, offset=None, size=None, no_part_scan=None): """ Setup a loop device. :param str image: path of the image file :param bool read_only: :param int offset: :param int size: :param bool no_part_scan:...
[ "async", "def", "losetup", "(", "self", ",", "image", ",", "read_only", "=", "True", ",", "offset", "=", "None", ",", "size", "=", "None", ",", "no_part_scan", "=", "None", ")", ":", "try", ":", "device", "=", "self", ".", "udisks", ".", "find", "(...
Setup a loop device. :param str image: path of the image file :param bool read_only: :param int offset: :param int size: :param bool no_part_scan: :returns: the device object for the loop device
[ "Setup", "a", "loop", "device", "." ]
python
train
bcbio/bcbio-nextgen
bcbio/rnaseq/sailfish.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/rnaseq/sailfish.py#L170-L176
def _libtype_string(fq1, fq2, strandedness): """ supports just the Tophat unstranded/firstrand/secondstrand """ libtype = "-l I" if fq2 else "-l " strand = _sailfish_strand_string(strandedness) return libtype + strand
[ "def", "_libtype_string", "(", "fq1", ",", "fq2", ",", "strandedness", ")", ":", "libtype", "=", "\"-l I\"", "if", "fq2", "else", "\"-l \"", "strand", "=", "_sailfish_strand_string", "(", "strandedness", ")", "return", "libtype", "+", "strand" ]
supports just the Tophat unstranded/firstrand/secondstrand
[ "supports", "just", "the", "Tophat", "unstranded", "/", "firstrand", "/", "secondstrand" ]
python
train
jopohl/urh
src/urh/awre/FormatFinder.py
https://github.com/jopohl/urh/blob/2eb33b125c8407964cd1092843cde5010eb88aae/src/urh/awre/FormatFinder.py#L77-L106
def cluster_lengths(self): """ This method clusters some bitvectors based on their length. An example output is 2: [0.5, 1] 4: [1, 0.75, 1, 1] Meaning there were two message lengths: 2 and 4 bit. (0.5, 1) means, the first bit was equal in 50% of cases (meaning maximum d...
[ "def", "cluster_lengths", "(", "self", ")", ":", "number_ones", "=", "dict", "(", ")", "# dict of tuple. 0 = number ones vector, 1 = number of blocks for this vector", "for", "vector", "in", "self", ".", "bitvectors", ":", "vec_len", "=", "4", "*", "(", "len", "(", ...
This method clusters some bitvectors based on their length. An example output is 2: [0.5, 1] 4: [1, 0.75, 1, 1] Meaning there were two message lengths: 2 and 4 bit. (0.5, 1) means, the first bit was equal in 50% of cases (meaning maximum difference) and bit 2 was equal in all messages ...
[ "This", "method", "clusters", "some", "bitvectors", "based", "on", "their", "length", ".", "An", "example", "output", "is" ]
python
train
CalebBell/fpi
fpi/drag.py
https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/drag.py#L105-L153
def Barati_high(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9....
[ "def", "Barati_high", "(", "Re", ")", ":", "Cd", "=", "(", "8E-6", "*", "(", "(", "Re", "/", "6530.", ")", "**", "2", "+", "tanh", "(", "Re", ")", "-", "8", "*", "log", "(", "Re", ")", "/", "log", "(", "10.", ")", ")", "-", "0.4119", "*",...
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.9867\}/Re) +0.135...
[ "r", "Calculates", "drag", "coefficient", "of", "a", "smooth", "sphere", "using", "the", "method", "in", "[", "1", "]", "_", "." ]
python
train
aleju/imgaug
imgaug/external/poly_point_isect_py2py3.py
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/external/poly_point_isect_py2py3.py#L902-L941
def prev_item(self, key, default=_sentinel): """Get predecessor (k,v) pair of key, raises KeyError if key is min key or key does not exist. optimized for pypy. """ # removed graingets version, because it was little slower on CPython and much slower on pypy # this version runs abo...
[ "def", "prev_item", "(", "self", ",", "key", ",", "default", "=", "_sentinel", ")", ":", "# removed graingets version, because it was little slower on CPython and much slower on pypy", "# this version runs about 4x faster with pypy than the Cython version", "# Note: Code sharing of prev_...
Get predecessor (k,v) pair of key, raises KeyError if key is min key or key does not exist. optimized for pypy.
[ "Get", "predecessor", "(", "k", "v", ")", "pair", "of", "key", "raises", "KeyError", "if", "key", "is", "min", "key", "or", "key", "does", "not", "exist", ".", "optimized", "for", "pypy", "." ]
python
valid
xolox/python-vcs-repo-mgr
vcs_repo_mgr/backends/hg.py
https://github.com/xolox/python-vcs-repo-mgr/blob/fdad2441a3e7ba5deeeddfa1c2f5ebc00c393aed/vcs_repo_mgr/backends/hg.py#L208-L223
def get_commit_command(self, message, author=None): """ Get the command to commit changes to tracked files in the working tree. This method uses the ``hg remove --after`` to match the semantics of ``git commit --all`` (which is _not_ the same as ``hg commit --addremove``) howeve...
[ "def", "get_commit_command", "(", "self", ",", "message", ",", "author", "=", "None", ")", ":", "tokens", "=", "[", "'hg remove --after 2>/dev/null; hg commit'", "]", "if", "author", ":", "tokens", ".", "append", "(", "'--user=%s'", "%", "quote", "(", "author"...
Get the command to commit changes to tracked files in the working tree. This method uses the ``hg remove --after`` to match the semantics of ``git commit --all`` (which is _not_ the same as ``hg commit --addremove``) however ``hg remove --after`` is _very_ verbose (it comments on every ...
[ "Get", "the", "command", "to", "commit", "changes", "to", "tracked", "files", "in", "the", "working", "tree", "." ]
python
train
minio/minio-py
minio/api.py
https://github.com/minio/minio-py/blob/7107c84183cf5fb4deff68c0a16ab9f1c0b4c37e/minio/api.py#L1151-L1197
def _list_incomplete_uploads(self, bucket_name, prefix='', recursive=False, is_aggregate_size=True): """ List incomplete uploads list all previously uploaded incomplete multipart objects. :param bucket_name: Bucket name to list uploaded objects. :param p...
[ "def", "_list_incomplete_uploads", "(", "self", ",", "bucket_name", ",", "prefix", "=", "''", ",", "recursive", "=", "False", ",", "is_aggregate_size", "=", "True", ")", ":", "is_valid_bucket_name", "(", "bucket_name", ")", "# If someone explicitly set prefix to None ...
List incomplete uploads list all previously uploaded incomplete multipart objects. :param bucket_name: Bucket name to list uploaded objects. :param prefix: String specifying objects returned must begin with. :param recursive: If yes, returns all incomplete objects for a specified prefix. ...
[ "List", "incomplete", "uploads", "list", "all", "previously", "uploaded", "incomplete", "multipart", "objects", "." ]
python
train
praw-dev/prawtools
prawtools/stats.py
https://github.com/praw-dev/prawtools/blob/571d5c28c2222f6f8dbbca8c815b8da0a776ab85/prawtools/stats.py#L184-L218
def process_commenters(self): """Group comments by author.""" for index, submission in enumerate(self.submissions.values()): if submission.num_comments == 0: continue real_submission = self.reddit.submission(id=submission.id) real_submission.comment_so...
[ "def", "process_commenters", "(", "self", ")", ":", "for", "index", ",", "submission", "in", "enumerate", "(", "self", ".", "submissions", ".", "values", "(", ")", ")", ":", "if", "submission", ".", "num_comments", "==", "0", ":", "continue", "real_submiss...
Group comments by author.
[ "Group", "comments", "by", "author", "." ]
python
train
thomasleese/mo
mo/frontends.py
https://github.com/thomasleese/mo/blob/b757f52b42e51ad19c14724ceb7c5db5d52abaea/mo/frontends.py#L152-L179
def serialise(self, obj): """ Take an object from the project or the runner and serialise it into a dictionary. Parameters ---------- obj : object An object to serialise. Returns ------- object A serialised version of the ...
[ "def", "serialise", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "VariableCollection", ",", "StepCollection", ")", ")", ":", "return", "[", "self", ".", "serialise", "(", "element", ")", "for", "element", "i...
Take an object from the project or the runner and serialise it into a dictionary. Parameters ---------- obj : object An object to serialise. Returns ------- object A serialised version of the input object.
[ "Take", "an", "object", "from", "the", "project", "or", "the", "runner", "and", "serialise", "it", "into", "a", "dictionary", "." ]
python
train
tempodb/tempodb-python
tempodb/protocol/objects.py
https://github.com/tempodb/tempodb-python/blob/8ce45231bd728c6c97ef799cf0f1513ea3a9a7d3/tempodb/protocol/objects.py#L277-L312
def from_data(self, time, value, series_id=None, key=None, tz=None): """Create a DataPoint object from data, rather than a JSON object or string. This should be used by user code to construct DataPoints from Python-based data like Datetime objects and floats. The series_id and key argu...
[ "def", "from_data", "(", "self", ",", "time", ",", "value", ",", "series_id", "=", "None", ",", "key", "=", "None", ",", "tz", "=", "None", ")", ":", "t", "=", "check_time_param", "(", "time", ")", "if", "type", "(", "value", ")", "in", "[", "flo...
Create a DataPoint object from data, rather than a JSON object or string. This should be used by user code to construct DataPoints from Python-based data like Datetime objects and floats. The series_id and key arguments are only necessary if you are doing a multi write, in which case t...
[ "Create", "a", "DataPoint", "object", "from", "data", "rather", "than", "a", "JSON", "object", "or", "string", ".", "This", "should", "be", "used", "by", "user", "code", "to", "construct", "DataPoints", "from", "Python", "-", "based", "data", "like", "Date...
python
train
librosa/librosa
librosa/segment.py
https://github.com/librosa/librosa/blob/180e8e6eb8f958fa6b20b8cba389f7945d508247/librosa/segment.py#L563-L655
def subsegment(data, frames, n_segments=4, axis=-1): '''Sub-divide a segmentation by feature clustering. Given a set of frame boundaries (`frames`), and a data matrix (`data`), each successive interval defined by `frames` is partitioned into `n_segments` by constrained agglomerative clustering. .....
[ "def", "subsegment", "(", "data", ",", "frames", ",", "n_segments", "=", "4", ",", "axis", "=", "-", "1", ")", ":", "frames", "=", "util", ".", "fix_frames", "(", "frames", ",", "x_min", "=", "0", ",", "x_max", "=", "data", ".", "shape", "[", "ax...
Sub-divide a segmentation by feature clustering. Given a set of frame boundaries (`frames`), and a data matrix (`data`), each successive interval defined by `frames` is partitioned into `n_segments` by constrained agglomerative clustering. .. note:: If an interval spans fewer than `n_segments`...
[ "Sub", "-", "divide", "a", "segmentation", "by", "feature", "clustering", "." ]
python
test
tanghaibao/goatools
goatools/obo_parser.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/obo_parser.py#L198-L203
def has_child(self, term): """Return True if this GO object has a child GO ID.""" for parent in self.children: if parent.item_id == term or parent.has_child(term): return True return False
[ "def", "has_child", "(", "self", ",", "term", ")", ":", "for", "parent", "in", "self", ".", "children", ":", "if", "parent", ".", "item_id", "==", "term", "or", "parent", ".", "has_child", "(", "term", ")", ":", "return", "True", "return", "False" ]
Return True if this GO object has a child GO ID.
[ "Return", "True", "if", "this", "GO", "object", "has", "a", "child", "GO", "ID", "." ]
python
train
bsolomon1124/pyfinance
pyfinance/options.py
https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/options.py#L351-L383
def summary(self, St=None): """Tabular summary of strategy composition, broken out by option. Returns ------- pd.DataFrame Columns: kind, position, strike, price, St, payoff, profit. """ St = self.St if St is None else St if self.options: ...
[ "def", "summary", "(", "self", ",", "St", "=", "None", ")", ":", "St", "=", "self", ".", "St", "if", "St", "is", "None", "else", "St", "if", "self", ".", "options", ":", "payoffs", "=", "[", "op", ".", "payoff", "(", "St", "=", "St", ")", "fo...
Tabular summary of strategy composition, broken out by option. Returns ------- pd.DataFrame Columns: kind, position, strike, price, St, payoff, profit.
[ "Tabular", "summary", "of", "strategy", "composition", "broken", "out", "by", "option", ".", "Returns", "-------", "pd", ".", "DataFrame", "Columns", ":", "kind", "position", "strike", "price", "St", "payoff", "profit", "." ]
python
train
google/grr
grr/core/grr_response_core/lib/rdfvalues/structs.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/rdfvalues/structs.py#L2026-L2063
def FromDict(self, dictionary): """Initializes itself from a given dictionary.""" dynamic_fields = [] for key, value in iteritems(dictionary): field_type_info = self.type_infos.get(key) if isinstance(field_type_info, ProtoEmbedded): nested_value = field_type_info.GetDefault(container=se...
[ "def", "FromDict", "(", "self", ",", "dictionary", ")", ":", "dynamic_fields", "=", "[", "]", "for", "key", ",", "value", "in", "iteritems", "(", "dictionary", ")", ":", "field_type_info", "=", "self", ".", "type_infos", ".", "get", "(", "key", ")", "i...
Initializes itself from a given dictionary.
[ "Initializes", "itself", "from", "a", "given", "dictionary", "." ]
python
train
opencobra/cobrapy
cobra/core/gene.py
https://github.com/opencobra/cobrapy/blob/9d1987cdb3a395cf4125a3439c3b002ff2be2009/cobra/core/gene.py#L218-L277
def remove_from_model(self, model=None, make_dependent_reactions_nonfunctional=True): """Removes the association Parameters ---------- model : cobra model The model to remove the gene from make_dependent_reactions_nonfunctional : bool ...
[ "def", "remove_from_model", "(", "self", ",", "model", "=", "None", ",", "make_dependent_reactions_nonfunctional", "=", "True", ")", ":", "warn", "(", "\"Use cobra.manipulation.remove_genes instead\"", ")", "if", "model", "is", "not", "None", ":", "if", "model", "...
Removes the association Parameters ---------- model : cobra model The model to remove the gene from make_dependent_reactions_nonfunctional : bool If True then replace the gene with 'False' in the gene association, else replace the gene with 'True' ...
[ "Removes", "the", "association" ]
python
valid
DLR-RM/RAFCON
source/rafcon/gui/backup/session.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/backup/session.py#L76-L186
def restore_session_from_runtime_config(): """ Restore stored tabs from runtime config The method checks if the last status of a state machine is in the backup or in tis original path and loads it from there. The original path of these state machines are also insert into the recently opened state machines ...
[ "def", "restore_session_from_runtime_config", "(", ")", ":", "# TODO add a dirty lock for a crashed rafcon instance also into backup session feature", "# TODO in case a dialog is needed to give the user control", "# TODO combine this and auto-backup in one structure/controller/observer", "from", "...
Restore stored tabs from runtime config The method checks if the last status of a state machine is in the backup or in tis original path and loads it from there. The original path of these state machines are also insert into the recently opened state machines list.
[ "Restore", "stored", "tabs", "from", "runtime", "config" ]
python
train
by46/simplekit
simplekit/docker/docker.py
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L126-L138
def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] ...
[ "def", "get_containers_by_name", "(", "self", ",", "name", ")", ":", "code", ",", "containers", "=", "self", ".", "get_containers", "(", ")", "if", "code", "!=", "httplib", ".", "OK", ":", "return", "[", "]", "return", "[", "container", "for", "container...
get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list
[ "get", "all", "task", "which", "relative", "with", "task", "name", ":", "param", "name", ":", ":", "class", ":", "str", "task", "name", ":", "return", ":", ":", "class", ":", "list", "container", "list" ]
python
train
GNS3/gns3-server
gns3server/controller/link.py
https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/link.py#L152-L175
def update_filters(self, filters): """ Modify the filters list. Filter with value 0 will be dropped because not active """ new_filters = {} for (filter, values) in filters.items(): new_values = [] for value in values: if isinstance...
[ "def", "update_filters", "(", "self", ",", "filters", ")", ":", "new_filters", "=", "{", "}", "for", "(", "filter", ",", "values", ")", "in", "filters", ".", "items", "(", ")", ":", "new_values", "=", "[", "]", "for", "value", "in", "values", ":", ...
Modify the filters list. Filter with value 0 will be dropped because not active
[ "Modify", "the", "filters", "list", "." ]
python
train
materialsproject/pymatgen
pymatgen/phonon/dos.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/phonon/dos.py#L346-L362
def get_element_dos(self): """ Get element projected Dos. Returns: dict of {Element: Dos} """ el_dos = {} for site, atom_dos in self.pdos.items(): el = site.specie if el not in el_dos: el_dos[el] = np.array(atom_dos) ...
[ "def", "get_element_dos", "(", "self", ")", ":", "el_dos", "=", "{", "}", "for", "site", ",", "atom_dos", "in", "self", ".", "pdos", ".", "items", "(", ")", ":", "el", "=", "site", ".", "specie", "if", "el", "not", "in", "el_dos", ":", "el_dos", ...
Get element projected Dos. Returns: dict of {Element: Dos}
[ "Get", "element", "projected", "Dos", "." ]
python
train
jazzband/django-mongonaut
mongonaut/forms/forms.py
https://github.com/jazzband/django-mongonaut/blob/5485b2e029dff8ae267a4cb39c92d0a72cb5b144/mongonaut/forms/forms.py#L35-L45
def set_fields(self): """Sets existing data to form fields.""" # Get dictionary map of current model if self.is_initialized: self.model_map_dict = self.create_document_dictionary(self.model_instance) else: self.model_map_dict = self.create_document_dictionary(sel...
[ "def", "set_fields", "(", "self", ")", ":", "# Get dictionary map of current model", "if", "self", ".", "is_initialized", ":", "self", ".", "model_map_dict", "=", "self", ".", "create_document_dictionary", "(", "self", ".", "model_instance", ")", "else", ":", "sel...
Sets existing data to form fields.
[ "Sets", "existing", "data", "to", "form", "fields", "." ]
python
valid
radjkarl/imgProcessor
imgProcessor/camera/PerspectiveCorrection.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/PerspectiveCorrection.py#L506-L514
def foreground(self, quad=None): '''return foreground (quad) mask''' fg = np.zeros(shape=self._newBorders[::-1], dtype=np.uint8) if quad is None: quad = self.quad else: quad = quad.astype(np.int32) cv2.fillConvexPoly(fg, quad, 1) return fg....
[ "def", "foreground", "(", "self", ",", "quad", "=", "None", ")", ":", "fg", "=", "np", ".", "zeros", "(", "shape", "=", "self", ".", "_newBorders", "[", ":", ":", "-", "1", "]", ",", "dtype", "=", "np", ".", "uint8", ")", "if", "quad", "is", ...
return foreground (quad) mask
[ "return", "foreground", "(", "quad", ")", "mask" ]
python
train
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/modules/mavproxy_dataflash_logger.py#L98-L114
def start_new_log(self): '''open a new dataflash log, reset state''' filename = self.new_log_filepath() self.block_cnt = 0 self.logfile = open(filename, 'w+b') print("DFLogger: logging started (%s)" % (filename)) self.prev_cnt = 0 self.download = 0 self.p...
[ "def", "start_new_log", "(", "self", ")", ":", "filename", "=", "self", ".", "new_log_filepath", "(", ")", "self", ".", "block_cnt", "=", "0", "self", ".", "logfile", "=", "open", "(", "filename", ",", "'w+b'", ")", "print", "(", "\"DFLogger: logging start...
open a new dataflash log, reset state
[ "open", "a", "new", "dataflash", "log", "reset", "state" ]
python
train
gem/oq-engine
openquake/hazardlib/gsim/abrahamson_2015.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/abrahamson_2015.py#L178-L198
def _compute_site_response_term(self, C, sites, pga1000): """ Compute and return site response model term This GMPE adopts the same site response scaling model of Walling et al (2008) as implemented in the Abrahamson & Silva (2008) GMPE. The functional form is retained here. ...
[ "def", "_compute_site_response_term", "(", "self", ",", "C", ",", "sites", ",", "pga1000", ")", ":", "vs_star", "=", "sites", ".", "vs30", ".", "copy", "(", ")", "vs_star", "[", "vs_star", ">", "1000.0", "]", "=", "1000.", "arg", "=", "vs_star", "/", ...
Compute and return site response model term This GMPE adopts the same site response scaling model of Walling et al (2008) as implemented in the Abrahamson & Silva (2008) GMPE. The functional form is retained here.
[ "Compute", "and", "return", "site", "response", "model", "term", "This", "GMPE", "adopts", "the", "same", "site", "response", "scaling", "model", "of", "Walling", "et", "al", "(", "2008", ")", "as", "implemented", "in", "the", "Abrahamson", "&", "Silva", "...
python
train
shreyaspotnis/rampage
rampage/daq/daq.py
https://github.com/shreyaspotnis/rampage/blob/e2565aef7ee16ee06523de975e8aa41aca14e3b2/rampage/daq/daq.py#L80-L100
def set_digital_line_state(line_name, state): """Set the state of a single digital line. line_name (str) - The physical name of the line. e.g line_name="Dev1/port0/line3" This should be a single digital line. Specifying more than one would result in unexpected behaviour. For example "De...
[ "def", "set_digital_line_state", "(", "line_name", ",", "state", ")", ":", "# get the line number from the line name. Thats the number of bits to shift", "bits_to_shift", "=", "int", "(", "line_name", ".", "split", "(", "'line'", ")", "[", "-", "1", "]", ")", "dig_dat...
Set the state of a single digital line. line_name (str) - The physical name of the line. e.g line_name="Dev1/port0/line3" This should be a single digital line. Specifying more than one would result in unexpected behaviour. For example "Dev1/port0/line0:5" is not allowed. see...
[ "Set", "the", "state", "of", "a", "single", "digital", "line", "." ]
python
train
desbma/sacad
sacad/cover.py
https://github.com/desbma/sacad/blob/a7a010c4d9618a0c90927f1acb530101ca05fac4/sacad/cover.py#L460-L491
async def crunch(image_data, format, silent=False): """ Crunch image data, and return the processed data, or orignal data if operation failed. """ if (((format is CoverImageFormat.PNG) and (not HAS_OPTIPNG)) or ((format is CoverImageFormat.JPEG) and (not HAS_JPEGOPTIM))): return image_data ...
[ "async", "def", "crunch", "(", "image_data", ",", "format", ",", "silent", "=", "False", ")", ":", "if", "(", "(", "(", "format", "is", "CoverImageFormat", ".", "PNG", ")", "and", "(", "not", "HAS_OPTIPNG", ")", ")", "or", "(", "(", "format", "is", ...
Crunch image data, and return the processed data, or orignal data if operation failed.
[ "Crunch", "image", "data", "and", "return", "the", "processed", "data", "or", "orignal", "data", "if", "operation", "failed", "." ]
python
train
vtkiorg/vtki
vtki/pointset.py
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L766-L835
def subdivide(self, nsub, subfilter='linear', inplace=False): """ Increase the number of triangles in a single, connected triangular mesh. Uses one of the following vtk subdivision filters to subdivide a mesh. vtkButterflySubdivisionFilter vtkLoopSubdivisionFilter ...
[ "def", "subdivide", "(", "self", ",", "nsub", ",", "subfilter", "=", "'linear'", ",", "inplace", "=", "False", ")", ":", "subfilter", "=", "subfilter", ".", "lower", "(", ")", "if", "subfilter", "==", "'linear'", ":", "sfilter", "=", "vtk", ".", "vtkLi...
Increase the number of triangles in a single, connected triangular mesh. Uses one of the following vtk subdivision filters to subdivide a mesh. vtkButterflySubdivisionFilter vtkLoopSubdivisionFilter vtkLinearSubdivisionFilter Linear subdivision results in the fastest me...
[ "Increase", "the", "number", "of", "triangles", "in", "a", "single", "connected", "triangular", "mesh", "." ]
python
train
ptmcg/littletable
littletable.py
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1349-L1374
def unique(self, key=None): """ Create a new table of objects,containing no duplicate values. @param key: (default=None) optional callable for computing a representative unique key for each object in the table. If None, then a key will be composed as a tuple of all the values in the obj...
[ "def", "unique", "(", "self", ",", "key", "=", "None", ")", ":", "if", "isinstance", "(", "key", ",", "basestring", ")", ":", "key", "=", "lambda", "r", ",", "attr", "=", "key", ":", "getattr", "(", "r", ",", "attr", ",", "None", ")", "ret", "=...
Create a new table of objects,containing no duplicate values. @param key: (default=None) optional callable for computing a representative unique key for each object in the table. If None, then a key will be composed as a tuple of all the values in the object. @type key: callable, takes the reco...
[ "Create", "a", "new", "table", "of", "objects", "containing", "no", "duplicate", "values", "." ]
python
train
SmokinCaterpillar/pypet
pypet/pypetlogging.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/pypetlogging.py#L550-L574
def _handle_config_parsing(self, log_config): """ Checks for filenames within a config file and translates them. Moreover, directories for the files are created as well. :param log_config: Config file as a stream (like StringIO) """ parser = NoInterpolationParser() par...
[ "def", "_handle_config_parsing", "(", "self", ",", "log_config", ")", ":", "parser", "=", "NoInterpolationParser", "(", ")", "parser", ".", "readfp", "(", "log_config", ")", "rename_func", "=", "lambda", "string", ":", "rename_log_file", "(", "string", ",", "e...
Checks for filenames within a config file and translates them. Moreover, directories for the files are created as well. :param log_config: Config file as a stream (like StringIO)
[ "Checks", "for", "filenames", "within", "a", "config", "file", "and", "translates", "them", "." ]
python
test
dbcli/cli_helpers
cli_helpers/tabular_output/preprocessors.py
https://github.com/dbcli/cli_helpers/blob/3ebd891ac0c02bad061182dbcb54a47fb21980ae/cli_helpers/tabular_output/preprocessors.py#L11-L24
def truncate_string(data, headers, max_field_width=None, **_): """Truncate very long strings. Only needed for tabular representation, because trying to tabulate very long data is problematic in terms of performance, and does not make any sense visually. :param iterable data: An :term:`iterable` (e....
[ "def", "truncate_string", "(", "data", ",", "headers", ",", "max_field_width", "=", "None", ",", "*", "*", "_", ")", ":", "return", "(", "(", "[", "utils", ".", "truncate_string", "(", "v", ",", "max_field_width", ")", "for", "v", "in", "row", "]", "...
Truncate very long strings. Only needed for tabular representation, because trying to tabulate very long data is problematic in terms of performance, and does not make any sense visually. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The column headers. ...
[ "Truncate", "very", "long", "strings", ".", "Only", "needed", "for", "tabular", "representation", "because", "trying", "to", "tabulate", "very", "long", "data", "is", "problematic", "in", "terms", "of", "performance", "and", "does", "not", "make", "any", "sens...
python
test
saltstack/salt
salt/modules/sysmod.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sysmod.py#L920-L939
def state_schema(module=''): ''' Return a JSON Schema for the given state function(s) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' sys.state_schema salt '*' sys.state_schema pkg.installed ''' specs = state_argspec(module) schemas = [] for...
[ "def", "state_schema", "(", "module", "=", "''", ")", ":", "specs", "=", "state_argspec", "(", "module", ")", "schemas", "=", "[", "]", "for", "state_mod", ",", "state_spec", "in", "specs", ".", "items", "(", ")", ":", "schemas", ".", "append", "(", ...
Return a JSON Schema for the given state function(s) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' sys.state_schema salt '*' sys.state_schema pkg.installed
[ "Return", "a", "JSON", "Schema", "for", "the", "given", "state", "function", "(", "s", ")" ]
python
train
tornadoweb/tornado
tornado/iostream.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/iostream.py#L447-L494
def read_into(self, buf: bytearray, partial: bool = False) -> Awaitable[int]: """Asynchronously read a number of bytes. ``buf`` must be a writable buffer into which data will be read. If ``partial`` is true, the callback is run as soon as any bytes have been read. Otherwise, it is run...
[ "def", "read_into", "(", "self", ",", "buf", ":", "bytearray", ",", "partial", ":", "bool", "=", "False", ")", "->", "Awaitable", "[", "int", "]", ":", "future", "=", "self", ".", "_start_read", "(", ")", "# First copy data already in read buffer", "availabl...
Asynchronously read a number of bytes. ``buf`` must be a writable buffer into which data will be read. If ``partial`` is true, the callback is run as soon as any bytes have been read. Otherwise, it is run when the ``buf`` has been entirely filled with read data. .. versionadd...
[ "Asynchronously", "read", "a", "number", "of", "bytes", "." ]
python
train
planetarypy/pvl
pvl/decoder.py
https://github.com/planetarypy/pvl/blob/ed92b284c4208439b033d28c9c176534c0faac0e/pvl/decoder.py#L433-L452
def parse_object(self, stream): """Block Name must match Block Name in paired End Object Statement if Block Name is present in End Object Statement StatementDelim. BeginObjectStmt ::= BeginObjectKeywd WSC AssignmentSymbol WSC BlockName StatementDelim """ self.expect_...
[ "def", "parse_object", "(", "self", ",", "stream", ")", ":", "self", ".", "expect_in", "(", "stream", ",", "self", ".", "begin_object_tokens", ")", "self", ".", "ensure_assignment", "(", "stream", ")", "name", "=", "self", ".", "next_token", "(", "stream",...
Block Name must match Block Name in paired End Object Statement if Block Name is present in End Object Statement StatementDelim. BeginObjectStmt ::= BeginObjectKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
[ "Block", "Name", "must", "match", "Block", "Name", "in", "paired", "End", "Object", "Statement", "if", "Block", "Name", "is", "present", "in", "End", "Object", "Statement", "StatementDelim", "." ]
python
train
hendrix/hendrix
hendrix/contrib/concurrency/messaging.py
https://github.com/hendrix/hendrix/blob/175af011a7e5822b772bfec0e11a46466bb8688d/hendrix/contrib/concurrency/messaging.py#L125-L139
def send_json_message(address, message, **kwargs): """ a shortcut for message sending """ data = { 'message': message, } if not kwargs.get('subject_id'): data['subject_id'] = address data.update(kwargs) hxdispatcher.send(address, data)
[ "def", "send_json_message", "(", "address", ",", "message", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'message'", ":", "message", ",", "}", "if", "not", "kwargs", ".", "get", "(", "'subject_id'", ")", ":", "data", "[", "'subject_id'", "]", ...
a shortcut for message sending
[ "a", "shortcut", "for", "message", "sending" ]
python
train
openpermissions/perch
perch/model.py
https://github.com/openpermissions/perch/blob/36d78994133918f3c52c187f19e50132960a0156/perch/model.py#L541-L549
def update(self, user, **kwargs): """If parent resource is not an editable state, should not be able to update""" yield self.get_parent() if not self.parent.editable: err = 'Cannot update child of {} resource'.format(self.parent.state.name) raise exceptions.Unauthorized(...
[ "def", "update", "(", "self", ",", "user", ",", "*", "*", "kwargs", ")", ":", "yield", "self", ".", "get_parent", "(", ")", "if", "not", "self", ".", "parent", ".", "editable", ":", "err", "=", "'Cannot update child of {} resource'", ".", "format", "(", ...
If parent resource is not an editable state, should not be able to update
[ "If", "parent", "resource", "is", "not", "an", "editable", "state", "should", "not", "be", "able", "to", "update" ]
python
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L8353-L8359
def tablet(self, x, rot=0): """Tablet test objective function""" if rot and rot is not fcts.tablet: x = rotate(x) x = [x] if isscalar(x[0]) else x # scalar into list f = [1e6 * x[0]**2 + sum(x[1:]**2) for x in x] return f if len(f) > 1 else f[0] # 1-element-list int...
[ "def", "tablet", "(", "self", ",", "x", ",", "rot", "=", "0", ")", ":", "if", "rot", "and", "rot", "is", "not", "fcts", ".", "tablet", ":", "x", "=", "rotate", "(", "x", ")", "x", "=", "[", "x", "]", "if", "isscalar", "(", "x", "[", "0", ...
Tablet test objective function
[ "Tablet", "test", "objective", "function" ]
python
train
chrislit/abydos
abydos/distance/_typo.py
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/distance/_typo.py#L392-L435
def dist_typo( src, tar, metric='euclidean', cost=(1, 1, 0.5, 0.5), layout='QWERTY' ): """Return the normalized typo distance between two strings. This is a wrapper for :py:meth:`Typo.dist`. Parameters ---------- src : str Source string for comparison tar : str Target strin...
[ "def", "dist_typo", "(", "src", ",", "tar", ",", "metric", "=", "'euclidean'", ",", "cost", "=", "(", "1", ",", "1", ",", "0.5", ",", "0.5", ")", ",", "layout", "=", "'QWERTY'", ")", ":", "return", "Typo", "(", ")", ".", "dist", "(", "src", ","...
Return the normalized typo distance between two strings. This is a wrapper for :py:meth:`Typo.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison metric : str Supported values include: ``euclidean``, ``manhattan``, ...
[ "Return", "the", "normalized", "typo", "distance", "between", "two", "strings", "." ]
python
valid
pandas-dev/pandas
pandas/core/panel.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/panel.py#L991-L1054
def apply(self, func, axis='major', **kwargs): """ Apply function along axis (or axes) of the Panel. Parameters ---------- func : function Function to apply to each combination of 'other' axes e.g. if axis = 'items', the combination of major_axis/minor_ax...
[ "def", "apply", "(", "self", ",", "func", ",", "axis", "=", "'major'", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", "and", "not", "isinstance", "(", "func", ",", "np", ".", "ufunc", ")", ":", "f", "=", "lambda", "x", ":", "func", "(", "x"...
Apply function along axis (or axes) of the Panel. Parameters ---------- func : function Function to apply to each combination of 'other' axes e.g. if axis = 'items', the combination of major_axis/minor_axis will each be passed as a Series; if axis = ('items',...
[ "Apply", "function", "along", "axis", "(", "or", "axes", ")", "of", "the", "Panel", "." ]
python
train
Microsoft/nni
examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/examples/tuners/weight_sharing/ga_customer_tuner/customer_tuner.py#L199-L222
def receive_trial_result(self, parameter_id, parameters, value): ''' Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward ''' logger.debug('acquiring lock for param {...
[ "def", "receive_trial_result", "(", "self", ",", "parameter_id", ",", "parameters", ",", "value", ")", ":", "logger", ".", "debug", "(", "'acquiring lock for param {}'", ".", "format", "(", "parameter_id", ")", ")", "self", ".", "thread_lock", ".", "acquire", ...
Record an observation of the objective function parameter_id : int parameters : dict of parameters value: final metrics of the trial, including reward
[ "Record", "an", "observation", "of", "the", "objective", "function", "parameter_id", ":", "int", "parameters", ":", "dict", "of", "parameters", "value", ":", "final", "metrics", "of", "the", "trial", "including", "reward" ]
python
train
nion-software/nionswift
nion/swift/model/FileStorageSystem.py
https://github.com/nion-software/nionswift/blob/d43693eaf057b8683b9638e575000f055fede452/nion/swift/model/FileStorageSystem.py#L601-L658
def auto_migrate_storage_system(*, persistent_storage_system=None, new_persistent_storage_system=None, data_item_uuids=None, deletions: typing.List[uuid.UUID] = None, utilized_deletions: typing.Set[uuid.UUID] = None, ignore_older_files: bool = True): """Migrate items from the storage system to the object context. ...
[ "def", "auto_migrate_storage_system", "(", "*", ",", "persistent_storage_system", "=", "None", ",", "new_persistent_storage_system", "=", "None", ",", "data_item_uuids", "=", "None", ",", "deletions", ":", "typing", ".", "List", "[", "uuid", ".", "UUID", "]", "=...
Migrate items from the storage system to the object context. Files in data_item_uuids have already been loaded and are ignored (not migrated). Files in deletes have been deleted in object context and are ignored (not migrated) and then added to the utilized deletions list. Data items will have persis...
[ "Migrate", "items", "from", "the", "storage", "system", "to", "the", "object", "context", "." ]
python
train
kensho-technologies/graphql-compiler
graphql_compiler/schema_generation/schema_properties.py
https://github.com/kensho-technologies/graphql-compiler/blob/f6079c6d10f64932f6b3af309b79bcea2123ca8f/graphql_compiler/schema_generation/schema_properties.py#L126-L132
def _parse_date_default_value(property_name, default_value_string): """Parse and return the default value for a date property.""" # OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually # and then turn it into a python datetime object. strptime() will raise an exception # if the...
[ "def", "_parse_date_default_value", "(", "property_name", ",", "default_value_string", ")", ":", "# OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually", "# and then turn it into a python datetime object. strptime() will raise an exception", "# if the provided value ca...
Parse and return the default value for a date property.
[ "Parse", "and", "return", "the", "default", "value", "for", "a", "date", "property", "." ]
python
train
TUNE-Archive/freight_forwarder
freight_forwarder/container/host_config.py
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container/host_config.py#L568-L592
def volumes_from(self, value): """ :param value: :return: """ volumes_from = [] if isinstance(value, list): for volume_from in value: if not isinstance(volume_from, six.string_types): raise TypeError("each bind must be a st...
[ "def", "volumes_from", "(", "self", ",", "value", ")", ":", "volumes_from", "=", "[", "]", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "volume_from", "in", "value", ":", "if", "not", "isinstance", "(", "volume_from", ",", "six", "."...
:param value: :return:
[ ":", "param", "value", ":", ":", "return", ":" ]
python
train
log2timeline/plaso
plaso/multi_processing/psort.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/multi_processing/psort.py#L222-L344
def _AnalyzeEvents(self, storage_writer, analysis_plugins, event_filter=None): """Analyzes events in a plaso storage. Args: storage_writer (StorageWriter): storage writer. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names. event_filter...
[ "def", "_AnalyzeEvents", "(", "self", ",", "storage_writer", ",", "analysis_plugins", ",", "event_filter", "=", "None", ")", ":", "self", ".", "_status", "=", "definitions", ".", "STATUS_INDICATOR_RUNNING", "self", ".", "_number_of_consumed_events", "=", "0", "sel...
Analyzes events in a plaso storage. Args: storage_writer (StorageWriter): storage writer. analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that should be run and their names. event_filter (Optional[FilterObject]): event filter. Returns: collections.Counter: coun...
[ "Analyzes", "events", "in", "a", "plaso", "storage", "." ]
python
train
sunt05/SuPy
docs/source/proc_var_info/gen_df_state_csv.py
https://github.com/sunt05/SuPy/blob/47178bd5aee50a059414e3e504940662fbfae0dc/docs/source/proc_var_info/gen_df_state_csv.py#L105-L178
def gen_df_site( list_csv_in=list_table, url_base=url_repo_input_site)->pd.DataFrame: '''Generate description info of supy output results as a dataframe Parameters ---------- path_csv_out : str, optional path to the output csv file (the default is 'df_output.csv') list_csv_i...
[ "def", "gen_df_site", "(", "list_csv_in", "=", "list_table", ",", "url_base", "=", "url_repo_input_site", ")", "->", "pd", ".", "DataFrame", ":", "# list of URLs", "list_url_table", "=", "[", "url_base", "/", "table", "for", "table", "in", "list_csv_in", "]", ...
Generate description info of supy output results as a dataframe Parameters ---------- path_csv_out : str, optional path to the output csv file (the default is 'df_output.csv') list_csv_in : list, optional list of file names for csv files with meta info (the default is url_repo_input_sit...
[ "Generate", "description", "info", "of", "supy", "output", "results", "as", "a", "dataframe" ]
python
train
woolfson-group/isambard
isambard/ampal/ligands.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/ligands.py#L45-L50
def category_count(self): """Returns the number of categories in `categories`.""" category_dict = self.categories count_dict = {category: len( category_dict[category]) for category in category_dict} return count_dict
[ "def", "category_count", "(", "self", ")", ":", "category_dict", "=", "self", ".", "categories", "count_dict", "=", "{", "category", ":", "len", "(", "category_dict", "[", "category", "]", ")", "for", "category", "in", "category_dict", "}", "return", "count_...
Returns the number of categories in `categories`.
[ "Returns", "the", "number", "of", "categories", "in", "categories", "." ]
python
train
mathiasertl/django-ca
ca/django_ca/management/base.py
https://github.com/mathiasertl/django-ca/blob/976d7ea05276320f20daed2a6d59c8f5660fe976/ca/django_ca/management/base.py#L281-L290
def add_format(self, parser, default=Encoding.PEM, help_text=None, opts=None): """Add the --format option.""" if opts is None: opts = ['-f', '--format'] if help_text is None: help_text = 'The format to use ("ASN1" is an alias for "DER", default: %(default)s).' he...
[ "def", "add_format", "(", "self", ",", "parser", ",", "default", "=", "Encoding", ".", "PEM", ",", "help_text", "=", "None", ",", "opts", "=", "None", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "[", "'-f'", ",", "'--format'", "]", "if"...
Add the --format option.
[ "Add", "the", "--", "format", "option", "." ]
python
train
cackharot/suds-py3
suds/properties.py
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/properties.py#L173-L184
def validate(self, value): """ Validate the I{value} is of the correct class. @param value: The value to validate. @type value: any @raise AttributeError: When I{value} is invalid. """ if value is None: return if len(self.classes) and not isins...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "if", "len", "(", "self", ".", "classes", ")", "and", "not", "isinstance", "(", "value", ",", "self", ".", "classes", ")", ":", "msg", "=", "'\"%s\"...
Validate the I{value} is of the correct class. @param value: The value to validate. @type value: any @raise AttributeError: When I{value} is invalid.
[ "Validate", "the", "I", "{", "value", "}", "is", "of", "the", "correct", "class", "." ]
python
train
sirfoga/pyhal
hal/internet/email/templates.py
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/email/templates.py#L45-L58
def get_mime_message(self): """Gets email MIME message :return: Email formatted as HTML ready to be sent """ message = MIMEText( "<html>" + self.get_email_header() + get_email_content(self.content_file) + self.get_email_footer() + ...
[ "def", "get_mime_message", "(", "self", ")", ":", "message", "=", "MIMEText", "(", "\"<html>\"", "+", "self", ".", "get_email_header", "(", ")", "+", "get_email_content", "(", "self", ".", "content_file", ")", "+", "self", ".", "get_email_footer", "(", ")", ...
Gets email MIME message :return: Email formatted as HTML ready to be sent
[ "Gets", "email", "MIME", "message" ]
python
train
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L31-L33
def DELETE(self, *args, **kwargs): """ DELETE request """ return self._handle_api(self.API_DELETE, args, kwargs)
[ "def", "DELETE", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_handle_api", "(", "self", ".", "API_DELETE", ",", "args", ",", "kwargs", ")" ]
DELETE request
[ "DELETE", "request" ]
python
train
kplindegaard/smbus2
smbus2/smbus2.py
https://github.com/kplindegaard/smbus2/blob/a1088a03438dba84c266b73ad61b0c06750d0961/smbus2/smbus2.py#L292-L308
def _set_address(self, address, force=None): """ Set i2c slave address to use for subsequent calls. :param address: :type address: int :param force: :type force: Boolean """ force = force if force is not None else self.force if self.address != add...
[ "def", "_set_address", "(", "self", ",", "address", ",", "force", "=", "None", ")", ":", "force", "=", "force", "if", "force", "is", "not", "None", "else", "self", ".", "force", "if", "self", ".", "address", "!=", "address", "or", "self", ".", "_forc...
Set i2c slave address to use for subsequent calls. :param address: :type address: int :param force: :type force: Boolean
[ "Set", "i2c", "slave", "address", "to", "use", "for", "subsequent", "calls", "." ]
python
train
pereorga/csvshuf
csvshuf/csvshuf.py
https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L19-L24
def shuffle_sattolo(items): """Shuffle items in place using Sattolo's algorithm.""" _randrange = random.randrange for i in reversed(range(1, len(items))): j = _randrange(i) # 0 <= j < i items[j], items[i] = items[i], items[j]
[ "def", "shuffle_sattolo", "(", "items", ")", ":", "_randrange", "=", "random", ".", "randrange", "for", "i", "in", "reversed", "(", "range", "(", "1", ",", "len", "(", "items", ")", ")", ")", ":", "j", "=", "_randrange", "(", "i", ")", "# 0 <= j < i"...
Shuffle items in place using Sattolo's algorithm.
[ "Shuffle", "items", "in", "place", "using", "Sattolo", "s", "algorithm", "." ]
python
train
cocaine/cocaine-tools
cocaine/tools/dispatch.py
https://github.com/cocaine/cocaine-tools/blob/d8834f8e04ca42817d5f4e368d471484d4b3419f/cocaine/tools/dispatch.py#L1863-L1876
def access_storage_edit(name, cid, uid, perm, **kwargs): """ Edits ACL for the specified collection. Creates if necessary. """ ctx = Context(**kwargs) ctx.execute_action('access:storage:edit', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, 'cids'...
[ "def", "access_storage_edit", "(", "name", ",", "cid", ",", "uid", ",", "perm", ",", "*", "*", "kwargs", ")", ":", "ctx", "=", "Context", "(", "*", "*", "kwargs", ")", "ctx", ".", "execute_action", "(", "'access:storage:edit'", ",", "*", "*", "{", "'...
Edits ACL for the specified collection. Creates if necessary.
[ "Edits", "ACL", "for", "the", "specified", "collection", "." ]
python
train
crs4/hl7apy
hl7apy/core.py
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/core.py#L435-L447
def _find_name(self, name): """ Find the reference of a child having the given name :type name: ``str`` :param name: the child name (e.g. PID) :return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the element has not been...
[ "def", "_find_name", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "upper", "(", ")", "element", "=", "self", ".", "element", ".", "find_child_reference", "(", "name", ")", "return", "element", "[", "'name'", "]", "if", "element", "is",...
Find the reference of a child having the given name :type name: ``str`` :param name: the child name (e.g. PID) :return: the element structure (see :func:`load_reference <hl7apy.load_reference>`) or ``None`` if the element has not been found
[ "Find", "the", "reference", "of", "a", "child", "having", "the", "given", "name" ]
python
train
annoviko/pyclustering
pyclustering/cluster/bang.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/bang.py#L1167-L1191
def __expand_cluster_block(self, block, cluster_index, leaf_blocks, unhandled_block_indexes): """! @brief Expand cluster from specific block that is considered as a central block. @param[in] block (bang_block): Block that is considered as a central block for cluster. @param[in] clu...
[ "def", "__expand_cluster_block", "(", "self", ",", "block", ",", "cluster_index", ",", "leaf_blocks", ",", "unhandled_block_indexes", ")", ":", "block", ".", "set_cluster", "(", "cluster_index", ")", "self", ".", "__update_cluster_dendrogram", "(", "cluster_index", ...
! @brief Expand cluster from specific block that is considered as a central block. @param[in] block (bang_block): Block that is considered as a central block for cluster. @param[in] cluster_index (uint): Index of cluster that is assigned to blocks that forms new cluster. @param[in]...
[ "!" ]
python
valid
databricks/spark-sklearn
python/spark_sklearn/converter.py
https://github.com/databricks/spark-sklearn/blob/cbde36f6311b73d967e2ec8a97040dfd71eca579/python/spark_sklearn/converter.py#L131-L163
def toPandas(self, df): """ This is similar to the Spark DataFrame built-in toPandas() method, but it handles MLlib Vector columns differently. It converts MLlib Vectors into rows of scipy.sparse.csr_matrix, which is generally friendlier for PyData tools like scikit-learn. .. n...
[ "def", "toPandas", "(", "self", ",", "df", ")", ":", "cols", "=", "df", ".", "columns", "# Convert any MLlib Vector columns to scipy.sparse.csr_matrix", "matrixCols", "=", "[", "]", "def", "toscipy", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "De...
This is similar to the Spark DataFrame built-in toPandas() method, but it handles MLlib Vector columns differently. It converts MLlib Vectors into rows of scipy.sparse.csr_matrix, which is generally friendlier for PyData tools like scikit-learn. .. note:: Experimental: This will likely be repl...
[ "This", "is", "similar", "to", "the", "Spark", "DataFrame", "built", "-", "in", "toPandas", "()", "method", "but", "it", "handles", "MLlib", "Vector", "columns", "differently", ".", "It", "converts", "MLlib", "Vectors", "into", "rows", "of", "scipy", ".", ...
python
train