text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def add_variable(self, name, fetch_as=None): """Add a new variable to the configuration. name - Complete name of the variable in the form group.name fetch_as - String representation of the type the variable should be fetched as (i.e uint8_t, float, FP16, etc) If no f...
[ "def", "add_variable", "(", "self", ",", "name", ",", "fetch_as", "=", "None", ")", ":", "if", "fetch_as", ":", "self", ".", "variables", ".", "append", "(", "LogVariable", "(", "name", ",", "fetch_as", ")", ")", "else", ":", "# We cannot determine the def...
47.9375
0.002558
def read_paraphrase_file(filename): ''' Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) assert doc.getroot().tag == 'w...
[ "def", "read_paraphrase_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "input_file", ":", "doc", "=", "etree", ".", "parse", "(", "input_file", ")", "assert", "doc", ".", "getroot", "(", ")", ".", "tag", "=="...
40.131579
0.00064
def parse(self, words, S='S'): """Parse a list of words; according to the grammar. Leave results in the chart.""" self.chart = [[] for i in range(len(words)+1)] self.add_edge([0, 0, 'S_', [], [S]]) for i in range(len(words)): self.scanner(i, words[i]) return s...
[ "def", "parse", "(", "self", ",", "words", ",", "S", "=", "'S'", ")", ":", "self", ".", "chart", "=", "[", "[", "]", "for", "i", "in", "range", "(", "len", "(", "words", ")", "+", "1", ")", "]", "self", ".", "add_edge", "(", "[", "0", ",", ...
40.25
0.006079
def on_message(self, ws, message): """Websocket on_message event handler Saves message as RTMMessage in self._inbox """ try: data = json.loads(message) except Exception: self._set_error(message, "decode message failed") else: self._inb...
[ "def", "on_message", "(", "self", ",", "ws", ",", "message", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "message", ")", "except", "Exception", ":", "self", ".", "_set_error", "(", "message", ",", "\"decode message failed\"", ")", "else...
30.363636
0.005814
def concatenate(cls, datasets, datatype=None, new_type=None): """ Utility function to concatenate an NdMapping of Dataset objects. """ from . import Dataset, default_datatype new_type = new_type or Dataset if isinstance(datasets, NdMapping): dimensions = datas...
[ "def", "concatenate", "(", "cls", ",", "datasets", ",", "datatype", "=", "None", ",", "new_type", "=", "None", ")", ":", "from", ".", "import", "Dataset", ",", "default_datatype", "new_type", "=", "new_type", "or", "Dataset", "if", "isinstance", "(", "data...
50.111111
0.004894
def extract(self, html_text: str, strategy: Strategy=Strategy.ALL_TEXT) \ -> List[Extraction]: """ Extracts text from an HTML page using a variety of strategies Args: html_text (str): html page in string strategy (enum[Strategy.ALL_TEXT, Strategy.MAIN_CONTENT...
[ "def", "extract", "(", "self", ",", "html_text", ":", "str", ",", "strategy", ":", "Strategy", "=", "Strategy", ".", "ALL_TEXT", ")", "->", "List", "[", "Extraction", "]", ":", "if", "html_text", ":", "if", "strategy", "==", "Strategy", ".", "ALL_TEXT", ...
46.275862
0.006569
def populate_token_attributes(self, response): """Add attributes from a token exchange response to self.""" if 'access_token' in response: self.access_token = response.get('access_token') if 'refresh_token' in response: self.refresh_token = response.get('refresh_token')...
[ "def", "populate_token_attributes", "(", "self", ",", "response", ")", ":", "if", "'access_token'", "in", "response", ":", "self", ".", "access_token", "=", "response", ".", "get", "(", "'access_token'", ")", "if", "'refresh_token'", "in", "response", ":", "se...
35.166667
0.002307
def do_startInstance(self,args): """Start specified instance""" parser = CommandArgumentParser("startInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] force = args['force'] ...
[ "def", "do_startInstance", "(", "self", ",", "args", ")", ":", "parser", "=", "CommandArgumentParser", "(", "\"startInstance\"", ")", "parser", ".", "add_argument", "(", "dest", "=", "'instance'", ",", "help", "=", "'instance index or name'", ")", "args", "=", ...
38.294118
0.008996
def config(): """ Load system configuration @rtype: ConfigParser """ cfg = ConfigParser() cfg.read(os.path.join(os.path.dirname(os.path.realpath(ips_vagrant.__file__)), 'config/ipsv.conf')) return cfg
[ "def", "config", "(", ")", ":", "cfg", "=", "ConfigParser", "(", ")", "cfg", ".", "read", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "ips_vagrant", ".", "__file__", "...
27.625
0.008772
def nvmlDeviceRegisterEvents(handle, eventTypes, eventSet): r""" /** * Starts recording of events on a specified devices and add the events to specified \ref nvmlEventSet_t * * For Fermi &tm; or newer fully supported devices. * Ecc events are available only on ECC enabled devices (see \ref n...
[ "def", "nvmlDeviceRegisterEvents", "(", "handle", ",", "eventTypes", ",", "eventSet", ")", ":", "fn", "=", "_nvmlGetFunctionPointer", "(", "\"nvmlDeviceRegisterEvents\"", ")", "ret", "=", "fn", "(", "handle", ",", "c_ulonglong", "(", "eventTypes", ")", ",", "eve...
51.454545
0.005635
def clip_by_extent(layer, extent): """Clip a raster using a bounding box using processing. Issue https://github.com/inasafe/inasafe/issues/3183 :param layer: The layer to clip. :type layer: QgsRasterLayer :param extent: The extent. :type extent: QgsRectangle :return: Clipped layer. :...
[ "def", "clip_by_extent", "(", "layer", ",", "extent", ")", ":", "parameters", "=", "dict", "(", ")", "# noinspection PyBroadException", "try", ":", "output_layer_name", "=", "quick_clip_steps", "[", "'output_layer_name'", "]", "output_layer_name", "=", "output_layer_n...
34.904762
0.000265
def write_template(fn, lang="python"): """ Write language-specific script template to file. Arguments: - fn(``string``) path to save the template to - lang('python', 'bash') which programming language """ with open(fn, "wb") as fh: if lang == "python": fh.wri...
[ "def", "write_template", "(", "fn", ",", "lang", "=", "\"python\"", ")", ":", "with", "open", "(", "fn", ",", "\"wb\"", ")", "as", "fh", ":", "if", "lang", "==", "\"python\"", ":", "fh", ".", "write", "(", "PY_TEMPLATE", ")", "elif", "lang", "==", ...
25.6
0.005025
def attach(self, container, stdout=True, stderr=True, stream=False, logs=False, demux=False): """ Attach to a container. The ``.logs()`` function is a wrapper around this method, which you can use instead if you want to fetch/stream container output without first ...
[ "def", "attach", "(", "self", ",", "container", ",", "stdout", "=", "True", ",", "stderr", "=", "True", ",", "stream", "=", "False", ",", "logs", "=", "False", ",", "demux", "=", "False", ")", ":", "params", "=", "{", "'logs'", ":", "logs", "and", ...
35.057692
0.001601
def can_attack_air(self) -> bool: """ Does not include upgrades """ if self._weapons: weapon = next( (weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}), None, ) return weapon is not None ...
[ "def", "can_attack_air", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_weapons", ":", "weapon", "=", "next", "(", "(", "weapon", "for", "weapon", "in", "self", ".", "_weapons", "if", "weapon", ".", "type", "in", "{", "TargetType", ".", "A...
36.888889
0.008824
def main(): """ NAME convert2unix.py DESCRIPTION converts mac or dos formatted file to unix file in place SYNTAX convert2unix.py FILE OPTIONS -h prints help and quits """ if '-h' in sys.argv: print(main.__doc__) sys.exit() ...
[ "def", "main", "(", ")", ":", "if", "'-h'", "in", "sys", ".", "argv", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "file", "=", "sys", ".", "argv", "[", "1", "]", "f", "=", "open", "(", "file", ",", "'r'", "...
17.615385
0.024845
def is_owner(self, user): """ Checks if user is the owner of object Parameters ---------- user: get_user_model() instance Returns ------- bool Author ------ Himanshu Shankar (https://himanshus.com) """ if user.is_...
[ "def", "is_owner", "(", "self", ",", "user", ")", ":", "if", "user", ".", "is_authenticated", ":", "return", "self", ".", "created_by", ".", "id", "==", "user", ".", "id", "return", "False" ]
20.315789
0.00495
def account_overview(object): """Create layout for user profile""" return Layout( Container( Row( Column2( Panel( 'Avatar', Img(src="{}{}".format(settings.MEDIA_URL, object.avatar)), c...
[ "def", "account_overview", "(", "object", ")", ":", "return", "Layout", "(", "Container", "(", "Row", "(", "Column2", "(", "Panel", "(", "'Avatar'", ",", "Img", "(", "src", "=", "\"{}{}\"", ".", "format", "(", "settings", ".", "MEDIA_URL", ",", "object",...
28.4
0.002725
def low(self, fun, low, print_event=True, full_return=False): ''' Execute a function from low data Low data includes: required: - fun: the name of the function to run optional: - arg: a list of args to pass to fun - kwarg: k...
[ "def", "low", "(", "self", ",", "fun", ",", "low", ",", "print_event", "=", "True", ",", "full_return", "=", "False", ")", ":", "# fire the mminion loading (if not already done) here", "# this is not to clutter the output with the module loading", "# if we have a high debug l...
43.271084
0.001633
def dataset_create_new_cli(self, folder=None, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ client wrapper for creating a new dataset...
[ "def", "dataset_create_new_cli", "(", "self", ",", "folder", "=", "None", ",", "public", "=", "False", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "dir_mode", "=", "'skip'", ")", ":", "folder", "=", "folder", "or", "os", ".", "...
48.466667
0.005394
def field(cls, field, query, boost=None, enable_position_increments=None): ''' A query that executes a query string against a specific field. It is a simplified version of query_string query (by setting the default_field to the field this query executed against). In its simplest form: { ...
[ "def", "field", "(", "cls", ",", "field", ",", "query", ",", "boost", "=", "None", ",", "enable_position_increments", "=", "None", ")", ":", "instance", "=", "cls", "(", "field", "=", "{", "field", ":", "{", "'query'", ":", "query", "}", "}", ")", ...
40.296296
0.004488
def get(path, name): # type: (str, str) -> _EntryPointType """ Args: path (string): Directory where the entry point is located name (string): Name of the entry point file Returns: (_EntryPointType): The type of the entry point """ if 'setup.py' in os.listdir(path): ...
[ "def", "get", "(", "path", ",", "name", ")", ":", "# type: (str, str) -> _EntryPointType", "if", "'setup.py'", "in", "os", ".", "listdir", "(", "path", ")", ":", "return", "_EntryPointType", ".", "PYTHON_PACKAGE", "elif", "name", ".", "endswith", "(", "'.py'",...
31.266667
0.00207
def _check_file_field(self, field): """Check that field exists and is a file field""" is_field = field in self.field_names is_file = self.__meta_metadata(field, 'field_type') == 'file' if not (is_field and is_file): msg = "'%s' is not a field or not a 'file' field" % field ...
[ "def", "_check_file_field", "(", "self", ",", "field", ")", ":", "is_field", "=", "field", "in", "self", ".", "field_names", "is_file", "=", "self", ".", "__meta_metadata", "(", "field", ",", "'field_type'", ")", "==", "'file'", "if", "not", "(", "is_field...
42.333333
0.005141
def destroy_vm(self, vm, logger): """ destroy the given vm :param vm: virutal machine pyvmomi object :param logger: """ self.power_off_before_destroy(logger, vm) logger.info(("Destroying VM {0}".format(vm.name))) task = vm.Destroy_Task() retu...
[ "def", "destroy_vm", "(", "self", ",", "vm", ",", "logger", ")", ":", "self", ".", "power_off_before_destroy", "(", "logger", ",", "vm", ")", "logger", ".", "info", "(", "(", "\"Destroying VM {0}\"", ".", "format", "(", "vm", ".", "name", ")", ")", ")"...
30.230769
0.012346
def ll(self,*args,**kwargs): """ NAME: ll PURPOSE: return Galactic longitude INPUT: t - (optional) time at which to get ll (can be Quantity) obs=[X,Y,Z] - (optional) position of observer (in kpc; entries can be Quantity) (defa...
[ "def", "ll", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "out", "=", "self", ".", "_orb", ".", "ll", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "len", "(", "out", ")", "==", "1", ":", "return", "out", "[", ...
23.40625
0.015385
def capwords(s, sep=None): """capwords(s [,sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single spac...
[ "def", "capwords", "(", "s", ",", "sep", "=", "None", ")", ":", "return", "(", "sep", "or", "' '", ")", ".", "join", "(", "x", ".", "capitalize", "(", ")", "for", "x", "in", "s", ".", "split", "(", "sep", ")", ")" ]
41.166667
0.00198
def pmllpmbb_to_pmrapmdec(pmll,pmbb,l,b,degree=False,epoch=2000.0): """ NAME: pmllpmbb_to_pmrapmdec PURPOSE: rotate proper motions in (l,b) into proper motions in (ra,dec) INPUT: pmll - proper motion in l (multplied with cos(b)) [mas/yr] pmbb - proper motion in b [mas/y...
[ "def", "pmllpmbb_to_pmrapmdec", "(", "pmll", ",", "pmbb", ",", "l", ",", "b", ",", "degree", "=", "False", ",", "epoch", "=", "2000.0", ")", ":", "theta", ",", "dec_ngp", ",", "ra_ngp", "=", "get_epoch_angles", "(", "epoch", ")", "#Whether to use degrees a...
31.789474
0.025161
def generatePandaEnumCols(pandaFtrain, cname, nrows, domainL): """ For an H2O Enum column, we perform one-hot-encoding here and add one more column, "missing(NA)" to it. :param pandaFtrain: panda frame derived from H2OFrame :param cname: column name of enum col :param nrows: number of rows of enum ...
[ "def", "generatePandaEnumCols", "(", "pandaFtrain", ",", "cname", ",", "nrows", ",", "domainL", ")", ":", "import", "numpy", "as", "np", "import", "pandas", "as", "pd", "cmissingNames", "=", "[", "cname", "+", "\".missing(NA)\"", "]", "tempnp", "=", "np", ...
35.029412
0.007353
def draw(self, clear=True): """Draw each visible mesh in the scene from the perspective of the scene's camera and lit by its light.""" if clear: self.clear() with self.gl_states, self.camera, self.light: for mesh in self.meshes: try: m...
[ "def", "draw", "(", "self", ",", "clear", "=", "True", ")", ":", "if", "clear", ":", "self", ".", "clear", "(", ")", "with", "self", ".", "gl_states", ",", "self", ".", "camera", ",", "self", ".", "light", ":", "for", "mesh", "in", "self", ".", ...
34.909091
0.007614
def extract_pagination(self, params): '''Extract and build pagination from parameters''' try: params_page = int(params.pop('page', 1) or 1) self.page = max(params_page, 1) except: # Failsafe, if page cannot be parsed, we falback on first page self....
[ "def", "extract_pagination", "(", "self", ",", "params", ")", ":", "try", ":", "params_page", "=", "int", "(", "params", ".", "pop", "(", "'page'", ",", "1", ")", "or", "1", ")", "self", ".", "page", "=", "max", "(", "params_page", ",", "1", ")", ...
45.5
0.005384
def merge_overlaps(self): """ Merges overlaps by merging overlapping Intervals. The function takes no arguments and returns ``None``. It operates on the striplog 'in place' TODO: This function will not work if any interval overlaps more than one other intervals at e...
[ "def", "merge_overlaps", "(", "self", ")", ":", "overlaps", "=", "np", ".", "array", "(", "self", ".", "find_overlaps", "(", "index", "=", "True", ")", ")", "if", "not", "overlaps", ".", "any", "(", ")", ":", "return", "for", "overlap", "in", "overla...
27.125
0.002225
def write_alf_params_(self): """ DEPRECATED """ if not hasattr(self, 'alf_dirs'): self.make_alf_dirs() if not hasattr(self, 'class_trees'): self.generate_class_trees() alf_params = {} for k in range(self.num_classes): alfdir = self.alf_dirs[k...
[ "def", "write_alf_params_", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'alf_dirs'", ")", ":", "self", ".", "make_alf_dirs", "(", ")", "if", "not", "hasattr", "(", "self", ",", "'class_trees'", ")", ":", "self", ".", "generate_class...
38.758621
0.003472
def harris_feature(im, region_size=5, to_return='harris', scale=0.05): """ Harris-motivated feature detection on a d-dimensional image. Parameters --------- im region_size to_return : {'harris','matrix','trace-determinant'} """ ndim = im.ndim #1. Gradient of image ...
[ "def", "harris_feature", "(", "im", ",", "region_size", "=", "5", ",", "to_return", "=", "'harris'", ",", "scale", "=", "0.05", ")", ":", "ndim", "=", "im", ".", "ndim", "#1. Gradient of image", "grads", "=", "[", "nd", ".", "sobel", "(", "im", ",", ...
29.225806
0.007479
def get_PCA_parameters(self, specimen, fit, tmin, tmax, coordinate_system, calculation_type): """ Uses pmag.domean to preform a line, line-with-origin, line-anchored, or plane least squared regression or a fisher mean on the measurement data of specimen in coordinate system between bound...
[ "def", "get_PCA_parameters", "(", "self", ",", "specimen", ",", "fit", ",", "tmin", ",", "tmax", ",", "coordinate_system", ",", "calculation_type", ")", ":", "if", "tmin", "==", "''", "or", "tmax", "==", "''", ":", "return", "beg_pca", ",", "end_pca", "=...
42.044118
0.003759
def can_remove(self): ''' Get if current node can be removed based on app config's directory_remove. :returns: True if current node can be removed, False otherwise. :rtype: bool ''' dirbase = self.app.config["directory_remove"] return bool(dirbase and che...
[ "def", "can_remove", "(", "self", ")", ":", "dirbase", "=", "self", ".", "app", ".", "config", "[", "\"directory_remove\"", "]", "return", "bool", "(", "dirbase", "and", "check_under_base", "(", "self", ".", "path", ",", "dirbase", ")", ")" ]
34.5
0.00565
def _check_keyserver(location): """Check that a given keyserver is a known protocol and does not contain shell escape characters. :param str location: A string containing the default keyserver. This should contain the desired keyserver protocol which is sup...
[ "def", "_check_keyserver", "(", "location", ")", ":", "protocols", "=", "[", "'hkp://'", ",", "'hkps://'", ",", "'http://'", ",", "'https://'", ",", "'ldap://'", ",", "'mailto:'", "]", "## xxx feels like i´m forgetting one...", "for", "proto", "in", "protocols", "...
46.333333
0.003132
def spiceFoundExceptionThrower(f): """ Decorator for wrapping functions that use status codes """ @functools.wraps(f) def wrapper(*args, **kwargs): res = f(*args, **kwargs) if config.catch_false_founds: found = res[-1] if isinstance(found, bool) and not found:...
[ "def", "spiceFoundExceptionThrower", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", ...
37.782609
0.003367
def post(json_data, url, dry_run=False): """ POST json data to the url provided and verify the requests was successful """ if dry_run: info('POST: %s' % json.dumps(json_data, indent=4)) else: response = SESSION.post(url, data=json.d...
[ "def", "post", "(", "json_data", ",", "url", ",", "dry_run", "=", "False", ")", ":", "if", "dry_run", ":", "info", "(", "'POST: %s'", "%", "json", ".", "dumps", "(", "json_data", ",", "indent", "=", "4", ")", ")", "else", ":", "response", "=", "SES...
32.222222
0.001675
def IsDevice(self): """Determines if the file entry is a device. Returns: bool: True if the file entry is a device. """ if self._stat_object is None: self._stat_object = self._GetStat() if self._stat_object is not None: self.entry_type = self._stat_object.type return self.entr...
[ "def", "IsDevice", "(", "self", ")", ":", "if", "self", ".", "_stat_object", "is", "None", ":", "self", ".", "_stat_object", "=", "self", ".", "_GetStat", "(", ")", "if", "self", ".", "_stat_object", "is", "not", "None", ":", "self", ".", "entry_type",...
32.181818
0.008242
def fullname(self) -> str: """ Description of the process. """ fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs, self.details.name) if self.running: fullname += " (PID={})".format(self.process.pid) ...
[ "def", "fullname", "(", "self", ")", "->", "str", ":", "fullname", "=", "\"Process {}/{} ({})\"", ".", "format", "(", "self", ".", "procnum", ",", "self", ".", "nprocs", ",", "self", ".", "details", ".", "name", ")", "if", "self", ".", "running", ":", ...
36.444444
0.005952
def OpenAndRead(relative_path='debugger-blacklist.yaml'): """Attempts to find the yaml configuration file, then read it. Args: relative_path: Optional relative path override. Returns: A Config object if the open and read were successful, None if the file does not exist (which is not considered an er...
[ "def", "OpenAndRead", "(", "relative_path", "=", "'debugger-blacklist.yaml'", ")", ":", "# Note: This logic follows the convention established by source-context.json", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "sys", ".", "path", "[", "0", ...
30
0.009693
def _compute_remote_size(self, options): # type: (Descriptor, blobxfer.models.options.Upload) -> None """Compute total remote file size :param Descriptor self: this :param blobxfer.models.options.Upload options: upload options :rtype: int :return: remote file size ...
[ "def", "_compute_remote_size", "(", "self", ",", "options", ")", ":", "# type: (Descriptor, blobxfer.models.options.Upload) -> None", "size", "=", "self", ".", "local_path", ".", "size", "if", "(", "self", ".", "_ase", ".", "mode", "==", "blobxfer", ".", "models",...
42.21875
0.002171
def result(self, *args, **kwargs): """ Construye la consulta SQL """ prettify = kwargs.get('pretty', False) sql = 'CREATE %s %s' % (self._type, self._class) if prettify: sql += '\n' else: sql += ' ' if self._type.lower() ...
[ "def", "result", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "prettify", "=", "kwargs", ".", "get", "(", "'pretty'", ",", "False", ")", "sql", "=", "'CREATE %s %s'", "%", "(", "self", ".", "_type", ",", "self", ".", "_class", ...
25.076923
0.007386
def filter_by_value(cls, value): """ Get all constants which have given value. :param value: value of the constants to look for :returns: list of all found constants with given value """ constants = [] for constant in cls.iterconstants(): if constant....
[ "def", "filter_by_value", "(", "cls", ",", "value", ")", ":", "constants", "=", "[", "]", "for", "constant", "in", "cls", ".", "iterconstants", "(", ")", ":", "if", "constant", ".", "value", "==", "value", ":", "constants", ".", "append", "(", "constan...
32.666667
0.004963
def _analyse(self, table=''): """Analyses the database, or `table` if it is supplied. :param table: optional name of table to analyse :type table: `str` """ self._logger.info('Starting analysis of database') self._conn.execute(constants.ANALYSE_SQL.format(table)) ...
[ "def", "_analyse", "(", "self", ",", "table", "=", "''", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Starting analysis of database'", ")", "self", ".", "_conn", ".", "execute", "(", "constants", ".", "ANALYSE_SQL", ".", "format", "(", "table", ...
36.3
0.005376
def parse_config(self, config_file): """ Given a configuration file, read in and interpret the results :param config_file: :return: """ with open(config_file, 'r') as f: config = json.load(f) self.params = config if self.params['proxy']['prox...
[ "def", "parse_config", "(", "self", ",", "config_file", ")", ":", "with", "open", "(", "config_file", ",", "'r'", ")", "as", "f", ":", "config", "=", "json", ".", "load", "(", "f", ")", "self", ".", "params", "=", "config", "if", "self", ".", "para...
32.785714
0.004237
def copy(self): ''' Return a copy of this color value. Returns: :class:`~bokeh.colors.rgb.RGB` ''' return RGB(self.r, self.g, self.b, self.a)
[ "def", "copy", "(", "self", ")", ":", "return", "RGB", "(", "self", ".", "r", ",", "self", ".", "g", ",", "self", ".", "b", ",", "self", ".", "a", ")" ]
22.5
0.010695
def preloop(self): ''' Keep persistent command history. ''' if not self.already_prelooped: self.already_prelooped = True open('.psiturk_history', 'a').close() # create file if it doesn't exist readline.read_history_file('.psiturk_history') for i in range(...
[ "def", "preloop", "(", "self", ")", ":", "if", "not", "self", ".", "already_prelooped", ":", "self", ".", "already_prelooped", "=", "True", "open", "(", "'.psiturk_history'", ",", "'a'", ")", ".", "close", "(", ")", "# create file if it doesn't exist", "readli...
53.555556
0.006122
def get_assignable_book_ids(self, book_id): """Gets a list of books including and under the given book node in which any comment can be assigned. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` return: (osid.id.IdList) - list of assignable book ``Ids`` raise: NullArgument - ``...
[ "def", "get_assignable_book_ids", "(", "self", ",", "book_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinAssignmentSession.get_assignable_bin_ids", "# This will likely be overridden by an authorization adapter", "mgr", "=", "self", ".", "_get_provider_man...
47.6
0.00309
def countok(self): """ Boolean array showing which stars pass all count constraints. A "count constraint" is a constraint that affects the number of stars. """ ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name]...
[ "def", "countok", "(", "self", ")", ":", "ok", "=", "np", ".", "ones", "(", "len", "(", "self", ".", "stars", ")", ")", ".", "astype", "(", "bool", ")", "for", "name", "in", "self", ".", "constraints", ":", "c", "=", "self", ".", "constraints", ...
33.75
0.004808
def del_object(self, obj): """Debug deletes obj of obj[_type] with id of obj['_id']""" if obj['_index'] is None or obj['_index'] == "": raise Exception("Invalid Object") if obj['_id'] is None or obj['_id'] == "": raise Exception("Invalid Object") if obj['_type'] i...
[ "def", "del_object", "(", "self", ",", "obj", ")", ":", "if", "obj", "[", "'_index'", "]", "is", "None", "or", "obj", "[", "'_index'", "]", "==", "\"\"", ":", "raise", "Exception", "(", "\"Invalid Object\"", ")", "if", "obj", "[", "'_id'", "]", "is",...
44.833333
0.003643
def create_paired_device(self, dev_id, agent_path, capability, cb_notify_device, cb_notify_error): """ Creates a new object path for a remote device. This method will connect to the remote device and retrieve all SDP records and then initiate the pairing. ...
[ "def", "create_paired_device", "(", "self", ",", "dev_id", ",", "agent_path", ",", "capability", ",", "cb_notify_device", ",", "cb_notify_error", ")", ":", "return", "self", ".", "_interface", ".", "CreatePairedDevice", "(", "dev_id", ",", "agent_path", ",", "ca...
49.47619
0.001888
def to_pb(self): """Converts the column family to a protobuf. :rtype: :class:`.table_v2_pb2.ColumnFamily` :returns: The converted current object. """ if self.gc_rule is None: return table_v2_pb2.ColumnFamily() else: return table_v2_pb2.ColumnFamil...
[ "def", "to_pb", "(", "self", ")", ":", "if", "self", ".", "gc_rule", "is", "None", ":", "return", "table_v2_pb2", ".", "ColumnFamily", "(", ")", "else", ":", "return", "table_v2_pb2", ".", "ColumnFamily", "(", "gc_rule", "=", "self", ".", "gc_rule", ".",...
34.2
0.005698
def to_py(o, keyword_fn: Callable[[kw.Keyword], Any] = _kw_name): """Recursively convert Lisp collections into Python collections.""" if isinstance(o, ISeq): return _to_py_list(o, keyword_fn=keyword_fn) elif not isinstance( o, (IPersistentList, IPersistentMap, IPersistentSet, IPersistentVect...
[ "def", "to_py", "(", "o", ",", "keyword_fn", ":", "Callable", "[", "[", "kw", ".", "Keyword", "]", ",", "Any", "]", "=", "_kw_name", ")", ":", "if", "isinstance", "(", "o", ",", "ISeq", ")", ":", "return", "_to_py_list", "(", "o", ",", "keyword_fn"...
42.3
0.002315
def evaluate_variable(self, name): """Evaluates the variable given by name.""" if isinstance(self.variables[name], six.string_types): # TODO: this does not allow more than one level deep variable, like a depends on b, b on c, c is a const value = eval(self.variables[name], expres...
[ "def", "evaluate_variable", "(", "self", ",", "name", ")", ":", "if", "isinstance", "(", "self", ".", "variables", "[", "name", "]", ",", "six", ".", "string_types", ")", ":", "# TODO: this does not allow more than one level deep variable, like a depends on b, b on c, c...
52.875
0.009302
def get_service_types(self): """ Get all service types supported by this cluster. @return: A list of service types (strings) """ resp = self._get_resource_root().get(self._path() + '/serviceTypes') return resp[ApiList.LIST_KEY]
[ "def", "get_service_types", "(", "self", ")", ":", "resp", "=", "self", ".", "_get_resource_root", "(", ")", ".", "get", "(", "self", ".", "_path", "(", ")", "+", "'/serviceTypes'", ")", "return", "resp", "[", "ApiList", ".", "LIST_KEY", "]" ]
30.625
0.003968
def check_street_suffix(self, token): """ Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized and a period after it. E.g. "St." or "Ave." """ # Suffix must come before street # print "Suffix check", token, "suffi...
[ "def", "check_street_suffix", "(", "self", ",", "token", ")", ":", "# Suffix must come before street", "# print \"Suffix check\", token, \"suffix\", self.street_suffix, \"street\", self.street", "if", "self", ".", "street_suffix", "is", "None", "and", "self", ".", "street", "...
51.176471
0.004515
def getDefaultItems(self): """ Returns a list with the default plugins in the repo tree item registry. """ return [ RtiRegItem('HDF-5 file', 'argos.repo.rtiplugins.hdf5.H5pyFileRti', extensions=['hdf5', 'h5', 'h5e', 'he5', 'nc']), # hdf e...
[ "def", "getDefaultItems", "(", "self", ")", ":", "return", "[", "RtiRegItem", "(", "'HDF-5 file'", ",", "'argos.repo.rtiplugins.hdf5.H5pyFileRti'", ",", "extensions", "=", "[", "'hdf5'", ",", "'h5'", ",", "'h5e'", ",", "'he5'", ",", "'nc'", "]", ")", ",", "#...
42.638298
0.006341
def update_fname_label(self): """Upadte file name label.""" filename = to_text_string(self.get_current_filename()) if len(filename) > 100: shorten_filename = u'...' + filename[-100:] else: shorten_filename = filename self.fname_label.setText(shorten...
[ "def", "update_fname_label", "(", "self", ")", ":", "filename", "=", "to_text_string", "(", "self", ".", "get_current_filename", "(", ")", ")", "if", "len", "(", "filename", ")", ">", "100", ":", "shorten_filename", "=", "u'...'", "+", "filename", "[", "-"...
40.375
0.006061
def _bump_version(version, component='patch'): # type: (str, str) -> str """ Bump the given version component. Args: version (str): The current version. The format is: MAJOR.MINOR[.PATCH]. component (str): What part of the version should be bumped. Can be one of: ...
[ "def", "_bump_version", "(", "version", ",", "component", "=", "'patch'", ")", ":", "# type: (str, str) -> str", "if", "component", "not", "in", "(", "'major'", ",", "'minor'", ",", "'patch'", ")", ":", "raise", "ValueError", "(", "\"Invalid version component: {}\...
24.183673
0.000811
def check_password(self, raw_password): """Calls :py:func:`~xmpp_backends.base.XmppBackendBase.check_password` for the user.""" return xmpp_backend.check_password(self.node, self.domain, raw_password)
[ "def", "check_password", "(", "self", ",", "raw_password", ")", ":", "return", "xmpp_backend", ".", "check_password", "(", "self", ".", "node", ",", "self", ".", "domain", ",", "raw_password", ")" ]
71.333333
0.018519
def solve_kkt(U_Q, d, G, A, U_S, rx, rs, rz, ry, dbg=False): """ Solve KKT equations for the affine step""" nineq, nz, neq, _ = get_sizes(G, A) invQ_rx = torch.potrs(rx.view(-1, 1), U_Q).view(-1) if neq > 0: h = torch.cat([torch.mv(A, invQ_rx) - ry, torch.mv(G, invQ_rx) +...
[ "def", "solve_kkt", "(", "U_Q", ",", "d", ",", "G", ",", "A", ",", "U_S", ",", "rx", ",", "rs", ",", "rz", ",", "ry", ",", "dbg", "=", "False", ")", ":", "nineq", ",", "nz", ",", "neq", ",", "_", "=", "get_sizes", "(", "G", ",", "A", ")",...
29
0.001043
def count(self, key): """Return the number of pairs with key *key*.""" count = 0 pos = self.index(key, -1) if pos == -1: return count count += 1 for i in range(pos+1, len(self)): if self[i][0] != key: break count += 1 ...
[ "def", "count", "(", "self", ",", "key", ")", ":", "count", "=", "0", "pos", "=", "self", ".", "index", "(", "key", ",", "-", "1", ")", "if", "pos", "==", "-", "1", ":", "return", "count", "count", "+=", "1", "for", "i", "in", "range", "(", ...
27.25
0.005917
def register(nbtool): """ Register the provided NBTool object """ global _py_funcs _lazy_init() # Save references to the tool's load() and render() functions load_key = nbtool.origin + '|' + nbtool.id + '|load' render_key = nbtool.origin + '|' + nbtool.id + '|render' _py_funcs[load_...
[ "def", "register", "(", "nbtool", ")", ":", "global", "_py_funcs", "_lazy_init", "(", ")", "# Save references to the tool's load() and render() functions", "load_key", "=", "nbtool", ".", "origin", "+", "'|'", "+", "nbtool", ".", "id", "+", "'|load'", "render_key", ...
39.347826
0.003593
def _validate_message(self, message): """ Is C{message} a valid direct child of this action? @param message: Either a C{WrittenAction} or a C{WrittenMessage}. @raise WrongTask: If C{message} has a C{task_uuid} that differs from the action's C{task_uuid}. @raise Wron...
[ "def", "_validate_message", "(", "self", ",", "message", ")", ":", "if", "message", ".", "task_uuid", "!=", "self", ".", "task_uuid", ":", "raise", "WrongTask", "(", "self", ",", "message", ")", "if", "not", "message", ".", "task_level", ".", "parent", "...
40.866667
0.004785
def xSectionChunk(lines): """ Parse XSEC Method """ # Constants KEYWORDS = ('MANNINGS_N', 'BOTTOM_WIDTH', 'BANKFULL_DEPTH', 'SIDE_SLOPE', 'NPAIRS', 'NUM_INTERP', 'X1', 'ERODE', ...
[ "def", "xSectionChunk", "(", "lines", ")", ":", "# Constants", "KEYWORDS", "=", "(", "'MANNINGS_N'", ",", "'BOTTOM_WIDTH'", ",", "'BANKFULL_DEPTH'", ",", "'SIDE_SLOPE'", ",", "'NPAIRS'", ",", "'NUM_INTERP'", ",", "'X1'", ",", "'ERODE'", ",", "'MAX_EROSION'", ","...
28.163636
0.000624
def rmmkdir(dir_path): # type: (AnyStr) -> None """If directory existed, then remove and make; else make it.""" if not os.path.isdir(dir_path) or not os.path.exists(dir_path): os.makedirs(dir_path) else: rmtree(dir_path, True) os.makedirs(dir_path)
[ "def", "rmmkdir", "(", "dir_path", ")", ":", "# type: (AnyStr) -> None", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", "or", "not", "os", ".", "path", ".", "exists", "(", "dir_path", ")", ":", "os", ".", "makedirs", "(", "dir_path...
38.625
0.009494
def recordsDF(token='', version=''): '''https://iexcloud.io/docs/api/#stats-records Args: token (string); Access token version (string); API version Returns: DataFrame: result ''' df = pd.DataFrame(records(token, version)) _toDatetime(df) return df
[ "def", "recordsDF", "(", "token", "=", "''", ",", "version", "=", "''", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "records", "(", "token", ",", "version", ")", ")", "_toDatetime", "(", "df", ")", "return", "df" ]
22.307692
0.003311
def _create_delete_request(self, resource, billomat_id): """ Creates a post request and return the response data """ assert (isinstance(resource, str)) if isinstance(billomat_id, int): billomat_id = str(billomat_id) response = self.session.delete( ...
[ "def", "_create_delete_request", "(", "self", ",", "resource", ",", "billomat_id", ")", ":", "assert", "(", "isinstance", "(", "resource", ",", "str", ")", ")", "if", "isinstance", "(", "billomat_id", ",", "int", ")", ":", "billomat_id", "=", "str", "(", ...
29.642857
0.004673
def _filter(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Apply view filters""" view = self._view.get(filename) if view is None: return df for col, values in view.items(): # If applicable, filter this dataframe by the given set of values ...
[ "def", "_filter", "(", "self", ",", "filename", ":", "str", ",", "df", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "view", "=", "self", ".", "_view", ".", "get", "(", "filename", ")", "if", "view", "is", "None", ":", "ret...
33.666667
0.004819
def decrypt(payload, private_key): """Decrypt an encrypted JSON payload and return the Magic Envelope document inside.""" cipher = PKCS1_v1_5.new(private_key) aes_key_str = cipher.decrypt(b64decode(payload.get("aes_key")), sentinel=None) aes_key = json.loads(aes_key_str.decode("utf-8")) ...
[ "def", "decrypt", "(", "payload", ",", "private_key", ")", ":", "cipher", "=", "PKCS1_v1_5", ".", "new", "(", "private_key", ")", "aes_key_str", "=", "cipher", ".", "decrypt", "(", "b64decode", "(", "payload", ".", "get", "(", "\"aes_key\"", ")", ")", ",...
58.909091
0.007599
def logical_repr(self, value): """Set the string representation of logical values.""" if not any(isinstance(value, t) for t in (list, tuple)): raise TypeError("Logical representation must be a tuple with " "a valid true and false value.") if not len(value)...
[ "def", "logical_repr", "(", "self", ",", "value", ")", ":", "if", "not", "any", "(", "isinstance", "(", "value", ",", "t", ")", "for", "t", "in", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"Logical representation must be a tup...
44.9
0.004367
def change_column_name( conn, table, old_column_name, new_column_name, schema=None ): """ Changes given `activity` jsonb data column key. This function is useful when you want to reflect column name changes to activity table. :: from alembic import op from postgresq...
[ "def", "change_column_name", "(", "conn", ",", "table", ",", "old_column_name", ",", "new_column_name", ",", "schema", "=", "None", ")", ":", "activity_table", "=", "get_activity_table", "(", "schema", "=", "schema", ")", "query", "=", "(", "activity_table", "...
26.034483
0.000638
def find_all(cls, vid=None, pid=None): """ Returns all FTDI devices matching our vendor and product IDs. :returns: list of devices :raises: :py:class:`~alarmdecoder.util.CommError` """ if not have_pyftdi: raise ImportError('The USBDevice class has been disabl...
[ "def", "find_all", "(", "cls", ",", "vid", "=", "None", ",", "pid", "=", "None", ")", ":", "if", "not", "have_pyftdi", ":", "raise", "ImportError", "(", "'The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.'", ")", "cls", ".", "__devic...
31.217391
0.005405
def _validate_other( self, other, axis, numeric_only=False, numeric_or_time_only=False, numeric_or_object_only=False, comparison_dtypes_only=False, ): """Helper method to check validity of other in inter-df operations""" axis = self._...
[ "def", "_validate_other", "(", "self", ",", "other", ",", "axis", ",", "numeric_only", "=", "False", ",", "numeric_or_time_only", "=", "False", ",", "numeric_or_object_only", "=", "False", ",", "comparison_dtypes_only", "=", "False", ",", ")", ":", "axis", "="...
43.085366
0.003874
def ConsultarTiposLiquidacion(self, sep="||"): "Retorna un listado de tipos de liquidación con código y descripción" ret = self.client.consultarTiposLiquidacion( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cu...
[ "def", "ConsultarTiposLiquidacion", "(", "self", ",", "sep", "=", "\"||\"", ")", ":", "ret", "=", "self", ".", "client", ".", "consultarTiposLiquidacion", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign...
49.071429
0.002857
def poke(self, context): """ Checks for existence of the partition in the AWS Glue Catalog table """ if '.' in self.table_name: self.database_name, self.table_name = self.table_name.split('.') self.log.info( 'Poking for table %s. %s, expression %s', self.d...
[ "def", "poke", "(", "self", ",", "context", ")", ":", "if", "'.'", "in", "self", ".", "table_name", ":", "self", ".", "database_name", ",", "self", ".", "table_name", "=", "self", ".", "table_name", ".", "split", "(", "'.'", ")", "self", ".", "log", ...
40.333333
0.006061
def get_name(self, language): """ Return the name of this course """ return self.gettext(language, self._name) if self._name else ""
[ "def", "get_name", "(", "self", ",", "language", ")", ":", "return", "self", ".", "gettext", "(", "language", ",", "self", ".", "_name", ")", "if", "self", ".", "_name", "else", "\"\"" ]
48.666667
0.013514
def instanceStarted(self, *args, **kwargs): """ Report an instance starting An instance will report in by giving its instance id as well as its security token. The token is given and checked to ensure that it matches a real token that exists to ensure that random machin...
[ "def", "instanceStarted", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"instanceStarted\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
38
0.005505
def install_build_requires(pkg_targets): """Iterate through build_requires list and pip install if package is not present accounting for version""" def pip_install(pkg_name, pkg_vers=None): pkg_name_version = '%s==%s' % (pkg_name, pkg_vers) if pkg_vers else pkg_name print '[WARNING] %s not ...
[ "def", "install_build_requires", "(", "pkg_targets", ")", ":", "def", "pip_install", "(", "pkg_name", ",", "pkg_vers", "=", "None", ")", ":", "pkg_name_version", "=", "'%s==%s'", "%", "(", "pkg_name", ",", "pkg_vers", ")", "if", "pkg_vers", "else", "pkg_name",...
43.866667
0.005204
def ifaces(cls, name): """ Get vlan attached ifaces. """ ifaces = Iface.list({'vlan_id': cls.usable_id(name)}) ret = [] for iface in ifaces: ret.append(Iface.info(iface['id'])) return ret
[ "def", "ifaces", "(", "cls", ",", "name", ")", ":", "ifaces", "=", "Iface", ".", "list", "(", "{", "'vlan_id'", ":", "cls", ".", "usable_id", "(", "name", ")", "}", ")", "ret", "=", "[", "]", "for", "iface", "in", "ifaces", ":", "ret", ".", "ap...
33.285714
0.008368
def container_new_folder(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /container-xxxx/newFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder """ return DXHTTPRequest('/%s/...
[ "def", "container_new_folder", "(", "object_id", ",", "input_params", "=", "{", "}", ",", "always_retry", "=", "True", ",", "*", "*", "kwargs", ")", ":", "return", "DXHTTPRequest", "(", "'/%s/newFolder'", "%", "object_id", ",", "input_params", ",", "always_ret...
55.428571
0.010152
def get_object_from_content(entity, key): """Get an object from the database given an entity and the content key. :param entity: Class type of the object to retrieve. :param key: Array that defines the path of the value inside the message. """ def object_from_content_function(service, message): ...
[ "def", "get_object_from_content", "(", "entity", ",", "key", ")", ":", "def", "object_from_content_function", "(", "service", ",", "message", ")", ":", "\"\"\"Actual implementation of get_object_from_content function.\n\n :param service: SelenolService object.\n :param ...
41
0.001325
def gunzip(input_gzip_file, block_size=1024): """ Gunzips the input file to the same directory :param input_gzip_file: File to be gunzipped :return: path to the gunzipped file :rtype: str """ assert os.path.splitext(input_gzip_file)[1] == '.gz' assert is_gzipfile(input_gzip_file) wi...
[ "def", "gunzip", "(", "input_gzip_file", ",", "block_size", "=", "1024", ")", ":", "assert", "os", ".", "path", ".", "splitext", "(", "input_gzip_file", ")", "[", "1", "]", "==", "'.gz'", "assert", "is_gzipfile", "(", "input_gzip_file", ")", "with", "gzip"...
33.263158
0.001538
def xmatch_cpdir_external_catalogs(cpdir, xmatchpkl, cpfileglob='checkplot-*.pkl*', xmatchradiusarcsec=2.0, updateexisting=True, resultstodir=Non...
[ "def", "xmatch_cpdir_external_catalogs", "(", "cpdir", ",", "xmatchpkl", ",", "cpfileglob", "=", "'checkplot-*.pkl*'", ",", "xmatchradiusarcsec", "=", "2.0", ",", "updateexisting", "=", "True", ",", "resultstodir", "=", "None", ")", ":", "cplist", "=", "glob", "...
34.444444
0.001045
def parse_updates(rule): ''' Parse the updates line ''' rules = shlex.split(rule) rules.pop(0) return {'url': rules[0]} if rules else True
[ "def", "parse_updates", "(", "rule", ")", ":", "rules", "=", "shlex", ".", "split", "(", "rule", ")", "rules", ".", "pop", "(", "0", ")", "return", "{", "'url'", ":", "rules", "[", "0", "]", "}", "if", "rules", "else", "True" ]
22.285714
0.006173
async def genKeys(self, schemaId: ID, p_prime=None, q_prime=None) -> ( PublicKey, RevocationPublicKey): """ Generates and submits keys (both public and secret, primary and non-revocation). :param schemaId: The schema ID (reference to claim definition schema) ...
[ "async", "def", "genKeys", "(", "self", ",", "schemaId", ":", "ID", ",", "p_prime", "=", "None", ",", "q_prime", "=", "None", ")", "->", "(", "PublicKey", ",", "RevocationPublicKey", ")", ":", "pk", ",", "sk", "=", "await", "self", ".", "_primaryIssuer...
48.263158
0.002139
def remove(self, cls, originalMemberNameList, classNamingConvention): """ :type cls: type :type originalMemberNameList: list(str) :type classNamingConvention: INamingConvention """ self._memberDelegate.remove(cls = cls, originalMemberNameList = originalMem...
[ "def", "remove", "(", "self", ",", "cls", ",", "originalMemberNameList", ",", "classNamingConvention", ")", ":", "self", ".", "_memberDelegate", ".", "remove", "(", "cls", "=", "cls", ",", "originalMemberNameList", "=", "originalMemberNameList", ",", "memberName",...
47.3
0.024896
def get_threats_update(self, client_state): """Fetch hash prefixes update for given threat list. client_state is a dict which looks like {(threatType, platformType, threatEntryType): clientState} """ request_body = { "client": { "clientId": self.client_id, ...
[ "def", "get_threats_update", "(", "self", ",", "client_state", ")", ":", "request_body", "=", "{", "\"client\"", ":", "{", "\"clientId\"", ":", "self", ".", "client_id", ",", "\"clientVersion\"", ":", "self", ".", "client_version", ",", "}", ",", "\"listUpdate...
41.888889
0.004322
def extract_file_name(content_dispo): """Extract file name from the input request body""" # print type(content_dispo) # print repr(content_dispo) # convertion of escape string (str type) from server # to unicode object content_dispo = content_dispo.decode('unicode-escape').strip('"') file_na...
[ "def", "extract_file_name", "(", "content_dispo", ")", ":", "# print type(content_dispo)", "# print repr(content_dispo)", "# convertion of escape string (str type) from server", "# to unicode object", "content_dispo", "=", "content_dispo", ".", "decode", "(", "'unicode-escape'", ")...
37.142857
0.001876
def get_open_trackers_from_local(): """Returns open trackers announce URLs list from local backup.""" with open(path.join(path.dirname(__file__), 'repo', OPEN_TRACKERS_FILENAME)) as f: open_trackers = map(str.strip, f.readlines()) return list(open_trackers)
[ "def", "get_open_trackers_from_local", "(", ")", ":", "with", "open", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "'repo'", ",", "OPEN_TRACKERS_FILENAME", ")", ")", "as", "f", ":", "open_trackers", "=", "map", "(", "...
45.5
0.007194
def _transformBy(self, matrix, **kwargs): """ This is the environment implementation of :meth:`BaseGuideline.transformBy`. **matrix** will be a :ref:`type-transformation`. that has been normalized with :func:`normalizers.normalizeTransformationMatrix`. Subclasses may ov...
[ "def", "_transformBy", "(", "self", ",", "matrix", ",", "*", "*", "kwargs", ")", ":", "t", "=", "transform", ".", "Transform", "(", "*", "matrix", ")", "# coordinates", "x", ",", "y", "=", "t", ".", "transformPoint", "(", "(", "self", ".", "x", ","...
33.181818
0.003995
def get_check_digit(unchecked): """returns the check digit of the card number.""" digits = digits_of(unchecked) checksum = sum(even_digits(unchecked)) + sum([ sum(digits_of(2 * d)) for d in odd_digits(unchecked)]) return 9 * checksum % 10
[ "def", "get_check_digit", "(", "unchecked", ")", ":", "digits", "=", "digits_of", "(", "unchecked", ")", "checksum", "=", "sum", "(", "even_digits", "(", "unchecked", ")", ")", "+", "sum", "(", "[", "sum", "(", "digits_of", "(", "2", "*", "d", ")", "...
42.833333
0.003817
def import_apps_submodule(submodule): """ Look for a submodule is a series of packages, e.g. ".pagetype_plugins" in all INSTALLED_APPS. """ found_apps = [] for appconfig in apps.get_app_configs(): app = appconfig.name if import_module_or_none('{0}.{1}'.format(app, submodule)) is not ...
[ "def", "import_apps_submodule", "(", "submodule", ")", ":", "found_apps", "=", "[", "]", "for", "appconfig", "in", "apps", ".", "get_app_configs", "(", ")", ":", "app", "=", "appconfig", ".", "name", "if", "import_module_or_none", "(", "'{0}.{1}'", ".", "for...
33.909091
0.005222
def redirect(self, redirect_url=None, message=None, level="info"): """Redirect with a message """ if redirect_url is None: redirect_url = self.back_url if message is not None: self.add_status_message(message, level) return self.request.response.redirect(re...
[ "def", "redirect", "(", "self", ",", "redirect_url", "=", "None", ",", "message", "=", "None", ",", "level", "=", "\"info\"", ")", ":", "if", "redirect_url", "is", "None", ":", "redirect_url", "=", "self", ".", "back_url", "if", "message", "is", "not", ...
40.5
0.006042
def _handle_waited_log(self, event: dict): """ A subroutine of handle_log Increment self.event_count, forget about waiting, and call the callback if any. """ txn_hash = event['transactionHash'] event_name = event['event'] assert event_name in self.event_waiting as...
[ "def", "_handle_waited_log", "(", "self", ",", "event", ":", "dict", ")", ":", "txn_hash", "=", "event", "[", "'transactionHash'", "]", "event_name", "=", "event", "[", "'event'", "]", "assert", "event_name", "in", "self", ".", "event_waiting", "assert", "tx...
39.666667
0.004104
def to_bb(YY, y="deprecated"): """Convert mask YY to a bounding box, assumes 0 as background nonzero object""" cols,rows = np.nonzero(YY) if len(cols)==0: return np.zeros(4, dtype=np.float32) top_row = np.min(rows) left_col = np.min(cols) bottom_row = np.max(rows) right_col = np.max(cols) ...
[ "def", "to_bb", "(", "YY", ",", "y", "=", "\"deprecated\"", ")", ":", "cols", ",", "rows", "=", "np", ".", "nonzero", "(", "YY", ")", "if", "len", "(", "cols", ")", "==", "0", ":", "return", "np", ".", "zeros", "(", "4", ",", "dtype", "=", "n...
43.444444
0.015038
def output_barplot(df, figformat, path, title=None, palette=None): """Create barplots based on number of reads and total sum of nucleotides sequenced.""" logging.info("Nanoplotter: Creating barplots for number of reads and total throughput.") read_count = Plot(path=path + "NanoComp_number_of_reads." + figfo...
[ "def", "output_barplot", "(", "df", ",", "figformat", ",", "path", ",", "title", "=", "None", ",", "palette", "=", "None", ")", ":", "logging", ".", "info", "(", "\"Nanoplotter: Creating barplots for number of reads and total throughput.\"", ")", "read_count", "=", ...
44.911765
0.002564
def load_frequencyseries(path, group=None): """ Load a FrequencySeries from a .hdf, .txt or .npy file. The default data types will be double precision floating point. Parameters ---------- path: string source file path. Must end with either .npy or .txt. group: string Addi...
[ "def", "load_frequencyseries", "(", "path", ",", "group", "=", "None", ")", ":", "ext", "=", "_os", ".", "path", ".", "splitext", "(", "path", ")", "[", "1", "]", "if", "ext", "==", "'.npy'", ":", "data", "=", "_numpy", ".", "load", "(", "path", ...
34.510638
0.005995
def _setup_language_variables(self): """Check for availability of corpora for a language. TODO: Make the selection of available languages dynamic from dirs within ``corpora`` which contain a ``corpora.py`` file. """ if self.language not in AVAILABLE_LANGUAGES: # If no...
[ "def", "_setup_language_variables", "(", "self", ")", ":", "if", "self", ".", "language", "not", "in", "AVAILABLE_LANGUAGES", ":", "# If no official repos, check if user has custom", "user_defined_corpora", "=", "self", ".", "_check_distributed_corpora_file", "(", ")", "i...
49.705882
0.003484
def calcu0(self,E,Lz): """ NAME: calcu0 PURPOSE: calculate the minimum of the u potential INPUT: E - energy Lz - angular momentum OUTPUT: u0 HISTORY: 2012-11-29 - Written - Bovy (IAS) """ ...
[ "def", "calcu0", "(", "self", ",", "E", ",", "Lz", ")", ":", "logu0", "=", "optimize", ".", "brent", "(", "_u0Eq", ",", "args", "=", "(", "self", ".", "_delta", ",", "self", ".", "_pot", ",", "E", ",", "Lz", "**", "2.", "/", "2.", ")", ")", ...
27.611111
0.015564