repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
mitsei/dlkit
dlkit/records/osid/base_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/osid/base_records.py#L1013-L1017
def clear_text(self, label): """stub""" if label not in self.my_osid_object_form._my_map['texts']: raise NotFound() del self.my_osid_object_form._my_map['texts'][label]
[ "def", "clear_text", "(", "self", ",", "label", ")", ":", "if", "label", "not", "in", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'texts'", "]", ":", "raise", "NotFound", "(", ")", "del", "self", ".", "my_osid_object_form", ".", "_my_map", ...
stub
[ "stub" ]
python
train
40
annoviko/pyclustering
pyclustering/cluster/optics.py
https://github.com/annoviko/pyclustering/blob/98aa0dd89fd36f701668fb1eb29c8fb5662bf7d0/pyclustering/cluster/optics.py#L445-L461
def __process_by_python(self): """! @brief Performs cluster analysis using python code. """ if self.__data_type == 'points': self.__kdtree = kdtree(self.__sample_pointer, range(len(self.__sample_pointer))) self.__allocate_clusters() if (self.__a...
[ "def", "__process_by_python", "(", "self", ")", ":", "if", "self", ".", "__data_type", "==", "'points'", ":", "self", ".", "__kdtree", "=", "kdtree", "(", "self", ".", "__sample_pointer", ",", "range", "(", "len", "(", "self", ".", "__sample_pointer", ")",...
! @brief Performs cluster analysis using python code.
[ "!" ]
python
valid
38.705882
lxc/python2-lxc
lxc/__init__.py
https://github.com/lxc/python2-lxc/blob/b7ec757d2bea1e5787c3e65b1359b8893491ef90/lxc/__init__.py#L289-L301
def get_config_item(self, key): """ Returns the value for a given config key. A list is returned when multiple values are set. """ value = _lxc.Container.get_config_item(self, key) if value is False: return False elif value.endswith("\n"): ...
[ "def", "get_config_item", "(", "self", ",", "key", ")", ":", "value", "=", "_lxc", ".", "Container", ".", "get_config_item", "(", "self", ",", "key", ")", "if", "value", "is", "False", ":", "return", "False", "elif", "value", ".", "endswith", "(", "\"\...
Returns the value for a given config key. A list is returned when multiple values are set.
[ "Returns", "the", "value", "for", "a", "given", "config", "key", ".", "A", "list", "is", "returned", "when", "multiple", "values", "are", "set", "." ]
python
train
30.230769
nickmckay/LiPD-utilities
Python/lipd/excel.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L515-L558
def _create_skeleton_3(pc, l, num_section): """ Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]} Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions. :param str pc: Paleo or Chron "mode" :param list l: :param dict...
[ "def", "_create_skeleton_3", "(", "pc", ",", "l", ",", "num_section", ")", ":", "logger_excel", ".", "info", "(", "\"enter create_skeleton_inner_2\"", ")", "# Table Template: Model", "template_model", "=", "{", "\"summaryTable\"", ":", "{", "}", ",", "\"ensembleTabl...
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]} Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions. :param str pc: Paleo or Chron "mode" :param list l: :param dict num_section: :return dict:
[ "Bottom", "level", ":", "{", "measurement", ":", "[]", "model", ":", "[", "{", "summary", "distributions", "ensemble", "}", "]", "}", "Fill", "in", "measurement", "and", "model", "tables", "with", "N", "number", "of", "EMPTY", "meas", "summary", "ensemble"...
python
train
43.636364
aestrivex/bctpy
bct/algorithms/core.py
https://github.com/aestrivex/bctpy/blob/4cb0e759eb4a038750b07e23bd29958c400684b8/bct/algorithms/core.py#L595-L633
def score_wu(CIJ, s): ''' The s-core is the largest subnetwork comprising nodes of strength at least s. This function computes the s-core for a given weighted undirected connection matrix. Computation is analogous to the more widely used k-core, but is based on node strengths instead of node deg...
[ "def", "score_wu", "(", "CIJ", ",", "s", ")", ":", "CIJscore", "=", "CIJ", ".", "copy", "(", ")", "while", "True", ":", "str", "=", "strengths_und", "(", "CIJscore", ")", "# get strengths of matrix", "# find nodes with strength <s", "ff", ",", "=", "np", "...
The s-core is the largest subnetwork comprising nodes of strength at least s. This function computes the s-core for a given weighted undirected connection matrix. Computation is analogous to the more widely used k-core, but is based on node strengths instead of node degrees. Parameters --------...
[ "The", "s", "-", "core", "is", "the", "largest", "subnetwork", "comprising", "nodes", "of", "strength", "at", "least", "s", ".", "This", "function", "computes", "the", "s", "-", "core", "for", "a", "given", "weighted", "undirected", "connection", "matrix", ...
python
train
28.179487
StackStorm/pybind
pybind/slxos/v17s_1_02/brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/__init__.py
https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/__init__.py#L292-L316
def _set_config_src(self, v, load=False): """ Setter method for config_src, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/config_src (config-src-type) If this variable is read-only (config: false) in the source YANG file, then _set_config_src is considered as a private...
[ "def", "_set_config_src", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "bas...
Setter method for config_src, mapped from YANG variable /brocade_tunnels_ext_rpc/get_tunnel_info/output/tunnel/config_src (config-src-type) If this variable is read-only (config: false) in the source YANG file, then _set_config_src is considered as a private method. Backends looking to populate this variabl...
[ "Setter", "method", "for", "config_src", "mapped", "from", "YANG", "variable", "/", "brocade_tunnels_ext_rpc", "/", "get_tunnel_info", "/", "output", "/", "tunnel", "/", "config_src", "(", "config", "-", "src", "-", "type", ")", "If", "this", "variable", "is",...
python
train
82.04
hotdoc/hotdoc
hotdoc/extensions/c/clang/cindex.py
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L500-L530
def get_tokens(tu, extent): """Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place. """ tokens_memory = POINTER(Token)() tokens_count = c_uint() con...
[ "def", "get_tokens", "(", "tu", ",", "extent", ")", ":", "tokens_memory", "=", "POINTER", "(", "Token", ")", "(", ")", "tokens_count", "=", "c_uint", "(", ")", "conf", ".", "lib", ".", "clang_tokenize", "(", "tu", ",", "extent", ",", "byref", "(", "t...
Helper method to return all tokens in an extent. This functionality is needed multiple places in this module. We define it here because it seems like a logical place.
[ "Helper", "method", "to", "return", "all", "tokens", "in", "an", "extent", "." ]
python
train
32.709677
MakerReduxCorp/MARDS
MARDS/mards_library.py
https://github.com/MakerReduxCorp/MARDS/blob/f8ddecc70f2ce1703984cb403c9d5417895170d6/MARDS/mards_library.py#L204-L238
def value_output(value, quote_method='all', none_handle='strict'): ''' Format types: 'all'. (default) everything is embraced with quotes 'needed'. Quote only if needed. Values are on placed in quotes if: a. the value contains a quote b. there is whitespace at the beginning or...
[ "def", "value_output", "(", "value", ",", "quote_method", "=", "'all'", ",", "none_handle", "=", "'strict'", ")", ":", "p", "=", "str", "(", "value", ")", "if", "value", "is", "None", ":", "if", "none_handle", "==", "'strict'", ":", "return", "\"\"", "...
Format types: 'all'. (default) everything is embraced with quotes 'needed'. Quote only if needed. Values are on placed in quotes if: a. the value contains a quote b. there is whitespace at the beginning or end of string 'none'. Quote nothing.
[ "Format", "types", ":", "all", ".", "(", "default", ")", "everything", "is", "embraced", "with", "quotes", "needed", ".", "Quote", "only", "if", "needed", ".", "Values", "are", "on", "placed", "in", "quotes", "if", ":", "a", ".", "the", "value", "conta...
python
train
28.657143
OrkoHunter/keep
keep/cli.py
https://github.com/OrkoHunter/keep/blob/2253c60b4024c902115ae0472227059caee4a5eb/keep/cli.py#L22-L25
def vlog(self, msg, *args): """Logs a message to stderr only if verbose is enabled.""" if self.verbose: self.log(msg, *args)
[ "def", "vlog", "(", "self", ",", "msg", ",", "*", "args", ")", ":", "if", "self", ".", "verbose", ":", "self", ".", "log", "(", "msg", ",", "*", "args", ")" ]
Logs a message to stderr only if verbose is enabled.
[ "Logs", "a", "message", "to", "stderr", "only", "if", "verbose", "is", "enabled", "." ]
python
train
37.25
yero13/na3x
na3x/db/data.py
https://github.com/yero13/na3x/blob/b31ef801ea574081125020a7d0f9c4242f8f8b02/na3x/db/data.py#L94-L106
def factory(db, collection, action): """ Instantiate trigger :param db: db descriptor :param collection: collection to be updated :param action: ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE :return: trigger instance if trigger confi...
[ "def", "factory", "(", "db", ",", "collection", ",", "action", ")", ":", "triggers_cfg", "=", "na3x_cfg", "[", "NA3X_TRIGGERS", "]", "if", "(", "collection", "in", "triggers_cfg", ")", "and", "(", "action", "in", "triggers_cfg", "[", "collection", "]", ")"...
Instantiate trigger :param db: db descriptor :param collection: collection to be updated :param action: ACTION_BEFORE_DELETE, ACTION_AFTER_DELETE, ACTION_BEFORE_UPSERT, ACTION_AFTER_DELETE :return: trigger instance if trigger configured in triggers.json or None
[ "Instantiate", "trigger", ":", "param", "db", ":", "db", "descriptor", ":", "param", "collection", ":", "collection", "to", "be", "updated", ":", "param", "action", ":", "ACTION_BEFORE_DELETE", "ACTION_AFTER_DELETE", "ACTION_BEFORE_UPSERT", "ACTION_AFTER_DELETE", ":",...
python
train
46.076923
spotify/gordon-gcp
src/gordon_gcp/plugins/service/__init__.py
https://github.com/spotify/gordon-gcp/blob/5ab19e3c2fe6ace72ee91e2ef1a1326f90b805da/src/gordon_gcp/plugins/service/__init__.py#L83-L100
def get_gdns_publisher(config, metrics, **kwargs): """Get a GDNSPublisher client. A factory function that validates configuration and returns a publisher client (:interface:`gordon.interfaces.IMessageHandler`) provider. Args: config (dict): Google Cloud DNS API related configuration. ...
[ "def", "get_gdns_publisher", "(", "config", ",", "metrics", ",", "*", "*", "kwargs", ")", ":", "builder", "=", "gdns_publisher", ".", "GDNSPublisherBuilder", "(", "config", ",", "metrics", ",", "*", "*", "kwargs", ")", "return", "builder", ".", "build_publis...
Get a GDNSPublisher client. A factory function that validates configuration and returns a publisher client (:interface:`gordon.interfaces.IMessageHandler`) provider. Args: config (dict): Google Cloud DNS API related configuration. metrics (obj): :interface:`IMetricRelay` implementation...
[ "Get", "a", "GDNSPublisher", "client", "." ]
python
train
35.5
Esri/ArcREST
src/arcrest/manageorg/_content.py
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_content.py#L2146-L2153
def folders(self): '''gets the property value for folders''' if self._folders is None : self.__init() if self._folders is not None and isinstance(self._folders, list): if len(self._folders) == 0: self._loadFolders() return self._folders
[ "def", "folders", "(", "self", ")", ":", "if", "self", ".", "_folders", "is", "None", ":", "self", ".", "__init", "(", ")", "if", "self", ".", "_folders", "is", "not", "None", "and", "isinstance", "(", "self", ".", "_folders", ",", "list", ")", ":"...
gets the property value for folders
[ "gets", "the", "property", "value", "for", "folders" ]
python
train
37.625
pycampers/zproc
zproc/context.py
https://github.com/pycampers/zproc/blob/352a3c7166e2ccc3597c28385a8354b5a22afdc2/zproc/context.py#L34-L61
def wait( self, timeout: Union[int, float] = None, safe: bool = False ) -> List[Union[Any, Exception]]: """ Call :py:meth:`~Process.wait()` on all the Processes in this list. :param timeout: Same as :py:meth:`~Process.wait()`. This parameter controls the tim...
[ "def", "wait", "(", "self", ",", "timeout", ":", "Union", "[", "int", ",", "float", "]", "=", "None", ",", "safe", ":", "bool", "=", "False", ")", "->", "List", "[", "Union", "[", "Any", ",", "Exception", "]", "]", ":", "if", "safe", ":", "_wai...
Call :py:meth:`~Process.wait()` on all the Processes in this list. :param timeout: Same as :py:meth:`~Process.wait()`. This parameter controls the timeout for all the Processes combined, not a single :py:meth:`~Process.wait()` call. :param safe: Suppress...
[ "Call", ":", "py", ":", "meth", ":", "~Process", ".", "wait", "()", "on", "all", "the", "Processes", "in", "this", "list", "." ]
python
train
37.571429
inveniosoftware/invenio-oauthclient
invenio_oauthclient/utils.py
https://github.com/inveniosoftware/invenio-oauthclient/blob/2500dc6935738107617aeade79e050d7608004bb/invenio_oauthclient/utils.py#L147-L165
def get_safe_redirect_target(arg='next'): """Get URL to redirect to and ensure that it is local. :param arg: URL argument. :returns: The redirect target or ``None``. """ for target in request.args.get(arg), request.referrer: if target: redirect_uri = urisplit(target) ...
[ "def", "get_safe_redirect_target", "(", "arg", "=", "'next'", ")", ":", "for", "target", "in", "request", ".", "args", ".", "get", "(", "arg", ")", ",", "request", ".", "referrer", ":", "if", "target", ":", "redirect_uri", "=", "urisplit", "(", "target",...
Get URL to redirect to and ensure that it is local. :param arg: URL argument. :returns: The redirect target or ``None``.
[ "Get", "URL", "to", "redirect", "to", "and", "ensure", "that", "it", "is", "local", "." ]
python
train
36.473684
vimeo/graphite-influxdb
graphite_influxdb.py
https://github.com/vimeo/graphite-influxdb/blob/56e4aeec57f39c90f14f3fbec57641b90d06c08b/graphite_influxdb.py#L166-L186
def _setup_logger(self, level, log_file): """Setup log level and log file if set""" if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( '[%(levelname)s] %(asctime)s - %(module)s.%(funcNam...
[ "def", "_setup_logger", "(", "self", ",", "level", ",", "log_file", ")", ":", "if", "logger", ".", "handlers", ":", "return", "level", "=", "getattr", "(", "logging", ",", "level", ".", "upper", "(", ")", ")", "logger", ".", "setLevel", "(", "level", ...
Setup log level and log file if set
[ "Setup", "log", "level", "and", "log", "file", "if", "set" ]
python
train
37.238095
dmlc/gluon-nlp
scripts/machine_translation/dataprocessor.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/scripts/machine_translation/dataprocessor.py#L33-L49
def _cache_dataset(dataset, prefix): """Cache the processed npy dataset the dataset into a npz Parameters ---------- dataset : SimpleDataset file_path : str """ if not os.path.exists(_constants.CACHE_PATH): os.makedirs(_constants.CACHE_PATH) src_data = np.concatenate([e[0] for e...
[ "def", "_cache_dataset", "(", "dataset", ",", "prefix", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "_constants", ".", "CACHE_PATH", ")", ":", "os", ".", "makedirs", "(", "_constants", ".", "CACHE_PATH", ")", "src_data", "=", "np", "....
Cache the processed npy dataset the dataset into a npz Parameters ---------- dataset : SimpleDataset file_path : str
[ "Cache", "the", "processed", "npy", "dataset", "the", "dataset", "into", "a", "npz" ]
python
train
39.470588
aganezov/gos
gos/manager.py
https://github.com/aganezov/gos/blob/fb4d210284f3037c5321250cb95f3901754feb6b/gos/manager.py#L21-L30
def instantiate_tasks(self): """ All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent """ self.tasks_instances = {} for task_name, task_class in self.tasks_classes.items(): try: self.tasks_instances[task_name] = task_...
[ "def", "instantiate_tasks", "(", "self", ")", ":", "self", ".", "tasks_instances", "=", "{", "}", "for", "task_name", ",", "task_class", "in", "self", ".", "tasks_classes", ".", "items", "(", ")", ":", "try", ":", "self", ".", "tasks_instances", "[", "ta...
All loaded tasks are initialized. Depending on configuration fails in such instantiations may be silent
[ "All", "loaded", "tasks", "are", "initialized", ".", "Depending", "on", "configuration", "fails", "in", "such", "instantiations", "may", "be", "silent" ]
python
train
61.9
libChEBI/libChEBIpy
libchebipy/_parsers.py
https://github.com/libChEBI/libChEBIpy/blob/89f223a91f518619d5e3910070d283adcac1626e/libchebipy/_parsers.py#L425-L447
def get_references(chebi_ids): '''Returns references''' references = [] chebi_ids = [str(chebi_id) for chebi_id in chebi_ids] filename = get_file('reference.tsv.gz') with io.open(filename, 'r', encoding='cp1252') as textfile: next(textfile) for line in textfile: tokens...
[ "def", "get_references", "(", "chebi_ids", ")", ":", "references", "=", "[", "]", "chebi_ids", "=", "[", "str", "(", "chebi_id", ")", "for", "chebi_id", "in", "chebi_ids", "]", "filename", "=", "get_file", "(", "'reference.tsv.gz'", ")", "with", "io", ".",...
Returns references
[ "Returns", "references" ]
python
train
30.217391
Chilipp/psyplot
psyplot/project.py
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/project.py#L70-L77
def _update_versions(): """Update :attr:`_versions` with the registered plotter methods""" for pm_name in plot._plot_methods: pm = getattr(plot, pm_name) plugin = pm._plugin if (plugin is not None and plugin not in _versions and pm.module in sys.modules): _ver...
[ "def", "_update_versions", "(", ")", ":", "for", "pm_name", "in", "plot", ".", "_plot_methods", ":", "pm", "=", "getattr", "(", "plot", ",", "pm_name", ")", "plugin", "=", "pm", ".", "_plugin", "if", "(", "plugin", "is", "not", "None", "and", "plugin",...
Update :attr:`_versions` with the registered plotter methods
[ "Update", ":", "attr", ":", "_versions", "with", "the", "registered", "plotter", "methods" ]
python
train
45.75
inspirehep/inspire-json-merger
inspire_json_merger/utils.py
https://github.com/inspirehep/inspire-json-merger/blob/6af3140fcf7c3f851141c0928eedfe99fddeeda0/inspire_json_merger/utils.py#L147-L153
def filter_records(root, head, update, filters=()): """Apply the filters to the records.""" root, head, update = freeze(root), freeze(head), freeze(update) for filter_ in filters: root, head, update = filter_(root, head, update) return thaw(root), thaw(head), thaw(update)
[ "def", "filter_records", "(", "root", ",", "head", ",", "update", ",", "filters", "=", "(", ")", ")", ":", "root", ",", "head", ",", "update", "=", "freeze", "(", "root", ")", ",", "freeze", "(", "head", ")", ",", "freeze", "(", "update", ")", "f...
Apply the filters to the records.
[ "Apply", "the", "filters", "to", "the", "records", "." ]
python
train
41.571429
AdvancedClimateSystems/uModbus
umodbus/functions.py
https://github.com/AdvancedClimateSystems/uModbus/blob/0560a42308003f4072d988f28042b8d55b694ad4/umodbus/functions.py#L1192-L1204
def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A response PDU. """ _, address, value = \ struct.unpack('>BH' + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, pdu) instance = WriteSingleRegister() instance.address = address ...
[ "def", "create_from_request_pdu", "(", "pdu", ")", ":", "_", ",", "address", ",", "value", "=", "struct", ".", "unpack", "(", "'>BH'", "+", "conf", ".", "MULTI_BIT_VALUE_FORMAT_CHARACTER", ",", "pdu", ")", "instance", "=", "WriteSingleRegister", "(", ")", "i...
Create instance from request PDU. :param pdu: A response PDU.
[ "Create", "instance", "from", "request", "PDU", "." ]
python
train
27.461538
joytunes/JTLocalize
localization_flow/jtlocalize/core/localization_diff.py
https://github.com/joytunes/JTLocalize/blob/87864dc60114e0e61c768d057c6eddfadff3f40a/localization_flow/jtlocalize/core/localization_diff.py#L32-L88
def localization_diff(localizable_file, translated_file, excluded_strings_file, output_translation_file): """ Generates a strings file representing the strings that were yet to be translated. Args: localizable_file (str): The path to the localization strings file, meaning the file that represents the s...
[ "def", "localization_diff", "(", "localizable_file", ",", "translated_file", ",", "excluded_strings_file", ",", "output_translation_file", ")", ":", "old_translated_file_dictionary", "=", "generate_localization_key_to_entry_dictionary_from_file", "(", "translated_file", ")", "if"...
Generates a strings file representing the strings that were yet to be translated. Args: localizable_file (str): The path to the localization strings file, meaning the file that represents the strings that require translation. translated_file (str): The path to the translated strings fil...
[ "Generates", "a", "strings", "file", "representing", "the", "strings", "that", "were", "yet", "to", "be", "translated", "." ]
python
train
53.315789
google/grr
grr/server/grr_response_server/gui/api_plugins/user.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_plugins/user.py#L375-L408
def _InitApiApprovalFromAff4Object(api_approval, approval_obj): """Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object.""" api_approval.id = approval_obj.urn.Basename() api_approval.reason = approval_obj.Get(approval_obj.Schema.REASON) api_approval.requestor = approval_obj.Get(approval_obj.Schema....
[ "def", "_InitApiApprovalFromAff4Object", "(", "api_approval", ",", "approval_obj", ")", ":", "api_approval", ".", "id", "=", "approval_obj", ".", "urn", ".", "Basename", "(", ")", "api_approval", ".", "reason", "=", "approval_obj", ".", "Get", "(", "approval_obj...
Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object.
[ "Initializes", "Api", "(", "Client|Hunt|CronJob", ")", "Approval", "from", "an", "AFF4", "object", "." ]
python
train
39.264706
PlaidWeb/Publ
publ/image/local.py
https://github.com/PlaidWeb/Publ/blob/ce7893632ddc3cb70b4978a41ffd7dd06fa13565/publ/image/local.py#L23-L55
def fix_orientation(image): """ adapted from https://stackoverflow.com/a/30462851/318857 Apply Image.transpose to ensure 0th row of pixels is at the visual top of the image, and 0th column is the visual left-hand side. Return the original image if unable to determine the orientation. ...
[ "def", "fix_orientation", "(", "image", ")", ":", "exif_orientation_tag", "=", "0x0112", "exif_transpose_sequences", "=", "[", "[", "]", ",", "[", "]", ",", "[", "PIL", ".", "Image", ".", "FLIP_LEFT_RIGHT", "]", ",", "[", "PIL", ".", "Image", ".", "ROTAT...
adapted from https://stackoverflow.com/a/30462851/318857 Apply Image.transpose to ensure 0th row of pixels is at the visual top of the image, and 0th column is the visual left-hand side. Return the original image if unable to determine the orientation. As per CIPA DC-008-2012, the orie...
[ "adapted", "from", "https", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "30462851", "/", "318857" ]
python
train
35.484848
RedHatInsights/insights-core
insights/client/archive.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/archive.py#L114-L132
def create_tar_file(self, full_archive=False): """ Create tar file to be compressed """ tar_file_name = os.path.join(self.archive_tmp_dir, self.archive_name) ext = "" if self.compressor == "none" else ".%s" % self.compressor tar_file_name = tar_file_name + ".tar" + ext ...
[ "def", "create_tar_file", "(", "self", ",", "full_archive", "=", "False", ")", ":", "tar_file_name", "=", "os", ".", "path", ".", "join", "(", "self", ".", "archive_tmp_dir", ",", "self", ".", "archive_name", ")", "ext", "=", "\"\"", "if", "self", ".", ...
Create tar file to be compressed
[ "Create", "tar", "file", "to", "be", "compressed" ]
python
train
49
pjuren/pyokit
src/pyokit/scripts/index.py
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/scripts/index.py#L271-L280
def __get_lookup(in_fn, selected_type=None): """Determine which lookup func to use based on inpt files and type option.""" lookup_func = None if selected_type is not None: lookup_func = get_lookup_by_filetype(selected_type) else: extension = os.path.splitext(in_fn)[1] lookup_func = get_lookup_by_fil...
[ "def", "__get_lookup", "(", "in_fn", ",", "selected_type", "=", "None", ")", ":", "lookup_func", "=", "None", "if", "selected_type", "is", "not", "None", ":", "lookup_func", "=", "get_lookup_by_filetype", "(", "selected_type", ")", "else", ":", "extension", "=...
Determine which lookup func to use based on inpt files and type option.
[ "Determine", "which", "lookup", "func", "to", "use", "based", "on", "inpt", "files", "and", "type", "option", "." ]
python
train
38.8
IDSIA/sacred
sacred/config/custom_containers.py
https://github.com/IDSIA/sacred/blob/72633776bed9b5bddf93ae7d215188e61970973a/sacred/config/custom_containers.py#L273-L278
def is_different(old_value, new_value): """Numpy aware comparison between two values.""" if opt.has_numpy: return not opt.np.array_equal(old_value, new_value) else: return old_value != new_value
[ "def", "is_different", "(", "old_value", ",", "new_value", ")", ":", "if", "opt", ".", "has_numpy", ":", "return", "not", "opt", ".", "np", ".", "array_equal", "(", "old_value", ",", "new_value", ")", "else", ":", "return", "old_value", "!=", "new_value" ]
Numpy aware comparison between two values.
[ "Numpy", "aware", "comparison", "between", "two", "values", "." ]
python
train
36.166667
Ceasar/trees
trees/heap.py
https://github.com/Ceasar/trees/blob/09059857112d3607942c81e87ab9ad04be4641f7/trees/heap.py#L51-L56
def push(self, item): '''Push the value item onto the heap, maintaining the heap invariant. If the item is not hashable, a TypeError is raised. ''' hash(item) heapq.heappush(self._items, item)
[ "def", "push", "(", "self", ",", "item", ")", ":", "hash", "(", "item", ")", "heapq", ".", "heappush", "(", "self", ".", "_items", ",", "item", ")" ]
Push the value item onto the heap, maintaining the heap invariant. If the item is not hashable, a TypeError is raised.
[ "Push", "the", "value", "item", "onto", "the", "heap", "maintaining", "the", "heap", "invariant", ".", "If", "the", "item", "is", "not", "hashable", "a", "TypeError", "is", "raised", "." ]
python
train
37.833333
bitesofcode/projexui
projexui/widgets/xrichtextedit/xrichtextedit.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L442-L451
def pickTextBackgroundColor(self): """ Prompts the user to select a text color. """ clr = QColorDialog.getColor(self.textBackgroundColor(), self.window(), 'Pick Background Color') if clr.isVa...
[ "def", "pickTextBackgroundColor", "(", "self", ")", ":", "clr", "=", "QColorDialog", ".", "getColor", "(", "self", ".", "textBackgroundColor", "(", ")", ",", "self", ".", "window", "(", ")", ",", "'Pick Background Color'", ")", "if", "clr", ".", "isValid", ...
Prompts the user to select a text color.
[ "Prompts", "the", "user", "to", "select", "a", "text", "color", "." ]
python
train
36.3
combust/mleap
python/mleap/gensim/word2vec.py
https://github.com/combust/mleap/blob/dc6b79db03ec27a0ba08b289842551e73d517ab3/python/mleap/gensim/word2vec.py#L85-L100
def sent2vec(self, words, transformer): """ Used with sqrt kernel :param words: :param transformer: :return: """ sent_vec = np.zeros(transformer.vector_size) numw = 0 for w in words: try: sent_vec = np.add(sent_vec, tran...
[ "def", "sent2vec", "(", "self", ",", "words", ",", "transformer", ")", ":", "sent_vec", "=", "np", ".", "zeros", "(", "transformer", ".", "vector_size", ")", "numw", "=", "0", "for", "w", "in", "words", ":", "try", ":", "sent_vec", "=", "np", ".", ...
Used with sqrt kernel :param words: :param transformer: :return:
[ "Used", "with", "sqrt", "kernel", ":", "param", "words", ":", ":", "param", "transformer", ":", ":", "return", ":" ]
python
train
28
divio/django-filer
filer/admin/patched/admin_utils.py
https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/patched/admin_utils.py#L34-L84
def get_deleted_objects(objs, opts, user, admin_site, using): """ Find all objects related to ``objs`` that should also be deleted. ``objs`` must be a homogeneous iterable of objects (e.g. a QuerySet). Returns a nested list of strings suitable for display in the template with the ``unordered_list`` ...
[ "def", "get_deleted_objects", "(", "objs", ",", "opts", ",", "user", ",", "admin_site", ",", "using", ")", ":", "# --- begin patch ---", "collector", "=", "PolymorphicAwareNestedObjects", "(", "using", "=", "using", ")", "# --- end patch ---", "collector", ".", "c...
Find all objects related to ``objs`` that should also be deleted. ``objs`` must be a homogeneous iterable of objects (e.g. a QuerySet). Returns a nested list of strings suitable for display in the template with the ``unordered_list`` filter.
[ "Find", "all", "objects", "related", "to", "objs", "that", "should", "also", "be", "deleted", ".", "objs", "must", "be", "a", "homogeneous", "iterable", "of", "objects", "(", "e", ".", "g", ".", "a", "QuerySet", ")", ".", "Returns", "a", "nested", "lis...
python
train
40.137255
RedHatInsights/insights-core
insights/contrib/ipaddress.py
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/ipaddress.py#L557-L569
def _ip_string_from_prefix(self, prefixlen=None): """Turn a prefix length into a dotted decimal string. Args: prefixlen: An integer, the netmask prefix length. Returns: A string, the dotted decimal netmask string. """ if not prefixlen: prefi...
[ "def", "_ip_string_from_prefix", "(", "self", ",", "prefixlen", "=", "None", ")", ":", "if", "not", "prefixlen", ":", "prefixlen", "=", "self", ".", "_prefixlen", "return", "self", ".", "_string_from_ip_int", "(", "self", ".", "_ip_int_from_prefix", "(", "pref...
Turn a prefix length into a dotted decimal string. Args: prefixlen: An integer, the netmask prefix length. Returns: A string, the dotted decimal netmask string.
[ "Turn", "a", "prefix", "length", "into", "a", "dotted", "decimal", "string", "." ]
python
train
31.307692
saltstack/salt
salt/cloud/clouds/msazure.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2061-L2086
def show_input_endpoint(kwargs=None, conn=None, call=None): ''' .. versionadded:: 2015.8.0 Show an input endpoint associated with the deployment CLI Example: .. code-block:: bash salt-cloud -f show_input_endpoint my-azure service=myservice \\ deployment=mydeployment name=SSH ...
[ "def", "show_input_endpoint", "(", "kwargs", "=", "None", ",", "conn", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The show_input_endpoint function must be called with -f or --function....
.. versionadded:: 2015.8.0 Show an input endpoint associated with the deployment CLI Example: .. code-block:: bash salt-cloud -f show_input_endpoint my-azure service=myservice \\ deployment=mydeployment name=SSH
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
python
train
27.769231
suzaku/cachelper
cachelper/remote.py
https://github.com/suzaku/cachelper/blob/7da36614f9a23abb97c4d4c871dd45e07080dfb5/cachelper/remote.py#L48-L86
def map(self, key_pattern, func, all_args, timeout=None): '''Cache return value of multiple calls. Args: key_pattern (str): the key pattern to use for generating keys for caches of the decorated function. func (function): the function to call. ...
[ "def", "map", "(", "self", ",", "key_pattern", ",", "func", ",", "all_args", ",", "timeout", "=", "None", ")", ":", "results", "=", "[", "]", "keys", "=", "[", "make_key", "(", "key_pattern", ",", "func", ",", "args", ",", "{", "}", ")", "for", "...
Cache return value of multiple calls. Args: key_pattern (str): the key pattern to use for generating keys for caches of the decorated function. func (function): the function to call. all_args (list): a list of args to be used to make calls to ...
[ "Cache", "return", "value", "of", "multiple", "calls", "." ]
python
train
32.769231
google/apitools
apitools/gen/util.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/gen/util.py#L105-L115
def NormalizeRelativePath(path): """Normalize camelCase entries in path.""" path_components = path.split('/') normalized_components = [] for component in path_components: if re.match(r'{[A-Za-z0-9_]+}$', component): normalized_components.append( ...
[ "def", "NormalizeRelativePath", "(", "path", ")", ":", "path_components", "=", "path", ".", "split", "(", "'/'", ")", "normalized_components", "=", "[", "]", "for", "component", "in", "path_components", ":", "if", "re", ".", "match", "(", "r'{[A-Za-z0-9_]+}$'"...
Normalize camelCase entries in path.
[ "Normalize", "camelCase", "entries", "in", "path", "." ]
python
train
43.545455
krinj/k-util
k_util/region.py
https://github.com/krinj/k-util/blob/b118826b1d6f49ca4e1ca7327d5b171db332ac23/k_util/region.py#L245-L247
def fast_distance(r1: 'Region', r2: 'Region'): """ A quicker way of calculating approximate distance. Lower accuracy but faster results.""" return abs(r1.x - r2.x) + abs(r1.y - r2.y)
[ "def", "fast_distance", "(", "r1", ":", "'Region'", ",", "r2", ":", "'Region'", ")", ":", "return", "abs", "(", "r1", ".", "x", "-", "r2", ".", "x", ")", "+", "abs", "(", "r1", ".", "y", "-", "r2", ".", "y", ")" ]
A quicker way of calculating approximate distance. Lower accuracy but faster results.
[ "A", "quicker", "way", "of", "calculating", "approximate", "distance", ".", "Lower", "accuracy", "but", "faster", "results", "." ]
python
train
65.333333
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/core/extensions.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/extensions.py#L80-L92
def load_extension(self, module_str): """Load an IPython extension by its module name. If :func:`load_ipython_extension` returns anything, this function will return that object. """ from IPython.utils.syspathcontext import prepended_to_syspath if module_str not in sys.m...
[ "def", "load_extension", "(", "self", ",", "module_str", ")", ":", "from", "IPython", ".", "utils", ".", "syspathcontext", "import", "prepended_to_syspath", "if", "module_str", "not", "in", "sys", ".", "modules", ":", "with", "prepended_to_syspath", "(", "self",...
Load an IPython extension by its module name. If :func:`load_ipython_extension` returns anything, this function will return that object.
[ "Load", "an", "IPython", "extension", "by", "its", "module", "name", "." ]
python
test
39.461538
emirozer/fake2db
fake2db/fake2db.py
https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/fake2db.py#L70-L86
def _redis_process_checkpoint(host, port): '''this helper method checks if redis server is available in the sys if not fires up one ''' try: subprocess.check_output("pgrep redis", shell=True) except Exception: logger.warning( 'Your redis server is offline, fake2db wil...
[ "def", "_redis_process_checkpoint", "(", "host", ",", "port", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "\"pgrep redis\"", ",", "shell", "=", "True", ")", "except", "Exception", ":", "logger", ".", "warning", "(", "'Your redis server is offli...
this helper method checks if redis server is available in the sys if not fires up one
[ "this", "helper", "method", "checks", "if", "redis", "server", "is", "available", "in", "the", "sys", "if", "not", "fires", "up", "one" ]
python
train
39.705882
rgalanakis/goless
goless/selecting.py
https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/goless/selecting.py#L41-L93
def select(*cases): """ Select the first case that becomes ready. If a default case (:class:`goless.dcase`) is present, return that if no other cases are ready. If there is no default case and no case is ready, block until one becomes ready. See Go's ``reflect.Select`` method for an analog ...
[ "def", "select", "(", "*", "cases", ")", ":", "if", "len", "(", "cases", ")", "==", "0", ":", "return", "# If the first argument is a list, it should be the only argument", "if", "isinstance", "(", "cases", "[", "0", "]", ",", "list", ")", ":", "if", "len", ...
Select the first case that becomes ready. If a default case (:class:`goless.dcase`) is present, return that if no other cases are ready. If there is no default case and no case is ready, block until one becomes ready. See Go's ``reflect.Select`` method for an analog (http://golang.org/pkg/refle...
[ "Select", "the", "first", "case", "that", "becomes", "ready", ".", "If", "a", "default", "case", "(", ":", "class", ":", "goless", ".", "dcase", ")", "is", "present", "return", "that", "if", "no", "other", "cases", "are", "ready", ".", "If", "there", ...
python
train
37.924528
fossasia/knittingpattern
knittingpattern/convert/InstructionToSVG.py
https://github.com/fossasia/knittingpattern/blob/8e608896b0ab82fea1ca9fbfa2b4ee023d8c8027/knittingpattern/convert/InstructionToSVG.py#L139-L153
def default_instruction_to_svg(self, instruction): """As :meth:`instruction_to_svg` but it only takes the ``default.svg`` file into account. In case no file is found for an instruction in :meth:`instruction_to_svg`, this method is used to determine the default svg for it. ...
[ "def", "default_instruction_to_svg", "(", "self", ",", "instruction", ")", ":", "svg_dict", "=", "self", ".", "default_instruction_to_svg_dict", "(", "instruction", ")", "return", "xmltodict", ".", "unparse", "(", "svg_dict", ")" ]
As :meth:`instruction_to_svg` but it only takes the ``default.svg`` file into account. In case no file is found for an instruction in :meth:`instruction_to_svg`, this method is used to determine the default svg for it. The content is created by replacing the text ``{instruction...
[ "As", ":", "meth", ":", "instruction_to_svg", "but", "it", "only", "takes", "the", "default", ".", "svg", "file", "into", "account", "." ]
python
valid
42
saltstack/salt
salt/wheel/pillar_roots.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/pillar_roots.py#L69-L77
def list_roots(): ''' Return all of the files names in all available environments ''' ret = {} for saltenv in __opts__['pillar_roots']: ret[saltenv] = [] ret[saltenv].append(list_env(saltenv)) return ret
[ "def", "list_roots", "(", ")", ":", "ret", "=", "{", "}", "for", "saltenv", "in", "__opts__", "[", "'pillar_roots'", "]", ":", "ret", "[", "saltenv", "]", "=", "[", "]", "ret", "[", "saltenv", "]", ".", "append", "(", "list_env", "(", "saltenv", ")...
Return all of the files names in all available environments
[ "Return", "all", "of", "the", "files", "names", "in", "all", "available", "environments" ]
python
train
26.111111
eventbrite/eventbrite-sdk-python
eventbrite/access_methods.py
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L213-L222
def get_event_questions(self, id, **data): """ GET /events/:id/questions/ Eventbrite allows event organizers to add custom questions that attendees fill out upon registration. This endpoint can be helpful for determining what custom information is collected and available per even...
[ "def", "get_event_questions", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/questions/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
GET /events/:id/questions/ Eventbrite allows event organizers to add custom questions that attendees fill out upon registration. This endpoint can be helpful for determining what custom information is collected and available per event. This endpoint will return :format:`question`.
[ "GET", "/", "events", "/", ":", "id", "/", "questions", "/", "Eventbrite", "allows", "event", "organizers", "to", "add", "custom", "questions", "that", "attendees", "fill", "out", "upon", "registration", ".", "This", "endpoint", "can", "be", "helpful", "for"...
python
train
46
lingpy/sinopy
src/sinopy/sinopy.py
https://github.com/lingpy/sinopy/blob/59a47fcdfae3e0000ac6d2b3d7919bf875ec2056/src/sinopy/sinopy.py#L402-L529
def parse_chinese_morphemes(seq, context=False): """ Parse a Chinese syllable and return its basic structure. """ # get the tokens if isinstance(seq, list): tokens = [s for s in seq] else: tokens = lingpy.ipa2tokens(seq, merge_vowels=False) # get the sound classes ...
[ "def", "parse_chinese_morphemes", "(", "seq", ",", "context", "=", "False", ")", ":", "# get the tokens", "if", "isinstance", "(", "seq", ",", "list", ")", ":", "tokens", "=", "[", "s", "for", "s", "in", "seq", "]", "else", ":", "tokens", "=", "lingpy"...
Parse a Chinese syllable and return its basic structure.
[ "Parse", "a", "Chinese", "syllable", "and", "return", "its", "basic", "structure", "." ]
python
train
29.023438
tensorflow/tensor2tensor
tensor2tensor/models/transformer.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/transformer.py#L1736-L1742
def transformer_ada_lmpackedbase_dialog(): """Set of hyperparameters.""" hparams = transformer_base_vq_ada_32ex_packed() hparams.max_length = 1024 hparams.ffn_layer = "dense_relu_dense" hparams.batch_size = 4096 return hparams
[ "def", "transformer_ada_lmpackedbase_dialog", "(", ")", ":", "hparams", "=", "transformer_base_vq_ada_32ex_packed", "(", ")", "hparams", ".", "max_length", "=", "1024", "hparams", ".", "ffn_layer", "=", "\"dense_relu_dense\"", "hparams", ".", "batch_size", "=", "4096"...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
python
train
33.142857
IndicoDataSolutions/IndicoIo-python
indicoio/utils/docx.py
https://github.com/IndicoDataSolutions/IndicoIo-python/blob/6f262a23f09d76fede63d1ccb87f9f7cf2cfc8aa/indicoio/utils/docx.py#L5-L17
def docx_preprocess(docx, batch=False): """ Load docx files from local filepath if not already b64 encoded """ if batch: return [docx_preprocess(doc, batch=False) for doc in docx] if os.path.isfile(docx): # a filepath is provided, read and encode return b64encode(open(docx, ...
[ "def", "docx_preprocess", "(", "docx", ",", "batch", "=", "False", ")", ":", "if", "batch", ":", "return", "[", "docx_preprocess", "(", "doc", ",", "batch", "=", "False", ")", "for", "doc", "in", "docx", "]", "if", "os", ".", "path", ".", "isfile", ...
Load docx files from local filepath if not already b64 encoded
[ "Load", "docx", "files", "from", "local", "filepath", "if", "not", "already", "b64", "encoded" ]
python
train
30.384615
awacha/sastool
sastool/io/header.py
https://github.com/awacha/sastool/blob/deaddfa3002f3f6818697e36139633b7e30427a3/sastool/io/header.py#L545-L678
def readbhfv1(filename, load_data=False, bdfext='.bdf', bhfext='.bhf'): """Read header data from bdf/bhf file (Bessy Data Format v1) Input: filename: the name of the file load_data: if the matrices are to be loaded Output: bdf: the BDF header structure Adapted the bdf_read.m m...
[ "def", "readbhfv1", "(", "filename", ",", "load_data", "=", "False", ",", "bdfext", "=", "'.bdf'", ",", "bhfext", "=", "'.bhf'", ")", ":", "# strip the bhf or bdf extension if there.", "if", "filename", ".", "endswith", "(", "bdfext", ")", ":", "basename", "="...
Read header data from bdf/bhf file (Bessy Data Format v1) Input: filename: the name of the file load_data: if the matrices are to be loaded Output: bdf: the BDF header structure Adapted the bdf_read.m macro from Sylvio Haas.
[ "Read", "header", "data", "from", "bdf", "/", "bhf", "file", "(", "Bessy", "Data", "Format", "v1", ")" ]
python
train
44.985075
ccubed/PyMoe
Pymoe/Bakatsuki/__init__.py
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Bakatsuki/__init__.py#L159-L195
def chapters(self, title): """ Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage. :param str title: The title of the novel you want chapters from :return OrderedDic...
[ "def", "chapters", "(", "self", ",", "title", ")", ":", "r", "=", "requests", ".", "get", "(", "\"https://www.baka-tsuki.org/project/index.php?title={}\"", ".", "format", "(", "title", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", ")", ",", "headers", "="...
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage. :param str title: The title of the novel you want chapters from :return OrderedDict: An OrderedDict which contains the chapters f...
[ "Get", "a", "list", "of", "chapters", "for", "a", "visual", "novel", ".", "Keep", "in", "mind", "this", "can", "be", "slow", ".", "I", "ve", "certainly", "tried", "to", "make", "it", "as", "fast", "as", "possible", "but", "it", "s", "still", "pulling...
python
train
55.135135
tensorflow/tensorboard
tensorboard/plugins/debugger/tensor_store.py
https://github.com/tensorflow/tensorboard/blob/8e5f497b48e40f2a774f85416b8a35ac0693c35e/tensorboard/plugins/debugger/tensor_store.py#L139-L168
def query(self, time_indices): """Query the values at given time indices. Args: time_indices: 0-based time indices to query, as a `list` of `int`. Returns: Values as a list of `numpy.ndarray` (for time indices in memory) or `None` (for time indices discarded). """ if self._dispos...
[ "def", "query", "(", "self", ",", "time_indices", ")", ":", "if", "self", ".", "_disposed", ":", "raise", "ValueError", "(", "'Cannot query: this _WatchStore instance is already disposed'", ")", "if", "not", "isinstance", "(", "time_indices", ",", "(", "tuple", ",...
Query the values at given time indices. Args: time_indices: 0-based time indices to query, as a `list` of `int`. Returns: Values as a list of `numpy.ndarray` (for time indices in memory) or `None` (for time indices discarded).
[ "Query", "the", "values", "at", "given", "time", "indices", "." ]
python
train
34.866667
spulec/moto
moto/core/utils.py
https://github.com/spulec/moto/blob/4a286c4bc288933bb023396e2784a6fdbb966bc9/moto/core/utils.py#L80-L96
def convert_regex_to_flask_path(url_path): """ Converts a regex matching url to one that can be used with flask """ for token in ["$"]: url_path = url_path.replace(token, "") def caller(reg): match_name, match_pattern = reg.groups() return '<regex("{0}"):{1}>'.format(match_p...
[ "def", "convert_regex_to_flask_path", "(", "url_path", ")", ":", "for", "token", "in", "[", "\"$\"", "]", ":", "url_path", "=", "url_path", ".", "replace", "(", "token", ",", "\"\"", ")", "def", "caller", "(", "reg", ")", ":", "match_name", ",", "match_p...
Converts a regex matching url to one that can be used with flask
[ "Converts", "a", "regex", "matching", "url", "to", "one", "that", "can", "be", "used", "with", "flask" ]
python
train
31.470588
MartinHjelmare/leicacam
leicacam/cam.py
https://github.com/MartinHjelmare/leicacam/blob/1df37bccd34884737d3b5e169fae71dd2f21f1e2/leicacam/cam.py#L174-L181
def connect(self): """Connect to LASAF through a CAM-socket.""" self.socket = socket.socket() self.socket.connect((self.host, self.port)) self.socket.settimeout(False) # non-blocking sleep(self.delay) # wait for response self.welcome_msg = self.socket.recv( ...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", ")", "self", ".", "socket", ".", "connect", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "self", ".", "socket", ".", "settime...
Connect to LASAF through a CAM-socket.
[ "Connect", "to", "LASAF", "through", "a", "CAM", "-", "socket", "." ]
python
test
41.25
materialsproject/pymatgen
pymatgen/analysis/structure_prediction/dopant_predictor.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/structure_prediction/dopant_predictor.py#L137-L173
def _shannon_radii_from_cn(species_list, cn_roman, radius_to_compare=0): """ Utility func to get Shannon radii for a particular coordination number. As the Shannon radii depends on charge state and coordination number, species without an entry for a particular coordination number will be skipped. ...
[ "def", "_shannon_radii_from_cn", "(", "species_list", ",", "cn_roman", ",", "radius_to_compare", "=", "0", ")", ":", "shannon_radii", "=", "[", "]", "for", "s", "in", "species_list", ":", "try", ":", "radius", "=", "s", ".", "get_shannon_radius", "(", "cn_ro...
Utility func to get Shannon radii for a particular coordination number. As the Shannon radii depends on charge state and coordination number, species without an entry for a particular coordination number will be skipped. Args: species_list (list): A list of Species to get the Shannon radii for...
[ "Utility", "func", "to", "get", "Shannon", "radii", "for", "a", "particular", "coordination", "number", "." ]
python
train
38
hollenstein/maspy
maspy/core.py
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/core.py#L344-L354
def _addSpecfile(self, specfile, path): """Adds a new specfile entry to MsrunContainer.info. See also :class:`MsrunContainer.addSpecfile()`. :param specfile: the name of an ms-run file :param path: filedirectory used for loading and saving ``mrc`` files """ datatypeStatu...
[ "def", "_addSpecfile", "(", "self", ",", "specfile", ",", "path", ")", ":", "datatypeStatus", "=", "{", "'rm'", ":", "False", ",", "'ci'", ":", "False", ",", "'smi'", ":", "False", ",", "'sai'", ":", "False", ",", "'si'", ":", "False", "}", "self", ...
Adds a new specfile entry to MsrunContainer.info. See also :class:`MsrunContainer.addSpecfile()`. :param specfile: the name of an ms-run file :param path: filedirectory used for loading and saving ``mrc`` files
[ "Adds", "a", "new", "specfile", "entry", "to", "MsrunContainer", ".", "info", ".", "See", "also", ":", "class", ":", "MsrunContainer", ".", "addSpecfile", "()", "." ]
python
train
45.909091
pyQode/pyqode.core
pyqode/core/panels/search_and_replace.py
https://github.com/pyQode/pyqode.core/blob/a99ec6cd22d519394f613309412f8329dc4e90cb/pyqode/core/panels/search_and_replace.py#L336-L344
def _set_widget_background_color(widget, color): """ Changes the base color of a widget (background). :param widget: widget to modify :param color: the color to apply """ pal = widget.palette() pal.setColor(pal.Base, color) widget.setPalette(pal)
[ "def", "_set_widget_background_color", "(", "widget", ",", "color", ")", ":", "pal", "=", "widget", ".", "palette", "(", ")", "pal", ".", "setColor", "(", "pal", ".", "Base", ",", "color", ")", "widget", ".", "setPalette", "(", "pal", ")" ]
Changes the base color of a widget (background). :param widget: widget to modify :param color: the color to apply
[ "Changes", "the", "base", "color", "of", "a", "widget", "(", "background", ")", ".", ":", "param", "widget", ":", "widget", "to", "modify", ":", "param", "color", ":", "the", "color", "to", "apply" ]
python
train
33.555556
napalm-automation/napalm
napalm/nxos_ssh/nxos_ssh.py
https://github.com/napalm-automation/napalm/blob/c11ae8bb5ce395698704a0051cdf8d144fbb150d/napalm/nxos_ssh/nxos_ssh.py#L263-L276
def bgp_normalize_table_data(bgp_table): """The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 ...
[ "def", "bgp_normalize_table_data", "(", "bgp_table", ")", ":", "bgp_table", "=", "bgp_table", ".", "strip", "(", ")", "bgp_multiline_pattern", "=", "r\"({})\\s*\\n\"", ".", "format", "(", "IPV4_OR_IPV6_REGEX", ")", "# Strip out the newline", "return", "re", ".", "su...
The 'show bgp all summary vrf all' table can have entries that wrap multiple lines. 2001:db8:4:701::2 4 65535 163664 163693 145 0 0 3w2d 3 2001:db8:e0:dd::1 4 10 327491 327278 145 0 0 3w1d 4 Normalize this so the line wrap doesn't exit.
[ "The", "show", "bgp", "all", "summary", "vrf", "all", "table", "can", "have", "entries", "that", "wrap", "multiple", "lines", "." ]
python
train
39.357143
alex-kostirin/pyatomac
atomac/ldtpd/core.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/ldtpd/core.py#L829-L857
def check(self, window_name, object_name): """ Check item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name ...
[ "def", "check", "(", "self", ",", "window_name", ",", "object_name", ")", ":", "# FIXME: Check for object type", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "object_handle", ".", "AXEnabled", "...
Check item. @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to look for, either full name, LDTP's name convention, or a Unix glob. @type object_name: string ...
[ "Check", "item", "." ]
python
valid
38.793103
xolox/python-coloredlogs
coloredlogs/__init__.py
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L888-L911
def walk_propagation_tree(logger): """ Walk through the propagation hierarchy of the given logger. :param logger: The logger whose hierarchy to walk (a :class:`~logging.Logger` object). :returns: A generator of :class:`~logging.Logger` objects. .. note:: This uses the undocument...
[ "def", "walk_propagation_tree", "(", "logger", ")", ":", "while", "isinstance", "(", "logger", ",", "logging", ".", "Logger", ")", ":", "# Yield the logger to our caller.", "yield", "logger", "# Check if the logger has propagation enabled.", "if", "logger", ".", "propag...
Walk through the propagation hierarchy of the given logger. :param logger: The logger whose hierarchy to walk (a :class:`~logging.Logger` object). :returns: A generator of :class:`~logging.Logger` objects. .. note:: This uses the undocumented :class:`logging.Logger.parent` ...
[ "Walk", "through", "the", "propagation", "hierarchy", "of", "the", "given", "logger", "." ]
python
train
42.208333
senaite/senaite.core
bika/lims/upgrade/v01_03_000.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/upgrade/v01_03_000.py#L1886-L1911
def update_ar_listing_catalog(portal): """Add Indexes/Metadata to bika_catalog_analysisrequest_listing """ cat_id = CATALOG_ANALYSIS_REQUEST_LISTING catalog = api.get_tool(cat_id) logger.info("Updating Indexes/Metadata of Catalog '{}'".format(cat_id)) indexes_to_add = [ # name, attrib...
[ "def", "update_ar_listing_catalog", "(", "portal", ")", ":", "cat_id", "=", "CATALOG_ANALYSIS_REQUEST_LISTING", "catalog", "=", "api", ".", "get_tool", "(", "cat_id", ")", "logger", ".", "info", "(", "\"Updating Indexes/Metadata of Catalog '{}'\"", ".", "format", "(",...
Add Indexes/Metadata to bika_catalog_analysisrequest_listing
[ "Add", "Indexes", "/", "Metadata", "to", "bika_catalog_analysisrequest_listing" ]
python
train
29.5
jaredLunde/vital-tools
vital/security/__init__.py
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L381-L402
def iter_random_chars(bits, keyspace=string.ascii_letters + string.digits + '#/.', rng=None): """ Yields a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entr...
[ "def", "iter_random_chars", "(", "bits", ",", "keyspace", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", "+", "'#/.'", ",", "rng", "=", "None", ")", ":", "if", "bits", "<", "8", ":", "raise", "ValueError", "(", "'Bits cannot be <8'", ...
Yields a cryptographically secure random key of desired @bits of entropy within @keyspace using :class:random.SystemRandom @bits: (#int) minimum bits of entropy @keyspace: (#str) or iterable allowed output chars .. from vital.security import iter_rand for char ...
[ "Yields", "a", "cryptographically", "secure", "random", "key", "of", "desired", "@bits", "of", "entropy", "within", "@keyspace", "using", ":", "class", ":", "random", ".", "SystemRandom" ]
python
train
33.636364
mosdef-hub/mbuild
mbuild/compound.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L927-L953
def remove_bond(self, particle_pair): """Deletes a bond between a pair of Particles Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to remove the bond between """ from mbuild.port import Port ...
[ "def", "remove_bond", "(", "self", ",", "particle_pair", ")", ":", "from", "mbuild", ".", "port", "import", "Port", "if", "self", ".", "root", ".", "bond_graph", "is", "None", "or", "not", "self", ".", "root", ".", "bond_graph", ".", "has_edge", "(", "...
Deletes a bond between a pair of Particles Parameters ---------- particle_pair : indexable object, length=2, dtype=mb.Compound The pair of Particles to remove the bond between
[ "Deletes", "a", "bond", "between", "a", "pair", "of", "Particles" ]
python
train
47.148148
CloverHealth/temple
temple/update.py
https://github.com/CloverHealth/temple/blob/d7b75da2459f72ba74d6f3b6e1ab95c3d1b92ccd/temple/update.py#L152-L162
def _needs_new_cc_config_for_update(old_template, old_version, new_template, new_version): """ Given two templates and their respective versions, return True if a new cookiecutter config needs to be obtained from the user """ if old_template != new_template: return True else: ret...
[ "def", "_needs_new_cc_config_for_update", "(", "old_template", ",", "old_version", ",", "new_template", ",", "new_version", ")", ":", "if", "old_template", "!=", "new_template", ":", "return", "True", "else", ":", "return", "_cookiecutter_configs_have_changed", "(", "...
Given two templates and their respective versions, return True if a new cookiecutter config needs to be obtained from the user
[ "Given", "two", "templates", "and", "their", "respective", "versions", "return", "True", "if", "a", "new", "cookiecutter", "config", "needs", "to", "be", "obtained", "from", "the", "user" ]
python
valid
44.363636
keenlabs/KeenClient-Python
keen/__init__.py
https://github.com/keenlabs/KeenClient-Python/blob/266387c3376d1e000d117e17c45045ae3439d43f/keen/__init__.py#L14-L33
def _initialize_client_from_environment(): ''' Initialize a KeenClient instance using environment variables. ''' global _client, project_id, write_key, read_key, master_key, base_url if _client is None: # check environment for project ID and keys project_id = project_id or os.environ.get("K...
[ "def", "_initialize_client_from_environment", "(", ")", ":", "global", "_client", ",", "project_id", ",", "write_key", ",", "read_key", ",", "master_key", ",", "base_url", "if", "_client", "is", "None", ":", "# check environment for project ID and keys", "project_id", ...
Initialize a KeenClient instance using environment variables.
[ "Initialize", "a", "KeenClient", "instance", "using", "environment", "variables", "." ]
python
train
48.35
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/config/loader.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L609-L612
def _convert_to_config(self): """self.parsed_data->self.config""" for k, v in vars(self.parsed_data).iteritems(): exec "self.config.%s = v"%k in locals(), globals()
[ "def", "_convert_to_config", "(", "self", ")", ":", "for", "k", ",", "v", "in", "vars", "(", "self", ".", "parsed_data", ")", ".", "iteritems", "(", ")", ":", "exec", "\"self.config.%s = v\"", "%", "k", "in", "locals", "(", ")", ",", "globals", "(", ...
self.parsed_data->self.config
[ "self", ".", "parsed_data", "-", ">", "self", ".", "config" ]
python
test
47.25
hyperledger/indy-plenum
plenum/server/replica.py
https://github.com/hyperledger/indy-plenum/blob/dcd144e238af7f17a869ffc9412f13dc488b7020/plenum/server/replica.py#L1611-L1682
def validatePrepare(self, prepare: Prepare, sender: str) -> bool: """ Return whether the PREPARE specified is valid. :param prepare: the PREPARE to validate :param sender: the name of the node that sent the PREPARE :return: True if PREPARE is valid, False otherwise """ ...
[ "def", "validatePrepare", "(", "self", ",", "prepare", ":", "Prepare", ",", "sender", ":", "str", ")", "->", "bool", ":", "key", "=", "(", "prepare", ".", "viewNo", ",", "prepare", ".", "ppSeqNo", ")", "primaryStatus", "=", "self", ".", "isPrimaryForMsg"...
Return whether the PREPARE specified is valid. :param prepare: the PREPARE to validate :param sender: the name of the node that sent the PREPARE :return: True if PREPARE is valid, False otherwise
[ "Return", "whether", "the", "PREPARE", "specified", "is", "valid", "." ]
python
train
41.847222
matrix-org/matrix-python-sdk
matrix_client/room.py
https://github.com/matrix-org/matrix-python-sdk/blob/e734cce3ccd35f2d355c6a19a7a701033472498a/matrix_client/room.py#L150-L165
def send_file(self, url, name, **fileinfo): """Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. filei...
[ "def", "send_file", "(", "self", ",", "url", ",", "name", ",", "*", "*", "fileinfo", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_content", "(", "self", ".", "room_id", ",", "url", ",", "name", ",", "\"m.file\"", ",", "extra_info...
Send a pre-uploaded file to the room. See http://matrix.org/docs/spec/r0.2.0/client_server.html#m-file for fileinfo. Args: url (str): The mxc url of the file. name (str): The filename of the image. fileinfo (): Extra information about the file
[ "Send", "a", "pre", "-", "uploaded", "file", "to", "the", "room", "." ]
python
train
31.1875
StellarCN/py-stellar-base
stellar_base/horizon.py
https://github.com/StellarCN/py-stellar-base/blob/cce2e782064fb3955c85e1696e630d67b1010848/stellar_base/horizon.py#L399-L412
def transaction(self, tx_hash): """The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transactio...
[ "def", "transaction", "(", "self", ",", "tx_hash", ")", ":", "endpoint", "=", "'/transactions/{tx_hash}'", ".", "format", "(", "tx_hash", "=", "tx_hash", ")", "return", "self", ".", "query", "(", "endpoint", ")" ]
The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transaction hash. :return: A single transacti...
[ "The", "transaction", "details", "endpoint", "provides", "information", "on", "a", "single", "transaction", "." ]
python
train
35.857143
jmbhughes/suvi-trainer
suvitrainer/gui.py
https://github.com/jmbhughes/suvi-trainer/blob/3d89894a4a037286221974c7eb5634d229b4f5d4/suvitrainer/gui.py#L511-L529
def make_configure_tab(self): """ initial set up of configure tab""" # Setup the choice between single and multicolor modeframe = tk.Frame(self.tab_configure) self.mode = tk.IntVar() singlecolor = tk.Radiobutton(modeframe, text="Single color", variable=self.mode, ...
[ "def", "make_configure_tab", "(", "self", ")", ":", "# Setup the choice between single and multicolor", "modeframe", "=", "tk", ".", "Frame", "(", "self", ".", "tab_configure", ")", "self", ".", "mode", "=", "tk", ".", "IntVar", "(", ")", "singlecolor", "=", "...
initial set up of configure tab
[ "initial", "set", "up", "of", "configure", "tab" ]
python
train
49.105263
Azure/msrest-for-python
msrest/serialization.py
https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/serialization.py#L191-L203
def _create_xml_node(cls): """Create XML node from "_xml_map". """ try: xml_map = cls._xml_map except AttributeError: raise ValueError("This model has no XML definition") return _create_xml_node( xml_map.get('name', cls.__name__), ...
[ "def", "_create_xml_node", "(", "cls", ")", ":", "try", ":", "xml_map", "=", "cls", ".", "_xml_map", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"This model has no XML definition\"", ")", "return", "_create_xml_node", "(", "xml_map", ".", "get",...
Create XML node from "_xml_map".
[ "Create", "XML", "node", "from", "_xml_map", "." ]
python
train
29.384615
PierreRust/apigpio
apigpio/apigpio.py
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L459-L469
def remove(self, cb): """Removes a callback.""" if cb in self.callbacks: self.callbacks.remove(cb) new_monitor = 0 for c in self.callbacks: new_monitor |= c.bit if new_monitor != self.monitor: self.monitor = new_monitor ...
[ "def", "remove", "(", "self", ",", "cb", ")", ":", "if", "cb", "in", "self", ".", "callbacks", ":", "self", ".", "callbacks", ".", "remove", "(", "cb", ")", "new_monitor", "=", "0", "for", "c", "in", "self", ".", "callbacks", ":", "new_monitor", "|...
Removes a callback.
[ "Removes", "a", "callback", "." ]
python
train
38.181818
getpelican/pelican-plugins
gzip_cache/gzip_cache.py
https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/gzip_cache/gzip_cache.py#L60-L70
def create_gzip_cache(pelican): '''Create a gzip cache file for every file that a webserver would reasonably want to cache (e.g., text type files). :param pelican: The Pelican instance ''' for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']): for name in filenames: ...
[ "def", "create_gzip_cache", "(", "pelican", ")", ":", "for", "dirpath", ",", "_", ",", "filenames", "in", "os", ".", "walk", "(", "pelican", ".", "settings", "[", "'OUTPUT_PATH'", "]", ")", ":", "for", "name", "in", "filenames", ":", "if", "should_compre...
Create a gzip cache file for every file that a webserver would reasonably want to cache (e.g., text type files). :param pelican: The Pelican instance
[ "Create", "a", "gzip", "cache", "file", "for", "every", "file", "that", "a", "webserver", "would", "reasonably", "want", "to", "cache", "(", "e", ".", "g", ".", "text", "type", "files", ")", "." ]
python
train
43
senseobservationsystems/commonsense-python-lib
senseapi.py
https://github.com/senseobservationsystems/commonsense-python-lib/blob/aac59a1751ef79eb830b3ca1fab6ef2c83931f87/senseapi.py#L46-L58
def setVerbosity(self, verbose): """ Set verbosity of the SenseApi object. @param verbose (boolean) - True of False @return (boolean) - Boolean indicating whether setVerbosity succeeded """ if not (verbose == True or verbose =...
[ "def", "setVerbosity", "(", "self", ",", "verbose", ")", ":", "if", "not", "(", "verbose", "==", "True", "or", "verbose", "==", "False", ")", ":", "return", "False", "else", ":", "self", ".", "__verbose__", "=", "verbose", "return", "True" ]
Set verbosity of the SenseApi object. @param verbose (boolean) - True of False @return (boolean) - Boolean indicating whether setVerbosity succeeded
[ "Set", "verbosity", "of", "the", "SenseApi", "object", "." ]
python
train
32.538462
KelSolaar/Umbra
umbra/components/factory/script_editor/models.py
https://github.com/KelSolaar/Umbra/blob/66f45f08d9d723787f1191989f8b0dda84b412ce/umbra/components/factory/script_editor/models.py#L1110-L1131
def remove_pattern(self, pattern): """ Removes given pattern from the Model. :param pattern: Pattern. :type pattern: unicode :return: Method success. :rtype: bool """ for index, node in enumerate(self.root_node.children): if node.name != patt...
[ "def", "remove_pattern", "(", "self", ",", "pattern", ")", ":", "for", "index", ",", "node", "in", "enumerate", "(", "self", ".", "root_node", ".", "children", ")", ":", "if", "node", ".", "name", "!=", "pattern", ":", "continue", "LOGGER", ".", "debug...
Removes given pattern from the Model. :param pattern: Pattern. :type pattern: unicode :return: Method success. :rtype: bool
[ "Removes", "given", "pattern", "from", "the", "Model", "." ]
python
train
32.227273
openeemeter/eeweather
eeweather/stations.py
https://github.com/openeemeter/eeweather/blob/d32b7369b26edfa3ee431c60457afeb0593123a7/eeweather/stations.py#L1174-L1176
def get_gsod_filenames(self, year=None, with_host=False): """ Get filenames of raw GSOD station data. """ return get_gsod_filenames(self.usaf_id, year, with_host=with_host)
[ "def", "get_gsod_filenames", "(", "self", ",", "year", "=", "None", ",", "with_host", "=", "False", ")", ":", "return", "get_gsod_filenames", "(", "self", ".", "usaf_id", ",", "year", ",", "with_host", "=", "with_host", ")" ]
Get filenames of raw GSOD station data.
[ "Get", "filenames", "of", "raw", "GSOD", "station", "data", "." ]
python
train
62
SheffieldML/GPy
GPy/util/univariate_Gaussian.py
https://github.com/SheffieldML/GPy/blob/54c32d79d289d622fb18b898aee65a2a431d90cf/GPy/util/univariate_Gaussian.py#L54-L68
def logCdfNormal(z): """ Robust implementations of log cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger. """ if (abs(z) < ERF_CODY_LIMIT1): # Phi(z) approx (1+y...
[ "def", "logCdfNormal", "(", "z", ")", ":", "if", "(", "abs", "(", "z", ")", "<", "ERF_CODY_LIMIT1", ")", ":", "# Phi(z) approx (1+y R_3(y^2))/2, y=z/sqrt(2)", "return", "np", ".", "log1p", "(", "(", "z", "/", "M_SQRT2", ")", "*", "_erfRationalHelperR3", "("...
Robust implementations of log cdf of a standard normal. @see [[https://github.com/mseeger/apbsint/blob/master/src/eptools/potentials/SpecfunServices.h original implementation]] in C from Matthias Seeger.
[ "Robust", "implementations", "of", "log", "cdf", "of", "a", "standard", "normal", "." ]
python
train
43
apache/incubator-mxnet
python/mxnet/gluon/nn/basic_layers.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/gluon/nn/basic_layers.py#L77-L92
def hybridize(self, active=True, **kwargs): """Activates or deactivates `HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. **kwargs : string Additi...
[ "def", "hybridize", "(", "self", ",", "active", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_children", "and", "all", "(", "isinstance", "(", "c", ",", "HybridBlock", ")", "for", "c", "in", "self", ".", "_children", ".", "va...
Activates or deactivates `HybridBlock` s recursively. Has no effect on non-hybrid children. Parameters ---------- active : bool, default True Whether to turn hybrid on or off. **kwargs : string Additional flags for hybridized operator.
[ "Activates", "or", "deactivates", "HybridBlock", "s", "recursively", ".", "Has", "no", "effect", "on", "non", "-", "hybrid", "children", "." ]
python
train
44.875
bskinn/opan
opan/utils/symm.py
https://github.com/bskinn/opan/blob/0b1b21662df6abc971407a9386db21a8796fbfe5/opan/utils/symm.py#L150-L169
def geom_reflect(g, nv): """ Reflection symmetry operation. nv is normal vector to reflection plane g is assumed already translated to center of mass @ origin .. todo:: Complete geom_reflect docstring """ # Imports import numpy as np # Force g to n-vector g = make_nd_vec(g, nd=N...
[ "def", "geom_reflect", "(", "g", ",", "nv", ")", ":", "# Imports", "import", "numpy", "as", "np", "# Force g to n-vector", "g", "=", "make_nd_vec", "(", "g", ",", "nd", "=", "None", ",", "t", "=", "np", ".", "float64", ",", "norm", "=", "False", ")",...
Reflection symmetry operation. nv is normal vector to reflection plane g is assumed already translated to center of mass @ origin .. todo:: Complete geom_reflect docstring
[ "Reflection", "symmetry", "operation", "." ]
python
train
24.7
QUANTAXIS/QUANTAXIS
QUANTAXIS/QAFetch/QATdx.py
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAFetch/QATdx.py#L1285-L1305
def QA_fetch_get_hkstock_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2...
[ "def", "QA_fetch_get_hkstock_list", "(", "ip", "=", "None", ",", "port", "=", "None", ")", ":", "global", "extension_market_list", "extension_market_list", "=", "QA_fetch_get_extensionmarket_list", "(", ")", "if", "extension_market_list", "is", "None", "else", "extens...
[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 2 香港创业板 KG 49 2 香港基金 ...
[ "[", "summary", "]" ]
python
train
30.619048
google/mobly
mobly/controllers/android_device_lib/event_dispatcher.py
https://github.com/google/mobly/blob/38ba2cf7d29a20e6a2fca1718eecb337df38db26/mobly/controllers/android_device_lib/event_dispatcher.py#L247-L285
def pop_events(self, regex_pattern, timeout): """Pop events whose names match a regex pattern. If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout. Results are...
[ "def", "pop_events", "(", "self", ",", "regex_pattern", ",", "timeout", ")", ":", "if", "not", "self", ".", "started", ":", "raise", "IllegalStateError", "(", "\"Dispatcher needs to be started before popping.\"", ")", "deadline", "=", "time", ".", "time", "(", "...
Pop events whose names match a regex pattern. If such event(s) exist, pop one event from each event queue that satisfies the condition. Otherwise, wait for an event that satisfies the condition to occur, with timeout. Results are sorted by timestamp in ascending order. Args: ...
[ "Pop", "events", "whose", "names", "match", "a", "regex", "pattern", "." ]
python
train
40.102564
faucamp/python-gsmmodem
gsmmodem/modem.py
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L847-L855
def _handleModemNotification(self, lines): """ Handler for unsolicited notifications from the modem This method simply spawns a separate thread to handle the actual notification (in order to release the read thread so that the handlers are able to write back to the modem, etc) ...
[ "def", "_handleModemNotification", "(", "self", ",", "lines", ")", ":", "threading", ".", "Thread", "(", "target", "=", "self", ".", "__threadedHandleModemNotification", ",", "kwargs", "=", "{", "'lines'", ":", "lines", "}", ")", ".", "start", "(", ")" ]
Handler for unsolicited notifications from the modem This method simply spawns a separate thread to handle the actual notification (in order to release the read thread so that the handlers are able to write back to the modem, etc) :param lines The lines that were read
[ "Handler", "for", "unsolicited", "notifications", "from", "the", "modem", "This", "method", "simply", "spawns", "a", "separate", "thread", "to", "handle", "the", "actual", "notification", "(", "in", "order", "to", "release", "the", "read", "thread", "so", "tha...
python
train
52.777778
bpython/curtsies
curtsies/formatstring.py
https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/formatstring.py#L348-L351
def copy_with_new_atts(self, **attributes): """Returns a new FmtStr with the same content but new formatting""" return FmtStr(*[Chunk(bfs.s, bfs.atts.extend(attributes)) for bfs in self.chunks])
[ "def", "copy_with_new_atts", "(", "self", ",", "*", "*", "attributes", ")", ":", "return", "FmtStr", "(", "*", "[", "Chunk", "(", "bfs", ".", "s", ",", "bfs", ".", "atts", ".", "extend", "(", "attributes", ")", ")", "for", "bfs", "in", "self", ".",...
Returns a new FmtStr with the same content but new formatting
[ "Returns", "a", "new", "FmtStr", "with", "the", "same", "content", "but", "new", "formatting" ]
python
train
57.75
MKLab-ITI/reveal-graph-embedding
reveal_graph_embedding/learning/holdout.py
https://github.com/MKLab-ITI/reveal-graph-embedding/blob/eda862687aa5a64b79c6b12de1b4dca6ce986dc8/reveal_graph_embedding/learning/holdout.py#L80-L111
def generate_folds(node_label_matrix, labelled_node_indices, number_of_categories, percentage, number_of_folds=10): """ Form the seed nodes for training and testing. Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format. - labelled_node_indices: A NumPy arra...
[ "def", "generate_folds", "(", "node_label_matrix", ",", "labelled_node_indices", ",", "number_of_categories", ",", "percentage", ",", "number_of_folds", "=", "10", ")", ":", "number_of_labeled_nodes", "=", "labelled_node_indices", ".", "size", "training_set_size", "=", ...
Form the seed nodes for training and testing. Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format. - labelled_node_indices: A NumPy array containing the labelled node indices. - number_of_categories: The number of categories/classes in the learning. ...
[ "Form", "the", "seed", "nodes", "for", "training", "and", "testing", "." ]
python
train
49.03125
coleifer/irc
botnet/worker.py
https://github.com/coleifer/irc/blob/f9d2bd6369aafe6cb0916c9406270ca8ecea2080/botnet/worker.py#L123-L134
def register_success(self, nick, message, channel, cmd_channel): """\ Received registration acknowledgement from the BotnetBot, as well as the name of the command channel, so join up and indicate that registration succeeded """ # the boss will tell what channel to join ...
[ "def", "register_success", "(", "self", ",", "nick", ",", "message", ",", "channel", ",", "cmd_channel", ")", ":", "# the boss will tell what channel to join", "self", ".", "channel", "=", "cmd_channel", "self", ".", "conn", ".", "join", "(", "self", ".", "cha...
\ Received registration acknowledgement from the BotnetBot, as well as the name of the command channel, so join up and indicate that registration succeeded
[ "\\", "Received", "registration", "acknowledgement", "from", "the", "BotnetBot", "as", "well", "as", "the", "name", "of", "the", "command", "channel", "so", "join", "up", "and", "indicate", "that", "registration", "succeeded" ]
python
test
39.416667
saltstack/salt
salt/modules/boto_elb.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L879-L904
def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, ...
[ "def", "delete_policy", "(", "name", ",", "policy_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", ...
Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy
[ "Delete", "an", "ELB", "policy", "." ]
python
train
30.230769
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L494-L509
def init_environment(self): """Configure the user's environment. """ env = os.environ # These two ensure 'ls' produces nice coloring on BSD-derived systems env['TERM'] = 'xterm-color' env['CLICOLOR'] = '1' # Since normal pagers don't work at all (over pexpect we ...
[ "def", "init_environment", "(", "self", ")", ":", "env", "=", "os", ".", "environ", "# These two ensure 'ls' produces nice coloring on BSD-derived systems", "env", "[", "'TERM'", "]", "=", "'xterm-color'", "env", "[", "'CLICOLOR'", "]", "=", "'1'", "# Since normal pag...
Configure the user's environment.
[ "Configure", "the", "user", "s", "environment", "." ]
python
test
36.625
Microsoft/nni
src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/networkmorphism_tuner/layer_transformer.py#L223-L229
def add_noise(weights, other_weights): '''add noise to the layer. ''' w_range = np.ptp(other_weights.flatten()) noise_range = NOISE_RATIO * w_range noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape) return np.add(noise, weights)
[ "def", "add_noise", "(", "weights", ",", "other_weights", ")", ":", "w_range", "=", "np", ".", "ptp", "(", "other_weights", ".", "flatten", "(", ")", ")", "noise_range", "=", "NOISE_RATIO", "*", "w_range", "noise", "=", "np", ".", "random", ".", "uniform...
add noise to the layer.
[ "add", "noise", "to", "the", "layer", "." ]
python
train
39.285714
quantopian/zipline
zipline/data/data_portal.py
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/data/data_portal.py#L410-L420
def _is_extra_source(asset, field, map): """ Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup. """ # If we have an extra source with a column called "price", only look # at it if it's on something like p...
[ "def", "_is_extra_source", "(", "asset", ",", "field", ",", "map", ")", ":", "# If we have an extra source with a column called \"price\", only look", "# at it if it's on something like palladium and not AAPL (since our", "# own price data always wins when dealing with assets).", "return",...
Internal method that determines if this asset/field combination represents a fetcher value or a regular OHLCVP lookup.
[ "Internal", "method", "that", "determines", "if", "this", "asset", "/", "field", "combination", "represents", "a", "fetcher", "value", "or", "a", "regular", "OHLCVP", "lookup", "." ]
python
train
47.272727
vsoch/helpme
helpme/utils/settings.py
https://github.com/vsoch/helpme/blob/e609172260b10cddadb2d2023ab26da8082a9feb/helpme/utils/settings.py#L56-L80
def generate_keypair(keypair_file): '''generate_keypair is used by some of the helpers that need a keypair. The function should be used if the client doesn't have the attribute self.key. We generate the key and return it. We use pycryptodome (3.7.2) Parameters ========= ...
[ "def", "generate_keypair", "(", "keypair_file", ")", ":", "from", "Crypto", ".", "PublicKey", "import", "RSA", "key", "=", "RSA", ".", "generate", "(", "2048", ")", "# Ensure helper directory exists", "keypair_dir", "=", "os", ".", "path", ".", "dirname", "(",...
generate_keypair is used by some of the helpers that need a keypair. The function should be used if the client doesn't have the attribute self.key. We generate the key and return it. We use pycryptodome (3.7.2) Parameters ========= keypair_file: fullpath to where to s...
[ "generate_keypair", "is", "used", "by", "some", "of", "the", "helpers", "that", "need", "a", "keypair", ".", "The", "function", "should", "be", "used", "if", "the", "client", "doesn", "t", "have", "the", "attribute", "self", ".", "key", ".", "We", "gener...
python
train
28.08
Azure/blobxfer
blobxfer/operations/azure/__init__.py
https://github.com/Azure/blobxfer/blob/3eccbe7530cc6a20ab2d30f9e034b6f021817f34/blobxfer/operations/azure/__init__.py#L443-L479
def _convert_to_storage_entity_with_encryption_metadata( self, options, store_raw_metadata, sa, entity, vio, is_file, container, dir, file_snapshot): # type: (SourcePath, StorageCredentials, any, bool, StorageAccount, # any, blobxfer.models.metadata.VectoredStripe, bool, s...
[ "def", "_convert_to_storage_entity_with_encryption_metadata", "(", "self", ",", "options", ",", "store_raw_metadata", ",", "sa", ",", "entity", ",", "vio", ",", "is_file", ",", "container", ",", "dir", ",", "file_snapshot", ")", ":", "# type: (SourcePath, StorageCrede...
Convert entity into StorageEntity with encryption metadata if avail :param SourcePath self: this :param StorageCredentials creds: storage creds :param object options: download or synccopy options :param bool store_raw_metadata: store raw metadata :param StorageAccount sa: storage...
[ "Convert", "entity", "into", "StorageEntity", "with", "encryption", "metadata", "if", "avail", ":", "param", "SourcePath", "self", ":", "this", ":", "param", "StorageCredentials", "creds", ":", "storage", "creds", ":", "param", "object", "options", ":", "downloa...
python
train
48.027027
cggh/scikit-allel
allel/model/ndarray.py
https://github.com/cggh/scikit-allel/blob/3c979a57a100240ba959dd13f98839349530f215/allel/model/ndarray.py#L1036-L1099
def map_alleles(self, mapping, copy=True): """Transform alleles via a mapping. Parameters ---------- mapping : ndarray, int8, shape (n_variants, max_allele) An array defining the allele mapping for each variant. copy : bool, optional If True, return a new...
[ "def", "map_alleles", "(", "self", ",", "mapping", ",", "copy", "=", "True", ")", ":", "h", "=", "self", ".", "to_haplotypes", "(", ")", "hm", "=", "h", ".", "map_alleles", "(", "mapping", ",", "copy", "=", "copy", ")", "if", "self", ".", "ndim", ...
Transform alleles via a mapping. Parameters ---------- mapping : ndarray, int8, shape (n_variants, max_allele) An array defining the allele mapping for each variant. copy : bool, optional If True, return a new array; if False, apply mapping in place (...
[ "Transform", "alleles", "via", "a", "mapping", "." ]
python
train
30.640625
Legobot/Legobot
Legobot/Connectors/Discord.py
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L37-L50
def send(self, ws, seq): """ Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat """ payload = {'op': 1, 'd': seq} payload = json.dumps(payload) logger.debug("Sending heartb...
[ "def", "send", "(", "self", ",", "ws", ",", "seq", ")", ":", "payload", "=", "{", "'op'", ":", "1", ",", "'d'", ":", "seq", "}", "payload", "=", "json", ".", "dumps", "(", "payload", ")", "logger", ".", "debug", "(", "\"Sending heartbeat with payload...
Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat
[ "Sends", "heartbeat", "message", "to", "Discord" ]
python
train
27.428571
pyroscope/pyrobase
src/pyrobase/webservice/imgur.py
https://github.com/pyroscope/pyrobase/blob/7a2591baa492c3d8997ab4801b97c7b1f2ebc6b1/src/pyrobase/webservice/imgur.py#L178-L192
def _main(): """ Command line interface for testing. """ import pprint import tempfile try: image = sys.argv[1] except IndexError: print("Usage: python -m pyrobase.webservice.imgur <url>") else: try: pprint.pprint(copy_image_from_url(image, cache_dir=temp...
[ "def", "_main", "(", ")", ":", "import", "pprint", "import", "tempfile", "try", ":", "image", "=", "sys", ".", "argv", "[", "1", "]", "except", "IndexError", ":", "print", "(", "\"Usage: python -m pyrobase.webservice.imgur <url>\"", ")", "else", ":", "try", ...
Command line interface for testing.
[ "Command", "line", "interface", "for", "testing", "." ]
python
train
26.933333
facebook/pyre-check
sapp/sapp/trimmed_trace_graph.py
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/trimmed_trace_graph.py#L333-L347
def _add_trace_frame(self, graph: TraceGraph, trace_frame: TraceFrame) -> None: """ Copies the trace frame from 'graph' to this (self) graph. Also copies all the trace_frame-leaf assocs since we don't know which ones are needed until we know the issue that reaches it """ trace_fr...
[ "def", "_add_trace_frame", "(", "self", ",", "graph", ":", "TraceGraph", ",", "trace_frame", ":", "TraceFrame", ")", "->", "None", ":", "trace_frame_id", "=", "trace_frame", ".", "id", ".", "local_id", "self", ".", "add_trace_frame", "(", "trace_frame", ")", ...
Copies the trace frame from 'graph' to this (self) graph. Also copies all the trace_frame-leaf assocs since we don't know which ones are needed until we know the issue that reaches it
[ "Copies", "the", "trace", "frame", "from", "graph", "to", "this", "(", "self", ")", "graph", ".", "Also", "copies", "all", "the", "trace_frame", "-", "leaf", "assocs", "since", "we", "don", "t", "know", "which", "ones", "are", "needed", "until", "we", ...
python
train
57.8
adafruit/Adafruit_Python_LED_Backpack
Adafruit_LED_Backpack/HT16K33.py
https://github.com/adafruit/Adafruit_Python_LED_Backpack/blob/7356b4dd8b4bb162d60987878c2cb752fdd017d5/Adafruit_LED_Backpack/HT16K33.py#L69-L75
def set_brightness(self, brightness): """Set brightness of entire display to specified value (16 levels, from 0 to 15). """ if brightness < 0 or brightness > 15: raise ValueError('Brightness must be a value of 0 to 15.') self._device.writeList(HT16K33_CMD_BRIGHTNESS |...
[ "def", "set_brightness", "(", "self", ",", "brightness", ")", ":", "if", "brightness", "<", "0", "or", "brightness", ">", "15", ":", "raise", "ValueError", "(", "'Brightness must be a value of 0 to 15.'", ")", "self", ".", "_device", ".", "writeList", "(", "HT...
Set brightness of entire display to specified value (16 levels, from 0 to 15).
[ "Set", "brightness", "of", "entire", "display", "to", "specified", "value", "(", "16", "levels", "from", "0", "to", "15", ")", "." ]
python
train
47.142857
twosigma/marbles
marbles/mixins/marbles/mixins/mixins.py
https://github.com/twosigma/marbles/blob/f0c668be8344c70d4d63bc57e82c6f2da43c6925/marbles/mixins/marbles/mixins/mixins.py#L1707-L1731
def assertTimeZoneNotEqual(self, dt, tz, msg=None): '''Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as determined by the '!=' operator. Parameters ---------- dt : datetime tz : timezone msg : str If not provided, the :mod:`marbles.mixins` or ...
[ "def", "assertTimeZoneNotEqual", "(", "self", ",", "dt", ",", "tz", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "'First argument is not a datetime object'", ")", "if", "not", ...
Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as determined by the '!=' operator. Parameters ---------- dt : datetime tz : timezone msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. ...
[ "Fail", "if", "dt", "s", "tzinfo", "attribute", "equals", "tz", "as", "determined", "by", "the", "!", "=", "operator", "." ]
python
train
32.2
josiahcarlson/rom
rom/query.py
https://github.com/josiahcarlson/rom/blob/8b5607a856341df85df33422accc30ba9294dbdb/rom/query.py#L198-L291
def filter(self, **kwargs): ''' Only columns/attributes that have been specified as having an index with the ``index=True`` option on the column definition can be filtered with this method. Prefix, suffix, and pattern match filters must be provided using the ``.startswith()``, ``...
[ "def", "filter", "(", "self", ",", "*", "*", "kwargs", ")", ":", "cur_filters", "=", "list", "(", "self", ".", "_filters", ")", "for", "attr", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "value", "=", "self", ".", "_check", "(", "a...
Only columns/attributes that have been specified as having an index with the ``index=True`` option on the column definition can be filtered with this method. Prefix, suffix, and pattern match filters must be provided using the ``.startswith()``, ``.endswith()``, and the ``.like()`` metho...
[ "Only", "columns", "/", "attributes", "that", "have", "been", "specified", "as", "having", "an", "index", "with", "the", "index", "=", "True", "option", "on", "the", "column", "definition", "can", "be", "filtered", "with", "this", "method", ".", "Prefix", ...
python
test
39.478723
cimm-kzn/CGRtools
CGRtools/algorithms/isomorphism.py
https://github.com/cimm-kzn/CGRtools/blob/15a19b04f6e4e1d0dab8e0d32a0877c7f7d70f34/CGRtools/algorithms/isomorphism.py#L64-L79
def get_substructure_mapping(self, other, limit=1): """ get self to other substructure mapping :param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None; if > 1 return list of dicts """ i = self._matcher(other).subgraph_isomorph...
[ "def", "get_substructure_mapping", "(", "self", ",", "other", ",", "limit", "=", "1", ")", ":", "i", "=", "self", ".", "_matcher", "(", "other", ")", ".", "subgraph_isomorphisms_iter", "(", ")", "if", "limit", "==", "1", ":", "m", "=", "next", "(", "...
get self to other substructure mapping :param limit: number of matches. if 0 return iterator for all possible; if 1 return dict or None; if > 1 return list of dicts
[ "get", "self", "to", "other", "substructure", "mapping" ]
python
train
38.5
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/thread.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1892-L1919
def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False): """ Remotely creates a new thread in the process. @type lpStartAddress: int @param lpStartAddress: Start address for the new thread. @type lpParameter: int @param lpParameter: Optional argumen...
[ "def", "start_thread", "(", "self", ",", "lpStartAddress", ",", "lpParameter", "=", "0", ",", "bSuspended", "=", "False", ")", ":", "if", "bSuspended", ":", "dwCreationFlags", "=", "win32", ".", "CREATE_SUSPENDED", "else", ":", "dwCreationFlags", "=", "0", "...
Remotely creates a new thread in the process. @type lpStartAddress: int @param lpStartAddress: Start address for the new thread. @type lpParameter: int @param lpParameter: Optional argument for the new thread. @type bSuspended: bool @param bSuspended: C{True} if the...
[ "Remotely", "creates", "a", "new", "thread", "in", "the", "process", "." ]
python
train
43.357143
hazelcast/hazelcast-python-client
hazelcast/proxy/queue.py
https://github.com/hazelcast/hazelcast-python-client/blob/3f6639443c23d6d036aa343f8e094f052250d2c1/hazelcast/proxy/queue.py#L252-L265
def retain_all(self, items): """ Removes the items which are not contained in the specified collection. In other words, only the items that are contained in the specified collection will be retained. :param items: (Collection), collection which includes the elements to be retained in th...
[ "def", "retain_all", "(", "self", ",", "items", ")", ":", "check_not_none", "(", "items", ",", "\"Value can't be None\"", ")", "data_items", "=", "[", "]", "for", "item", "in", "items", ":", "check_not_none", "(", "item", ",", "\"Value can't be None\"", ")", ...
Removes the items which are not contained in the specified collection. In other words, only the items that are contained in the specified collection will be retained. :param items: (Collection), collection which includes the elements to be retained in this set. :return: (bool), ``true`` if this...
[ "Removes", "the", "items", "which", "are", "not", "contained", "in", "the", "specified", "collection", ".", "In", "other", "words", "only", "the", "items", "that", "are", "contained", "in", "the", "specified", "collection", "will", "be", "retained", "." ]
python
train
50.785714
bcbio/bcbio-nextgen
bcbio/structural/purecn.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/structural/purecn.py#L77-L118
def _run_purecn(paired, work_dir): """Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs. """ segfns = {"cnvkit": _segment_normalized_cnvkit, "gatk-cnv": _segment_normalized_gatk} out_base, out, all_files = _get_purecn_files(paired, work_dir) failed_file = out_base + "-failed.log" cn...
[ "def", "_run_purecn", "(", "paired", ",", "work_dir", ")", ":", "segfns", "=", "{", "\"cnvkit\"", ":", "_segment_normalized_cnvkit", ",", "\"gatk-cnv\"", ":", "_segment_normalized_gatk", "}", "out_base", ",", "out", ",", "all_files", "=", "_get_purecn_files", "(",...
Run PureCN.R wrapper with pre-segmented CNVkit or GATK4 inputs.
[ "Run", "PureCN", ".", "R", "wrapper", "with", "pre", "-", "segmented", "CNVkit", "or", "GATK4", "inputs", "." ]
python
train
65.142857
nyrkovalex/httpsrv
httpsrv/httpsrv.py
https://github.com/nyrkovalex/httpsrv/blob/0acc3298be56856f73bda1ed10c9ab5153894b01/httpsrv/httpsrv.py#L248-L261
def start(self): ''' Starts a server on the port provided in the :class:`Server` constructor in a separate thread :rtype: Server :returns: server instance for chaining ''' self._handler = _create_handler_class(self._rules, self._always_rules) self._server...
[ "def", "start", "(", "self", ")", ":", "self", ".", "_handler", "=", "_create_handler_class", "(", "self", ".", "_rules", ",", "self", ".", "_always_rules", ")", "self", ".", "_server", "=", "HTTPServer", "(", "(", "''", ",", "self", ".", "_port", ")",...
Starts a server on the port provided in the :class:`Server` constructor in a separate thread :rtype: Server :returns: server instance for chaining
[ "Starts", "a", "server", "on", "the", "port", "provided", "in", "the", ":", "class", ":", "Server", "constructor", "in", "a", "separate", "thread" ]
python
train
36.285714
gem/oq-engine
openquake/hazardlib/gsim/nshmp_2014.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/nshmp_2014.py#L75-L96
def nga_west2_epistemic_adjustment(magnitude, distance): """ Applies the "average" adjustment factor for epistemic uncertainty as defined in Table 17 of Petersen et al., (2014):: | R < 10. | 10.0 <= R < 30.0 | R >= 30.0 -----------------------------------------------------------...
[ "def", "nga_west2_epistemic_adjustment", "(", "magnitude", ",", "distance", ")", ":", "if", "magnitude", "<", "6.0", ":", "adjustment", "=", "0.22", "*", "np", ".", "ones_like", "(", "distance", ")", "adjustment", "[", "distance", "<", "10.0", "]", "=", "0...
Applies the "average" adjustment factor for epistemic uncertainty as defined in Table 17 of Petersen et al., (2014):: | R < 10. | 10.0 <= R < 30.0 | R >= 30.0 ----------------------------------------------------------- M < 6.0 | 0.37 | 0.22 | 0.22 6...
[ "Applies", "the", "average", "adjustment", "factor", "for", "epistemic", "uncertainty", "as", "defined", "in", "Table", "17", "of", "Petersen", "et", "al", ".", "(", "2014", ")", "::" ]
python
train
41