repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
xflows/rdm
rdm/db/library.py
https://github.com/xflows/rdm/blob/d984e2a0297e5fa8d799953bbd0dba79b05d403d/rdm/db/library.py#L39-L66
def _update_context(context, postdata): ''' Updates the default selections with user's selections. ''' listCheck = lambda el: el[0] if type(el) == list else el # For handling lists of size 1 widget_id = listCheck(postdata.get('widget_id')) context.target_table = listCheck(postdata.get('target_t...
[ "def", "_update_context", "(", "context", ",", "postdata", ")", ":", "listCheck", "=", "lambda", "el", ":", "el", "[", "0", "]", "if", "type", "(", "el", ")", "==", "list", "else", "el", "# For handling lists of size 1", "widget_id", "=", "listCheck", "(",...
Updates the default selections with user's selections.
[ "Updates", "the", "default", "selections", "with", "user", "s", "selections", "." ]
python
train
binux/pyspider
pyspider/run.py
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/run.py#L277-L294
def processor(ctx, processor_cls, process_time_limit, enable_stdout_capture=True, get_object=False): """ Run Processor. """ g = ctx.obj Processor = load_cls(None, None, processor_cls) processor = Processor(projectdb=g.projectdb, inqueue=g.fetcher2processor, status_queu...
[ "def", "processor", "(", "ctx", ",", "processor_cls", ",", "process_time_limit", ",", "enable_stdout_capture", "=", "True", ",", "get_object", "=", "False", ")", ":", "g", "=", "ctx", ".", "obj", "Processor", "=", "load_cls", "(", "None", ",", "None", ",",...
Run Processor.
[ "Run", "Processor", "." ]
python
train
pandas-dev/pandas
pandas/core/dtypes/concat.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/dtypes/concat.py#L168-L206
def _concat_categorical(to_concat, axis=0): """Concatenate an object/categorical array of arrays, each of which is a single dtype Parameters ---------- to_concat : array of arrays axis : int Axis to provide concatenation in the current implementation this is always 0, e.g. we on...
[ "def", "_concat_categorical", "(", "to_concat", ",", "axis", "=", "0", ")", ":", "# we could have object blocks and categoricals here", "# if we only have a single categoricals then combine everything", "# else its a non-compat categorical", "categoricals", "=", "[", "x", "for", ...
Concatenate an object/categorical array of arrays, each of which is a single dtype Parameters ---------- to_concat : array of arrays axis : int Axis to provide concatenation in the current implementation this is always 0, e.g. we only have 1D categoricals Returns ------- ...
[ "Concatenate", "an", "object", "/", "categorical", "array", "of", "arrays", "each", "of", "which", "is", "a", "single", "dtype" ]
python
train
singularityhub/sregistry-cli
sregistry/main/globus/utils.py
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/globus/utils.py#L126-L144
def get_endpoint(self, endpoint_id): '''use a transfer client to get a specific endpoint based on an endpoint id. Parameters ========== endpoint_id: the endpoint_id to retrieve ''' endpoint = None if not hasattr(self, 'transfer_client'): self._init_transfer_cl...
[ "def", "get_endpoint", "(", "self", ",", "endpoint_id", ")", ":", "endpoint", "=", "None", "if", "not", "hasattr", "(", "self", ",", "'transfer_client'", ")", ":", "self", ".", "_init_transfer_client", "(", ")", "try", ":", "endpoint", "=", "self", ".", ...
use a transfer client to get a specific endpoint based on an endpoint id. Parameters ========== endpoint_id: the endpoint_id to retrieve
[ "use", "a", "transfer", "client", "to", "get", "a", "specific", "endpoint", "based", "on", "an", "endpoint", "id", ".", "Parameters", "==========", "endpoint_id", ":", "the", "endpoint_id", "to", "retrieve" ]
python
test
ultrabug/py3status
py3status/command.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/command.py#L205-L217
def run_command(self, data): """ check the given command and send to the correct dispatcher """ command = data.get("command") if self.debug: self.py3_wrapper.log("Running remote command %s" % command) if command == "refresh": self.refresh(data) ...
[ "def", "run_command", "(", "self", ",", "data", ")", ":", "command", "=", "data", ".", "get", "(", "\"command\"", ")", "if", "self", ".", "debug", ":", "self", ".", "py3_wrapper", ".", "log", "(", "\"Running remote command %s\"", "%", "command", ")", "if...
check the given command and send to the correct dispatcher
[ "check", "the", "given", "command", "and", "send", "to", "the", "correct", "dispatcher" ]
python
train
pytroll/satpy
satpy/scene.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/scene.py#L427-L449
def copy(self, datasets=None): """Create a copy of the Scene including dependency information. Args: datasets (list, tuple): `DatasetID` objects for the datasets to include in the new Scene object. """ new_scn = self.__class__() n...
[ "def", "copy", "(", "self", ",", "datasets", "=", "None", ")", ":", "new_scn", "=", "self", ".", "__class__", "(", ")", "new_scn", ".", "attrs", "=", "self", ".", "attrs", ".", "copy", "(", ")", "new_scn", ".", "dep_tree", "=", "self", ".", "dep_tr...
Create a copy of the Scene including dependency information. Args: datasets (list, tuple): `DatasetID` objects for the datasets to include in the new Scene object.
[ "Create", "a", "copy", "of", "the", "Scene", "including", "dependency", "information", "." ]
python
train
StackStorm/pybind
pybind/slxos/v17s_1_02/routing_system/interface/ve/ip/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/routing_system/interface/ve/ip/__init__.py#L413-L434
def _set_interface_vlan_ospf_conf(self, v, load=False): """ Setter method for interface_vlan_ospf_conf, mapped from YANG variable /routing_system/interface/ve/ip/interface_vlan_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_vlan_ospf_conf...
[ "def", "_set_interface_vlan_ospf_conf", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v",...
Setter method for interface_vlan_ospf_conf, mapped from YANG variable /routing_system/interface/ve/ip/interface_vlan_ospf_conf (container) If this variable is read-only (config: false) in the source YANG file, then _set_interface_vlan_ospf_conf is considered as a private method. Backends looking to populate...
[ "Setter", "method", "for", "interface_vlan_ospf_conf", "mapped", "from", "YANG", "variable", "/", "routing_system", "/", "interface", "/", "ve", "/", "ip", "/", "interface_vlan_ospf_conf", "(", "container", ")", "If", "this", "variable", "is", "read", "-", "only...
python
train
jason-weirather/pythologist
pythologist/__init__.py
https://github.com/jason-weirather/pythologist/blob/6eb4082be9dffa9570e4ceaa06d97845eac4c006/pythologist/__init__.py#L196-L210
def serialize(self): """ Convert the data to one that can be saved in h5 structures Returns: pandas.DataFrame: like a cell data frame but serialized. columns """ df = self.copy() df['scored_calls'] = df['scored_calls'].apply(lambda x: json.dumps(x)) d...
[ "def", "serialize", "(", "self", ")", ":", "df", "=", "self", ".", "copy", "(", ")", "df", "[", "'scored_calls'", "]", "=", "df", "[", "'scored_calls'", "]", ".", "apply", "(", "lambda", "x", ":", "json", ".", "dumps", "(", "x", ")", ")", "df", ...
Convert the data to one that can be saved in h5 structures Returns: pandas.DataFrame: like a cell data frame but serialized. columns
[ "Convert", "the", "data", "to", "one", "that", "can", "be", "saved", "in", "h5", "structures" ]
python
train
appliedsec/pygeoip
pygeoip/__init__.py
https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L553-L562
def record_by_name(self, hostname): """ Returns dictionary with city data containing `country_code`, `country_name`, `region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`, `metro_code`, `area_code`, `region_code` and `time_zone`. :arg hostname: Hostname (e.g. exam...
[ "def", "record_by_name", "(", "self", ",", "hostname", ")", ":", "addr", "=", "self", ".", "_gethostbyname", "(", "hostname", ")", "return", "self", ".", "record_by_addr", "(", "addr", ")" ]
Returns dictionary with city data containing `country_code`, `country_name`, `region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`, `metro_code`, `area_code`, `region_code` and `time_zone`. :arg hostname: Hostname (e.g. example.com)
[ "Returns", "dictionary", "with", "city", "data", "containing", "country_code", "country_name", "region", "city", "postal_code", "latitude", "longitude", "dma_code", "metro_code", "area_code", "region_code", "and", "time_zone", "." ]
python
valid
ranaroussi/qtpylib
qtpylib/blotter.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/blotter.py#L887-L950
def _fix_history_sequence(self, df, table): """ fix out-of-sequence ticks/bars """ # remove "Unnamed: x" columns cols = df.columns[df.columns.str.startswith('Unnamed:')].tolist() df.drop(cols, axis=1, inplace=True) # remove future dates df['datetime'] = pd.to_datetime(d...
[ "def", "_fix_history_sequence", "(", "self", ",", "df", ",", "table", ")", ":", "# remove \"Unnamed: x\" columns", "cols", "=", "df", ".", "columns", "[", "df", ".", "columns", ".", "str", ".", "startswith", "(", "'Unnamed:'", ")", "]", ".", "tolist", "(",...
fix out-of-sequence ticks/bars
[ "fix", "out", "-", "of", "-", "sequence", "ticks", "/", "bars" ]
python
train
robgolding/django-radius
radiusauth/backends/radius.py
https://github.com/robgolding/django-radius/blob/5b90f4ae4cbd680988197386d882491317e6b20c/radiusauth/backends/radius.py#L140-L147
def _radius_auth(self, server, username, password): """ Authenticate the given username/password against the RADIUS server described by `server`. """ client = self._get_client(server) packet = self._get_auth_packet(username, password, client) return self._perform_...
[ "def", "_radius_auth", "(", "self", ",", "server", ",", "username", ",", "password", ")", ":", "client", "=", "self", ".", "_get_client", "(", "server", ")", "packet", "=", "self", ".", "_get_auth_packet", "(", "username", ",", "password", ",", "client", ...
Authenticate the given username/password against the RADIUS server described by `server`.
[ "Authenticate", "the", "given", "username", "/", "password", "against", "the", "RADIUS", "server", "described", "by", "server", "." ]
python
train
scikit-tda/kepler-mapper
kmapper/visuals.py
https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/visuals.py#L81-L114
def _map_val2color(val, vmin, vmax, colorscale=None): """ Maps a value val in [vmin, vmax] to the corresponding color in the colorscale returns the rgb color code of that color """ colorscale = colorscale or colorscale_default if vmin >= vmax: raise ValueError("vmin should be < ...
[ "def", "_map_val2color", "(", "val", ",", "vmin", ",", "vmax", ",", "colorscale", "=", "None", ")", ":", "colorscale", "=", "colorscale", "or", "colorscale_default", "if", "vmin", ">=", "vmax", ":", "raise", "ValueError", "(", "\"vmin should be < vmax\"", ")",...
Maps a value val in [vmin, vmax] to the corresponding color in the colorscale returns the rgb color code of that color
[ "Maps", "a", "value", "val", "in", "[", "vmin", "vmax", "]", "to", "the", "corresponding", "color", "in", "the", "colorscale", "returns", "the", "rgb", "color", "code", "of", "that", "color" ]
python
train
yfpeng/bioc
bioc/biocjson/decoder.py
https://github.com/yfpeng/bioc/blob/47ddaa010960d9ba673aefe068e7bbaf39f0fff4/bioc/biocjson/decoder.py#L26-L34
def parse_annotation(obj: dict) -> BioCAnnotation: """Deserialize a dict obj to a BioCAnnotation object""" ann = BioCAnnotation() ann.id = obj['id'] ann.infons = obj['infons'] ann.text = obj['text'] for loc in obj['locations']: ann.add_location(BioCLocation(loc['offset'], loc['len...
[ "def", "parse_annotation", "(", "obj", ":", "dict", ")", "->", "BioCAnnotation", ":", "ann", "=", "BioCAnnotation", "(", ")", "ann", ".", "id", "=", "obj", "[", "'id'", "]", "ann", ".", "infons", "=", "obj", "[", "'infons'", "]", "ann", ".", "text", ...
Deserialize a dict obj to a BioCAnnotation object
[ "Deserialize", "a", "dict", "obj", "to", "a", "BioCAnnotation", "object" ]
python
train
rbw/flask-journey
flask_journey/journey.py
https://github.com/rbw/flask-journey/blob/6181f59a7b5eef6a85b86ce6ed7d03c91f6bd285/flask_journey/journey.py#L113-L133
def attach_bundle(self, bundle): """Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path ...
[ "def", "attach_bundle", "(", "self", ",", "bundle", ")", ":", "if", "not", "isinstance", "(", "bundle", ",", "BlueprintBundle", ")", ":", "raise", "IncompatibleBundle", "(", "'BlueprintBundle object passed to attach_bundle must be of type {0}'", ".", "format", "(", "B...
Attaches a bundle object :param bundle: :class:`flask_journey.BlueprintBundle` object :raises: - IncompatibleBundle if the bundle is not of type `BlueprintBundle` - ConflictingPath if a bundle already exists at bundle.path - MissingBlueprints if the bundle doesn't co...
[ "Attaches", "a", "bundle", "object" ]
python
valid
NASA-AMMOS/AIT-Core
ait/core/bsc.py
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/bsc.py#L632-L647
def get_handler_stats(self): ''' Return handler read statistics Returns a dictionary of managed handler data read statistics. The format is primarily controlled by the :func:`SocketStreamCapturer.dump_all_handler_stats` function:: { <capture address>: <list ...
[ "def", "get_handler_stats", "(", "self", ")", ":", "return", "{", "address", ":", "stream_capturer", "[", "0", "]", ".", "dump_all_handler_stats", "(", ")", "for", "address", ",", "stream_capturer", "in", "self", ".", "_stream_capturers", ".", "iteritems", "("...
Return handler read statistics Returns a dictionary of managed handler data read statistics. The format is primarily controlled by the :func:`SocketStreamCapturer.dump_all_handler_stats` function:: { <capture address>: <list of handler capture statistics> ...
[ "Return", "handler", "read", "statistics" ]
python
train
tanghaibao/jcvi
jcvi/assembly/allmaps.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/assembly/allmaps.py#L292-L341
def assign_order(self): """ The goal is to assign scaffold orders. To help order the scaffolds, two dummy node, START and END, mark the ends of the chromosome. We connect START to each scaffold (directed), and each scaffold to END. """ linkage_groups = self.linkage_groups...
[ "def", "assign_order", "(", "self", ")", ":", "linkage_groups", "=", "self", ".", "linkage_groups", "for", "mlg", "in", "linkage_groups", ":", "mapname", "=", "mlg", ".", "mapname", "if", "mapname", "==", "self", ".", "pivot", ":", "pivot_position", "=", "...
The goal is to assign scaffold orders. To help order the scaffolds, two dummy node, START and END, mark the ends of the chromosome. We connect START to each scaffold (directed), and each scaffold to END.
[ "The", "goal", "is", "to", "assign", "scaffold", "orders", ".", "To", "help", "order", "the", "scaffolds", "two", "dummy", "node", "START", "and", "END", "mark", "the", "ends", "of", "the", "chromosome", ".", "We", "connect", "START", "to", "each", "scaf...
python
train
shaypal5/utilp
utilp/func/_path.py
https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L112-L132
def path_exists_or_creatable(pathname: str) -> bool: """Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------- `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypoth...
[ "def", "path_exists_or_creatable", "(", "pathname", ":", "str", ")", "->", "bool", ":", "try", ":", "# To prevent \"os\" module calls from raising undesirable exceptions on", "# invalid pathnames, is_pathname_valid() is explicitly called first.", "return", "is_pathname_valid", "(", ...
Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------- `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypothetically creatable; `False` otherwise.
[ "Checks", "whether", "the", "given", "path", "exists", "or", "is", "creatable", "." ]
python
train
bitesofcode/projexui
projexui/widgets/xviewwidget/xviewprofiletoolbar.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiletoolbar.py#L239-L255
def handleActionTrigger(self, action): """ Handles when an action has been triggered. If the inputed action is a XViewProfileAction, then the currentProfileChanged signal will emit. :param action | <QAction> """ # trigger a particular profile ...
[ "def", "handleActionTrigger", "(", "self", ",", "action", ")", ":", "# trigger a particular profile\r", "if", "isinstance", "(", "action", ",", "XViewProfileAction", ")", ":", "# if the user CTRL+Clicks on the action, then attempt\r", "# to load it in a new window\r", "if", "...
Handles when an action has been triggered. If the inputed action is a XViewProfileAction, then the currentProfileChanged signal will emit. :param action | <QAction>
[ "Handles", "when", "an", "action", "has", "been", "triggered", ".", "If", "the", "inputed", "action", "is", "a", "XViewProfileAction", "then", "the", "currentProfileChanged", "signal", "will", "emit", ".", ":", "param", "action", "|", "<QAction", ">" ]
python
train
sosy-lab/benchexec
contrib/plots/quantile-generator.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/contrib/plots/quantile-generator.py#L35-L48
def get_extract_value_function(column_identifier): """ returns a function that extracts the value for a column. """ def extract_value(run_result): pos = None for i, column in enumerate(run_result.columns): if column.title == column_identifier: pos = i ...
[ "def", "get_extract_value_function", "(", "column_identifier", ")", ":", "def", "extract_value", "(", "run_result", ")", ":", "pos", "=", "None", "for", "i", ",", "column", "in", "enumerate", "(", "run_result", ".", "columns", ")", ":", "if", "column", ".", ...
returns a function that extracts the value for a column.
[ "returns", "a", "function", "that", "extracts", "the", "value", "for", "a", "column", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/gui/models/state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/models/state.py#L191-L214
def re_initiate_model_list(self, model_list_or_dict, core_objects_dict, model_name, model_class, model_key): """Recreate model list The method re-initiate a handed list or dictionary of models with the new dictionary of core-objects. :param model_list_or_dict: could be a list or dictionary of ...
[ "def", "re_initiate_model_list", "(", "self", ",", "model_list_or_dict", ",", "core_objects_dict", ",", "model_name", ",", "model_class", ",", "model_key", ")", ":", "if", "model_name", "==", "\"income\"", ":", "if", "self", ".", "income", ".", "income", "!=", ...
Recreate model list The method re-initiate a handed list or dictionary of models with the new dictionary of core-objects. :param model_list_or_dict: could be a list or dictionary of one model type :param core_objects_dict: new dictionary of one type of core-elements (rafcon.core) :para...
[ "Recreate", "model", "list" ]
python
train
mdgoldberg/sportsref
sportsref/nfl/teams.py
https://github.com/mdgoldberg/sportsref/blob/09f11ac856a23c96d666d1d510bb35d6f050b5c3/sportsref/nfl/teams.py#L146-L159
def boxscores(self, year): """Gets list of BoxScore objects corresponding to the box scores from that year. :year: The year for which we want the boxscores; defaults to current year. :returns: np.array of strings representing boxscore IDs. """ doc = self.get_year...
[ "def", "boxscores", "(", "self", ",", "year", ")", ":", "doc", "=", "self", ".", "get_year_doc", "(", "year", ")", "table", "=", "doc", "(", "'table#games'", ")", "df", "=", "sportsref", ".", "utils", ".", "parse_table", "(", "table", ")", "if", "df"...
Gets list of BoxScore objects corresponding to the box scores from that year. :year: The year for which we want the boxscores; defaults to current year. :returns: np.array of strings representing boxscore IDs.
[ "Gets", "list", "of", "BoxScore", "objects", "corresponding", "to", "the", "box", "scores", "from", "that", "year", "." ]
python
test
googleapis/oauth2client
oauth2client/contrib/django_util/models.py
https://github.com/googleapis/oauth2client/blob/50d20532a748f18e53f7d24ccbe6647132c979a9/oauth2client/contrib/django_util/models.py#L44-L57
def to_python(self, value): """Overrides ``models.Field`` method. This is used to convert bytes (from serialization etc) to an instance of this class""" if value is None: return None elif isinstance(value, oauth2client.client.Credentials): return value els...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "value", ",", "oauth2client", ".", "client", ".", "Credentials", ")", ":", "return", "value", "else", ":", "try", ":...
Overrides ``models.Field`` method. This is used to convert bytes (from serialization etc) to an instance of this class
[ "Overrides", "models", ".", "Field", "method", ".", "This", "is", "used", "to", "convert", "bytes", "(", "from", "serialization", "etc", ")", "to", "an", "instance", "of", "this", "class" ]
python
valid
the01/python-paps
examples/measure/server.py
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/examples/measure/server.py#L122-L133
def cmd_line(line, ctrl): server = ctrl.modules[0] """ :type : StartServer """ if line == "statistic start": server.stat_gather = True elif line == "statistic stop": server.stat_gather = False elif line == "statistic reset": server.statistic_reset() elif line == "statisti...
[ "def", "cmd_line", "(", "line", ",", "ctrl", ")", ":", "server", "=", "ctrl", ".", "modules", "[", "0", "]", "if", "line", "==", "\"statistic start\"", ":", "server", ".", "stat_gather", "=", "True", "elif", "line", "==", "\"statistic stop\"", ":", "serv...
:type : StartServer
[ ":", "type", ":", "StartServer" ]
python
train
TorkamaniLab/metapipe
metapipe/models/grammar.py
https://github.com/TorkamaniLab/metapipe/blob/15592e5b0c217afb00ac03503f8d0d7453d4baf4/metapipe/models/grammar.py#L64-L70
def file(): """ Grammar for files found in the overall input files. """ return ( Optional(Word(alphanums).setResultsName('alias') + Suppress(Literal('.'))) + Suppress(White()) + Word(approved_printables).setResultsName('filename') )
[ "def", "file", "(", ")", ":", "return", "(", "Optional", "(", "Word", "(", "alphanums", ")", ".", "setResultsName", "(", "'alias'", ")", "+", "Suppress", "(", "Literal", "(", "'.'", ")", ")", ")", "+", "Suppress", "(", "White", "(", ")", ")", "+", ...
Grammar for files found in the overall input files.
[ "Grammar", "for", "files", "found", "in", "the", "overall", "input", "files", "." ]
python
train
inveniosoftware/invenio-oauthclient
invenio_oauthclient/utils.py
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L224-L235
def _get_csrf_disabled_param(): """Return the right param to disable CSRF depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`. """ import flask_wtf from pkg_resources import parse_version supports_meta = parse_...
[ "def", "_get_csrf_disabled_param", "(", ")", ":", "import", "flask_wtf", "from", "pkg_resources", "import", "parse_version", "supports_meta", "=", "parse_version", "(", "flask_wtf", ".", "__version__", ")", ">=", "parse_version", "(", "\"0.14.0\"", ")", "return", "d...
Return the right param to disable CSRF depending on WTF-Form version. From Flask-WTF 0.14.0, `csrf_enabled` param has been deprecated in favor of `meta={csrf: True/False}`.
[ "Return", "the", "right", "param", "to", "disable", "CSRF", "depending", "on", "WTF", "-", "Form", "version", "." ]
python
train
galaxy-genome-annotation/python-apollo
apollo/annotations/__init__.py
https://github.com/galaxy-genome-annotation/python-apollo/blob/2bc9991302abe4402ec2885dcaac35915475b387/apollo/annotations/__init__.py#L891-L915
def get_gff3(self, feature_id, organism=None, sequence=None): """ Get the GFF3 associated with a feature :type feature_id: str :param feature_id: Feature UUID :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence:...
[ "def", "get_gff3", "(", "self", ",", "feature_id", ",", "organism", "=", "None", ",", "sequence", "=", "None", ")", ":", "data", "=", "{", "'features'", ":", "[", "{", "'uniquename'", ":", "feature_id", "}", "]", "}", "data", "=", "self", ".", "_upda...
Get the GFF3 associated with a feature :type feature_id: str :param feature_id: Feature UUID :type organism: str :param organism: Organism Common Name :type sequence: str :param sequence: Sequence Name :rtype: str :return: GFF3 text content
[ "Get", "the", "GFF3", "associated", "with", "a", "feature" ]
python
train
RockFeng0/rtsf
rtsf/p_common.py
https://github.com/RockFeng0/rtsf/blob/fbc0d57edaeca86418af3942472fcc6d3e9ce591/rtsf/p_common.py#L725-L746
def echo_size(self, transferred=1, status=None): '''Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) progress = ProgressBarUtils("refresh", toBeTransferred=toBeTransferred, unit="KB", chunk_siz...
[ "def", "echo_size", "(", "self", ",", "transferred", "=", "1", ",", "status", "=", "None", ")", ":", "self", ".", "transferred", "+=", "transferred", "# if status is not None:\r", "self", ".", "status", "=", "status", "or", "self", ".", "status", "end_str", ...
Sample usage: f=lambda x,y:x+y ldata = range(10) toBeTransferred = reduce(f,range(10)) progress = ProgressBarUtils("refresh", toBeTransferred=toBeTransferred, unit="KB", chunk_size=1.0, run_status="正在下载", fin_status="下载完成") imp...
[ "Sample", "usage", ":", "f", "=", "lambda", "x", "y", ":", "x", "+", "y", "ldata", "=", "range", "(", "10", ")", "toBeTransferred", "=", "reduce", "(", "f", "range", "(", "10", "))", "progress", "=", "ProgressBarUtils", "(", "refresh", "toBeTransferred...
python
train
oanda/v20-python
src/v20/order.py
https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/order.py#L4580-L4595
def stop(self, accountID, **kwargs): """ Shortcut to create a Stop Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopOrderRequest Returns: v20.response.Response containing the results from submitting ...
[ "def", "stop", "(", "self", ",", "accountID", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "create", "(", "accountID", ",", "order", "=", "StopOrderRequest", "(", "*", "*", "kwargs", ")", ")" ]
Shortcut to create a Stop Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopOrderRequest Returns: v20.response.Response containing the results from submitting the request
[ "Shortcut", "to", "create", "a", "Stop", "Order", "in", "an", "Account" ]
python
train
tensorforce/tensorforce
tensorforce/agents/agent.py
https://github.com/tensorforce/tensorforce/blob/520a8d992230e382f08e315ede5fc477f5e26bfb/tensorforce/agents/agent.py#L244-L264
def save_model(self, directory=None, append_timestep=True): """ Save TensorFlow model. If no checkpoint directory is given, the model's default saver directory is used. Optionally appends current timestep to prevent overwriting previous checkpoint files. Turn off to be able to load model...
[ "def", "save_model", "(", "self", ",", "directory", "=", "None", ",", "append_timestep", "=", "True", ")", ":", "return", "self", ".", "model", ".", "save", "(", "directory", "=", "directory", ",", "append_timestep", "=", "append_timestep", ")" ]
Save TensorFlow model. If no checkpoint directory is given, the model's default saver directory is used. Optionally appends current timestep to prevent overwriting previous checkpoint files. Turn off to be able to load model from the same given path argument as given here. Args: ...
[ "Save", "TensorFlow", "model", ".", "If", "no", "checkpoint", "directory", "is", "given", "the", "model", "s", "default", "saver", "directory", "is", "used", ".", "Optionally", "appends", "current", "timestep", "to", "prevent", "overwriting", "previous", "checkp...
python
valid
yjzhang/uncurl_python
uncurl/ensemble.py
https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/ensemble.py#L81-L101
def nmf_kfold(data, k, n_runs=10, **nmf_params): """ Runs K-fold ensemble topic modeling (Belford et al. 2017) """ # TODO nmf = NMF(k) W_list = [] kf = KFold(n_splits=n_runs, shuffle=True) # TODO: randomly divide data into n_runs folds for train_index, test_index in kf.split(data.T):...
[ "def", "nmf_kfold", "(", "data", ",", "k", ",", "n_runs", "=", "10", ",", "*", "*", "nmf_params", ")", ":", "# TODO", "nmf", "=", "NMF", "(", "k", ")", "W_list", "=", "[", "]", "kf", "=", "KFold", "(", "n_splits", "=", "n_runs", ",", "shuffle", ...
Runs K-fold ensemble topic modeling (Belford et al. 2017)
[ "Runs", "K", "-", "fold", "ensemble", "topic", "modeling", "(", "Belford", "et", "al", ".", "2017", ")" ]
python
train
72squared/redpipe
redpipe/keyspaces.py
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/keyspaces.py#L1683-L1694
def zremrangebyscore(self, name, min, max): """ Remove a range of element by between score ``min_value`` and ``max_value`` both included. :param name: str the name of the redis key :param min: :param max: :return: Future() """ with self.pipe a...
[ "def", "zremrangebyscore", "(", "self", ",", "name", ",", "min", ",", "max", ")", ":", "with", "self", ".", "pipe", "as", "pipe", ":", "return", "pipe", ".", "zremrangebyscore", "(", "self", ".", "redis_key", "(", "name", ")", ",", "min", ",", "max",...
Remove a range of element by between score ``min_value`` and ``max_value`` both included. :param name: str the name of the redis key :param min: :param max: :return: Future()
[ "Remove", "a", "range", "of", "element", "by", "between", "score", "min_value", "and", "max_value", "both", "included", "." ]
python
train
gapato/livestreamer-curses
src/livestreamer_curses/streamlist.py
https://github.com/gapato/livestreamer-curses/blob/d841a421422db8c5b5a8bcfcff6b3ddd7ea8a64b/src/livestreamer_curses/streamlist.py#L74-L83
def get_finished(self): """ Clean up terminated processes and returns the list of their ids """ indices = [] for idf, v in self.q.items(): if v.poll() != None: indices.append(idf) for i in indices: self.q.pop(i) return indices
[ "def", "get_finished", "(", "self", ")", ":", "indices", "=", "[", "]", "for", "idf", ",", "v", "in", "self", ".", "q", ".", "items", "(", ")", ":", "if", "v", ".", "poll", "(", ")", "!=", "None", ":", "indices", ".", "append", "(", "idf", ")...
Clean up terminated processes and returns the list of their ids
[ "Clean", "up", "terminated", "processes", "and", "returns", "the", "list", "of", "their", "ids" ]
python
train
rapidpro/expressions
python/temba_expressions/conversions.py
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/conversions.py#L29-L50
def to_integer(value, ctx): """ Tries conversion of any value to an integer """ if isinstance(value, bool): return 1 if value else 0 elif isinstance(value, int): return value elif isinstance(value, Decimal): try: val = int(value.to_integral_exact(ROUND_HALF_UP...
[ "def", "to_integer", "(", "value", ",", "ctx", ")", ":", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "1", "if", "value", "else", "0", "elif", "isinstance", "(", "value", ",", "int", ")", ":", "return", "value", "elif", "isinsta...
Tries conversion of any value to an integer
[ "Tries", "conversion", "of", "any", "value", "to", "an", "integer" ]
python
train
bachya/pyairvisual
pyairvisual/client.py
https://github.com/bachya/pyairvisual/blob/1d4809998d87f85d53bb281e1eb54d43acee06fa/pyairvisual/client.py#L25-L50
async def request( self, method: str, endpoint: str, *, base_url: str = API_URL_SCAFFOLD, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against AirVisual.""" if not ...
[ "async", "def", "request", "(", "self", ",", "method", ":", "str", ",", "endpoint", ":", "str", ",", "*", ",", "base_url", ":", "str", "=", "API_URL_SCAFFOLD", ",", "headers", ":", "dict", "=", "None", ",", "params", ":", "dict", "=", "None", ",", ...
Make a request against AirVisual.
[ "Make", "a", "request", "against", "AirVisual", "." ]
python
train
saltstack/salt
salt/modules/azurearm_resource.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L224-L257
def deployment_operation_get(operation, deployment, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Get a deployment operation within a deployment. :param operation: The operation ID of the operation within the deployment. :param deployment: The name of the deployment containing the ope...
[ "def", "deployment_operation_get", "(", "operation", ",", "deployment", ",", "resource_group", ",", "*", "*", "kwargs", ")", ":", "resconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'resource'", ",", "*", "*", "kwargs", ")", "try", ":", "op...
.. versionadded:: 2019.2.0 Get a deployment operation within a deployment. :param operation: The operation ID of the operation within the deployment. :param deployment: The name of the deployment containing the operation. :param resource_group: The resource group name assigned to the deploym...
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
python
train
selenol/selenol-python
selenol_python/connections.py
https://github.com/selenol/selenol-python/blob/53775fdfc95161f4aca350305cb3459e6f2f808d/selenol_python/connections.py#L37-L45
def send(self, message): """Send a the defined message to the backend. :param message: Message to be send, usually a Python dictionary. """ try: self.ws.send(json.dumps(message)) except websocket._exceptions.WebSocketConnectionClosedException: raise Selen...
[ "def", "send", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "ws", ".", "send", "(", "json", ".", "dumps", "(", "message", ")", ")", "except", "websocket", ".", "_exceptions", ".", "WebSocketConnectionClosedException", ":", "raise", "Se...
Send a the defined message to the backend. :param message: Message to be send, usually a Python dictionary.
[ "Send", "a", "the", "defined", "message", "to", "the", "backend", "." ]
python
train
apache/airflow
airflow/contrib/hooks/gcp_mlengine_hook.py
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_mlengine_hook.py#L53-L58
def get_conn(self): """ Returns a Google MLEngine service object. """ authed_http = self._authorize() return build('ml', 'v1', http=authed_http, cache_discovery=False)
[ "def", "get_conn", "(", "self", ")", ":", "authed_http", "=", "self", ".", "_authorize", "(", ")", "return", "build", "(", "'ml'", ",", "'v1'", ",", "http", "=", "authed_http", ",", "cache_discovery", "=", "False", ")" ]
Returns a Google MLEngine service object.
[ "Returns", "a", "Google", "MLEngine", "service", "object", "." ]
python
test
BreakingBytes/simkit
simkit/core/data_readers.py
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/data_readers.py#L312-L328
def apply_units_to_cache(self, data): """ Apply units to cached data read using :class:`JSONReader`. :param data: Cached data. :type data: dict :return: data with units """ # iterate through sheets in parameters # iterate through the parameters on each sh...
[ "def", "apply_units_to_cache", "(", "self", ",", "data", ")", ":", "# iterate through sheets in parameters", "# iterate through the parameters on each sheet", "for", "param", ",", "pval", "in", "self", ".", "parameters", ".", "iteritems", "(", ")", ":", "# try to apply ...
Apply units to cached data read using :class:`JSONReader`. :param data: Cached data. :type data: dict :return: data with units
[ "Apply", "units", "to", "cached", "data", "read", "using", ":", "class", ":", "JSONReader", "." ]
python
train
chbrown/viz
viz/stats.py
https://github.com/chbrown/viz/blob/683a8f91630582d74250690a0e8ea7743ab94058/viz/stats.py#L8-L14
def normalize(xs): ''' Restrict xs into the interval (0, 1) via a linear transformation as long as len(xs) > 1, 0 and 1 will be elements of the resulting array ''' x_min, x_max = np.min(xs), np.max(xs) return (xs - x_min) / (x_max - x_min)
[ "def", "normalize", "(", "xs", ")", ":", "x_min", ",", "x_max", "=", "np", ".", "min", "(", "xs", ")", ",", "np", ".", "max", "(", "xs", ")", "return", "(", "xs", "-", "x_min", ")", "/", "(", "x_max", "-", "x_min", ")" ]
Restrict xs into the interval (0, 1) via a linear transformation as long as len(xs) > 1, 0 and 1 will be elements of the resulting array
[ "Restrict", "xs", "into", "the", "interval", "(", "0", "1", ")", "via", "a", "linear", "transformation", "as", "long", "as", "len", "(", "xs", ")", ">", "1", "0", "and", "1", "will", "be", "elements", "of", "the", "resulting", "array" ]
python
train
spyder-ide/spyder
spyder/plugins/explorer/widgets.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/explorer/widgets.py#L291-L295
def toggle_all(self, checked): """Toggle all files mode""" self.parent_widget.sig_option_changed.emit('show_all', checked) self.show_all = checked self.set_show_all(checked)
[ "def", "toggle_all", "(", "self", ",", "checked", ")", ":", "self", ".", "parent_widget", ".", "sig_option_changed", ".", "emit", "(", "'show_all'", ",", "checked", ")", "self", ".", "show_all", "=", "checked", "self", ".", "set_show_all", "(", "checked", ...
Toggle all files mode
[ "Toggle", "all", "files", "mode" ]
python
train
mitsei/dlkit
dlkit/json_/assessment/managers.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/managers.py#L2456-L2473
def get_assessment_bank_session(self, proxy): """Gets the ``OsidSession`` associated with the assessment banking service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBankSession) - an ``AssessmentBankSession`` raise: NullArgument - ``pro...
[ "def", "get_assessment_bank_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_assessment_bank", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "Assessment...
Gets the ``OsidSession`` associated with the assessment banking service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBankSession) - an ``AssessmentBankSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable...
[ "Gets", "the", "OsidSession", "associated", "with", "the", "assessment", "banking", "service", "." ]
python
train
saltstack/salt
salt/states/statuspage.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/statuspage.py#L150-L165
def _update_on_fields(prev_ele, new_ele): ''' Return a dict with fields that differ between two dicts. ''' fields_update = dict( (prop_name, prop_val) for prop_name, prop_val in six.iteritems(new_ele) if new_ele.get(prop_name) != prev_ele.get(prop_name) or prop_name in _MATCH_KEY...
[ "def", "_update_on_fields", "(", "prev_ele", ",", "new_ele", ")", ":", "fields_update", "=", "dict", "(", "(", "prop_name", ",", "prop_val", ")", "for", "prop_name", ",", "prop_val", "in", "six", ".", "iteritems", "(", "new_ele", ")", "if", "new_ele", ".",...
Return a dict with fields that differ between two dicts.
[ "Return", "a", "dict", "with", "fields", "that", "differ", "between", "two", "dicts", "." ]
python
train
hyperledger/indy-plenum
state/util/utils.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/state/util/utils.py#L80-L93
def isHex(val: str) -> bool: """ Return whether the given str represents a hex value or not :param val: the string to check :return: whether the given str represents a hex value """ if isinstance(val, bytes): # only decodes utf-8 string try: val = val.decode() ...
[ "def", "isHex", "(", "val", ":", "str", ")", "->", "bool", ":", "if", "isinstance", "(", "val", ",", "bytes", ")", ":", "# only decodes utf-8 string", "try", ":", "val", "=", "val", ".", "decode", "(", ")", "except", "ValueError", ":", "return", "False...
Return whether the given str represents a hex value or not :param val: the string to check :return: whether the given str represents a hex value
[ "Return", "whether", "the", "given", "str", "represents", "a", "hex", "value", "or", "not" ]
python
train
avihad/twistes
twistes/client.py
https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/client.py#L63-L79
def get(self, index, id, fields=None, doc_type=EsConst.ALL_VALUES, **query_params): """ Retrieve specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name to query :param id: the id of the record :...
[ "def", "get", "(", "self", ",", "index", ",", "id", ",", "fields", "=", "None", ",", "doc_type", "=", "EsConst", ".", "ALL_VALUES", ",", "*", "*", "query_params", ")", ":", "if", "fields", ":", "query_params", "[", "EsConst", ".", "FIELDS", "]", "=",...
Retrieve specific record by id `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name to query :param id: the id of the record :param fields: the fields you what to fetch from the record (str separated by comma's) :param doc...
[ "Retrieve", "specific", "record", "by", "id", "<http", ":", "//", "www", ".", "elastic", ".", "co", "/", "guide", "/", "en", "/", "elasticsearch", "/", "reference", "/", "current", "/", "docs", "-", "get", ".", "html", ">", "_", ":", "param", "index"...
python
train
CalebBell/fluids
fluids/pump.py
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/pump.py#L81-L118
def Corripio_motor_efficiency(P): r'''Estimates motor efficiency using the method in Corripio (1982) as shown in [1]_ and originally in [2]_. Estimation only. .. math:: \eta_M = 0.8 + 0.0319\ln(P_B) - 0.00182\ln(P_B)^2 Parameters ---------- P : float Power, [W] Returns ...
[ "def", "Corripio_motor_efficiency", "(", "P", ")", ":", "P", "=", "P", "/", "745.69987", "logP", "=", "log", "(", "P", ")", "return", "0.8", "+", "0.0319", "*", "logP", "-", "0.00182", "*", "logP", "*", "logP" ]
r'''Estimates motor efficiency using the method in Corripio (1982) as shown in [1]_ and originally in [2]_. Estimation only. .. math:: \eta_M = 0.8 + 0.0319\ln(P_B) - 0.00182\ln(P_B)^2 Parameters ---------- P : float Power, [W] Returns ------- efficiency : float ...
[ "r", "Estimates", "motor", "efficiency", "using", "the", "method", "in", "Corripio", "(", "1982", ")", "as", "shown", "in", "[", "1", "]", "_", "and", "originally", "in", "[", "2", "]", "_", ".", "Estimation", "only", "." ]
python
train
ejeschke/ginga
ginga/web/pgw/ipg.py
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/pgw/ipg.py#L69-L75
def open(self, new=1): """ Open this viewer in a new browser window or tab. (requires `webbrowser` module) """ import webbrowser webbrowser.open(self.url, new=new)
[ "def", "open", "(", "self", ",", "new", "=", "1", ")", ":", "import", "webbrowser", "webbrowser", ".", "open", "(", "self", ".", "url", ",", "new", "=", "new", ")" ]
Open this viewer in a new browser window or tab. (requires `webbrowser` module)
[ "Open", "this", "viewer", "in", "a", "new", "browser", "window", "or", "tab", ".", "(", "requires", "webbrowser", "module", ")" ]
python
train
deanmalmgren/textract
textract/parsers/html_parser.py
https://github.com/deanmalmgren/textract/blob/117ea191d93d80321e4bf01f23cc1ac54d69a075/textract/parsers/html_parser.py#L44-L53
def _find_any_text(self, tag): """Looks for any possible text within given tag. """ text = '' if tag is not None: text = six.text_type(tag) text = re.sub(r'(<[^>]+>)', '', text) text = re.sub(r'\s', ' ', text) text = text.strip() re...
[ "def", "_find_any_text", "(", "self", ",", "tag", ")", ":", "text", "=", "''", "if", "tag", "is", "not", "None", ":", "text", "=", "six", ".", "text_type", "(", "tag", ")", "text", "=", "re", ".", "sub", "(", "r'(<[^>]+>)'", ",", "''", ",", "text...
Looks for any possible text within given tag.
[ "Looks", "for", "any", "possible", "text", "within", "given", "tag", "." ]
python
train
shoebot/shoebot
lib/svg/__init__.py
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/lib/svg/__init__.py#L85-L93
def get_attribute(element, attribute, default=0): """ Returns XML element's attribute, or default if none. """ a = element.getAttribute(attribute) if a == "": return default return a
[ "def", "get_attribute", "(", "element", ",", "attribute", ",", "default", "=", "0", ")", ":", "a", "=", "element", ".", "getAttribute", "(", "attribute", ")", "if", "a", "==", "\"\"", ":", "return", "default", "return", "a" ]
Returns XML element's attribute, or default if none.
[ "Returns", "XML", "element", "s", "attribute", "or", "default", "if", "none", "." ]
python
valid
pydsigner/taskit
taskit/common.py
https://github.com/pydsigner/taskit/blob/3b228e2dbac16b3b84b2581f5b46e027d1d8fa7f/taskit/common.py#L81-L89
def set_size(self, data_size): """ Set the data slice size. """ if len(str(data_size)) > self.first: raise ValueError( 'Send size is too large for message size-field width!') self.data_size = data_size
[ "def", "set_size", "(", "self", ",", "data_size", ")", ":", "if", "len", "(", "str", "(", "data_size", ")", ")", ">", "self", ".", "first", ":", "raise", "ValueError", "(", "'Send size is too large for message size-field width!'", ")", "self", ".", "data_size"...
Set the data slice size.
[ "Set", "the", "data", "slice", "size", "." ]
python
train
bovee/Aston
aston/trace/math_traces.py
https://github.com/bovee/Aston/blob/007630fdf074690373d03398fe818260d3d3cf5a/aston/trace/math_traces.py#L44-L51
def fft(ts): """ Perform a fast-fourier transform on a Trace """ t_step = ts.index[1] - ts.index[0] oc = np.abs(np.fft.fftshift(np.fft.fft(ts.values))) / len(ts.values) t = np.fft.fftshift(np.fft.fftfreq(len(oc), d=t_step)) return Trace(oc, t)
[ "def", "fft", "(", "ts", ")", ":", "t_step", "=", "ts", ".", "index", "[", "1", "]", "-", "ts", ".", "index", "[", "0", "]", "oc", "=", "np", ".", "abs", "(", "np", ".", "fft", ".", "fftshift", "(", "np", ".", "fft", ".", "fft", "(", "ts"...
Perform a fast-fourier transform on a Trace
[ "Perform", "a", "fast", "-", "fourier", "transform", "on", "a", "Trace" ]
python
train
consbio/parserutils
parserutils/elements.py
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/elements.py#L658-L669
def set_elements_tail(parent_to_parse, element_path=None, tail_values=None): """ Assigns an array of tail values to each of the elements parsed from the parent. The tail values are assigned in the same order they are provided. If there are less values then elements, the remaining elements are skipped; b...
[ "def", "set_elements_tail", "(", "parent_to_parse", ",", "element_path", "=", "None", ",", "tail_values", "=", "None", ")", ":", "if", "tail_values", "is", "None", ":", "tail_values", "=", "[", "]", "return", "_set_elements_property", "(", "parent_to_parse", ","...
Assigns an array of tail values to each of the elements parsed from the parent. The tail values are assigned in the same order they are provided. If there are less values then elements, the remaining elements are skipped; but if there are more, new elements will be inserted for each with the remaining tail ...
[ "Assigns", "an", "array", "of", "tail", "values", "to", "each", "of", "the", "elements", "parsed", "from", "the", "parent", ".", "The", "tail", "values", "are", "assigned", "in", "the", "same", "order", "they", "are", "provided", ".", "If", "there", "are...
python
train
wright-group/WrightTools
WrightTools/kit/_ini.py
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_ini.py#L95-L108
def has_section(self, section) -> bool: """Test if file has section. Parameters ---------- section : string Section. Returns ------- boolean """ self.config.read(self.filepath) return self.config.has_section(section)
[ "def", "has_section", "(", "self", ",", "section", ")", "->", "bool", ":", "self", ".", "config", ".", "read", "(", "self", ".", "filepath", ")", "return", "self", ".", "config", ".", "has_section", "(", "section", ")" ]
Test if file has section. Parameters ---------- section : string Section. Returns ------- boolean
[ "Test", "if", "file", "has", "section", "." ]
python
train
bw2/ConfigArgParse
configargparse.py
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L27-L43
def init_argument_parser(name=None, **kwargs): """Creates a global ArgumentParser instance with the given name, passing any args other than "name" to the ArgumentParser constructor. This instance can then be retrieved using get_argument_parser(..) """ if name is None: name = "default" ...
[ "def", "init_argument_parser", "(", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"default\"", "if", "name", "in", "_parsers", ":", "raise", "ValueError", "(", "(", "\"kwargs besides 'name' can only b...
Creates a global ArgumentParser instance with the given name, passing any args other than "name" to the ArgumentParser constructor. This instance can then be retrieved using get_argument_parser(..)
[ "Creates", "a", "global", "ArgumentParser", "instance", "with", "the", "given", "name", "passing", "any", "args", "other", "than", "name", "to", "the", "ArgumentParser", "constructor", ".", "This", "instance", "can", "then", "be", "retrieved", "using", "get_argu...
python
train
dropbox/stone
stone/ir/data_types.py
https://github.com/dropbox/stone/blob/2e95cbcd1c48e05cca68c919fd8d24adec6b0f58/stone/ir/data_types.py#L524-L547
def doc_unwrap(raw_doc): """ Applies two transformations to raw_doc: 1. N consecutive newlines are converted into N-1 newlines. 2. A lone newline is converted to a space, which basically unwraps text. Returns a new string, or None if the input was None. """ if raw_doc is None: retur...
[ "def", "doc_unwrap", "(", "raw_doc", ")", ":", "if", "raw_doc", "is", "None", ":", "return", "None", "docstring", "=", "''", "consecutive_newlines", "=", "0", "# Remove all leading and trailing whitespace in the documentation block", "for", "c", "in", "raw_doc", ".", ...
Applies two transformations to raw_doc: 1. N consecutive newlines are converted into N-1 newlines. 2. A lone newline is converted to a space, which basically unwraps text. Returns a new string, or None if the input was None.
[ "Applies", "two", "transformations", "to", "raw_doc", ":", "1", ".", "N", "consecutive", "newlines", "are", "converted", "into", "N", "-", "1", "newlines", ".", "2", ".", "A", "lone", "newline", "is", "converted", "to", "a", "space", "which", "basically", ...
python
train
Cymmetria/honeycomb
honeycomb/utils/plugin_utils.py
https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L246-L264
def uninstall_plugin(pkgpath, force): """Uninstall a plugin. :param pkgpath: Path to package to uninstall (delete) :param force: Force uninstall without asking """ pkgname = os.path.basename(pkgpath) if os.path.exists(pkgpath): if not force: click.confirm("[?] Are you sure y...
[ "def", "uninstall_plugin", "(", "pkgpath", ",", "force", ")", ":", "pkgname", "=", "os", ".", "path", ".", "basename", "(", "pkgpath", ")", "if", "os", ".", "path", ".", "exists", "(", "pkgpath", ")", ":", "if", "not", "force", ":", "click", ".", "...
Uninstall a plugin. :param pkgpath: Path to package to uninstall (delete) :param force: Force uninstall without asking
[ "Uninstall", "a", "plugin", "." ]
python
train
flowersteam/explauto
explauto/sensorimotor_model/inverse/cma.py
https://github.com/flowersteam/explauto/blob/cf0f81ecb9f6412f7276a95bd27359000e1e26b6/explauto/sensorimotor_model/inverse/cma.py#L1063-L1076
def repair(self, x, copy_if_changed=True, copy_always=False): """transforms ``x`` into the bounded domain. ``copy_always`` option might disappear. """ copy = copy_if_changed if copy_always: x = array(x, copy=True) copy = False if self.bounds is N...
[ "def", "repair", "(", "self", ",", "x", ",", "copy_if_changed", "=", "True", ",", "copy_always", "=", "False", ")", ":", "copy", "=", "copy_if_changed", "if", "copy_always", ":", "x", "=", "array", "(", "x", ",", "copy", "=", "True", ")", "copy", "="...
transforms ``x`` into the bounded domain. ``copy_always`` option might disappear.
[ "transforms", "x", "into", "the", "bounded", "domain", "." ]
python
train
vatlab/SoS
src/sos/parser.py
https://github.com/vatlab/SoS/blob/6b60ed0770916d135e17322e469520d778e9d4e7/src/sos/parser.py#L924-L934
def add_comment(self, line: str) -> None: '''Keeping track of "last comment" for section and parameter ''' # the rule is like # # # comment line --> add to last comment # blank line --> clears last comment # [ ] --> use last comment # parameter: --> use last comm...
[ "def", "add_comment", "(", "self", ",", "line", ":", "str", ")", "->", "None", ":", "# the rule is like", "#", "# # comment line --> add to last comment", "# blank line --> clears last comment", "# [ ] --> use last comment", "# parameter: --> use last comment", "# All others: cl...
Keeping track of "last comment" for section and parameter
[ "Keeping", "track", "of", "last", "comment", "for", "section", "and", "parameter" ]
python
train
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/data.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/data.py#L57-L62
def list2dict(lst): """Takes a list of (key,value) pairs and turns it into a dict.""" dic = {} for k,v in lst: dic[k] = v return dic
[ "def", "list2dict", "(", "lst", ")", ":", "dic", "=", "{", "}", "for", "k", ",", "v", "in", "lst", ":", "dic", "[", "k", "]", "=", "v", "return", "dic" ]
Takes a list of (key,value) pairs and turns it into a dict.
[ "Takes", "a", "list", "of", "(", "key", "value", ")", "pairs", "and", "turns", "it", "into", "a", "dict", "." ]
python
test
gbowerman/azurerm
examples/list_vmss_nics.py
https://github.com/gbowerman/azurerm/blob/79d40431d3b13f8a36aadbff5029888383d72674/examples/list_vmss_nics.py#L9-L13
def get_rg_from_id(vmss_id): '''get a resource group name from a VMSS ID string''' rgname = re.search('Groups/(.+?)/providers', vmss_id).group(1) print('Resource group: ' + rgname) return rgname
[ "def", "get_rg_from_id", "(", "vmss_id", ")", ":", "rgname", "=", "re", ".", "search", "(", "'Groups/(.+?)/providers'", ",", "vmss_id", ")", ".", "group", "(", "1", ")", "print", "(", "'Resource group: '", "+", "rgname", ")", "return", "rgname" ]
get a resource group name from a VMSS ID string
[ "get", "a", "resource", "group", "name", "from", "a", "VMSS", "ID", "string" ]
python
train
blockstack/blockstack-core
blockstack/lib/rpc.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/rpc.py#L553-L647
def GET_name_info( self, path_info, name ): """ Look up a name's zonefile, address, and last TXID Reply status, zonefile, zonefile hash, address, and last TXID. 'status' can be 'available', 'registered', 'revoked', or 'pending' """ if not check_name(name) and not check_su...
[ "def", "GET_name_info", "(", "self", ",", "path_info", ",", "name", ")", ":", "if", "not", "check_name", "(", "name", ")", "and", "not", "check_subdomain", "(", "name", ")", ":", "return", "self", ".", "_reply_json", "(", "{", "'error'", ":", "'Invalid n...
Look up a name's zonefile, address, and last TXID Reply status, zonefile, zonefile hash, address, and last TXID. 'status' can be 'available', 'registered', 'revoked', or 'pending'
[ "Look", "up", "a", "name", "s", "zonefile", "address", "and", "last", "TXID", "Reply", "status", "zonefile", "zonefile", "hash", "address", "and", "last", "TXID", ".", "status", "can", "be", "available", "registered", "revoked", "or", "pending" ]
python
train
PyHDI/Pyverilog
pyverilog/vparser/parser.py
https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L1095-L1098
def p_expression_land(self, p): 'expression : expression LAND expression' p[0] = Land(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_land", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Land", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ...
expression : expression LAND expression
[ "expression", ":", "expression", "LAND", "expression" ]
python
train
jantman/webhook2lambda2sqs
webhook2lambda2sqs/tf_generator.py
https://github.com/jantman/webhook2lambda2sqs/blob/c80c18d5a908ba8b8ee624dc3a977c633fba2b7c/webhook2lambda2sqs/tf_generator.py#L280-L303
def _set_account_info(self): """ Connect to the AWS IAM API via boto3 and run the GetUser operation on the current user. Use this to set ``self.aws_account_id`` and ``self.aws_region``. """ if 'AWS_DEFAULT_REGION' in os.environ: logger.debug('Connecting to IAM...
[ "def", "_set_account_info", "(", "self", ")", ":", "if", "'AWS_DEFAULT_REGION'", "in", "os", ".", "environ", ":", "logger", ".", "debug", "(", "'Connecting to IAM with region_name=%s'", ",", "os", ".", "environ", "[", "'AWS_DEFAULT_REGION'", "]", ")", "kwargs", ...
Connect to the AWS IAM API via boto3 and run the GetUser operation on the current user. Use this to set ``self.aws_account_id`` and ``self.aws_region``.
[ "Connect", "to", "the", "AWS", "IAM", "API", "via", "boto3", "and", "run", "the", "GetUser", "operation", "on", "the", "current", "user", ".", "Use", "this", "to", "set", "self", ".", "aws_account_id", "and", "self", ".", "aws_region", "." ]
python
train
manns/pyspread
pyspread/src/actions/_grid_cell_actions.py
https://github.com/manns/pyspread/blob/0e2fd44c2e0f06605efc3058c20a43a8c1f9e7e0/pyspread/src/actions/_grid_cell_actions.py#L71-L78
def quote_code(self, key): """Returns string quoted code """ code = self.grid.code_array(key) quoted_code = quote(code) if quoted_code is not None: self.set_code(key, quoted_code)
[ "def", "quote_code", "(", "self", ",", "key", ")", ":", "code", "=", "self", ".", "grid", ".", "code_array", "(", "key", ")", "quoted_code", "=", "quote", "(", "code", ")", "if", "quoted_code", "is", "not", "None", ":", "self", ".", "set_code", "(", ...
Returns string quoted code
[ "Returns", "string", "quoted", "code" ]
python
train
HazyResearch/fonduer
src/fonduer/learning/disc_models/sparse_logistic_regression.py
https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/learning/disc_models/sparse_logistic_regression.py#L44-L104
def _preprocess_data(self, X, Y=None, idxs=None, train=False): """ Preprocess the data: 1. Select subset of the input if idxs exists. :param X: The input data of the model. :type X: pair with candidates and corresponding features :param Y: The labels of input data. ...
[ "def", "_preprocess_data", "(", "self", ",", "X", ",", "Y", "=", "None", ",", "idxs", "=", "None", ",", "train", "=", "False", ")", ":", "C", ",", "F", "=", "X", "if", "Y", "is", "not", "None", ":", "Y", "=", "np", ".", "array", "(", "Y", "...
Preprocess the data: 1. Select subset of the input if idxs exists. :param X: The input data of the model. :type X: pair with candidates and corresponding features :param Y: The labels of input data. :type Y: list or numpy.array :param idxs: The selected indices of input ...
[ "Preprocess", "the", "data", ":", "1", ".", "Select", "subset", "of", "the", "input", "if", "idxs", "exists", "." ]
python
train
mk-fg/feedjack
feedjack/views.py
https://github.com/mk-fg/feedjack/blob/3fe65c0f66dc2cfdf45834aaa7235ec9f81b3ca3/feedjack/views.py#L28-L35
def cache_etag(request, *argz, **kwz): '''Produce etag value for a cached page. Intended for usage in conditional views (@condition decorator).''' response, site, cachekey = kwz.get('_view_data') or initview(request) if not response: return None return fjcache.str2md5( '{0}--{1}--{2}'.format( site.id if site el...
[ "def", "cache_etag", "(", "request", ",", "*", "argz", ",", "*", "*", "kwz", ")", ":", "response", ",", "site", ",", "cachekey", "=", "kwz", ".", "get", "(", "'_view_data'", ")", "or", "initview", "(", "request", ")", "if", "not", "response", ":", ...
Produce etag value for a cached page. Intended for usage in conditional views (@condition decorator).
[ "Produce", "etag", "value", "for", "a", "cached", "page", ".", "Intended", "for", "usage", "in", "conditional", "views", "(" ]
python
train
yjzhang/uncurl_python
uncurl/nmf_wrapper.py
https://github.com/yjzhang/uncurl_python/blob/55c58ca5670f87699d3bd5752fdfa4baa07724dd/uncurl/nmf_wrapper.py#L51-L95
def log_norm_nmf(data, k, normalize_w=True, return_cost=True, init_weights=None, init_means=None, write_progress_file=None, **kwargs): """ Args: data (array): dense or sparse array with shape (genes, cells) k (int): number of cell types normalize_w (bool, optional): True if W should be n...
[ "def", "log_norm_nmf", "(", "data", ",", "k", ",", "normalize_w", "=", "True", ",", "return_cost", "=", "True", ",", "init_weights", "=", "None", ",", "init_means", "=", "None", ",", "write_progress_file", "=", "None", ",", "*", "*", "kwargs", ")", ":", ...
Args: data (array): dense or sparse array with shape (genes, cells) k (int): number of cell types normalize_w (bool, optional): True if W should be normalized (so that each column sums to 1). Default: True return_cost (bool, optional): True if the NMF objective value (squared error) shou...
[ "Args", ":", "data", "(", "array", ")", ":", "dense", "or", "sparse", "array", "with", "shape", "(", "genes", "cells", ")", "k", "(", "int", ")", ":", "number", "of", "cell", "types", "normalize_w", "(", "bool", "optional", ")", ":", "True", "if", ...
python
train
tanghaibao/jcvi
jcvi/apps/bwa.py
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/apps/bwa.py#L120-L128
def set_align_options(p): """ Used in align() and batch() """ p.add_option("--bwa", default="bwa", help="Run bwa at this path") p.add_option("--rg", help="Read group") p.add_option("--readtype", choices=("pacbio", "pbread", "ont2d", "intractg"), help="Read type in b...
[ "def", "set_align_options", "(", "p", ")", ":", "p", ".", "add_option", "(", "\"--bwa\"", ",", "default", "=", "\"bwa\"", ",", "help", "=", "\"Run bwa at this path\"", ")", "p", ".", "add_option", "(", "\"--rg\"", ",", "help", "=", "\"Read group\"", ")", "...
Used in align() and batch()
[ "Used", "in", "align", "()", "and", "batch", "()" ]
python
train
spyder-ide/spyder
spyder/plugins/editor/plugin.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/plugin.py#L2376-L2390
def save_bookmark(self, slot_num): """Save current line and position as bookmark.""" bookmarks = CONF.get('editor', 'bookmarks') editorstack = self.get_current_editorstack() if slot_num in bookmarks: filename, line_num, column = bookmarks[slot_num] if osp.is...
[ "def", "save_bookmark", "(", "self", ",", "slot_num", ")", ":", "bookmarks", "=", "CONF", ".", "get", "(", "'editor'", ",", "'bookmarks'", ")", "editorstack", "=", "self", ".", "get_current_editorstack", "(", ")", "if", "slot_num", "in", "bookmarks", ":", ...
Save current line and position as bookmark.
[ "Save", "current", "line", "and", "position", "as", "bookmark", "." ]
python
train
sibirrer/lenstronomy
lenstronomy/ImSim/MultiBand/multiband.py
https://github.com/sibirrer/lenstronomy/blob/4edb100a4f3f4fdc4fac9b0032d2b0283d0aa1d6/lenstronomy/ImSim/MultiBand/multiband.py#L30-L52
def image_linear_solve(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_else, inv_bool=False): """ computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalizat...
[ "def", "image_linear_solve", "(", "self", ",", "kwargs_lens", ",", "kwargs_source", ",", "kwargs_lens_light", ",", "kwargs_else", ",", "inv_bool", "=", "False", ")", ":", "wls_list", ",", "error_map_list", ",", "cov_param_list", ",", "param_list", "=", "[", "]",...
computes the image (lens and source surface brightness with a given lens model). The linear parameters are computed with a weighted linear least square optimization (i.e. flux normalization of the brightness profiles) :param kwargs_lens: list of keyword arguments corresponding to the superposition of di...
[ "computes", "the", "image", "(", "lens", "and", "source", "surface", "brightness", "with", "a", "given", "lens", "model", ")", ".", "The", "linear", "parameters", "are", "computed", "with", "a", "weighted", "linear", "least", "square", "optimization", "(", "...
python
train
spotify/luigi
luigi/contrib/esindex.py
https://github.com/spotify/luigi/blob/c5eca1c3c3ee2a7eb612486192a0da146710a1e9/luigi/contrib/esindex.py#L404-L410
def delete_index(self): """ Delete the index, if it exists. """ es = self._init_connection() if es.indices.exists(index=self.index): es.indices.delete(index=self.index)
[ "def", "delete_index", "(", "self", ")", ":", "es", "=", "self", ".", "_init_connection", "(", ")", "if", "es", ".", "indices", ".", "exists", "(", "index", "=", "self", ".", "index", ")", ":", "es", ".", "indices", ".", "delete", "(", "index", "="...
Delete the index, if it exists.
[ "Delete", "the", "index", "if", "it", "exists", "." ]
python
train
CyberZHG/keras-bi-lm
keras_bi_lm/model.py
https://github.com/CyberZHG/keras-bi-lm/blob/615e1131052d488420d759bab2370d504c9fc074/keras_bi_lm/model.py#L168-L203
def get_batch(sentences, token_dict, ignore_case=False, unk_index=1, eos_index=2): """Get a batch of inputs and outputs from given sentences. :param sentences: A list of list of tokens. :param token_dict: The dict that maps...
[ "def", "get_batch", "(", "sentences", ",", "token_dict", ",", "ignore_case", "=", "False", ",", "unk_index", "=", "1", ",", "eos_index", "=", "2", ")", ":", "batch_size", "=", "len", "(", "sentences", ")", "max_sentence_len", "=", "max", "(", "map", "(",...
Get a batch of inputs and outputs from given sentences. :param sentences: A list of list of tokens. :param token_dict: The dict that maps a token to an integer. `<UNK>` and `<EOS>` should be preserved. :param ignore_case: Whether ignoring the case of the token. :param unk_index: The ind...
[ "Get", "a", "batch", "of", "inputs", "and", "outputs", "from", "given", "sentences", "." ]
python
train
reflexsc/reflex
src/rfxmon/__init__.py
https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/src/rfxmon/__init__.py#L122-L130
def feed_monitors(self): """ Pull from the cached monitors data and feed the workers queue. Run every interval (refresh:test). """ self.thread_debug("Filling worker queue...", module='feed_monitors') for mon in self.monitors: self.thread_debug(" Adding " +...
[ "def", "feed_monitors", "(", "self", ")", ":", "self", ".", "thread_debug", "(", "\"Filling worker queue...\"", ",", "module", "=", "'feed_monitors'", ")", "for", "mon", "in", "self", ".", "monitors", ":", "self", ".", "thread_debug", "(", "\" Adding \"", "...
Pull from the cached monitors data and feed the workers queue. Run every interval (refresh:test).
[ "Pull", "from", "the", "cached", "monitors", "data", "and", "feed", "the", "workers", "queue", ".", "Run", "every", "interval", "(", "refresh", ":", "test", ")", "." ]
python
train
noirbizarre/django.js
djangojs/templatetags/js.py
https://github.com/noirbizarre/django.js/blob/65b267b04ffc0f969b9f8e2f8ce2f922397c8af1/djangojs/templatetags/js.py#L156-L163
def jquery_js(version=None, migrate=False): '''A shortcut to render a ``script`` tag for the packaged jQuery''' version = version or settings.JQUERY_VERSION suffix = '.min' if not settings.DEBUG else '' libs = [js_lib('jquery-%s%s.js' % (version, suffix))] if _boolean(migrate): libs.append(j...
[ "def", "jquery_js", "(", "version", "=", "None", ",", "migrate", "=", "False", ")", ":", "version", "=", "version", "or", "settings", ".", "JQUERY_VERSION", "suffix", "=", "'.min'", "if", "not", "settings", ".", "DEBUG", "else", "''", "libs", "=", "[", ...
A shortcut to render a ``script`` tag for the packaged jQuery
[ "A", "shortcut", "to", "render", "a", "script", "tag", "for", "the", "packaged", "jQuery" ]
python
train
dturanski/springcloudstream
springcloudstream/tcp/stream.py
https://github.com/dturanski/springcloudstream/blob/208b542f9eba82e97882d52703af8e965a62a980/springcloudstream/tcp/stream.py#L96-L112
def validate(self,options): """ Validate the options or exit() """ if not options.port: self.parser.error("'port' is required") if options.port == options.monitor_port: self.parser.error("'port' and 'monitor-port' must not be the same.") if options...
[ "def", "validate", "(", "self", ",", "options", ")", ":", "if", "not", "options", ".", "port", ":", "self", ".", "parser", ".", "error", "(", "\"'port' is required\"", ")", "if", "options", ".", "port", "==", "options", ".", "monitor_port", ":", "self", ...
Validate the options or exit()
[ "Validate", "the", "options", "or", "exit", "()" ]
python
train
wiheto/teneto
teneto/plot/slice_plot.py
https://github.com/wiheto/teneto/blob/80d7a83a9adc1714589b020627c45bd5b66248ab/teneto/plot/slice_plot.py#L6-L181
def slice_plot(netin, ax, nodelabels=None, timelabels=None, communities=None, plotedgeweights=False, edgeweightscalar=1, timeunit='', linestyle='k-', cmap=None, nodesize=100, nodekwargs=None, edgekwargs=None): r''' Fuction draws "slice graph" and exports axis handles Parameters ---------- netin ...
[ "def", "slice_plot", "(", "netin", ",", "ax", ",", "nodelabels", "=", "None", ",", "timelabels", "=", "None", ",", "communities", "=", "None", ",", "plotedgeweights", "=", "False", ",", "edgeweightscalar", "=", "1", ",", "timeunit", "=", "''", ",", "line...
r''' Fuction draws "slice graph" and exports axis handles Parameters ---------- netin : array, dict temporal network input (graphlet or contact) ax : matplotlib figure handles. nodelabels : list nodes labels. List of strings. timelabels : list labels of dimension ...
[ "r" ]
python
train
pywbem/pywbem
pywbem/tupleparse.py
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem/tupleparse.py#L1133-L1169
def parse_instance(self, tup_tree): """ Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.RE...
[ "def", "parse_instance", "(", "self", ",", "tup_tree", ")", ":", "self", ".", "check_node", "(", "tup_tree", ",", "'INSTANCE'", ",", "(", "'CLASSNAME'", ",", ")", ",", "(", "'xml:lang'", ",", ")", ",", "(", "'QUALIFIER'", ",", "'PROPERTY'", ",", "'PROPER...
Return a CIMInstance. The instance contains the properties, qualifiers and classname for the instance. :: <!ELEMENT INSTANCE (QUALIFIER*, (PROPERTY | PROPERTY.ARRAY | PROPERTY.REFERENCE)*)> <!ATTLIST INSTANCE ...
[ "Return", "a", "CIMInstance", "." ]
python
train
dereneaton/ipyrad
ipyrad/analysis/twiist.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/twiist.py#L273-L281
def get_order(tre): """ return tree order """ anode = tre.tree&">A" sister = anode.get_sisters()[0] sisters = (anode.name[1:], sister.name[1:]) others = [i for i in list("ABCD") if i not in sisters] return sorted(sisters) + sorted(others)
[ "def", "get_order", "(", "tre", ")", ":", "anode", "=", "tre", ".", "tree", "&", "\">A\"", "sister", "=", "anode", ".", "get_sisters", "(", ")", "[", "0", "]", "sisters", "=", "(", "anode", ".", "name", "[", "1", ":", "]", ",", "sister", ".", "...
return tree order
[ "return", "tree", "order" ]
python
valid
SALib/SALib
src/SALib/analyze/ff.py
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/ff.py#L84-L106
def to_df(self): '''Conversion method to Pandas DataFrame. To be attached to ResultDict. Returns ------- main_effect, inter_effect: tuple A tuple of DataFrames for main effects and interaction effects. The second element (for interactions) will be `None` if not available. ''' na...
[ "def", "to_df", "(", "self", ")", ":", "names", "=", "self", "[", "'names'", "]", "main_effect", "=", "self", "[", "'ME'", "]", "interactions", "=", "self", ".", "get", "(", "'IE'", ",", "None", ")", "inter_effect", "=", "None", "if", "interactions", ...
Conversion method to Pandas DataFrame. To be attached to ResultDict. Returns ------- main_effect, inter_effect: tuple A tuple of DataFrames for main effects and interaction effects. The second element (for interactions) will be `None` if not available.
[ "Conversion", "method", "to", "Pandas", "DataFrame", ".", "To", "be", "attached", "to", "ResultDict", "." ]
python
train
BlackEarth/bl
bl/config.py
https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/config.py#L76-L103
def write(self, fn=None, sorted=False, wait=0): """write the contents of this config to fn or its __filename__. """ config = ConfigParser(interpolation=None) if sorted==True: keys.sort() for key in self.__dict__.get('ordered_keys') or self.keys(): config[key] = ...
[ "def", "write", "(", "self", ",", "fn", "=", "None", ",", "sorted", "=", "False", ",", "wait", "=", "0", ")", ":", "config", "=", "ConfigParser", "(", "interpolation", "=", "None", ")", "if", "sorted", "==", "True", ":", "keys", ".", "sort", "(", ...
write the contents of this config to fn or its __filename__.
[ "write", "the", "contents", "of", "this", "config", "to", "fn", "or", "its", "__filename__", "." ]
python
train
rushter/heamy
heamy/dataset.py
https://github.com/rushter/heamy/blob/c330854cee3c547417eb353a4a4a23331b40b4bc/heamy/dataset.py#L262-L280
def hash(self): """Return md5 hash for current dataset.""" if self._hash is None: m = hashlib.new('md5') if self._preprocessor is None: # generate hash from numpy array m.update(numpy_buffer(self._X_train)) m.update(numpy_buffer(sel...
[ "def", "hash", "(", "self", ")", ":", "if", "self", ".", "_hash", "is", "None", ":", "m", "=", "hashlib", ".", "new", "(", "'md5'", ")", "if", "self", ".", "_preprocessor", "is", "None", ":", "# generate hash from numpy array", "m", ".", "update", "(",...
Return md5 hash for current dataset.
[ "Return", "md5", "hash", "for", "current", "dataset", "." ]
python
train
senaite/senaite.core
bika/lims/content/instrumentcertification.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/instrumentcertification.py#L276-L299
def getDaysToExpire(self): """Returns the days until this certificate expires :returns: Days until the certificate expires :rtype: int """ delta = 0 today = DateTime() valid_from = self.getValidFrom() or today valid_to = self.getValidTo() # one ...
[ "def", "getDaysToExpire", "(", "self", ")", ":", "delta", "=", "0", "today", "=", "DateTime", "(", ")", "valid_from", "=", "self", ".", "getValidFrom", "(", ")", "or", "today", "valid_to", "=", "self", ".", "getValidTo", "(", ")", "# one of the fields is n...
Returns the days until this certificate expires :returns: Days until the certificate expires :rtype: int
[ "Returns", "the", "days", "until", "this", "certificate", "expires" ]
python
train
klahnakoski/pyLibrary
mo_math/vendor/strangman/stats.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L325-L351
def mode(inlist): """ Returns a list of the modal (most common) score(s) in the passed list. If there is more than one such score, all are returned. The bin-count for the mode(s) is also returned. Usage: lmode(inlist) Returns: bin-count for mode(s), a list of modal value(s) """ scores = pstat.unique(inlis...
[ "def", "mode", "(", "inlist", ")", ":", "scores", "=", "pstat", ".", "unique", "(", "inlist", ")", "scores", ".", "sort", "(", ")", "freq", "=", "[", "]", "for", "item", "in", "scores", ":", "freq", ".", "append", "(", "inlist", ".", "count", "("...
Returns a list of the modal (most common) score(s) in the passed list. If there is more than one such score, all are returned. The bin-count for the mode(s) is also returned. Usage: lmode(inlist) Returns: bin-count for mode(s), a list of modal value(s)
[ "Returns", "a", "list", "of", "the", "modal", "(", "most", "common", ")", "score", "(", "s", ")", "in", "the", "passed", "list", ".", "If", "there", "is", "more", "than", "one", "such", "score", "all", "are", "returned", ".", "The", "bin", "-", "co...
python
train
gitpython-developers/GitPython
git/index/base.py
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/index/base.py#L524-L547
def write_tree(self): """Writes this index to a corresponding Tree object into the repository's object database and return it. :return: Tree object representing this index :note: The tree will be written even if one or more objects the tree refers to does not yet exist in th...
[ "def", "write_tree", "(", "self", ")", ":", "# we obtain no lock as we just flush our contents to disk as tree", "# If we are a new index, the entries access will load our data accordingly", "mdb", "=", "MemoryDB", "(", ")", "entries", "=", "self", ".", "_entries_sorted", "(", ...
Writes this index to a corresponding Tree object into the repository's object database and return it. :return: Tree object representing this index :note: The tree will be written even if one or more objects the tree refers to does not yet exist in the object database. This could hap...
[ "Writes", "this", "index", "to", "a", "corresponding", "Tree", "object", "into", "the", "repository", "s", "object", "database", "and", "return", "it", "." ]
python
train
openego/eTraGo
etrago/tools/io.py
https://github.com/openego/eTraGo/blob/2a8fc6d4368d0e9abe6fe0d0c39baf66ea0126b9/etrago/tools/io.py#L693-L701
def run_sql_script(conn, scriptname='results_md2grid.sql'): """This function runs .sql scripts in the folder 'sql_scripts' """ script_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), 'sql_scripts')) script_str = open(os.path.join(script_dir, scriptname)).read() conn.execution_opti...
[ "def", "run_sql_script", "(", "conn", ",", "scriptname", "=", "'results_md2grid.sql'", ")", ":", "script_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",...
This function runs .sql scripts in the folder 'sql_scripts'
[ "This", "function", "runs", ".", "sql", "scripts", "in", "the", "folder", "sql_scripts" ]
python
train
klahnakoski/pyLibrary
mo_math/vendor/strangman/stats.py
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L667-L676
def sem(inlist): """ Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist) """ sd = stdev(inlist) n = len(inlist) return sd / math.sqrt(n)
[ "def", "sem", "(", "inlist", ")", ":", "sd", "=", "stdev", "(", "inlist", ")", "n", "=", "len", "(", "inlist", ")", "return", "sd", "/", "math", ".", "sqrt", "(", "n", ")" ]
Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist)
[ "Returns", "the", "estimated", "standard", "error", "of", "the", "mean", "(", "sx", "-", "bar", ")", "of", "the", "values", "in", "the", "passed", "list", ".", "sem", "=", "stdev", "/", "sqrt", "(", "n", ")" ]
python
train
onnx/onnxmltools
onnxutils/onnxconverter_common/topology.py
https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxutils/onnxconverter_common/topology.py#L232-L241
def delete_local_variable(self, onnx_name): ''' Remove the variable whose onnx_name is the input onnx_name ''' if onnx_name not in self.onnx_variable_names or onnx_name not in self.variables: raise RuntimeError('The variable to be removed not found') self.onnx_variabl...
[ "def", "delete_local_variable", "(", "self", ",", "onnx_name", ")", ":", "if", "onnx_name", "not", "in", "self", ".", "onnx_variable_names", "or", "onnx_name", "not", "in", "self", ".", "variables", ":", "raise", "RuntimeError", "(", "'The variable to be removed n...
Remove the variable whose onnx_name is the input onnx_name
[ "Remove", "the", "variable", "whose", "onnx_name", "is", "the", "input", "onnx_name" ]
python
train
CenturyLinkCloud/clc-python-sdk
src/clc/APIv2/server.py
https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/server.py#L495-L519
def DeleteSnapshot(self,names=None): """Removes an existing Hypervisor level snapshot. Supply one or more snapshot names to delete them concurrently. If no snapshot names are supplied will delete all existing snapshots. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').DeleteSnapshot().WaitUntilComplete() 0...
[ "def", "DeleteSnapshot", "(", "self", ",", "names", "=", "None", ")", ":", "if", "names", "is", "None", ":", "names", "=", "self", ".", "GetSnapshots", "(", ")", "requests_lst", "=", "[", "]", "for", "name", "in", "names", ":", "name_links", "=", "["...
Removes an existing Hypervisor level snapshot. Supply one or more snapshot names to delete them concurrently. If no snapshot names are supplied will delete all existing snapshots. >>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').DeleteSnapshot().WaitUntilComplete() 0
[ "Removes", "an", "existing", "Hypervisor", "level", "snapshot", "." ]
python
train
joke2k/faker
faker/providers/python/__init__.py
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/python/__init__.py#L141-L155
def pydict(self, nb_elements=10, variable_nb_elements=True, *value_types): """ Returns a dictionary. :nb_elements: number of elements for dictionary :variable_nb_elements: is use variable number of elements for dictionary :value_types: type of dictionary values """ ...
[ "def", "pydict", "(", "self", ",", "nb_elements", "=", "10", ",", "variable_nb_elements", "=", "True", ",", "*", "value_types", ")", ":", "if", "variable_nb_elements", ":", "nb_elements", "=", "self", ".", "randomize_nb_elements", "(", "nb_elements", ",", "min...
Returns a dictionary. :nb_elements: number of elements for dictionary :variable_nb_elements: is use variable number of elements for dictionary :value_types: type of dictionary values
[ "Returns", "a", "dictionary", "." ]
python
train
timothycrosley/blox
blox/text.py
https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/text.py#L49-L51
def output(self, to=None, *args, **kwargs): '''Outputs the set text''' to.write(str(self._value))
[ "def", "output", "(", "self", ",", "to", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "to", ".", "write", "(", "str", "(", "self", ".", "_value", ")", ")" ]
Outputs the set text
[ "Outputs", "the", "set", "text" ]
python
valid
tornadoweb/tornado
tornado/routing.py
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/routing.py#L193-L205
def find_handler( self, request: httputil.HTTPServerRequest, **kwargs: Any ) -> Optional[httputil.HTTPMessageDelegate]: """Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional...
[ "def", "find_handler", "(", "self", ",", "request", ":", "httputil", ".", "HTTPServerRequest", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Optional", "[", "httputil", ".", "HTTPMessageDelegate", "]", ":", "raise", "NotImplementedError", "(", ")" ]
Must be implemented to return an appropriate instance of `~.httputil.HTTPMessageDelegate` that can serve the request. Routing implementations may pass additional kwargs to extend the routing logic. :arg httputil.HTTPServerRequest request: current HTTP request. :arg kwargs: additional ke...
[ "Must", "be", "implemented", "to", "return", "an", "appropriate", "instance", "of", "~", ".", "httputil", ".", "HTTPMessageDelegate", "that", "can", "serve", "the", "request", ".", "Routing", "implementations", "may", "pass", "additional", "kwargs", "to", "exten...
python
train
openpaperwork/paperwork-backend
paperwork_backend/util.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/util.py#L263-L287
def image2surface(img): """ Convert a PIL image into a Cairo surface """ if not CAIRO_AVAILABLE: raise Exception("Cairo not available(). image2surface() cannot work.") # TODO(Jflesch): Python 3 problem # cairo.ImageSurface.create_for_data() raises NotImplementedYet ... # img.putalp...
[ "def", "image2surface", "(", "img", ")", ":", "if", "not", "CAIRO_AVAILABLE", ":", "raise", "Exception", "(", "\"Cairo not available(). image2surface() cannot work.\"", ")", "# TODO(Jflesch): Python 3 problem", "# cairo.ImageSurface.create_for_data() raises NotImplementedYet ...", ...
Convert a PIL image into a Cairo surface
[ "Convert", "a", "PIL", "image", "into", "a", "Cairo", "surface" ]
python
train
ev3dev/ev3dev-lang-python
ev3dev2/motor.py
https://github.com/ev3dev/ev3dev-lang-python/blob/afc98d35004b533dc161a01f7c966e78607d7c1e/ev3dev2/motor.py#L591-L598
def max_speed(self): """ Returns the maximum value that is accepted by the `speed_sp` attribute. This may be slightly different than the maximum speed that a particular motor can reach - it's the maximum theoretical speed. """ (self._max_speed, value) = self.get_cached_at...
[ "def", "max_speed", "(", "self", ")", ":", "(", "self", ".", "_max_speed", ",", "value", ")", "=", "self", ".", "get_cached_attr_int", "(", "self", ".", "_max_speed", ",", "'max_speed'", ")", "return", "value" ]
Returns the maximum value that is accepted by the `speed_sp` attribute. This may be slightly different than the maximum speed that a particular motor can reach - it's the maximum theoretical speed.
[ "Returns", "the", "maximum", "value", "that", "is", "accepted", "by", "the", "speed_sp", "attribute", ".", "This", "may", "be", "slightly", "different", "than", "the", "maximum", "speed", "that", "a", "particular", "motor", "can", "reach", "-", "it", "s", ...
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/serializer/xml.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/serializer/xml.py#L111-L124
def serialize_value(self, parent_elem, value): """ Serializes str, Attrib, or PathAttrib objects. Example:: <attribute>foobar</attribute> """ if isinstance(value, (str, int)) or type(value).__name__ == 'str': parent_elem.text = str(value) elif va...
[ "def", "serialize_value", "(", "self", ",", "parent_elem", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "str", ",", "int", ")", ")", "or", "type", "(", "value", ")", ".", "__name__", "==", "'str'", ":", "parent_elem", ".", "tex...
Serializes str, Attrib, or PathAttrib objects. Example:: <attribute>foobar</attribute>
[ "Serializes", "str", "Attrib", "or", "PathAttrib", "objects", "." ]
python
valid
FlorianRhiem/pyGLFW
glfw/__init__.py
https://github.com/FlorianRhiem/pyGLFW/blob/87767dfbe15ba15d2a8338cdfddf6afc6a25dff5/glfw/__init__.py#L983-L995
def get_window_size(window): """ Retrieves the size of the client area of the specified window. Wrapper for: void glfwGetWindowSize(GLFWwindow* window, int* width, int* height); """ width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) ...
[ "def", "get_window_size", "(", "window", ")", ":", "width_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "width", "=", "ctypes", ".", "pointer", "(", "width_value", ")", "height_value", "=", "ctypes", ".", "c_int", "(", "0", ")", "height", "=", "c...
Retrieves the size of the client area of the specified window. Wrapper for: void glfwGetWindowSize(GLFWwindow* window, int* width, int* height);
[ "Retrieves", "the", "size", "of", "the", "client", "area", "of", "the", "specified", "window", "." ]
python
train
googlefonts/fontbakery
Lib/fontbakery/profiles/universal.py
https://github.com/googlefonts/fontbakery/blob/b355aea2e619a4477769e060d24c32448aa65399/Lib/fontbakery/profiles/universal.py#L559-L586
def com_google_fonts_check_mandatory_glyphs(ttFont): """Font contains .notdef as first glyph? The OpenType specification v1.8.2 recommends that the first glyph is the .notdef glyph without a codepoint assigned and with a drawing. https://docs.microsoft.com/en-us/typography/opentype/spec/recom#glyph-0-the-notd...
[ "def", "com_google_fonts_check_mandatory_glyphs", "(", "ttFont", ")", ":", "from", "fontbakery", ".", "utils", "import", "glyph_has_ink", "if", "(", "ttFont", ".", "getGlyphOrder", "(", ")", "[", "0", "]", "==", "\".notdef\"", "and", "\".notdef\"", "not", "in", ...
Font contains .notdef as first glyph? The OpenType specification v1.8.2 recommends that the first glyph is the .notdef glyph without a codepoint assigned and with a drawing. https://docs.microsoft.com/en-us/typography/opentype/spec/recom#glyph-0-the-notdef-glyph Pre-v1.8, it was recommended that a font shoul...
[ "Font", "contains", ".", "notdef", "as", "first", "glyph?" ]
python
train
facelessuser/pyspelling
pyspelling/filters/__init__.py
https://github.com/facelessuser/pyspelling/blob/c25d5292cc2687ad65891a12ead43f7182ca8bb3/pyspelling/filters/__init__.py#L201-L222
def _guess(self, filename): """Guess the encoding and decode the content of the file.""" encoding = None file_size = os.path.getsize(filename) # If the file is really big, lets just call it binary. # We don't have time to let Python chug through a massive file. if not s...
[ "def", "_guess", "(", "self", ",", "filename", ")", ":", "encoding", "=", "None", "file_size", "=", "os", ".", "path", ".", "getsize", "(", "filename", ")", "# If the file is really big, lets just call it binary.", "# We don't have time to let Python chug through a massiv...
Guess the encoding and decode the content of the file.
[ "Guess", "the", "encoding", "and", "decode", "the", "content", "of", "the", "file", "." ]
python
train
genicam/harvesters
src/harvesters/core.py
https://github.com/genicam/harvesters/blob/c3314a7f9d320bbf943e599aabac02521cd8e80b/src/harvesters/core.py#L714-L725
def x_offset(self): # TODO: Check the naming convention. """ :return: The X offset of the data in the buffer in number of pixels from the image origin to handle areas of interest. """ try: if self._part: value = self._part.x_offset else: ...
[ "def", "x_offset", "(", "self", ")", ":", "# TODO: Check the naming convention.", "try", ":", "if", "self", ".", "_part", ":", "value", "=", "self", ".", "_part", ".", "x_offset", "else", ":", "value", "=", "self", ".", "_buffer", ".", "offset_x", "except"...
:return: The X offset of the data in the buffer in number of pixels from the image origin to handle areas of interest.
[ ":", "return", ":", "The", "X", "offset", "of", "the", "data", "in", "the", "buffer", "in", "number", "of", "pixels", "from", "the", "image", "origin", "to", "handle", "areas", "of", "interest", "." ]
python
valid
beetbox/audioread
audioread/rawread.py
https://github.com/beetbox/audioread/blob/c8bedf7880f13a7b7488b108aaf245d648674818/audioread/rawread.py#L43-L54
def byteswap(s): """Swaps the endianness of the bytesting s, which must be an array of shorts (16-bit signed integers). This is probably less efficient than it should be. """ assert len(s) % 2 == 0 parts = [] for i in range(0, len(s), 2): chunk = s[i:i + 2] newchunk = struct....
[ "def", "byteswap", "(", "s", ")", ":", "assert", "len", "(", "s", ")", "%", "2", "==", "0", "parts", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "2", ")", ":", "chunk", "=", "s", "[", "i", ":", "i...
Swaps the endianness of the bytesting s, which must be an array of shorts (16-bit signed integers). This is probably less efficient than it should be.
[ "Swaps", "the", "endianness", "of", "the", "bytesting", "s", "which", "must", "be", "an", "array", "of", "shorts", "(", "16", "-", "bit", "signed", "integers", ")", ".", "This", "is", "probably", "less", "efficient", "than", "it", "should", "be", "." ]
python
train
aws/aws-xray-sdk-python
aws_xray_sdk/ext/botocore/patch.py
https://github.com/aws/aws-xray-sdk-python/blob/707358cd3a516d51f2ebf71cf34f00e8d906a667/aws_xray_sdk/ext/botocore/patch.py#L8-L27
def patch(): """ Patch botocore client so it generates subsegments when calling AWS services. """ if hasattr(botocore.client, '_xray_enabled'): return setattr(botocore.client, '_xray_enabled', True) wrapt.wrap_function_wrapper( 'botocore.client', 'BaseClient._make_ap...
[ "def", "patch", "(", ")", ":", "if", "hasattr", "(", "botocore", ".", "client", ",", "'_xray_enabled'", ")", ":", "return", "setattr", "(", "botocore", ".", "client", ",", "'_xray_enabled'", ",", "True", ")", "wrapt", ".", "wrap_function_wrapper", "(", "'b...
Patch botocore client so it generates subsegments when calling AWS services.
[ "Patch", "botocore", "client", "so", "it", "generates", "subsegments", "when", "calling", "AWS", "services", "." ]
python
train
titusjan/argos
argos/config/qtctis.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/config/qtctis.py#L41-L51
def createPenStyleCti(nodeName, defaultData=0, includeNone=False): """ Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None. """ displayValues=PEN_STYLE_DISPLAY_VALUES configValues=PEN_STYLE_CONFIG_VALUES if includeNone: displayValues = [''] +...
[ "def", "createPenStyleCti", "(", "nodeName", ",", "defaultData", "=", "0", ",", "includeNone", "=", "False", ")", ":", "displayValues", "=", "PEN_STYLE_DISPLAY_VALUES", "configValues", "=", "PEN_STYLE_CONFIG_VALUES", "if", "includeNone", ":", "displayValues", "=", "...
Creates a ChoiceCti with Qt PenStyles. If includeEmtpy is True, the first option will be None.
[ "Creates", "a", "ChoiceCti", "with", "Qt", "PenStyles", ".", "If", "includeEmtpy", "is", "True", "the", "first", "option", "will", "be", "None", "." ]
python
train