repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
aiogram/aiogram
aiogram/bot/bot.py
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/bot/bot.py#L809-L848
async def send_contact(self, chat_id: typing.Union[base.Integer, base.String], phone_number: base.String, first_name: base.String, last_name: typing.Union[base.String, None] = None, vcard: typing.Union[base.String, None] = None, ...
[ "async", "def", "send_contact", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "phone_number", ":", "base", ".", "String", ",", "first_name", ":", "base", ".", "String", ",",...
Use this method to send phone contacts. Source: https://core.telegram.org/bots/api#sendcontact :param chat_id: Unique identifier for the target chat or username of the target channel :type chat_id: :obj:`typing.Union[base.Integer, base.String]` :param phone_number: Contact's phone numb...
[ "Use", "this", "method", "to", "send", "phone", "contacts", "." ]
python
train
59.25
IDSIA/sacred
sacred/commandline_options.py
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/commandline_options.py#L159-L165
def gather_command_line_options(filter_disabled=None): """Get a sorted list of all CommandLineOption subclasses.""" if filter_disabled is None: filter_disabled = not SETTINGS.COMMAND_LINE.SHOW_DISABLED_OPTIONS options = [opt for opt in get_inheritors(CommandLineOption) if not filter_d...
[ "def", "gather_command_line_options", "(", "filter_disabled", "=", "None", ")", ":", "if", "filter_disabled", "is", "None", ":", "filter_disabled", "=", "not", "SETTINGS", ".", "COMMAND_LINE", ".", "SHOW_DISABLED_OPTIONS", "options", "=", "[", "opt", "for", "opt",...
Get a sorted list of all CommandLineOption subclasses.
[ "Get", "a", "sorted", "list", "of", "all", "CommandLineOption", "subclasses", "." ]
python
train
56.428571
evandempsey/fp-growth
pyfpgrowth/pyfpgrowth.py
https://github.com/evandempsey/fp-growth/blob/6bf4503024e86c5bbea8a05560594f2f7f061c15/pyfpgrowth/pyfpgrowth.py#L197-L244
def mine_sub_trees(self, threshold): """ Generate subtrees and mine them for patterns. """ patterns = {} mining_order = sorted(self.frequent.keys(), key=lambda x: self.frequent[x]) # Get items in tree in reverse order of occurrences. ...
[ "def", "mine_sub_trees", "(", "self", ",", "threshold", ")", ":", "patterns", "=", "{", "}", "mining_order", "=", "sorted", "(", "self", ".", "frequent", ".", "keys", "(", ")", ",", "key", "=", "lambda", "x", ":", "self", ".", "frequent", "[", "x", ...
Generate subtrees and mine them for patterns.
[ "Generate", "subtrees", "and", "mine", "them", "for", "patterns", "." ]
python
train
35.875
cloud-custodian/cloud-custodian
tools/c7n_gcp/c7n_gcp/client.py
https://github.com/cloud-custodian/cloud-custodian/blob/52ef732eb3d7bc939d1579faf519314814695c08/tools/c7n_gcp/c7n_gcp/client.py#L465-L482
def _execute(self, request): """Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API. """ if self._rate_limiter: # Since the ratelimiter library only e...
[ "def", "_execute", "(", "self", ",", "request", ")", ":", "if", "self", ".", "_rate_limiter", ":", "# Since the ratelimiter library only exposes a context manager", "# interface the code has to be duplicated to handle the case where", "# no rate limiter is defined.", "with", "self"...
Run execute with retries and rate limiting. Args: request (object): The HttpRequest object to execute. Returns: dict: The response from the API.
[ "Run", "execute", "with", "retries", "and", "rate", "limiting", "." ]
python
train
39.944444
quantopian/pyfolio
pyfolio/risk.py
https://github.com/quantopian/pyfolio/blob/712716ab0cdebbec9fabb25eea3bf40e4354749d/pyfolio/risk.py#L119-L171
def compute_sector_exposures(positions, sectors, sector_dict=SECTORS): """ Returns arrays of long, short and gross sector exposures of an algorithm's positions Parameters ---------- positions : pd.DataFrame Daily equity positions of algorithm, in dollars. - See full explanation ...
[ "def", "compute_sector_exposures", "(", "positions", ",", "sectors", ",", "sector_dict", "=", "SECTORS", ")", ":", "sector_ids", "=", "sector_dict", ".", "keys", "(", ")", "long_exposures", "=", "[", "]", "short_exposures", "=", "[", "]", "gross_exposures", "=...
Returns arrays of long, short and gross sector exposures of an algorithm's positions Parameters ---------- positions : pd.DataFrame Daily equity positions of algorithm, in dollars. - See full explanation in compute_style_factor_exposures. sectors : pd.DataFrame Daily Mornin...
[ "Returns", "arrays", "of", "long", "short", "and", "gross", "sector", "exposures", "of", "an", "algorithm", "s", "positions" ]
python
valid
34.698113
ARMmbed/icetea
icetea_lib/DeviceConnectors/Dut.py
https://github.com/ARMmbed/icetea/blob/b2b97ac607429830cf7d62dae2e3903692c7c778/icetea_lib/DeviceConnectors/Dut.py#L312-L327
def set_default_init_cli_cmds(self): """ Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name> and set testcase <tc name> :return: List of default cli initialization commands. """ init_cli_cmds = [] init_cli_cmds.append("set ...
[ "def", "set_default_init_cli_cmds", "(", "self", ")", ":", "init_cli_cmds", "=", "[", "]", "init_cli_cmds", ".", "append", "(", "\"set --retcode true\"", ")", "init_cli_cmds", ".", "append", "(", "\"echo off\"", ")", "init_cli_cmds", ".", "append", "(", "\"set --v...
Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name> and set testcase <tc name> :return: List of default cli initialization commands.
[ "Default", "init", "commands", "are", "set", "--", "retcode", "true", "echo", "off", "set", "--", "vt100", "off", "set", "dut", "<dut", "name", ">", "and", "set", "testcase", "<tc", "name", ">" ]
python
train
37.9375
napalm-automation/napalm-logs
napalm_logs/proc.py
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/proc.py#L20-L34
def _suicide_when_without_parent(self, parent_pid): ''' Kill this process when the parent died. ''' while True: time.sleep(5) try: # Check pid alive os.kill(parent_pid, 0) except OSError: # Forcibly exit ...
[ "def", "_suicide_when_without_parent", "(", "self", ",", "parent_pid", ")", ":", "while", "True", ":", "time", ".", "sleep", "(", "5", ")", "try", ":", "# Check pid alive", "os", ".", "kill", "(", "parent_pid", ",", "0", ")", "except", "OSError", ":", "#...
Kill this process when the parent died.
[ "Kill", "this", "process", "when", "the", "parent", "died", "." ]
python
train
32.2
miguelgrinberg/python-engineio
engineio/asyncio_socket.py
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L98-L107
async def handle_post_request(self, environ): """Handle a long-polling POST request from the client.""" length = int(environ.get('CONTENT_LENGTH', '0')) if length > self.server.max_http_buffer_size: raise exceptions.ContentTooLongError() else: body = await environ...
[ "async", "def", "handle_post_request", "(", "self", ",", "environ", ")", ":", "length", "=", "int", "(", "environ", ".", "get", "(", "'CONTENT_LENGTH'", ",", "'0'", ")", ")", "if", "length", ">", "self", ".", "server", ".", "max_http_buffer_size", ":", "...
Handle a long-polling POST request from the client.
[ "Handle", "a", "long", "-", "polling", "POST", "request", "from", "the", "client", "." ]
python
train
46.6
blue-yonder/tsfresh
tsfresh/feature_extraction/feature_calculators.py
https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/feature_extraction/feature_calculators.py#L756-L768
def first_location_of_maximum(x): """ Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float """ ...
[ "def", "first_location_of_maximum", "(", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "np", ".", "ndarray", ",", "pd", ".", "Series", ")", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "return", "np", ".", "argmax", "(...
Returns the first location of the maximum value of x. The position is calculated relatively to the length of x. :param x: the time series to calculate the feature of :type x: numpy.ndarray :return: the value of this feature :return type: float
[ "Returns", "the", "first", "location", "of", "the", "maximum", "value", "of", "x", ".", "The", "position", "is", "calculated", "relatively", "to", "the", "length", "of", "x", "." ]
python
train
34
mozilla/PyPOM
src/pypom/page.py
https://github.com/mozilla/PyPOM/blob/1e7d7ac6e19ec2dac0ea04bad5f3daadbe0c43b8/src/pypom/page.py#L86-L117
def seed_url(self): """A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used to open the page. :rtype: str ...
[ "def", "seed_url", "(", "self", ")", ":", "url", "=", "self", ".", "base_url", "if", "self", ".", "URL_TEMPLATE", "is", "not", "None", ":", "url", "=", "urlparse", ".", "urljoin", "(", "self", ".", "base_url", ",", "self", ".", "URL_TEMPLATE", ".", "...
A URL that can be used to open the page. The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then appended to :py:attr:`base_url` unless the template results in an absolute URL. :return: URL that can be used to open the page. :rtype: str
[ "A", "URL", "that", "can", "be", "used", "to", "open", "the", "page", "." ]
python
valid
30.21875
darothen/xbpch
xbpch/util/gridspec.py
https://github.com/darothen/xbpch/blob/31972dd6fd5f3f7cecc3a46080ce4f43ca23fbe5/xbpch/util/gridspec.py#L575-L591
def _find_references(model_name, references=None): """ Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child). """ references = references or [] references.append(model_name) ref = M...
[ "def", "_find_references", "(", "model_name", ",", "references", "=", "None", ")", ":", "references", "=", "references", "or", "[", "]", "references", ".", "append", "(", "model_name", ")", "ref", "=", "MODELS", "[", "model_name", "]", ".", "get", "(", "...
Iterate over model references for `model_name` and return a list of parent model specifications (including those of `model_name`, ordered from parent to child).
[ "Iterate", "over", "model", "references", "for", "model_name", "and", "return", "a", "list", "of", "parent", "model", "specifications", "(", "including", "those", "of", "model_name", "ordered", "from", "parent", "to", "child", ")", "." ]
python
train
29.588235
HewlettPackard/python-hpOneView
hpOneView/resources/networking/fabrics.py
https://github.com/HewlettPackard/python-hpOneView/blob/3c6219723ef25e6e0c83d44a89007f89bc325b89/hpOneView/resources/networking/fabrics.py#L123-L140
def update_reserved_vlan_range(self, id_or_uri, vlan_pool, force=False): """ Updates the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. vlan_pool (dict): vlan-pool data...
[ "def", "update_reserved_vlan_range", "(", "self", ",", "id_or_uri", ",", "vlan_pool", ",", "force", "=", "False", ")", ":", "uri", "=", "self", ".", "_client", ".", "build_uri", "(", "id_or_uri", ")", "+", "\"/reserved-vlan-range\"", "return", "self", ".", "...
Updates the reserved vlan ID range for the fabric. Note: This method is only available on HPE Synergy. Args: id_or_uri: ID or URI of fabric. vlan_pool (dict): vlan-pool data to update. force: If set to true, the operation completes despite any problems ...
[ "Updates", "the", "reserved", "vlan", "ID", "range", "for", "the", "fabric", "." ]
python
train
41
volafiled/python-volapi
volapi/volapi.py
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/volapi.py#L417-L430
def __add_prop(self, key, admin=False): """Add gettable and settable room config property during runtime""" def getter(self): return self.config[key] def setter(self, val): if admin and not self.admin: raise RuntimeError( f"You can't ...
[ "def", "__add_prop", "(", "self", ",", "key", ",", "admin", "=", "False", ")", ":", "def", "getter", "(", "self", ")", ":", "return", "self", ".", "config", "[", "key", "]", "def", "setter", "(", "self", ",", "val", ")", ":", "if", "admin", "and"...
Add gettable and settable room config property during runtime
[ "Add", "gettable", "and", "settable", "room", "config", "property", "during", "runtime" ]
python
train
35.857143
mikedh/trimesh
trimesh/collision.py
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/collision.py#L161-L204
def add_object(self, name, mesh, transform=None): """ Add an object to the collision manager. If an object with the given name is already in the manager, replace it. Parameters ---------- name : str ...
[ "def", "add_object", "(", "self", ",", "name", ",", "mesh", ",", "transform", "=", "None", ")", ":", "# if no transform passed, assume identity transform", "if", "transform", "is", "None", ":", "transform", "=", "np", ".", "eye", "(", "4", ")", "transform", ...
Add an object to the collision manager. If an object with the given name is already in the manager, replace it. Parameters ---------- name : str An identifier for the object mesh : Trimesh object The geometry of the collision object transform...
[ "Add", "an", "object", "to", "the", "collision", "manager", "." ]
python
train
31.25
KelSolaar/Umbra
umbra/ui/widgets/notification_QLabel.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/ui/widgets/notification_QLabel.py#L283-L295
def anchor(self, value): """ Setter for **self.__anchor** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("anchor", value) assert v...
[ "def", "anchor", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "int", ",", "\"'{0}' attribute: '{1}' type is not 'int'!\"", ".", "format", "(", "\"anchor\"", ",", "value", ")", "ass...
Setter for **self.__anchor** attribute. :param value: Attribute value. :type value: int
[ "Setter", "for", "**", "self", ".", "__anchor", "**", "attribute", "." ]
python
train
35.076923
bcbio/bcbio-nextgen
bcbio/variation/validate.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/variation/validate.py#L470-L478
def bcbio_variation_comparison(config_file, base_dir, data): """Run a variant comparison using the bcbio.variation toolkit, given an input configuration. """ tmp_dir = utils.safe_makedir(os.path.join(base_dir, "tmp")) resources = config_utils.get_resources("bcbio_variation", data["config"]) jvm_opts...
[ "def", "bcbio_variation_comparison", "(", "config_file", ",", "base_dir", ",", "data", ")", ":", "tmp_dir", "=", "utils", ".", "safe_makedir", "(", "os", ".", "path", ".", "join", "(", "base_dir", ",", "\"tmp\"", ")", ")", "resources", "=", "config_utils", ...
Run a variant comparison using the bcbio.variation toolkit, given an input configuration.
[ "Run", "a", "variant", "comparison", "using", "the", "bcbio", ".", "variation", "toolkit", "given", "an", "input", "configuration", "." ]
python
train
62.333333
simonvh/genomepy
genomepy/functions.py
https://github.com/simonvh/genomepy/blob/abace2366511dbe855fe1430b1f7d9ec4cbf6d29/genomepy/functions.py#L436-L453
def gap_sizes(self): """Return gap sizes per chromosome. Returns ------- gap_sizes : dict a dictionary with chromosomes as key and the total number of Ns as values """ if not self._gap_sizes: gap_file = self.props["gaps"]["gap...
[ "def", "gap_sizes", "(", "self", ")", ":", "if", "not", "self", ".", "_gap_sizes", ":", "gap_file", "=", "self", ".", "props", "[", "\"gaps\"", "]", "[", "\"gaps\"", "]", "self", ".", "_gap_sizes", "=", "{", "}", "with", "open", "(", "gap_file", ")",...
Return gap sizes per chromosome. Returns ------- gap_sizes : dict a dictionary with chromosomes as key and the total number of Ns as values
[ "Return", "gap", "sizes", "per", "chromosome", ".", "Returns", "-------", "gap_sizes", ":", "dict", "a", "dictionary", "with", "chromosomes", "as", "key", "and", "the", "total", "number", "of", "Ns", "as", "values" ]
python
train
35.944444
zhanglab/psamm
psamm/gapfill.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/gapfill.py#L143-L273
def gapfill( model, core, blocked, exclude, solver, epsilon=0.001, v_max=1000, weights={}, implicit_sinks=True, allow_bounds_expansion=False): """Find a set of reactions to add such that no compounds are blocked. Returns two iterators: first an iterator of reactions not in core, that were a...
[ "def", "gapfill", "(", "model", ",", "core", ",", "blocked", ",", "exclude", ",", "solver", ",", "epsilon", "=", "0.001", ",", "v_max", "=", "1000", ",", "weights", "=", "{", "}", ",", "implicit_sinks", "=", "True", ",", "allow_bounds_expansion", "=", ...
Find a set of reactions to add such that no compounds are blocked. Returns two iterators: first an iterator of reactions not in core, that were added to resolve the model. Second, an iterator of reactions in core that had flux bounds expanded (i.e. irreversible reactions become reversible). Similarly t...
[ "Find", "a", "set", "of", "reactions", "to", "add", "such", "that", "no", "compounds", "are", "blocked", "." ]
python
train
43.358779
fermiPy/fermipy
fermipy/diffuse/residual_cr.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/residual_cr.py#L62-L102
def _match_cubes(ccube_clean, ccube_dirty, bexpcube_clean, bexpcube_dirty, hpx_order): """ Match the HEALPIX scheme and order of all the input cubes return a dictionary of cubes with the same HEALPIX scheme and order """ if hpx_order == ccube_cl...
[ "def", "_match_cubes", "(", "ccube_clean", ",", "ccube_dirty", ",", "bexpcube_clean", ",", "bexpcube_dirty", ",", "hpx_order", ")", ":", "if", "hpx_order", "==", "ccube_clean", ".", "hpx", ".", "order", ":", "ccube_clean_at_order", "=", "ccube_clean", "else", ":...
Match the HEALPIX scheme and order of all the input cubes return a dictionary of cubes with the same HEALPIX scheme and order
[ "Match", "the", "HEALPIX", "scheme", "and", "order", "of", "all", "the", "input", "cubes" ]
python
train
43.073171
IdentityPython/pysaml2
example/idp2/idp.py
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/example/idp2/idp.py#L1022-L1082
def application(environ, start_response): """ The main WSGI application. Dispatch the current request to the functions from above and store the regular expression captures in the WSGI environment as `myapp.url_args` so that the functions from above can access the url placeholders. If nothing m...
[ "def", "application", "(", "environ", ",", "start_response", ")", ":", "path", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ",", "\"\"", ")", ".", "lstrip", "(", "\"/\"", ")", "if", "path", "==", "\"metadata\"", ":", "return", "metadata", "(", "envi...
The main WSGI application. Dispatch the current request to the functions from above and store the regular expression captures in the WSGI environment as `myapp.url_args` so that the functions from above can access the url placeholders. If nothing matches, call the `not_found` function. :param env...
[ "The", "main", "WSGI", "application", ".", "Dispatch", "the", "current", "request", "to", "the", "functions", "from", "above", "and", "store", "the", "regular", "expression", "captures", "in", "the", "WSGI", "environment", "as", "myapp", ".", "url_args", "so",...
python
train
33.557377
evolbioinfo/pastml
pastml/parsimony.py
https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/parsimony.py#L292-L314
def choose_parsimonious_states(tree, ps_feature, out_feature): """ Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states and stores them in the `feature` feature to each node. The get_personalized_feature_name(feature, PARS_STATES) is delete...
[ "def", "choose_parsimonious_states", "(", "tree", ",", "ps_feature", ",", "out_feature", ")", ":", "num_scenarios", "=", "1", "unresolved_nodes", "=", "0", "num_states", "=", "0", "for", "node", "in", "tree", ".", "traverse", "(", ")", ":", "states", "=", ...
Converts the content of the get_personalized_feature_name(feature, PARS_STATES) node feature to the predicted states and stores them in the `feature` feature to each node. The get_personalized_feature_name(feature, PARS_STATES) is deleted. :param feature: str, character for which the parsimonious states ar...
[ "Converts", "the", "content", "of", "the", "get_personalized_feature_name", "(", "feature", "PARS_STATES", ")", "node", "feature", "to", "the", "predicted", "states", "and", "stores", "them", "in", "the", "feature", "feature", "to", "each", "node", ".", "The", ...
python
train
44.086957
DataBiosphere/toil
src/toil/fileStore.py
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/fileStore.py#L1966-L1989
def shutdownFileStore(workflowDir, workflowID): """ Run the deferred functions from any prematurely terminated jobs still lingering on the system and carry out any necessary filestore-specific cleanup. This is a destructive operation and it is important to ensure that there are no other running pro...
[ "def", "shutdownFileStore", "(", "workflowDir", ",", "workflowID", ")", ":", "cacheDir", "=", "os", ".", "path", ".", "join", "(", "workflowDir", ",", "cacheDirName", "(", "workflowID", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "cacheDir", "...
Run the deferred functions from any prematurely terminated jobs still lingering on the system and carry out any necessary filestore-specific cleanup. This is a destructive operation and it is important to ensure that there are no other running processes on the system that are modifying or using the file st...
[ "Run", "the", "deferred", "functions", "from", "any", "prematurely", "terminated", "jobs", "still", "lingering", "on", "the", "system", "and", "carry", "out", "any", "necessary", "filestore", "-", "specific", "cleanup", "." ]
python
train
49.5
pgmpy/pgmpy
pgmpy/inference/dbn_inference.py
https://github.com/pgmpy/pgmpy/blob/9381a66aba3c3871d3ccd00672b148d17d63239e/pgmpy/inference/dbn_inference.py#L151-L177
def _update_belief(self, belief_prop, clique, clique_potential, message=None): """ Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor w...
[ "def", "_update_belief", "(", "self", ",", "belief_prop", ",", "clique", ",", "clique_potential", ",", "message", "=", "None", ")", ":", "old_factor", "=", "belief_prop", ".", "junction_tree", ".", "get_factors", "(", "clique", ")", "belief_prop", ".", "juncti...
Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor which needs to be updated corresponding to the input clique. out_clique_potential: factor ...
[ "Method", "for", "updating", "the", "belief", "." ]
python
train
38.407407
StevenMaude/bbc-radio-tracklisting-downloader
bbc_tracklist.py
https://github.com/StevenMaude/bbc-radio-tracklisting-downloader/blob/9fe9096b4d889888f65756444e4fd71352b92458/bbc_tracklist.py#L178-L193
def tag_audio_file(audio_file, tracklisting): """ Adds tracklisting as list to lyrics tag of audio file if not present. Returns True if successful or not needed, False if tagging fails. """ try: save_tag_to_audio_file(audio_file, tracklisting) # TODO: is IOError required now or would the...
[ "def", "tag_audio_file", "(", "audio_file", ",", "tracklisting", ")", ":", "try", ":", "save_tag_to_audio_file", "(", "audio_file", ",", "tracklisting", ")", "# TODO: is IOError required now or would the mediafile exception cover it?", "except", "(", "IOError", ",", "mediaf...
Adds tracklisting as list to lyrics tag of audio file if not present. Returns True if successful or not needed, False if tagging fails.
[ "Adds", "tracklisting", "as", "list", "to", "lyrics", "tag", "of", "audio", "file", "if", "not", "present", ".", "Returns", "True", "if", "successful", "or", "not", "needed", "False", "if", "tagging", "fails", "." ]
python
train
40.125
gem/oq-engine
openquake/hazardlib/near_fault.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/near_fault.py#L238-L259
def isochone_ratio(e, rd, r_hyp): """ Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88. :param e: a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km. :param rd: float, distance from the sit...
[ "def", "isochone_ratio", "(", "e", ",", "rd", ",", "r_hyp", ")", ":", "if", "e", "==", "0.", ":", "c_prime", "=", "0.8", "elif", "e", ">", "0.", ":", "c_prime", "=", "1.", "/", "(", "(", "1.", "/", "0.8", ")", "-", "(", "(", "r_hyp", "-", "...
Get the isochone ratio as described in Spudich et al. (2013) PEER report, page 88. :param e: a float defining the E-path length, which is the distance from Pd(direction) point to hypocentre. In km. :param rd: float, distance from the site to the direct point. :param r_hyp: ...
[ "Get", "the", "isochone", "ratio", "as", "described", "in", "Spudich", "et", "al", ".", "(", "2013", ")", "PEER", "report", "page", "88", "." ]
python
train
26.681818
relwell/corenlp-xml-lib
corenlp_xml/document.py
https://github.com/relwell/corenlp-xml-lib/blob/9b0f8c912ba3ecedd34473f74a9f2d033a75baf9/corenlp_xml/document.py#L30-L41
def sentiment(self): """ Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float """ if self._sentiment is None: results = self._xml.xpath('/root/document/sentences') ...
[ "def", "sentiment", "(", "self", ")", ":", "if", "self", ".", "_sentiment", "is", "None", ":", "results", "=", "self", ".", "_xml", ".", "xpath", "(", "'/root/document/sentences'", ")", "self", ".", "_sentiment", "=", "float", "(", "results", "[", "0", ...
Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float
[ "Returns", "average", "sentiment", "of", "document", ".", "Must", "have", "sentiment", "enabled", "in", "XML", "output", "." ]
python
train
36.916667
deepmind/sonnet
sonnet/python/modules/nets/vqvae.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/nets/vqvae.py#L181-L252
def _build(self, inputs, is_training): """Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connection is to training data....
[ "def", "_build", "(", "self", ",", "inputs", ",", "is_training", ")", ":", "# Ensure that the weights are read fresh for each timestep, which otherwise", "# would not be guaranteed in an RNN setup. Note that this relies on inputs", "# having a data dependency with the output of the previous ...
Connects the module to some inputs. Args: inputs: Tensor, final dimension must be equal to embedding_dim. All other leading dimensions will be flattened and treated as a large batch. is_training: boolean, whether this connection is to training data. When this is set to False, the intern...
[ "Connects", "the", "module", "to", "some", "inputs", "." ]
python
train
48.291667
openstack/networking-arista
networking_arista/common/db_lib.py
https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L81-L95
def filter_unbound_ports(query): """Filter ports not bound to a host or network""" # hack for pep8 E711: comparison to None should be # 'if cond is not None' none = None port_model = models_v2.Port binding_level_model = ml2_models.PortBindingLevel query = (query .join_if_necessa...
[ "def", "filter_unbound_ports", "(", "query", ")", ":", "# hack for pep8 E711: comparison to None should be", "# 'if cond is not None'", "none", "=", "None", "port_model", "=", "models_v2", ".", "Port", "binding_level_model", "=", "ml2_models", ".", "PortBindingLevel", "quer...
Filter ports not bound to a host or network
[ "Filter", "ports", "not", "bound", "to", "a", "host", "or", "network" ]
python
train
37.133333
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L125-L144
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...
[ "def", "downsample_bottleneck", "(", "x", ",", "output_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "1", ",", "scope", "=", "'h'", ")", ":", "conv", "=", "CONFIG", "[", "dim", "]", "[", "'conv'", "]", "with", "tf", ".", "variable_scope", "...
Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: ...
[ "Downsamples", "x", "by", "stride", "using", "a", "1x1", "convolution", "filter", "." ]
python
train
36
LabKey/labkey-api-python
labkey/security.py
https://github.com/LabKey/labkey-api-python/blob/3c8d393384d7cbb2785f8a7f5fe34007b17a76b8/labkey/security.py#L194-L213
def __make_security_group_api_request(server_context, api, user_ids, group_id, container_path): """ Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param use...
[ "def", "__make_security_group_api_request", "(", "server_context", ",", "api", ",", "user_ids", ",", "group_id", ",", "container_path", ")", ":", "url", "=", "server_context", ".", "build_url", "(", "security_controller", ",", "api", ",", "container_path", ")", "#...
Execute a request against the LabKey Security Controller Group Membership apis :param server_context: A LabKey server context. See utils.create_server_context. :param api: Action to execute :param user_ids: user ids to apply action to :param group_id: group id to apply action to :param container_pat...
[ "Execute", "a", "request", "against", "the", "LabKey", "Security", "Controller", "Group", "Membership", "apis", ":", "param", "server_context", ":", "A", "LabKey", "server", "context", ".", "See", "utils", ".", "create_server_context", ".", ":", "param", "api", ...
python
train
40.55
PyHDI/Pyverilog
pyverilog/vparser/parser.py
https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L1373-L1377
def p_sens_all_paren(self, p): 'senslist : AT LPAREN TIMES RPAREN' p[0] = SensList( (Sens(None, 'all', lineno=p.lineno(1)),), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_sens_all_paren", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "SensList", "(", "(", "Sens", "(", "None", ",", "'all'", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", ",", ")", ",", "lineno", "=", "p", ".", ...
senslist : AT LPAREN TIMES RPAREN
[ "senslist", ":", "AT", "LPAREN", "TIMES", "RPAREN" ]
python
train
41.2
spotify/luigi
luigi/task.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/task.py#L120-L137
def task_id_str(task_family, params): """ Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the ...
[ "def", "task_id_str", "(", "task_family", ",", "params", ")", ":", "# task_id is a concatenation of task family, the first values of the first 3 parameters", "# sorted by parameter name and a md5hash of the family/parameters as a cananocalised json.", "param_str", "=", "json", ".", "dump...
Returns a canonical string used to identify a particular task :param task_family: The task family (class name) of the task :param params: a dict mapping parameter names to their serialized values :return: A unique, shortened identifier corresponding to the family and params
[ "Returns", "a", "canonical", "string", "used", "to", "identify", "a", "particular", "task" ]
python
train
54.444444
dtmilano/AndroidViewClient
src/com/dtmilano/android/viewclient.py
https://github.com/dtmilano/AndroidViewClient/blob/7e6e83fde63af99e5e4ab959712ecf94f9881aa2/src/com/dtmilano/android/viewclient.py#L2333-L2343
def CharacterData(self, data): ''' Expat character data event handler ''' if data.strip(): data = data.encode() if not self.data: self.data = data else: self.data += data
[ "def", "CharacterData", "(", "self", ",", "data", ")", ":", "if", "data", ".", "strip", "(", ")", ":", "data", "=", "data", ".", "encode", "(", ")", "if", "not", "self", ".", "data", ":", "self", ".", "data", "=", "data", "else", ":", "self", "...
Expat character data event handler
[ "Expat", "character", "data", "event", "handler" ]
python
train
23.727273
gmr/rejected
rejected/consumer.py
https://github.com/gmr/rejected/blob/610a3e1401122ecb98d891b6795cca0255e5b044/rejected/consumer.py#L990-L1009
def _handle_exception(self, exc): """Common exception handling behavior across all exceptions. .. note:: This for internal use and should not be extended or used directly. """ exc_info = sys.exc_info() self.logger.exception( '%s while processing message ...
[ "def", "_handle_exception", "(", "self", ",", "exc", ")", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "self", ".", "logger", ".", "exception", "(", "'%s while processing message #%s'", ",", "exc", ".", "__class__", ".", "__name__", ",", "self", ...
Common exception handling behavior across all exceptions. .. note:: This for internal use and should not be extended or used directly.
[ "Common", "exception", "handling", "behavior", "across", "all", "exceptions", "." ]
python
train
39
ga4gh/ga4gh-server
ga4gh/server/datamodel/variants.py
https://github.com/ga4gh/ga4gh-server/blob/1aa18922ef136db8604f6f098cb1732cba6f2a76/ga4gh/server/datamodel/variants.py#L555-L593
def _updateVariantAnnotationSets(self, variantFile, dataUrl): """ Updates the variant annotation set associated with this variant using information in the specified pysam variantFile. """ # TODO check the consistency of this between VCF files. if not self.isAnnotated(): ...
[ "def", "_updateVariantAnnotationSets", "(", "self", ",", "variantFile", ",", "dataUrl", ")", ":", "# TODO check the consistency of this between VCF files.", "if", "not", "self", ".", "isAnnotated", "(", ")", ":", "annotationType", "=", "None", "for", "record", "in", ...
Updates the variant annotation set associated with this variant using information in the specified pysam variantFile.
[ "Updates", "the", "variant", "annotation", "set", "associated", "with", "this", "variant", "using", "information", "in", "the", "specified", "pysam", "variantFile", "." ]
python
train
53.282051
Telefonica/toolium
toolium/utils.py
https://github.com/Telefonica/toolium/blob/56847c243b3a98876df74c184b75e43f8810e475/toolium/utils.py#L461-L472
def get_server_url(self): """Return the configured server url :returns: server url """ server_host = self.driver_wrapper.config.get('Server', 'host') server_port = self.driver_wrapper.config.get('Server', 'port') server_username = self.driver_wrapper.config.get_optional(...
[ "def", "get_server_url", "(", "self", ")", ":", "server_host", "=", "self", ".", "driver_wrapper", ".", "config", ".", "get", "(", "'Server'", ",", "'host'", ")", "server_port", "=", "self", ".", "driver_wrapper", ".", "config", ".", "get", "(", "'Server'"...
Return the configured server url :returns: server url
[ "Return", "the", "configured", "server", "url" ]
python
train
53.916667
deepmind/sonnet
sonnet/python/modules/spatial_transformer.py
https://github.com/deepmind/sonnet/blob/00612ca3178964d86b556e062694d808ff81fcca/sonnet/python/modules/spatial_transformer.py#L538-L546
def combine_with(self, additional_constraints): """Combines two sets of constraints into a coherent single set.""" x = additional_constraints if not isinstance(additional_constraints, AffineWarpConstraints): x = AffineWarpConstraints(additional_constraints) new_constraints = [] for left, right...
[ "def", "combine_with", "(", "self", ",", "additional_constraints", ")", ":", "x", "=", "additional_constraints", "if", "not", "isinstance", "(", "additional_constraints", ",", "AffineWarpConstraints", ")", ":", "x", "=", "AffineWarpConstraints", "(", "additional_const...
Combines two sets of constraints into a coherent single set.
[ "Combines", "two", "sets", "of", "constraints", "into", "a", "coherent", "single", "set", "." ]
python
train
53.888889
woolfson-group/isambard
isambard/ampal/protein.py
https://github.com/woolfson-group/isambard/blob/ebc33b48a28ad217e18f93b910dfba46e6e71e07/isambard/ampal/protein.py#L1218-L1250
def backbone(self): """Returns a new `Residue` containing only the backbone atoms. Returns ------- bb_monomer : Residue `Residue` containing only the backbone atoms of the original `Monomer`. Raises ------ IndexError Raise if ...
[ "def", "backbone", "(", "self", ")", ":", "try", ":", "backbone", "=", "OrderedDict", "(", "[", "(", "'N'", ",", "self", ".", "atoms", "[", "'N'", "]", ")", ",", "(", "'CA'", ",", "self", ".", "atoms", "[", "'CA'", "]", ")", ",", "(", "'C'", ...
Returns a new `Residue` containing only the backbone atoms. Returns ------- bb_monomer : Residue `Residue` containing only the backbone atoms of the original `Monomer`. Raises ------ IndexError Raise if the `atoms` dict does not conta...
[ "Returns", "a", "new", "Residue", "containing", "only", "the", "backbone", "atoms", "." ]
python
train
43.090909
odlgroup/odl
odl/space/pspace.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/pspace.py#L1704-L1727
def inner(self, x1, x2): """Calculate the constant-weighted inner product of two elements. Parameters ---------- x1, x2 : `ProductSpaceElement` Elements whose inner product is calculated. Returns ------- inner : float or complex The inner...
[ "def", "inner", "(", "self", ",", "x1", ",", "x2", ")", ":", "if", "self", ".", "exponent", "!=", "2.0", ":", "raise", "NotImplementedError", "(", "'no inner product defined for '", "'exponent != 2 (got {})'", "''", ".", "format", "(", "self", ".", "exponent",...
Calculate the constant-weighted inner product of two elements. Parameters ---------- x1, x2 : `ProductSpaceElement` Elements whose inner product is calculated. Returns ------- inner : float or complex The inner product of the two provided element...
[ "Calculate", "the", "constant", "-", "weighted", "inner", "product", "of", "two", "elements", "." ]
python
train
33.666667
craft-ai/craft-ai-client-python
craftai/client.py
https://github.com/craft-ai/craft-ai-client-python/blob/8bc1a9038511540930371aacfdde0f4040e08f24/craftai/client.py#L516-L552
def get_decision_tree(self, agent_id, timestamp=None, version=DEFAULT_DECISION_TREE_VERSION): """Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: ...
[ "def", "get_decision_tree", "(", "self", ",", "agent_id", ",", "timestamp", "=", "None", ",", "version", "=", "DEFAULT_DECISION_TREE_VERSION", ")", ":", "# Raises an error when agent_id is invalid", "self", ".", "_check_agent_id", "(", "agent_id", ")", "if", "self", ...
Get decision tree. :param str agent_id: the id of the agent to get the tree. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :param int timestamp: Optional. The decision tree is comptuted at this timestamp. :default timestamp: None, means t...
[ "Get", "decision", "tree", "." ]
python
train
37.405405
CivicSpleen/ambry
ambry/bundle/bundle.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L355-L372
def documentation(self): """Return the documentation, from the documentation.md file, with template substitutions""" # Return the documentation as a scalar term, which has .text() and .html methods to do # metadata substitution using Jinja s = '' rc = self.build_source_files.d...
[ "def", "documentation", "(", "self", ")", ":", "# Return the documentation as a scalar term, which has .text() and .html methods to do", "# metadata substitution using Jinja", "s", "=", "''", "rc", "=", "self", ".", "build_source_files", ".", "documentation", ".", "record_conte...
Return the documentation, from the documentation.md file, with template substitutions
[ "Return", "the", "documentation", "from", "the", "documentation", ".", "md", "file", "with", "template", "substitutions" ]
python
train
30.333333
aio-libs/aiomcache
aiomcache/client.py
https://github.com/aio-libs/aiomcache/blob/75d44b201aea91bc2856b10940922d5ebfbfcd7b/aiomcache/client.py#L362-L378
def decr(self, conn, key, decrement=1): """Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change ...
[ "def", "decr", "(", "self", ",", "conn", ",", "key", ",", "decrement", "=", "1", ")", ":", "assert", "self", ".", "_validate_key", "(", "key", ")", "resp", "=", "yield", "from", "self", ".", "_incr_decr", "(", "conn", ",", "b'decr'", ",", "key", ",...
Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change :param decrement: ``int``, is the amount by ...
[ "Command", "is", "used", "to", "change", "data", "for", "some", "item", "in", "-", "place", "decrementing", "it", ".", "The", "data", "for", "the", "item", "is", "treated", "as", "decimal", "representation", "of", "a", "64", "-", "bit", "unsigned", "inte...
python
train
42.235294
absent1706/sqlalchemy-mixins
sqlalchemy_mixins/serialize.py
https://github.com/absent1706/sqlalchemy-mixins/blob/a111e69fc5edc5d81a31dca45755f21c8c512ed1/sqlalchemy_mixins/serialize.py#L11-L31
def to_dict(self, nested=False): """Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict """ result = dict() for key in self.columns: result[key] = getattr(self, key) ...
[ "def", "to_dict", "(", "self", ",", "nested", "=", "False", ")", ":", "result", "=", "dict", "(", ")", "for", "key", "in", "self", ".", "columns", ":", "result", "[", "key", "]", "=", "getattr", "(", "self", ",", "key", ")", "if", "nested", ":", ...
Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict
[ "Return", "dict", "object", "with", "model", "s", "data", "." ]
python
train
29.714286
albahnsen/CostSensitiveClassification
costcla/models/cost_tree.py
https://github.com/albahnsen/CostSensitiveClassification/blob/75778ae32c70671c0cdde6c4651277b6a8b58871/costcla/models/cost_tree.py#L185-L242
def _calculate_gain(self, cost_base, y_true, X, cost_mat, split): """ Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix ...
[ "def", "_calculate_gain", "(", "self", ",", "cost_base", ",", "y_true", ",", "X", ",", "cost_mat", ",", "split", ")", ":", "# Check if cost_base == 0, then no gain is possible", "#TODO: This must be check in _best_split", "if", "cost_base", "==", "0.0", ":", "return", ...
Private function to calculate the gain in cost of using split in the current node. Parameters ---------- cost_base : float Cost of the naive prediction y_true : array indicator matrix Ground truth (correct) labels. X : array-like of shape = [n_...
[ "Private", "function", "to", "calculate", "the", "gain", "in", "cost", "of", "using", "split", "in", "the", "current", "node", "." ]
python
train
35.603448
Alignak-monitoring/alignak
alignak/http/arbiter_interface.py
https://github.com/Alignak-monitoring/alignak/blob/f3c145207e83159b799d3714e4241399c7740a64/alignak/http/arbiter_interface.py#L1479-L1616
def host(self): # pylint: disable=too-many-branches """Get a passive checks for an host and its services This function builds the external commands corresponding to the host and services provided information :param host_name: host name :param data: dictionary of the hos...
[ "def", "host", "(", "self", ")", ":", "# pylint: disable=too-many-branches", "logger", ".", "debug", "(", "\"Host status...\"", ")", "if", "cherrypy", ".", "request", ".", "method", "not", "in", "[", "\"PATCH\"", ",", "\"POST\"", "]", ":", "cherrypy", ".", "...
Get a passive checks for an host and its services This function builds the external commands corresponding to the host and services provided information :param host_name: host name :param data: dictionary of the host properties to be modified :return: command line
[ "Get", "a", "passive", "checks", "for", "an", "host", "and", "its", "services" ]
python
train
40.804348
joshspeagle/dynesty
dynesty/sampling.py
https://github.com/joshspeagle/dynesty/blob/9e482aafeb5cf84bedb896fa6f07a761d917983e/dynesty/sampling.py#L392-L566
def sample_slice(args): """ Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Parameters ---------- u : `...
[ "def", "sample_slice", "(", "args", ")", ":", "# Unzipping.", "(", "u", ",", "loglstar", ",", "axes", ",", "scale", ",", "prior_transform", ",", "loglikelihood", ",", "kwargs", ")", "=", "args", "rstate", "=", "np", ".", "random", "# Periodicity.", "nonper...
Return a new live point proposed by a series of random slices away from an existing live point. Standard "Gibs-like" implementation where a single multivariate "slice" is a combination of `ndim` univariate slices through each axis. Parameters ---------- u : `~numpy.ndarray` with shape (npdim,) ...
[ "Return", "a", "new", "live", "point", "proposed", "by", "a", "series", "of", "random", "slices", "away", "from", "an", "existing", "live", "point", ".", "Standard", "Gibs", "-", "like", "implementation", "where", "a", "single", "multivariate", "slice", "is"...
python
train
35.188571
Cue/scales
src/greplin/scales/util.py
https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/util.py#L85-L93
def disconnect(self): """Disconnect from the Graphite server if connected.""" if self.sock is not None: try: self.sock.close() except socket.error: pass finally: self.sock = None
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "sock", "is", "not", "None", ":", "try", ":", "self", ".", "sock", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "pass", "finally", ":", "self", ".", "sock", "=", "No...
Disconnect from the Graphite server if connected.
[ "Disconnect", "from", "the", "Graphite", "server", "if", "connected", "." ]
python
train
24.444444
bufferapp/pipub
pipub/cli.py
https://github.com/bufferapp/pipub/blob/1270b2cc3b72ddbe57874757dcf5537d3d36e189/pipub/cli.py#L6-L12
def standard_input(): """Generator that yields lines from standard input.""" with click.get_text_stream("stdin") as stdin: while stdin.readable(): line = stdin.readline() if line: yield line.strip().encode("utf-8")
[ "def", "standard_input", "(", ")", ":", "with", "click", ".", "get_text_stream", "(", "\"stdin\"", ")", "as", "stdin", ":", "while", "stdin", ".", "readable", "(", ")", ":", "line", "=", "stdin", ".", "readline", "(", ")", "if", "line", ":", "yield", ...
Generator that yields lines from standard input.
[ "Generator", "that", "yields", "lines", "from", "standard", "input", "." ]
python
train
37.714286
raamana/hiwenet
hiwenet/pairwise_dist.py
https://github.com/raamana/hiwenet/blob/b12699b3722fd0a6a835e7d7ca4baf58fb181809/hiwenet/pairwise_dist.py#L483-L495
def make_random_histogram(length=100, num_bins=10): "Returns a sequence of histogram density values that sum to 1.0" hist, bin_edges = np.histogram(np.random.random(length), bins=num_bins, density=True) # to ensure they sum to 1.0 hist = hist / sum(hist) if len(...
[ "def", "make_random_histogram", "(", "length", "=", "100", ",", "num_bins", "=", "10", ")", ":", "hist", ",", "bin_edges", "=", "np", ".", "histogram", "(", "np", ".", "random", ".", "random", "(", "length", ")", ",", "bins", "=", "num_bins", ",", "d...
Returns a sequence of histogram density values that sum to 1.0
[ "Returns", "a", "sequence", "of", "histogram", "density", "values", "that", "sum", "to", "1", ".", "0" ]
python
train
29.307692
gitpython-developers/GitPython
git/objects/submodule/base.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/submodule/base.py#L221-L230
def _config_parser_constrained(self, read_only): """:return: Config Parser constrained to our submodule in read or write mode""" try: pc = self.parent_commit except ValueError: pc = None # end handle empty parent repository parser = self._config_parser(sel...
[ "def", "_config_parser_constrained", "(", "self", ",", "read_only", ")", ":", "try", ":", "pc", "=", "self", ".", "parent_commit", "except", "ValueError", ":", "pc", "=", "None", "# end handle empty parent repository", "parser", "=", "self", ".", "_config_parser",...
:return: Config Parser constrained to our submodule in read or write mode
[ ":", "return", ":", "Config", "Parser", "constrained", "to", "our", "submodule", "in", "read", "or", "write", "mode" ]
python
train
43.2
Microsoft/knack
knack/arguments.py
https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L247-L267
def argument(self, argument_dest, arg_type=None, **kwargs): """ Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIAr...
[ "def", "argument", "(", "self", ",", "argument_dest", ",", "arg_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_stale", "(", ")", "if", "not", "self", ".", "_applicable", "(", ")", ":", "return", "deprecate_action", "=", "se...
Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs. ...
[ "Register", "an", "argument", "for", "the", "given", "command", "scope", "using", "a", "knack", ".", "arguments", ".", "CLIArgumentType" ]
python
train
58.142857
PlaidWeb/Publ
publ/markdown.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/markdown.py#L118-L129
def link(self, content, link, title=''): """ Emit a link, potentially remapped based on our embed or static rules """ link = links.resolve(link, self._search_path, self._config.get('absolute')) return '{}{}</a>'.format( utils.make_tag('a', { ...
[ "def", "link", "(", "self", ",", "content", ",", "link", ",", "title", "=", "''", ")", ":", "link", "=", "links", ".", "resolve", "(", "link", ",", "self", ".", "_search_path", ",", "self", ".", "_config", ".", "get", "(", "'absolute'", ")", ")", ...
Emit a link, potentially remapped based on our embed or static rules
[ "Emit", "a", "link", "potentially", "remapped", "based", "on", "our", "embed", "or", "static", "rules" ]
python
train
34.5
troeger/opensubmit
web/opensubmit/signalhandlers.py
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/web/opensubmit/signalhandlers.py#L17-L34
def post_user_login(sender, request, user, **kwargs): """ Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the ...
[ "def", "post_user_login", "(", "sender", ",", "request", ",", "user", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"Running post-processing for user login.\"", ")", "# Users created by social login or admins have no profile.", "# We fix that during thei...
Create a profile for the user, when missing. Make sure that all neccessary user groups exist and have the right permissions. We need that automatism for people not calling the configure tool, admin rights for admins after the first login, and similar cases.
[ "Create", "a", "profile", "for", "the", "user", "when", "missing", ".", "Make", "sure", "that", "all", "neccessary", "user", "groups", "exist", "and", "have", "the", "right", "permissions", ".", "We", "need", "that", "automatism", "for", "people", "not", "...
python
train
47.722222
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L872-L875
def _append_plain_text(self, text, before_prompt=False): """ Appends plain text, processing ANSI codes if enabled. """ self._append_custom(self._insert_plain_text, text, before_prompt)
[ "def", "_append_plain_text", "(", "self", ",", "text", ",", "before_prompt", "=", "False", ")", ":", "self", ".", "_append_custom", "(", "self", ".", "_insert_plain_text", ",", "text", ",", "before_prompt", ")" ]
Appends plain text, processing ANSI codes if enabled.
[ "Appends", "plain", "text", "processing", "ANSI", "codes", "if", "enabled", "." ]
python
test
51.25
jakevdp/supersmoother
supersmoother/windowed_sum.py
https://github.com/jakevdp/supersmoother/blob/0c96cf13dcd6f9006d3c0421f9cd6e18abe27a2f/supersmoother/windowed_sum.py#L215-L242
def _pad_arrays(t, arrays, indices, span, period): """Internal routine to pad arrays for periodic models.""" N = len(t) if indices is None: indices = np.arange(N) pad_left = max(0, 0 - np.min(indices - span // 2)) pad_right = max(0, np.max(indices + span - span // 2) - (N - 1)) if pad_...
[ "def", "_pad_arrays", "(", "t", ",", "arrays", ",", "indices", ",", "span", ",", "period", ")", ":", "N", "=", "len", "(", "t", ")", "if", "indices", "is", "None", ":", "indices", "=", "np", ".", "arange", "(", "N", ")", "pad_left", "=", "max", ...
Internal routine to pad arrays for periodic models.
[ "Internal", "routine", "to", "pad", "arrays", "for", "periodic", "models", "." ]
python
train
40.178571
allelos/vectors
vectors/vectors.py
https://github.com/allelos/vectors/blob/55db2a7e489ae5f4380e70b3c5b7a6ce39de5cee/vectors/vectors.py#L120-L122
def multiply(self, number): """Return a Vector as the product of the vector and a real number.""" return self.from_list([x * number for x in self.to_list()])
[ "def", "multiply", "(", "self", ",", "number", ")", ":", "return", "self", ".", "from_list", "(", "[", "x", "*", "number", "for", "x", "in", "self", ".", "to_list", "(", ")", "]", ")" ]
Return a Vector as the product of the vector and a real number.
[ "Return", "a", "Vector", "as", "the", "product", "of", "the", "vector", "and", "a", "real", "number", "." ]
python
train
57
globocom/GloboNetworkAPI-client-python
networkapiclient/ApiEnvironmentVip.py
https://github.com/globocom/GloboNetworkAPI-client-python/blob/cf34f913da48d9abbf750114f5d2ac4b2dde137d/networkapiclient/ApiEnvironmentVip.py#L46-L62
def environmentvip_step(self, finality='', client='', environmentp44=''): """ List finality, client or environment vip list. Param finality: finality of environment(optional) Param client: client of environment(optional) Param environmentp44: environmentp44(optional) Retu...
[ "def", "environmentvip_step", "(", "self", ",", "finality", "=", "''", ",", "client", "=", "''", ",", "environmentp44", "=", "''", ")", ":", "uri", "=", "'api/v3/environment-vip/step/?finality=%s&client=%s&environmentp44=%s'", "%", "(", "finality", ",", "client", ...
List finality, client or environment vip list. Param finality: finality of environment(optional) Param client: client of environment(optional) Param environmentp44: environmentp44(optional) Return finality list: when request has no finality and client. Return client list: when re...
[ "List", "finality", "client", "or", "environment", "vip", "list", ".", "Param", "finality", ":", "finality", "of", "environment", "(", "optional", ")", "Param", "client", ":", "client", "of", "environment", "(", "optional", ")", "Param", "environmentp44", ":",...
python
train
47
etcher-be/emiz
emiz/avwx/core.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/core.py#L23-L32
def valid_station(station: str): """ Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed """ station = station.strip() if len(station) != 4: raise BadStation('ICAO station idents must be four characters long') u...
[ "def", "valid_station", "(", "station", ":", "str", ")", ":", "station", "=", "station", ".", "strip", "(", ")", "if", "len", "(", "station", ")", "!=", "4", ":", "raise", "BadStation", "(", "'ICAO station idents must be four characters long'", ")", "uses_na_f...
Checks the validity of a station ident This function doesn't return anything. It merely raises a BadStation error if needed
[ "Checks", "the", "validity", "of", "a", "station", "ident" ]
python
train
33.3
scott-griffiths/bitstring
bitstring.py
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1830-L1842
def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" length = len(binstring) # pad with zeros up to byte boundary if needed boundary = ((length + 7) // 8) * 8 padded_binstring = binstring + '0' * (boun...
[ "def", "_setbin_unsafe", "(", "self", ",", "binstring", ")", ":", "length", "=", "len", "(", "binstring", ")", "# pad with zeros up to byte boundary if needed", "boundary", "=", "(", "(", "length", "+", "7", ")", "//", "8", ")", "*", "8", "padded_binstring", ...
Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.
[ "Same", "as", "_setbin_safe", "but", "input", "isn", "t", "sanity", "checked", ".", "binstring", "mustn", "t", "start", "with", "0b", "." ]
python
train
54.769231
openstack/proliantutils
proliantutils/hpssa/objects.py
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/hpssa/objects.py#L239-L256
def refresh(self): """Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: HPSSAOperationError, if hpssacli/ssacli...
[ "def", "refresh", "(", "self", ")", ":", "config", "=", "self", ".", "_get_all_details", "(", ")", "raid_info", "=", "_convert_to_dict", "(", "config", ")", "self", ".", "controllers", "=", "[", "]", "for", "key", ",", "value", "in", "raid_info", ".", ...
Refresh the server and it's child objects. This method removes all the cache information in the server and it's child objects, and fetches the information again from the server using hpssacli/ssacli command. :raises: HPSSAOperationError, if hpssacli/ssacli operation failed.
[ "Refresh", "the", "server", "and", "it", "s", "child", "objects", "." ]
python
train
33.5
mapillary/mapillary_tools
mapillary_tools/exif_write.py
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/exif_write.py#L97-L111
def write(self, filename=None): """Save exif data to file.""" if filename is None: filename = self._filename exif_bytes = piexif.dump(self._ef) with open(self._filename, "rb") as fin: img = fin.read() try: piexif.insert(exif_bytes, img, filen...
[ "def", "write", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "_filename", "exif_bytes", "=", "piexif", ".", "dump", "(", "self", ".", "_ef", ")", "with", "open", "(", "self", ...
Save exif data to file.
[ "Save", "exif", "data", "to", "file", "." ]
python
train
29.866667
dw/mitogen
mitogen/parent.py
https://github.com/dw/mitogen/blob/a7fdb55e1300a7e0a5e404b09eb730cf9a525da7/mitogen/parent.py#L807-L819
def wstatus_to_str(status): """ Parse and format a :func:`os.waitpid` exit status. """ if os.WIFEXITED(status): return 'exited with return code %d' % (os.WEXITSTATUS(status),) if os.WIFSIGNALED(status): n = os.WTERMSIG(status) return 'exited due to signal %d (%s)' % (n, SIGNA...
[ "def", "wstatus_to_str", "(", "status", ")", ":", "if", "os", ".", "WIFEXITED", "(", "status", ")", ":", "return", "'exited with return code %d'", "%", "(", "os", ".", "WEXITSTATUS", "(", "status", ")", ",", ")", "if", "os", ".", "WIFSIGNALED", "(", "sta...
Parse and format a :func:`os.waitpid` exit status.
[ "Parse", "and", "format", "a", ":", "func", ":", "os", ".", "waitpid", "exit", "status", "." ]
python
train
39.307692
mwouts/jupytext
jupytext/cell_reader.py
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_reader.py#L572-L578
def metadata_and_language_from_option_line(self, line): """Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.""" if self.start_code_re.match(line): self.language, self.metadata = self.options_to_metadata(line[line.find('%...
[ "def", "metadata_and_language_from_option_line", "(", "self", ",", "line", ")", ":", "if", "self", ".", "start_code_re", ".", "match", "(", "line", ")", ":", "self", ".", "language", ",", "self", ".", "metadata", "=", "self", ".", "options_to_metadata", "(",...
Parse code options on the given line. When a start of a code cell is found, self.metadata is set to a dictionary.
[ "Parse", "code", "options", "on", "the", "given", "line", ".", "When", "a", "start", "of", "a", "code", "cell", "is", "found", "self", ".", "metadata", "is", "set", "to", "a", "dictionary", "." ]
python
train
58.857143
fakedrake/overlay_parse
overlay_parse/overlays.py
https://github.com/fakedrake/overlay_parse/blob/9ac362d6aef1ea41aff7375af088c6ebef93d0cd/overlay_parse/overlays.py#L176-L191
def overlay(self, matchers, force=False): """ Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way and will avoid re-running them but you can `force` me to. This is the recommended way of running overlays.c """ ...
[ "def", "overlay", "(", "self", ",", "matchers", ",", "force", "=", "False", ")", ":", "for", "m", "in", "matchers", ":", "if", "m", "in", "self", ".", "_ran_matchers", ":", "continue", "self", ".", "_ran_matchers", ".", "append", "(", "m", ")", "self...
Given a list of matchers create overlays based on them. Normally I will remember what overlays were run this way and will avoid re-running them but you can `force` me to. This is the recommended way of running overlays.c
[ "Given", "a", "list", "of", "matchers", "create", "overlays", "based", "on", "them", ".", "Normally", "I", "will", "remember", "what", "overlays", "were", "run", "this", "way", "and", "will", "avoid", "re", "-", "running", "them", "but", "you", "can", "f...
python
train
35.125
mozilla-iot/webthing-python
webthing/thing.py
https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/thing.py#L442-L457
def action_notify(self, action): """ Notify all subscribers of an action status change. action -- the action whose status changed """ message = json.dumps({ 'messageType': 'actionStatus', 'data': action.as_action_description(), }) for sub...
[ "def", "action_notify", "(", "self", ",", "action", ")", ":", "message", "=", "json", ".", "dumps", "(", "{", "'messageType'", ":", "'actionStatus'", ",", "'data'", ":", "action", ".", "as_action_description", "(", ")", ",", "}", ")", "for", "subscriber", ...
Notify all subscribers of an action status change. action -- the action whose status changed
[ "Notify", "all", "subscribers", "of", "an", "action", "status", "change", "." ]
python
test
30.375
spacetelescope/drizzlepac
drizzlepac/sky.py
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/sky.py#L43-L107
def sky(input=None,outExt=None,configObj=None, group=None, editpars=False, **inputDict): """ Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an i...
[ "def", "sky", "(", "input", "=", "None", ",", "outExt", "=", "None", ",", "configObj", "=", "None", ",", "group", "=", "None", ",", "editpars", "=", "False", ",", "*", "*", "inputDict", ")", ":", "if", "input", "is", "not", "None", ":", "inputDict"...
Perform sky subtraction on input list of images Parameters ---------- input : str or list of str a python list of image filenames, or just a single filename configObj : configObject an instance of configObject inputDict : dict, optional an optional list of parameters specifi...
[ "Perform", "sky", "subtraction", "on", "input", "list", "of", "images" ]
python
train
38.123077
Erotemic/utool
utool/util_project.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_project.py#L96-L140
def main(self): """ python -m utool SetupRepo.main --modname=sklearn --repo=scikit-learn --codedir=~/code -w python -m utool SetupRepo.main --repo=ubelt --codedir=~/code --modname=ubelt -w Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_pr...
[ "def", "main", "(", "self", ")", ":", "self", ".", "regencmd", "=", "self", ".", "regenfmt", ".", "format", "(", "cmd", "=", "'main'", ",", "*", "*", "self", ".", "__dict__", ")", "import", "utool", "as", "ut", "self", ".", "ensure_text", "(", "fna...
python -m utool SetupRepo.main --modname=sklearn --repo=scikit-learn --codedir=~/code -w python -m utool SetupRepo.main --repo=ubelt --codedir=~/code --modname=ubelt -w Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> from utool.util_project import * # NOQA >...
[ "python", "-", "m", "utool", "SetupRepo", ".", "main", "--", "modname", "=", "sklearn", "--", "repo", "=", "scikit", "-", "learn", "--", "codedir", "=", "~", "/", "code", "-", "w", "python", "-", "m", "utool", "SetupRepo", ".", "main", "--", "repo", ...
python
train
33.244444
PMEAL/porespy
porespy/tools/__funcs__.py
https://github.com/PMEAL/porespy/blob/1e13875b56787d8f5b7ffdabce8c4342c33ba9f8/porespy/tools/__funcs__.py#L204-L234
def bbox_to_slices(bbox): r""" Given a tuple containing bounding box coordinates, return a tuple of slice objects. A bounding box in the form of a straight list is returned by several functions in skimage, but these cannot be used to direct index into an image. This function returns a tuples o...
[ "def", "bbox_to_slices", "(", "bbox", ")", ":", "if", "len", "(", "bbox", ")", "==", "4", ":", "ret", "=", "(", "slice", "(", "bbox", "[", "0", "]", ",", "bbox", "[", "2", "]", ")", ",", "slice", "(", "bbox", "[", "1", "]", ",", "bbox", "["...
r""" Given a tuple containing bounding box coordinates, return a tuple of slice objects. A bounding box in the form of a straight list is returned by several functions in skimage, but these cannot be used to direct index into an image. This function returns a tuples of slices can be, such as: ...
[ "r", "Given", "a", "tuple", "containing", "bounding", "box", "coordinates", "return", "a", "tuple", "of", "slice", "objects", "." ]
python
train
32.548387
jaraco/irc
irc/server.py
https://github.com/jaraco/irc/blob/571c1f448d5d5bb92bbe2605c33148bf6e698413/irc/server.py#L314-L344
def handle_privmsg(self, params): """ Handle sending a private message to a user or channel. """ target, sep, msg = params.partition(' ') if not msg: raise IRCError.from_name( 'needmoreparams', 'PRIVMSG :Not enough parameters') ...
[ "def", "handle_privmsg", "(", "self", ",", "params", ")", ":", "target", ",", "sep", ",", "msg", "=", "params", ".", "partition", "(", "' '", ")", "if", "not", "msg", ":", "raise", "IRCError", ".", "from_name", "(", "'needmoreparams'", ",", "'PRIVMSG :No...
Handle sending a private message to a user or channel.
[ "Handle", "sending", "a", "private", "message", "to", "a", "user", "or", "channel", "." ]
python
train
38.645161
androguard/androguard
androguard/core/bytecodes/axml/__init__.py
https://github.com/androguard/androguard/blob/984c0d981be2950cf0451e484f7b0d4d53bc4911/androguard/core/bytecodes/axml/__init__.py#L695-L718
def nsmap(self): """ Returns the current namespace mapping as a dictionary there are several problems with the map and we try to guess a few things here: 1) a URI can be mapped by many prefixes, so it is to decide which one to take 2) a prefix might map to an empty stri...
[ "def", "nsmap", "(", "self", ")", ":", "NSMAP", "=", "dict", "(", ")", "# solve 3) by using a set", "for", "k", ",", "v", "in", "set", "(", "self", ".", "namespaces", ")", ":", "s_prefix", "=", "self", ".", "sb", "[", "k", "]", "s_uri", "=", "self"...
Returns the current namespace mapping as a dictionary there are several problems with the map and we try to guess a few things here: 1) a URI can be mapped by many prefixes, so it is to decide which one to take 2) a prefix might map to an empty string (some packers) 3) uri+pref...
[ "Returns", "the", "current", "namespace", "mapping", "as", "a", "dictionary" ]
python
train
33.416667
theSage21/lanchat
lanchat/chat.py
https://github.com/theSage21/lanchat/blob/66f5dcead67fef815347b956b1d3e149a7e13b29/lanchat/chat.py#L155-L159
def __output_thread(self): "Output thread" while self.alive: instructions = self.__get_instructions() self.__process_instructions(instructions)
[ "def", "__output_thread", "(", "self", ")", ":", "while", "self", ".", "alive", ":", "instructions", "=", "self", ".", "__get_instructions", "(", ")", "self", ".", "__process_instructions", "(", "instructions", ")" ]
Output thread
[ "Output", "thread" ]
python
train
35.8
wonambi-python/wonambi
wonambi/ioeeg/egimff.py
https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/egimff.py#L35-L98
def return_hdr(self): """Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str ...
[ "def", "return_hdr", "(", "self", ")", ":", "orig", "=", "{", "}", "for", "xml_file", "in", "self", ".", "filename", ".", "glob", "(", "'*.xml'", ")", ":", "if", "xml_file", ".", "stem", "[", "0", "]", "!=", "'.'", ":", "orig", "[", "xml_file", "...
Return the header for further use. Returns ------- subj_id : str subject identification code start_time : datetime start time of the dataset s_freq : float sampling frequency chan_name : list of str list of all the channels...
[ "Return", "the", "header", "for", "further", "use", "." ]
python
train
35.09375
dcos/shakedown
shakedown/dcos/task.py
https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/task.py#L123-L125
def wait_for_task_property(service, task, prop, timeout_sec=120): """Waits for a task to have the specified property""" return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec)
[ "def", "wait_for_task_property", "(", "service", ",", "task", ",", "prop", ",", "timeout_sec", "=", "120", ")", ":", "return", "time_wait", "(", "lambda", ":", "task_property_present_predicate", "(", "service", ",", "task", ",", "prop", ")", ",", "timeout_seco...
Waits for a task to have the specified property
[ "Waits", "for", "a", "task", "to", "have", "the", "specified", "property" ]
python
train
77.666667
openid/python-openid
openid/message.py
https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/message.py#L464-L472
def updateArgs(self, namespace, updates): """Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode} """ namespace = self._fixNS(namespace) for k, v in updates.iteritems(): self.setArg(namespace, k, v)
[ "def", "updateArgs", "(", "self", ",", "namespace", ",", "updates", ")", ":", "namespace", "=", "self", ".", "_fixNS", "(", "namespace", ")", "for", "k", ",", "v", "in", "updates", ".", "iteritems", "(", ")", ":", "self", ".", "setArg", "(", "namespa...
Set multiple key/value pairs in one call @param updates: The values to set @type updates: {unicode:unicode}
[ "Set", "multiple", "key", "/", "value", "pairs", "in", "one", "call" ]
python
train
34
numenta/nupic
src/nupic/encoders/pass_through.py
https://github.com/numenta/nupic/blob/5922fafffdccc8812e72b3324965ad2f7d4bbdad/src/nupic/encoders/pass_through.py#L100-L108
def decode(self, encoded, parentFieldName=""): """See the function description in base.py""" if parentFieldName != "": fieldName = "%s.%s" % (parentFieldName, self.name) else: fieldName = self.name return ({fieldName: ([[0, 0]], "input")}, [fieldName])
[ "def", "decode", "(", "self", ",", "encoded", ",", "parentFieldName", "=", "\"\"", ")", ":", "if", "parentFieldName", "!=", "\"\"", ":", "fieldName", "=", "\"%s.%s\"", "%", "(", "parentFieldName", ",", "self", ".", "name", ")", "else", ":", "fieldName", ...
See the function description in base.py
[ "See", "the", "function", "description", "in", "base", ".", "py" ]
python
valid
30.444444
fermiPy/fermipy
fermipy/srcmap_utils.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/srcmap_utils.py#L380-L403
def delete_source_map(srcmap_file, names, logger=None): """Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted. """ with fits.open(sr...
[ "def", "delete_source_map", "(", "srcmap_file", ",", "names", ",", "logger", "=", "None", ")", ":", "with", "fits", ".", "open", "(", "srcmap_file", ")", "as", "hdulist", ":", "hdunames", "=", "[", "hdu", ".", "name", ".", "upper", "(", ")", "for", "...
Delete a map from a binned analysis source map file if it exists. Parameters ---------- srcmap_file : str Path to the source map file. names : list List of HDU keys of source maps to be deleted.
[ "Delete", "a", "map", "from", "a", "binned", "analysis", "source", "map", "file", "if", "it", "exists", "." ]
python
train
26.458333
materialsproject/pymatgen
pymatgen/analysis/diffusion_analyzer.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/diffusion_analyzer.py#L465-L516
def get_msd_plot(self, plt=None, mode="specie"): """ Get the plot of the smoothed msd vs time graph. Useful for checking convergence. This can be written to an image file. Args: plt: A plot object. Defaults to None, which means one will be generated. ...
[ "def", "get_msd_plot", "(", "self", ",", "plt", "=", "None", ",", "mode", "=", "\"specie\"", ")", ":", "from", "pymatgen", ".", "util", ".", "plotting", "import", "pretty_plot", "plt", "=", "pretty_plot", "(", "12", ",", "8", ",", "plt", "=", "plt", ...
Get the plot of the smoothed msd vs time graph. Useful for checking convergence. This can be written to an image file. Args: plt: A plot object. Defaults to None, which means one will be generated. mode (str): Determines type of msd plot. By "species", "sites", ...
[ "Get", "the", "plot", "of", "the", "smoothed", "msd", "vs", "time", "graph", ".", "Useful", "for", "checking", "convergence", ".", "This", "can", "be", "written", "to", "an", "image", "file", "." ]
python
train
41.019231
chaoss/grimoirelab-cereslib
cereslib/events/events.py
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/events/events.py#L791-L855
def eventize(self, granularity): """ This splits the JSON information found at self.events into the several events. For this there are three different levels of time consuming actions: 1-soft, 2-medium and 3-hard. Level 1 provides events about emails Level 2 not implemented ...
[ "def", "eventize", "(", "self", ",", "granularity", ")", ":", "email", "=", "{", "}", "# First level granularity", "email", "[", "Email", ".", "EMAIL_ID", "]", "=", "[", "]", "email", "[", "Email", ".", "EMAIL_EVENT", "]", "=", "[", "]", "email", "[", ...
This splits the JSON information found at self.events into the several events. For this there are three different levels of time consuming actions: 1-soft, 2-medium and 3-hard. Level 1 provides events about emails Level 2 not implemented Level 3 not implemented :param g...
[ "This", "splits", "the", "JSON", "information", "found", "at", "self", ".", "events", "into", "the", "several", "events", ".", "For", "this", "there", "are", "three", "different", "levels", "of", "time", "consuming", "actions", ":", "1", "-", "soft", "2", ...
python
train
38.446154
ucfopen/canvasapi
canvasapi/canvas.py
https://github.com/ucfopen/canvasapi/blob/319064b5fc97ba54250af683eb98723ef3f76cf8/canvasapi/canvas.py#L1058-L1078
def get_outcome(self, outcome): """ Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. :type outc...
[ "def", "get_outcome", "(", "self", ",", "outcome", ")", ":", "from", "canvasapi", ".", "outcome", "import", "Outcome", "outcome_id", "=", "obj_or_id", "(", "outcome", ",", "\"outcome\"", ",", "(", "Outcome", ",", ")", ")", "response", "=", "self", ".", "...
Returns the details of the outcome with the given id. :calls: `GET /api/v1/outcomes/:id \ <https://canvas.instructure.com/doc/api/outcomes.html#method.outcomes_api.show>`_ :param outcome: The outcome object or ID to return. :type outcome: :class:`canvasapi.outcome.Outcome` or int ...
[ "Returns", "the", "details", "of", "the", "outcome", "with", "the", "given", "id", "." ]
python
train
34.952381
aparsons/threadfix_api
threadfix_api/threadfix.py
https://github.com/aparsons/threadfix_api/blob/76fd1bd26e9ac863636112cd30d733543807ff7d/threadfix_api/threadfix.py#L409-L414
def data_json(self, pretty=False): """Returns the data as a valid JSON string.""" if pretty: return json.dumps(self.data, sort_keys=True, indent=4, separators=(',', ': ')) else: return json.dumps(self.data)
[ "def", "data_json", "(", "self", ",", "pretty", "=", "False", ")", ":", "if", "pretty", ":", "return", "json", ".", "dumps", "(", "self", ".", "data", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", ...
Returns the data as a valid JSON string.
[ "Returns", "the", "data", "as", "a", "valid", "JSON", "string", "." ]
python
train
41.5
PythonCharmers/python-future
src/future/backports/email/charset.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/charset.py#L284-L301
def header_encode(self, string): """Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible to encode th...
[ "def", "header_encode", "(", "self", ",", "string", ")", ":", "codec", "=", "self", ".", "output_codec", "or", "'us-ascii'", "header_bytes", "=", "_encode", "(", "string", ",", "codec", ")", "# 7bit/8bit encodings return the string unchanged (modulo conversions)", "en...
Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset's `header_encoding`. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's...
[ "Header", "-", "encode", "a", "string", "by", "converting", "it", "first", "to", "bytes", "." ]
python
train
44.444444
mitsei/dlkit
dlkit/json_/learning/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/learning/managers.py#L817-L832
def get_objective_objective_bank_session(self): """Gets the session for retrieving objective to objective bank mappings. return: (osid.learning.ObjectiveObjectiveBankSession) - an ``ObjectiveObjectiveBankSession`` raise: OperationFailed - unable to complete request rais...
[ "def", "get_objective_objective_bank_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_objective_objective_bank", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "ObjectiveO...
Gets the session for retrieving objective to objective bank mappings. return: (osid.learning.ObjectiveObjectiveBankSession) - an ``ObjectiveObjectiveBankSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_objective_objective_bank()``...
[ "Gets", "the", "session", "for", "retrieving", "objective", "to", "objective", "bank", "mappings", "." ]
python
train
46.6875
askedrelic/libgreader
libgreader/googlereader.py
https://github.com/askedrelic/libgreader/blob/7b668ee291c2464ea172ef44393100c369efa970/libgreader/googlereader.py#L74-L134
def buildSubscriptionList(self): """ Hits Google Reader for a users's alphabetically ordered list of feeds. Returns true if succesful. """ self._clearLists() unreadById = {} if not self.userId: self.getUserInfo() unreadJson = self.httpGet(Re...
[ "def", "buildSubscriptionList", "(", "self", ")", ":", "self", ".", "_clearLists", "(", ")", "unreadById", "=", "{", "}", "if", "not", "self", ".", "userId", ":", "self", ".", "getUserInfo", "(", ")", "unreadJson", "=", "self", ".", "httpGet", "(", "Re...
Hits Google Reader for a users's alphabetically ordered list of feeds. Returns true if succesful.
[ "Hits", "Google", "Reader", "for", "a", "users", "s", "alphabetically", "ordered", "list", "of", "feeds", "." ]
python
train
37.131148
gbowerman/azurerm
examples/list_locations.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/examples/list_locations.py#L7-L30
def main(): '''Main routine.''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit("Error: Expecting azurermconfig.json in current folder") tenant_id = config_data['tenant...
[ "def", "main", "(", ")", ":", "# Load Azure app defaults", "try", ":", "with", "open", "(", "'azurermconfig.json'", ")", "as", "config_file", ":", "config_data", "=", "json", ".", "load", "(", "config_file", ")", "except", "FileNotFoundError", ":", "sys", ".",...
Main routine.
[ "Main", "routine", "." ]
python
train
34.5
ContinuumIO/flask-ldap-login
flask_ldap_login/__init__.py
https://github.com/ContinuumIO/flask-ldap-login/blob/09a08be45f861823cb08f95883ee1e092a618c37/flask_ldap_login/__init__.py#L52-L58
def scalar(value): """ Take return a value[0] if `value` is a list of length 1 """ if isinstance(value, (list, tuple)) and len(value) == 1: return value[0] return value
[ "def", "scalar", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "value", ")", "==", "1", ":", "return", "value", "[", "0", "]", "return", "value" ]
Take return a value[0] if `value` is a list of length 1
[ "Take", "return", "a", "value", "[", "0", "]", "if", "value", "is", "a", "list", "of", "length", "1" ]
python
train
27.142857
yyuu/botornado
boto/sdb/item.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sdb/item.py#L114-L129
def save(self, replace=True): """ Saves this item to SDB. :param bool replace: If ``True``, delete any attributes on the remote SDB item that have a ``None`` value on this object. """ self.domain.put_attributes(self.name, self, replace) # Delete any a...
[ "def", "save", "(", "self", ",", "replace", "=", "True", ")", ":", "self", ".", "domain", ".", "put_attributes", "(", "self", ".", "name", ",", "self", ",", "replace", ")", "# Delete any attributes set to \"None\"", "if", "replace", ":", "del_attrs", "=", ...
Saves this item to SDB. :param bool replace: If ``True``, delete any attributes on the remote SDB item that have a ``None`` value on this object.
[ "Saves", "this", "item", "to", "SDB", ".", ":", "param", "bool", "replace", ":", "If", "True", "delete", "any", "attributes", "on", "the", "remote", "SDB", "item", "that", "have", "a", "None", "value", "on", "this", "object", "." ]
python
train
36.875
googlefonts/ufo2ft
Lib/ufo2ft/featureWriters/baseFeatureWriter.py
https://github.com/googlefonts/ufo2ft/blob/915b986558e87bee288765d9218cc1cd4ebf7f4c/Lib/ufo2ft/featureWriters/baseFeatureWriter.py#L97-L107
def shouldContinue(self): """ Decide whether to start generating features or return early. Returns a boolean: True to proceed, False to skip. Sublcasses may override this to skip generation based on the presence or lack of other required pieces of font data. """ if not s...
[ "def", "shouldContinue", "(", "self", ")", ":", "if", "not", "self", ".", "context", ".", "todo", ":", "self", ".", "log", ".", "debug", "(", "\"No features to be generated; skipped\"", ")", "return", "False", "return", "True" ]
Decide whether to start generating features or return early. Returns a boolean: True to proceed, False to skip. Sublcasses may override this to skip generation based on the presence or lack of other required pieces of font data.
[ "Decide", "whether", "to", "start", "generating", "features", "or", "return", "early", ".", "Returns", "a", "boolean", ":", "True", "to", "proceed", "False", "to", "skip", "." ]
python
train
39.909091
bbayles/vod_metadata
vod_metadata/md5_calc.py
https://github.com/bbayles/vod_metadata/blob/d91c5766864e0c4f274b0e887c57a026d25a5ac5/vod_metadata/md5_calc.py#L7-L18
def md5_checksum(file_path, chunk_bytes=4194304): """Return the MD5 checksum (hex digest) of the file""" with open(file_path, "rb") as infile: checksum = hashlib.md5() while 1: data = infile.read(chunk_bytes) if not data: break checksum.update...
[ "def", "md5_checksum", "(", "file_path", ",", "chunk_bytes", "=", "4194304", ")", ":", "with", "open", "(", "file_path", ",", "\"rb\"", ")", "as", "infile", ":", "checksum", "=", "hashlib", ".", "md5", "(", ")", "while", "1", ":", "data", "=", "infile"...
Return the MD5 checksum (hex digest) of the file
[ "Return", "the", "MD5", "checksum", "(", "hex", "digest", ")", "of", "the", "file" ]
python
train
29
StanfordVL/robosuite
robosuite/devices/keyboard.py
https://github.com/StanfordVL/robosuite/blob/65cd16810e2ed647e3ec88746af3412065b7f278/robosuite/devices/keyboard.py#L76-L113
def on_press(self, window, key, scancode, action, mods): """ Key handler for key presses. """ # controls for moving position if key == glfw.KEY_W: self.pos[0] -= self._pos_step # dec x elif key == glfw.KEY_S: self.pos[0] += self._pos_step # inc ...
[ "def", "on_press", "(", "self", ",", "window", ",", "key", ",", "scancode", ",", "action", ",", "mods", ")", ":", "# controls for moving position", "if", "key", "==", "glfw", ".", "KEY_W", ":", "self", ".", "pos", "[", "0", "]", "-=", "self", ".", "_...
Key handler for key presses.
[ "Key", "handler", "for", "key", "presses", "." ]
python
train
44.710526
log2timeline/plaso
plaso/parsers/systemd_journal.py
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/parsers/systemd_journal.py#L281-L346
def ParseFileObject(self, parser_mediator, file_object): """Parses a Systemd journal file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the header cannot be parsed. """ file_he...
[ "def", "ParseFileObject", "(", "self", ",", "parser_mediator", ",", "file_object", ")", ":", "file_header_map", "=", "self", ".", "_GetDataTypeMap", "(", "'systemd_journal_file_header'", ")", "try", ":", "file_header", ",", "_", "=", "self", ".", "_ReadStructureFr...
Parses a Systemd journal file-like object. Args: parser_mediator (ParserMediator): parser mediator. file_object (dfvfs.FileIO): a file-like object. Raises: UnableToParseFile: when the header cannot be parsed.
[ "Parses", "a", "Systemd", "journal", "file", "-", "like", "object", "." ]
python
train
37.909091
azraq27/gini
gini/matching.py
https://github.com/azraq27/gini/blob/3c2b5265d096d606b303bfe25ac9adb74b8cee14/gini/matching.py#L63-L68
def best_item_from_list(item,options,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns just the best item, or ``None``''' match = best_match_from_list(item,options,fuzzy,fname_match,fuzzy_fragment,guess) if match: return match[0] return None
[ "def", "best_item_from_list", "(", "item", ",", "options", ",", "fuzzy", "=", "90", ",", "fname_match", "=", "True", ",", "fuzzy_fragment", "=", "None", ",", "guess", "=", "False", ")", ":", "match", "=", "best_match_from_list", "(", "item", ",", "options"...
Returns just the best item, or ``None``
[ "Returns", "just", "the", "best", "item", "or", "None" ]
python
train
46.833333
juju/theblues
theblues/charmstore.py
https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/charmstore.py#L475-L479
def debug(self): '''Retrieve the debug information from the charmstore.''' url = '{}/debug/status'.format(self.url) data = self._get(url) return data.json()
[ "def", "debug", "(", "self", ")", ":", "url", "=", "'{}/debug/status'", ".", "format", "(", "self", ".", "url", ")", "data", "=", "self", ".", "_get", "(", "url", ")", "return", "data", ".", "json", "(", ")" ]
Retrieve the debug information from the charmstore.
[ "Retrieve", "the", "debug", "information", "from", "the", "charmstore", "." ]
python
train
36.8
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L38-L48
def query_int_attribute(self, target, display_mask, attr): """Return the value of an integer attribute""" reply = NVCtrlQueryAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), tar...
[ "def", "query_int_attribute", "(", "self", ",", "target", ",", "display_mask", ",", "attr", ")", ":", "reply", "=", "NVCtrlQueryAttributeReplyRequest", "(", "display", "=", "self", ".", "display", ",", "opcode", "=", "self", ".", "display", ".", "get_extension...
Return the value of an integer attribute
[ "Return", "the", "value", "of", "an", "integer", "attribute" ]
python
train
57
ryanjdillon/pylleo
pylleo/utils.py
https://github.com/ryanjdillon/pylleo/blob/b9b999fef19eaeccce4f207ab1b6198287c1bfec/pylleo/utils.py#L15-L24
def predict_encoding(file_path, n_lines=20): '''Get file encoding of a text file''' import chardet # Open the file as binary data with open(file_path, 'rb') as f: # Join binary lines for specified number of lines rawdata = b''.join([f.readline() for _ in range(n_lines)]) return cha...
[ "def", "predict_encoding", "(", "file_path", ",", "n_lines", "=", "20", ")", ":", "import", "chardet", "# Open the file as binary data", "with", "open", "(", "file_path", ",", "'rb'", ")", "as", "f", ":", "# Join binary lines for specified number of lines", "rawdata",...
Get file encoding of a text file
[ "Get", "file", "encoding", "of", "a", "text", "file" ]
python
train
34.3
LogicalDash/LiSE
ELiDE/ELiDE/board/board.py
https://github.com/LogicalDash/LiSE/blob/fe6fd4f0a7c1780e065f4c9babb9bc443af6bb84/ELiDE/ELiDE/board/board.py#L44-L72
def normalize_layout(l): """Make sure all the spots in a layout are where you can click. Returns a copy of the layout with all spot coordinates are normalized to within (0.0, 0.98). """ xs = [] ys = [] ks = [] for (k, (x, y)) in l.items(): xs.append(x) ys.append(y) ...
[ "def", "normalize_layout", "(", "l", ")", ":", "xs", "=", "[", "]", "ys", "=", "[", "]", "ks", "=", "[", "]", "for", "(", "k", ",", "(", "x", ",", "y", ")", ")", "in", "l", ".", "items", "(", ")", ":", "xs", ".", "append", "(", "x", ")"...
Make sure all the spots in a layout are where you can click. Returns a copy of the layout with all spot coordinates are normalized to within (0.0, 0.98).
[ "Make", "sure", "all", "the", "spots", "in", "a", "layout", "are", "where", "you", "can", "click", "." ]
python
train
28.689655
mitodl/PyLmod
pylmod/gradebook.py
https://github.com/mitodl/PyLmod/blob/b798b86c33d1eb615e7cd4f3457b5c15da1d86e0/pylmod/gradebook.py#L335-L425
def create_assignment( # pylint: disable=too-many-arguments self, name, short_name, weight, max_points, due_date_str, gradebook_id='', **kwargs ): """Create a new assignment. Create a new assignment. By...
[ "def", "create_assignment", "(", "# pylint: disable=too-many-arguments", "self", ",", "name", ",", "short_name", ",", "weight", ",", "max_points", ",", "due_date_str", ",", "gradebook_id", "=", "''", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'name'...
Create a new assignment. Create a new assignment. By default, assignments are created under the `Uncategorized` category. Args: name (str): descriptive assignment name, i.e. ``new NUMERIC SIMPLE ASSIGNMENT`` short_name (str): short name of assignment, on...
[ "Create", "a", "new", "assignment", "." ]
python
train
36.692308
justquick/django-activity-stream
actstream/views.py
https://github.com/justquick/django-activity-stream/blob/a1e06f2e6429cc5fc321e7801440dd7c5b9d5a35/actstream/views.py#L15-L23
def respond(request, code): """ Responds to the request with the given response code. If ``next`` is in the form, it will redirect instead. """ redirect = request.GET.get('next', request.POST.get('next')) if redirect: return HttpResponseRedirect(redirect) return type('Response%d' % c...
[ "def", "respond", "(", "request", ",", "code", ")", ":", "redirect", "=", "request", ".", "GET", ".", "get", "(", "'next'", ",", "request", ".", "POST", ".", "get", "(", "'next'", ")", ")", "if", "redirect", ":", "return", "HttpResponseRedirect", "(", ...
Responds to the request with the given response code. If ``next`` is in the form, it will redirect instead.
[ "Responds", "to", "the", "request", "with", "the", "given", "response", "code", ".", "If", "next", "is", "in", "the", "form", "it", "will", "redirect", "instead", "." ]
python
train
39.888889
saltstack/salt
salt/states/boto_elbv2.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elbv2.py#L153-L198
def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target...
[ "def", "delete_target_group", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ...
Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.delete_targets_group: - name: myALB - protocol...
[ "Delete", "target", "group", "." ]
python
train
31.608696
gwastro/pycbc-glue
pycbc_glue/ligolw/utils/time_slide.py
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/time_slide.py#L91-L144
def time_slides_vacuum(time_slides, verbose = False): """ Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return ...
[ "def", "time_slides_vacuum", "(", "time_slides", ",", "verbose", "=", "False", ")", ":", "# convert offsets to deltas", "time_slides", "=", "dict", "(", "(", "time_slide_id", ",", "offsetvect", ".", "deltas", ")", "for", "time_slide_id", ",", "offsetvect", "in", ...
Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return a mapping indicating time slide equivalences. This can be ...
[ "Given", "a", "dictionary", "mapping", "time", "slide", "IDs", "to", "instrument", "--", ">", "offset", "mappings", "for", "example", "as", "returned", "by", "the", "as_dict", "()", "method", "of", "the", "TimeSlideTable", "class", "in", "pycbc_glue", ".", "...
python
train
36.796296
Unidata/MetPy
metpy/calc/kinematics.py
https://github.com/Unidata/MetPy/blob/16f68a94919b9a82dcf9cada2169cf039129e67b/metpy/calc/kinematics.py#L529-L585
def storm_relative_helicity(u, v, heights, depth, bottom=0 * units.m, storm_u=0 * units('m/s'), storm_v=0 * units('m/s')): # Partially adapted from similar SharpPy code r"""Calculate storm relative helicity. Calculates storm relatively helicity following [Markowski2010] 230-231....
[ "def", "storm_relative_helicity", "(", "u", ",", "v", ",", "heights", ",", "depth", ",", "bottom", "=", "0", "*", "units", ".", "m", ",", "storm_u", "=", "0", "*", "units", "(", "'m/s'", ")", ",", "storm_v", "=", "0", "*", "units", "(", "'m/s'", ...
r"""Calculate storm relative helicity. Calculates storm relatively helicity following [Markowski2010] 230-231. .. math:: \int\limits_0^d (\bar v - c) \cdot \bar\omega_{h} \,dz This is applied to the data from a hodograph with the following summation: .. math:: \sum_{n = 1}^{N-1} [(u_{n+1} - c_{x})(v...
[ "r", "Calculate", "storm", "relative", "helicity", "." ]
python
train
37.385965