text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def flatFieldFromFit(self): ''' calculate flatField from 2d-polynomal fit filling all high gradient areas within averaged fit-image returns flatField, average background level, fitted image, valid indices mask ''' fitimg, mask = self._prepare() out = fi...
[ "def", "flatFieldFromFit", "(", "self", ")", ":", "fitimg", ",", "mask", "=", "self", ".", "_prepare", "(", ")", "out", "=", "fitimg", ".", "copy", "(", ")", "lastm", "=", "0", "for", "_", "in", "range", "(", "10", ")", ":", "out", "=", "polyfit2...
29.166667
0.004149
def warped_gp_cubic_sine(max_iters=100): """ A test replicating the cubic sine regression problem from Snelson's paper. """ X = (2 * np.pi) * np.random.random(151) - np.pi Y = np.sin(X) + np.random.normal(0,0.2,151) Y = np.array([np.power(abs(y),float(1)/3) * (1,-1)[y<0] for y in Y]) X =...
[ "def", "warped_gp_cubic_sine", "(", "max_iters", "=", "100", ")", ":", "X", "=", "(", "2", "*", "np", ".", "pi", ")", "*", "np", ".", "random", ".", "random", "(", "151", ")", "-", "np", ".", "pi", "Y", "=", "np", ".", "sin", "(", "X", ")", ...
36.870968
0.009378
def run_program(self, name, arguments=[], timeout=30, exclusive=False): """Runs a program in the working directory to completion. Args: name (str): The name of the program to be executed. arguments (tuple): Command-line arguments for the program. timeout (int)...
[ "def", "run_program", "(", "self", ",", "name", ",", "arguments", "=", "[", "]", ",", "timeout", "=", "30", ",", "exclusive", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Running program ...\"", ")", "if", "exclusive", ":", "kill_longrunning", ...
43.571429
0.003209
def remove_cycles(self): """ Forces graph to become acyclic, removes all loop back edges and edges between overlapped loop headers and their successors. """ # loop detection # only detect loops after potential graph normalization if not self._loop_back_edges: ...
[ "def", "remove_cycles", "(", "self", ")", ":", "# loop detection", "# only detect loops after potential graph normalization", "if", "not", "self", ".", "_loop_back_edges", ":", "l", ".", "debug", "(", "\"Detecting loops...\"", ")", "self", ".", "_detect_loops", "(", "...
46.16
0.003396
def modular_exponential(base, exponent, mod): """Computes (base ^ exponent) % mod. Time complexity - O(log n) Use similar to Python in-built function pow.""" if exponent < 0: raise ValueError("Exponent must be positive.") base %= mod result = 1 while exponent > 0: # If the l...
[ "def", "modular_exponential", "(", "base", ",", "exponent", ",", "mod", ")", ":", "if", "exponent", "<", "0", ":", "raise", "ValueError", "(", "\"Exponent must be positive.\"", ")", "base", "%=", "mod", "result", "=", "1", "while", "exponent", ">", "0", ":...
31.666667
0.003407
def read_secret_version(self, path, version=None, mount_point=DEFAULT_MOUNT_POINT): """Retrieve the secret at the specified location. Supported methods: GET: /{mount_point}/data/{path}. Produces: 200 application/json :param path: Specifies the path of the secret to read. This is s...
[ "def", "read_secret_version", "(", "self", ",", "path", ",", "version", "=", "None", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "}", "if", "version", "is", "not", "None", ":", "params", "[", "'version'", "]", "=", "vers...
40.04
0.005854
def get_temp_url(self, seconds, method="GET"): """ Returns a URL that can be used to access this object. The URL will expire after `seconds` seconds. The only methods supported are GET and PUT. Anything else will raise an InvalidTemporaryURLMethod exception. """ ...
[ "def", "get_temp_url", "(", "self", ",", "seconds", ",", "method", "=", "\"GET\"", ")", ":", "return", "self", ".", "container", ".", "get_temp_url", "(", "self", ",", "seconds", "=", "seconds", ",", "method", "=", "method", ")" ]
39.9
0.007353
def get_endpoint_path(self, endpoint_id): '''return the first fullpath to a folder in the endpoint based on expanding the user's home from the globus config file. This function is fragile but I don't see any other way to do it. Parameters ========== endpoint_id: the endpoint ...
[ "def", "get_endpoint_path", "(", "self", ",", "endpoint_id", ")", ":", "config", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.globusonline/lta/config-paths\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config", ")", ":", "bot", "."...
28.516129
0.002188
def update_from_item(self, item): """ Update from i3status output. returns if item has changed. """ if not self.is_time_module: # correct the output # Restore the name/instance. item["name"] = self.name item["instance"] = self.instance ...
[ "def", "update_from_item", "(", "self", ",", "item", ")", ":", "if", "not", "self", ".", "is_time_module", ":", "# correct the output", "# Restore the name/instance.", "item", "[", "\"name\"", "]", "=", "self", ".", "name", "item", "[", "\"instance\"", "]", "=...
44.5
0.001047
def setWidget(self, widget, index=0, row=None, col=0, rowspan=1, colspan=1): """ Add new widget inside dock, remove old one if existent """ if row is None: row = self.currentRow self.currentRow = max(row + 1, self.currentRow) if index > len(s...
[ "def", "setWidget", "(", "self", ",", "widget", ",", "index", "=", "0", ",", "row", "=", "None", ",", "col", "=", "0", ",", "rowspan", "=", "1", ",", "colspan", "=", "1", ")", ":", "if", "row", "is", "None", ":", "row", "=", "self", ".", "cur...
39
0.004695
def _get_extended_palette_entry(self, name, index, is_hex=False): ''' Compute extended entry, once on the fly. ''' values = None is_fbterm = (env.TERM == 'fbterm') # sigh if 'extended' in self._palette_support: # build entry if is_hex: index = str(find_near...
[ "def", "_get_extended_palette_entry", "(", "self", ",", "name", ",", "index", ",", "is_hex", "=", "False", ")", ":", "values", "=", "None", "is_fbterm", "=", "(", "env", ".", "TERM", "==", "'fbterm'", ")", "# sigh", "if", "'extended'", "in", "self", ".",...
46.034483
0.002201
def _reorder_columns(bed_file): """ Reorder columns to be compatible with CoRaL """ new_bed = utils.splitext_plus(bed_file)[0] + '_order.bed' with open(bed_file) as in_handle: with open(new_bed, 'w') as out_handle: for line in in_handle: cols = line.strip().split(...
[ "def", "_reorder_columns", "(", "bed_file", ")", ":", "new_bed", "=", "utils", ".", "splitext_plus", "(", "bed_file", ")", "[", "0", "]", "+", "'_order.bed'", "with", "open", "(", "bed_file", ")", "as", "in_handle", ":", "with", "open", "(", "new_bed", "...
37.692308
0.001992
def _marker_line(self): # type: () -> str """Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str """ output = '' for col in sorted(self.col_widths): line = self.COLUMN_MARK + (self....
[ "def", "_marker_line", "(", "self", ")", ":", "# type: () -> str", "output", "=", "''", "for", "col", "in", "sorted", "(", "self", ".", "col_widths", ")", ":", "line", "=", "self", ".", "COLUMN_MARK", "+", "(", "self", ".", "DASH", "*", "(", "self", ...
26.176471
0.008677
def create(technical_terms_filename, spellchecker_cache_path): """Create a Dictionary at spellchecker_cache_path with technical words.""" user_dictionary = os.path.join(os.getcwd(), "DICTIONARY") user_words = read_dictionary_file(user_dictionary) technical_terms_set = set(user_words) if technical_...
[ "def", "create", "(", "technical_terms_filename", ",", "spellchecker_cache_path", ")", ":", "user_dictionary", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "\"DICTIONARY\"", ")", "user_words", "=", "read_dictionary_file", "(", ...
44.375
0.001379
def open_in_composer(self): """Open in layout designer a given MapReport instance. .. versionadded: 4.3.0 """ impact_layer = self.impact_function.analysis_impacted report_path = dirname(impact_layer.source()) impact_report = self.impact_function.impact_report cu...
[ "def", "open_in_composer", "(", "self", ")", ":", "impact_layer", "=", "self", ".", "impact_function", ".", "analysis_impacted", "report_path", "=", "dirname", "(", "impact_layer", ".", "source", "(", ")", ")", "impact_report", "=", "self", ".", "impact_function...
35.166667
0.001318
def add_pull_request_comment(self, project, repository, pull_request_id, text): """ Add comment into pull request :param project: :param repository: :param pull_request_id: the ID of the pull request within the repository :param text comment text :return: ...
[ "def", "add_pull_request_comment", "(", "self", ",", "project", ",", "repository", ",", "pull_request_id", ",", "text", ")", ":", "url", "=", "'rest/api/1.0/projects/{project}/repos/{repository}/pull-requests/{pullRequestId}/comments'", ".", "format", "(", "project", "=", ...
40.066667
0.006504
def show_entry_map(self): """ Show entry map for a package @param dist: package @param type: srting @returns: 0 for success or 1 if error """ pprinter = pprint.PrettyPrinter() try: entry_map = pkg_resources.get_entry_map(self.options.show_ent...
[ "def", "show_entry_map", "(", "self", ")", ":", "pprinter", "=", "pprint", ".", "PrettyPrinter", "(", ")", "try", ":", "entry_map", "=", "pkg_resources", ".", "get_entry_map", "(", "self", ".", "options", ".", "show_entry_map", ")", "if", "entry_map", ":", ...
30.473684
0.008375
def _always_running_service(name): ''' Check if the service should always be running based on the KeepAlive Key in the service plist. :param str name: Service label, file name, or full path :return: True if the KeepAlive key is set to True, False if set to False or not set in the plist at ...
[ "def", "_always_running_service", "(", "name", ")", ":", "# get all the info from the launchctl service", "service_info", "=", "show", "(", "name", ")", "# get the value for the KeepAlive key in service plist", "try", ":", "keep_alive", "=", "service_info", "[", "'plist'", ...
27.105263
0.000937
def _load_credentials(self): """(Re-)loads the credentials from the file.""" if not self._file: return loaded_credentials = _load_credentials_file(self._file) self._credentials.update(loaded_credentials) logger.debug('Read credential file')
[ "def", "_load_credentials", "(", "self", ")", ":", "if", "not", "self", ".", "_file", ":", "return", "loaded_credentials", "=", "_load_credentials_file", "(", "self", ".", "_file", ")", "self", ".", "_credentials", ".", "update", "(", "loaded_credentials", ")"...
31.777778
0.006803
def remove_file(paths): """ Remove file from paths introduced. """ for path in force_list(paths): if os.path.exists(path): os.remove(path)
[ "def", "remove_file", "(", "paths", ")", ":", "for", "path", "in", "force_list", "(", "paths", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")" ]
21
0.005714
def puppeteer(ctx, port, auto_restart, args): """ Run puppeteer fetcher if puppeteer is installed. """ import subprocess g = ctx.obj _quit = [] puppeteer_fetcher = os.path.join( os.path.dirname(pyspider.__file__), 'fetcher/puppeteer_fetcher.js') cmd = ['node', puppeteer_fetcher,...
[ "def", "puppeteer", "(", "ctx", ",", "port", ",", "auto_restart", ",", "args", ")", ":", "import", "subprocess", "g", "=", "ctx", ".", "obj", "_quit", "=", "[", "]", "puppeteer_fetcher", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ...
26.837838
0.000972
def p_toc(self, toc): '''toc : HEADERSEC opttexts TOC opttexts''' toc[0] = TableOfContent(toc[1], toc[2], []) self.toc = toc[0]
[ "def", "p_toc", "(", "self", ",", "toc", ")", ":", "toc", "[", "0", "]", "=", "TableOfContent", "(", "toc", "[", "1", "]", ",", "toc", "[", "2", "]", ",", "[", "]", ")", "self", ".", "toc", "=", "toc", "[", "0", "]" ]
37
0.013245
def repr_as_line(self, additional_columns=None, only_show=None, sep=','): """ Returns a representation of the host as a single line, with columns joined by ``sep``. :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` ...
[ "def", "repr_as_line", "(", "self", ",", "additional_columns", "=", "None", ",", "only_show", "=", "None", ",", "sep", "=", "','", ")", ":", "additional_columns", "=", "additional_columns", "or", "[", "]", "if", "only_show", "is", "not", "None", ":", "colu...
41.52381
0.003363
def off(self, dev_id): """Turn OFF all features of the device. schedules, weather intelligence, water budget, etc. """ path = 'device/off' payload = {'id': dev_id} return self.rachio.put(path, payload)
[ "def", "off", "(", "self", ",", "dev_id", ")", ":", "path", "=", "'device/off'", "payload", "=", "{", "'id'", ":", "dev_id", "}", "return", "self", ".", "rachio", ".", "put", "(", "path", ",", "payload", ")" ]
30.375
0.008
def query(self, coords, mode='random_sample'): """ Returns A0 at the given coordinates. There are several different query modes, which handle the probabilistic nature of the map differently. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. ...
[ "def", "query", "(", "self", ",", "coords", ",", "mode", "=", "'random_sample'", ")", ":", "# Check that the query mode is supported", "valid_modes", "=", "[", "'random_sample'", ",", "'random_sample_per_pix'", ",", "'samples'", ",", "'median'", ",", "'mean'", "]", ...
41.518248
0.004121
def say(self, message=None, voice=None, loop=None, language=None, **kwargs): """ Create a <Say> element :param message: Message to say :param voice: Voice to use :param loop: Times to loop message :param language: Message langauge :param kwargs: additional attrib...
[ "def", "say", "(", "self", ",", "message", "=", "None", ",", "voice", "=", "None", ",", "loop", "=", "None", ",", "language", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "nest", "(", "Say", "(", "message", "=", "message...
35.153846
0.006397
def generate_signing_key(date, region, secret_key): """ Generate signing key. :param date: Date is input from :meth:`datetime.datetime` :param region: Region should be set to bucket region. :param secret_key: Secret access key. """ formatted_date = date.strftime("%Y%m%d") key1_string =...
[ "def", "generate_signing_key", "(", "date", ",", "region", ",", "secret_key", ")", ":", "formatted_date", "=", "date", ".", "strftime", "(", "\"%Y%m%d\"", ")", "key1_string", "=", "'AWS4'", "+", "secret_key", "key1", "=", "key1_string", ".", "encode", "(", "...
37.684211
0.001362
def factorization( n ): """Decompose n into a list of (prime,exponent) pairs.""" assert isinstance( n, integer_types ) if n < 2: return [] result = [] d = 2 # Test the small primes: for d in smallprimes: if d > n: break q, r = divmod( n, d ) if r == 0: count = 1 while d <= n: ...
[ "def", "factorization", "(", "n", ")", ":", "assert", "isinstance", "(", "n", ",", "integer_types", ")", "if", "n", "<", "2", ":", "return", "[", "]", "result", "=", "[", "]", "d", "=", "2", "# Test the small primes:", "for", "d", "in", "smallprimes", ...
28.1875
0.042143
def welcome_message(): """Welcome message for first running users. .. versionadded:: 4.3.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) ...
[ "def", "welcome_message", "(", ")", ":", "message", "=", "m", ".", "Message", "(", ")", "message", ".", "add", "(", "m", ".", "Brand", "(", ")", ")", "message", ".", "add", "(", "heading", "(", ")", ")", "message", ".", "add", "(", "content", "("...
23.071429
0.002976
def setlistdefault(self, key, default_list=None): # type: (Hashable, List[Any]) -> List[Any] """ Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by a...
[ "def", "setlistdefault", "(", "self", ",", "key", ",", "default_list", "=", "None", ")", ":", "# type: (Hashable, List[Any]) -> List[Any]", "if", "key", "not", "in", "self", ":", "default_list", "=", "list", "(", "default_list", "or", "(", ")", ")", "dict", ...
40
0.003906
def solve_ng(self, structure, wavelength_step=0.01, filename="ng.dat"): r""" Solve for the group index, :math:`n_g`, of a structure at a particular wavelength. Args: structure (Structure): The target structure to solve for modes. wavelength_step (...
[ "def", "solve_ng", "(", "self", ",", "structure", ",", "wavelength_step", "=", "0.01", ",", "filename", "=", "\"ng.dat\"", ")", ":", "wl_nom", "=", "structure", ".", "_wl", "self", ".", "solve", "(", "structure", ")", "n_ctrs", "=", "self", ".", "n_effs"...
35.204545
0.001256
def decode(something): """Decode something with SECRET_KEY.""" secret_key = current_app.config.get('SECRET_KEY') s = URLSafeSerializer(secret_key) try: return s.loads(something) except BadSignature: return None
[ "def", "decode", "(", "something", ")", ":", "secret_key", "=", "current_app", ".", "config", ".", "get", "(", "'SECRET_KEY'", ")", "s", "=", "URLSafeSerializer", "(", "secret_key", ")", "try", ":", "return", "s", ".", "loads", "(", "something", ")", "ex...
29.875
0.004065
def create(self): """Creates the Docker container.""" try: image_infos = yield from self._get_image_information() except DockerHttp404Error: log.info("Image %s is missing pulling it from docker hub", self._image) yield from self.pull_image(self._image) ...
[ "def", "create", "(", "self", ")", ":", "try", ":", "image_infos", "=", "yield", "from", "self", ".", "_get_image_information", "(", ")", "except", "DockerHttp404Error", ":", "log", ".", "info", "(", "\"Image %s is missing pulling it from docker hub\"", ",", "self...
43.553846
0.004145
def _add_orbfit_eph_to_database( self, orbfitMatches, expsoureObjects): """* add orbfit eph to database* **Key Arguments:** - ``orbfitMatches`` -- all of the ephemerides generated by Orbfit that match against the exact ATLAS exposure footprint ...
[ "def", "_add_orbfit_eph_to_database", "(", "self", ",", "orbfitMatches", ",", "expsoureObjects", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``_add_orbfit_eph_to_database`` method'", ")", "dbSettings", "=", "self", ".", "settings", "[", "\"database ...
32.872727
0.003222
def _base_placeholder(self): """ Return the master placeholder this layout placeholder inherits from. """ base_ph_type = { PP_PLACEHOLDER.BODY: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.CHART: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.BITMAP: ...
[ "def", "_base_placeholder", "(", "self", ")", ":", "base_ph_type", "=", "{", "PP_PLACEHOLDER", ".", "BODY", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "CHART", ":", "PP_PLACEHOLDER", ".", "BODY", ",", "PP_PLACEHOLDER", ".", "BITMAP", ":", ...
52.590909
0.001698
def setCol(self, x, l): """set the x-th column, starting at 0""" for i in xrange(0, self.__size): self.setCell(x, i, l[i])
[ "def", "setCol", "(", "self", ",", "x", ",", "l", ")", ":", "for", "i", "in", "xrange", "(", "0", ",", "self", ".", "__size", ")", ":", "self", ".", "setCell", "(", "x", ",", "i", ",", "l", "[", "i", "]", ")" ]
36.75
0.02
def com_google_fonts_check_family_panose_familytype(ttFonts): """Fonts have consistent PANOSE family type?""" failed = False familytype = None for ttfont in ttFonts: if familytype is None: familytype = ttfont['OS/2'].panose.bFamilyType if familytype != ttfont['OS/2'].panose.bFamilyType: fail...
[ "def", "com_google_fonts_check_family_panose_familytype", "(", "ttFonts", ")", ":", "failed", "=", "False", "familytype", "=", "None", "for", "ttfont", "in", "ttFonts", ":", "if", "familytype", "is", "None", ":", "familytype", "=", "ttfont", "[", "'OS/2'", "]", ...
37.157895
0.012431
def align_solar_fov(header, data, cdelt_min, naxis_min, translate_origin=True, rotate=True, scale=True): """ taken from suvi code by vhsu Apply field of view image corrections :param header: FITS header :param data: Image data :param cdelt_min: Mi...
[ "def", "align_solar_fov", "(", "header", ",", "data", ",", "cdelt_min", ",", "naxis_min", ",", "translate_origin", "=", "True", ",", "rotate", "=", "True", ",", "scale", "=", "True", ")", ":", "from", "skimage", ".", "transform", "import", "ProjectiveTransfo...
48.680272
0.004382
def set_time(self, vfy_time): """ Set the time against which the certificates are verified. Normally the current time is used. .. note:: For example, you can determine if a certificate was valid at a given time. .. versionadded:: 17.0.0 :param dat...
[ "def", "set_time", "(", "self", ",", "vfy_time", ")", ":", "param", "=", "_lib", ".", "X509_VERIFY_PARAM_new", "(", ")", "param", "=", "_ffi", ".", "gc", "(", "param", ",", "_lib", ".", "X509_VERIFY_PARAM_free", ")", "_lib", ".", "X509_VERIFY_PARAM_set_time"...
33.52381
0.002762
def combine_focus_with_next(self): """Combine the focus edit widget with the one below.""" below, ignore = self.get_next(self.focus) if below is None: # already at bottom return focus = self.lines[self.focus] focus.set_edit_text(focus.edit_text + below.e...
[ "def", "combine_focus_with_next", "(", "self", ")", ":", "below", ",", "ignore", "=", "self", ".", "get_next", "(", "self", ".", "focus", ")", "if", "below", "is", "None", ":", "# already at bottom", "return", "focus", "=", "self", ".", "lines", "[", "se...
32.545455
0.005435
def geckoboard_line_chart(request): """ Returns the data for a line chart for the specified metric. """ params = get_gecko_params(request, cumulative=False, days_back=7) metric = Metric.objects.get(uid=params['uid']) start_date = datetime.now()-timedelta(days=params['days_back']) stats = [...
[ "def", "geckoboard_line_chart", "(", "request", ")", ":", "params", "=", "get_gecko_params", "(", "request", ",", "cumulative", "=", "False", ",", "days_back", "=", "7", ")", "metric", "=", "Metric", ".", "objects", ".", "get", "(", "uid", "=", "params", ...
29.870968
0.004184
def update_config_mode(self, prompt): # pylint: disable=no-self-use """Update config mode based on the prompt analysis.""" mode = 'global' if prompt: if 'config' in prompt: mode = 'config' elif 'admin' in prompt: mode = 'admin' se...
[ "def", "update_config_mode", "(", "self", ",", "prompt", ")", ":", "# pylint: disable=no-self-use", "mode", "=", "'global'", "if", "prompt", ":", "if", "'config'", "in", "prompt", ":", "mode", "=", "'config'", "elif", "'admin'", "in", "prompt", ":", "mode", ...
32.818182
0.005391
def diff_bisect(self, text1, text2, deadline): """Find the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff. See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. Args: text1: Old string to be diffed. text2: New string to b...
[ "def", "diff_bisect", "(", "self", ",", "text1", ",", "text2", ",", "deadline", ")", ":", "# Cache the text lengths to prevent multiple calls.", "text1_length", "=", "len", "(", "text1", ")", "text2_length", "=", "len", "(", "text2", ")", "max_d", "=", "(", "t...
34.079208
0.009881
def add_individual(self, genotype): """Add the information for a individual This adds a genotype dict to variant['individuals'] Args: genotype (dict): A genotype dictionary """ logger.debug("Adding genotype {0} to variant {1}".format( genotyp...
[ "def", "add_individual", "(", "self", ",", "genotype", ")", ":", "logger", ".", "debug", "(", "\"Adding genotype {0} to variant {1}\"", ".", "format", "(", "genotype", ",", "self", "[", "'variant_id'", "]", ")", ")", "self", "[", "'individuals'", "]", ".", "...
34.363636
0.005155
def paint( self, painter, option, widget ): """ Overloads the paint method from QGraphicsPathItem to \ handle custom drawing of the path using this items \ pens and polygons. :param painter <QPainter> :param option <QGraphicsItemStyleOption> ...
[ "def", "paint", "(", "self", ",", "painter", ",", "option", ",", "widget", ")", ":", "super", "(", "XGanttDepItem", ",", "self", ")", ".", "paint", "(", "painter", ",", "option", ",", "widget", ")", "# redraw the poly to force-fill it", "if", "(", "self", ...
38.705882
0.011869
def fetch(opts): """ Create a local mirror of one or more resources. """ resources = _load(opts.resources, opts.output_dir) if opts.all: opts.resource_names = ALL reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name)) if opts.verbose: backend.V...
[ "def", "fetch", "(", "opts", ")", ":", "resources", "=", "_load", "(", "opts", ".", "resources", ",", "opts", ".", "output_dir", ")", "if", "opts", ".", "all", ":", "opts", ".", "resource_names", "=", "ALL", "reporthook", "=", "None", "if", "opts", "...
35.833333
0.006803
def get_appium_sessionId(self): """Returns the current session ID as a reference""" self._info("Appium Session ID: " + self._current_application().session_id) return self._current_application().session_id
[ "def", "get_appium_sessionId", "(", "self", ")", ":", "self", ".", "_info", "(", "\"Appium Session ID: \"", "+", "self", ".", "_current_application", "(", ")", ".", "session_id", ")", "return", "self", ".", "_current_application", "(", ")", ".", "session_id" ]
57
0.012987
def map_tree(visitor, tree): """Apply function to nodes""" newn = [map_tree(visitor, node) for node in tree.nodes] return visitor(tree, newn)
[ "def", "map_tree", "(", "visitor", ",", "tree", ")", ":", "newn", "=", "[", "map_tree", "(", "visitor", ",", "node", ")", "for", "node", "in", "tree", ".", "nodes", "]", "return", "visitor", "(", "tree", ",", "newn", ")" ]
37.5
0.006536
def _get_json(self, path, params=None, base=JIRA_BASE_URL, ): """Get the json for a given path and params. :param path: The subpath required :type path: str :param params: Parameters to filter the json query. ...
[ "def", "_get_json", "(", "self", ",", "path", ",", "params", "=", "None", ",", "base", "=", "JIRA_BASE_URL", ",", ")", ":", "url", "=", "self", ".", "_get_url", "(", "path", ",", "base", ")", "r", "=", "self", ".", "_session", ".", "get", "(", "u...
31.08
0.007491
def init_app(self, app): """ Initialize the app, e.g. can be used if factory pattern is used. """ # The connection related config values self.redis_url = app.config.setdefault( 'RQ_REDIS_URL', self.redis_url, ) self.connection_class = app.c...
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "# The connection related config values", "self", ".", "redis_url", "=", "app", ".", "config", ".", "setdefault", "(", "'RQ_REDIS_URL'", ",", "self", ".", "redis_url", ",", ")", "self", ".", "connection_cla...
30.859649
0.001102
def _set_flow_rate(pipette, params) -> None: """ Set flow rate in uL/mm, to value obtained from command's params. """ flow_rate_param = params['flowRate'] if not (flow_rate_param > 0): raise RuntimeError('Positive flowRate param required') pipette.flow_rate = { 'aspirate': flow...
[ "def", "_set_flow_rate", "(", "pipette", ",", "params", ")", "->", "None", ":", "flow_rate_param", "=", "params", "[", "'flowRate'", "]", "if", "not", "(", "flow_rate_param", ">", "0", ")", ":", "raise", "RuntimeError", "(", "'Positive flowRate param required'",...
27.846154
0.002674
def body(self) -> Union[bytes, str, List[Any], Dict[Any, Any], RawIOBase, None]: """ 获取body """ return self._body
[ "def", "body", "(", "self", ")", "->", "Union", "[", "bytes", ",", "str", ",", "List", "[", "Any", "]", ",", "Dict", "[", "Any", ",", "Any", "]", ",", "RawIOBase", ",", "None", "]", ":", "return", "self", ".", "_body" ]
28.2
0.02069
def _get_formatter(fmt): """ Args: fmt (str | unicode): Format specification Returns: (logging.Formatter): Associated logging formatter """ fmt = _replace_and_pad(fmt, "%(timezone)s", LogManager.spec.timezone) return logging.Formatter(fmt)
[ "def", "_get_formatter", "(", "fmt", ")", ":", "fmt", "=", "_replace_and_pad", "(", "fmt", ",", "\"%(timezone)s\"", ",", "LogManager", ".", "spec", ".", "timezone", ")", "return", "logging", ".", "Formatter", "(", "fmt", ")" ]
27.1
0.003571
def header(settings): """ Writes the Latex header using the settings file. The header includes all packages and defines all tikz styles. :param dictionary settings: LaTeX settings for document. :return: Header of the LaTeX document. :rtype: string """ packages = (r"\documentclass[conve...
[ "def", "header", "(", "settings", ")", ":", "packages", "=", "(", "r\"\\documentclass[convert={density=300,outext=.png}]{standalone}\"", ",", "r\"\\usepackage[margin=1in]{geometry}\"", ",", "r\"\\usepackage[hang,small,bf]{caption}\"", ",", "r\"\\usepackage{tikz}\"", ",", "r\"\\usep...
52.537037
0.005536
def satosa_logging(logger, level, message, state, **kwargs): """ Adds a session ID to the message. :type logger: logging :type level: int :type message: str :type state: satosa.state.State :param logger: Logger to use :param level: Logger level (ex: logging.DEBUG/logging.WARN/...) ...
[ "def", "satosa_logging", "(", "logger", ",", "level", ",", "message", ",", "state", ",", "*", "*", "kwargs", ")", ":", "if", "state", "is", "None", ":", "session_id", "=", "\"UNKNOWN\"", "else", ":", "try", ":", "session_id", "=", "state", "[", "LOGGER...
31.791667
0.002545
def getHashForFile(f): """Returns a hash value for a file :param f: File to hash :type f: str :returns: str """ hashVal = hashlib.sha1() while True: r = f.read(1024) if not r: break hashVal.update(r) f.seek(0) return hashVal.hexdigest()
[ "def", "getHashForFile", "(", "f", ")", ":", "hashVal", "=", "hashlib", ".", "sha1", "(", ")", "while", "True", ":", "r", "=", "f", ".", "read", "(", "1024", ")", "if", "not", "r", ":", "break", "hashVal", ".", "update", "(", "r", ")", "f", "."...
18.4375
0.003226
def _configure_subnet(config): """Pick a reasonable subnet if not specified by the config.""" # Rationale: avoid subnet lookup if the network is already # completely manually configured if ("networkInterfaces" in config["head_node"] and "networkInterfaces" in config["worker_nodes"]): ...
[ "def", "_configure_subnet", "(", "config", ")", ":", "# Rationale: avoid subnet lookup if the network is already", "# completely manually configured", "if", "(", "\"networkInterfaces\"", "in", "config", "[", "\"head_node\"", "]", "and", "\"networkInterfaces\"", "in", "config", ...
32.815789
0.000779
def _initBlockMajorMap(self): """Parses /proc/devices to initialize device class - major number map for block devices. """ self._mapMajorDevclass = {} try: fp = open(devicesFile, 'r') data = fp.read() fp.close() except: ...
[ "def", "_initBlockMajorMap", "(", "self", ")", ":", "self", ".", "_mapMajorDevclass", "=", "{", "}", "try", ":", "fp", "=", "open", "(", "devicesFile", ",", "'r'", ")", "data", "=", "fp", ".", "read", "(", ")", "fp", ".", "close", "(", ")", "except...
36
0.009365
def main(): """ generates a random world, sets terrain and runs agents in it TODO - need to change pieces in multiple places (see worlds.py, cls_grid, world_generator) (takes about 5 minutes to make 500x400 grid with 8% blockages) """ width = 20 # grid width height = 10 #...
[ "def", "main", "(", ")", ":", "width", "=", "20", "# grid width ", "height", "=", "10", "# grid height", "iterations", "=", "20", "# how many simulations to run", "num_agents", "=", "6", "# number of agents to enter the world", "w", "=", "build_world", "(", "height"...
40.352941
0.017094
def MakeSuiteFromDict(d, name=''): """Makes a suite from a map from values to probabilities. Args: d: dictionary that maps values to probabilities name: string name for this suite Returns: Suite object """ suite = Suite(name=name) suite.SetDict(d) suite.Normalize() ...
[ "def", "MakeSuiteFromDict", "(", "d", ",", "name", "=", "''", ")", ":", "suite", "=", "Suite", "(", "name", "=", "name", ")", "suite", ".", "SetDict", "(", "d", ")", "suite", ".", "Normalize", "(", ")", "return", "suite" ]
23.071429
0.002976
def seek_to_end(self, *partitions): """Seek to the most recent available offset for partitions. Arguments: *partitions: Optionally provide specific TopicPartitions, otherwise default to all assigned partitions. Raises: AssertionError: If any partition is...
[ "def", "seek_to_end", "(", "self", ",", "*", "partitions", ")", ":", "if", "not", "all", "(", "[", "isinstance", "(", "p", ",", "TopicPartition", ")", "for", "p", "in", "partitions", "]", ")", ":", "raise", "TypeError", "(", "'partitions must be TopicParti...
43.869565
0.00388
def element_to_objects(payload: Dict) -> List: """ Transform an Element to a list of entities recursively. """ entities = [] cls = MAPPINGS.get(payload.get('type')) if not cls: return [] transformed = transform_attributes(payload, cls) entity = cls(**transformed) if hasattr...
[ "def", "element_to_objects", "(", "payload", ":", "Dict", ")", "->", "List", ":", "entities", "=", "[", "]", "cls", "=", "MAPPINGS", ".", "get", "(", "payload", ".", "get", "(", "'type'", ")", ")", "if", "not", "cls", ":", "return", "[", "]", "tran...
22.666667
0.002353
def leverages(self, block='X'): """ Calculate the leverages for each observation :return: :rtype: """ # TODO check with matlab and simca try: if block == 'X': return np.dot(self.scores_t, np.dot(np.linalg.inv(np.dot(self.scores_t.T, sel...
[ "def", "leverages", "(", "self", ",", "block", "=", "'X'", ")", ":", "# TODO check with matlab and simca", "try", ":", "if", "block", "==", "'X'", ":", "return", "np", ".", "dot", "(", "self", ".", "scores_t", ",", "np", ".", "dot", "(", "np", ".", "...
40.3125
0.006061
def database(self, database_id, ddl_statements=(), pool=None): """Factory to create a database within this instance. :type database_id: str :param database_id: The ID of the instance. :type ddl_statements: list of string :param ddl_statements: (Optional) DDL statements, excludi...
[ "def", "database", "(", "self", ",", "database_id", ",", "ddl_statements", "=", "(", ")", ",", "pool", "=", "None", ")", ":", "return", "Database", "(", "database_id", ",", "self", ",", "ddl_statements", "=", "ddl_statements", ",", "pool", "=", "pool", "...
43.222222
0.003774
def pretty_print(self, carrot=True): """Print the previous and current line with line numbers and a carret under the current character position. Will also print a message if one is given to this exception. """ output = ['\n'] output.extend([line.pretty_print() for line i...
[ "def", "pretty_print", "(", "self", ",", "carrot", "=", "True", ")", ":", "output", "=", "[", "'\\n'", "]", "output", ".", "extend", "(", "[", "line", ".", "pretty_print", "(", ")", "for", "line", "in", "self", ".", "partpyobj", ".", "get_surrounding_l...
35.294118
0.003247
def GuinierPorod(q, G, Rg, alpha): """Empirical Guinier-Porod scattering Inputs: ------- ``q``: independent variable ``G``: factor of the Guinier-branch ``Rg``: radius of gyration ``alpha``: power-law exponent Formula: -------- ``G * exp(-q^2*Rg^2/3)`` if ``...
[ "def", "GuinierPorod", "(", "q", ",", "G", ",", "Rg", ",", "alpha", ")", ":", "return", "GuinierPorodMulti", "(", "q", ",", "G", ",", "Rg", ",", "alpha", ")" ]
28.454545
0.003091
def create(model_config, model, vec_env, algo, env_roller, parallel_envs, number_of_steps, batch_size=256, experience_replay=1, stochastic_experience_replay=False, shuffle_transitions=True): """ Vel factory function """ settings = OnPolicyIterationReinforcerSettings( number_of_steps=number_of...
[ "def", "create", "(", "model_config", ",", "model", ",", "vec_env", ",", "algo", ",", "env_roller", ",", "parallel_envs", ",", "number_of_steps", ",", "batch_size", "=", "256", ",", "experience_replay", "=", "1", ",", "stochastic_experience_replay", "=", "False"...
38.5
0.003802
def close(self, autocommit=True): """Close the coordinator, leave the current group, and reset local generation / member_id. Keyword Arguments: autocommit (bool): If auto-commit is configured for this consumer, this optional flag causes the consumer to attempt to com...
[ "def", "close", "(", "self", ",", "autocommit", "=", "True", ")", ":", "try", ":", "if", "autocommit", ":", "self", ".", "_maybe_auto_commit_offsets_sync", "(", ")", "finally", ":", "super", "(", "ConsumerCoordinator", ",", "self", ")", ".", "close", "(", ...
40.142857
0.003478
def simple_highlight(img1, img2, opts): """Try to align the two images to minimize pixel differences. Produces two masks for img1 and img2. The algorithm works by comparing every possible alignment of the images, finding the aligment that minimzes the differences, and then smoothing it a bit to re...
[ "def", "simple_highlight", "(", "img1", ",", "img2", ",", "opts", ")", ":", "try", ":", "diff", ",", "(", "(", "x1", ",", "y1", ")", ",", "(", "x2", ",", "y2", ")", ")", "=", "best_diff", "(", "img1", ",", "img2", ",", "opts", ")", "except", ...
39.846154
0.000943
def single_random_manipulation_low(molecule, manipulations): """Return a randomized copy of the molecule, without the nonbond check.""" manipulation = sample(manipulations, 1)[0] coordinates = molecule.coordinates.copy() transformation = manipulation.apply(coordinates) return molecule.copy_with(coo...
[ "def", "single_random_manipulation_low", "(", "molecule", ",", "manipulations", ")", ":", "manipulation", "=", "sample", "(", "manipulations", ",", "1", ")", "[", "0", "]", "coordinates", "=", "molecule", ".", "coordinates", ".", "copy", "(", ")", "transformat...
50.142857
0.002801
def get_gdb_response( self, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True ): """Get response from GDB, and block while doing so. If GDB does not have any response ready to be read by timeout_sec, an exception is raised. Args: timeout_sec (float): Maxim...
[ "def", "get_gdb_response", "(", "self", ",", "timeout_sec", "=", "DEFAULT_GDB_TIMEOUT_SEC", ",", "raise_error_on_timeout", "=", "True", ")", ":", "self", ".", "verify_valid_gdb_subprocess", "(", ")", "if", "timeout_sec", "<", "0", ":", "self", ".", "logger", "."...
38.421053
0.004676
def content(self): """ :return: string (unicode) with Dockerfile content """ if self.cache_content and self.cached_content: return self.cached_content try: with self._open_dockerfile('rb') as dockerfile: content = b2u(dockerfile.read()) ...
[ "def", "content", "(", "self", ")", ":", "if", "self", ".", "cache_content", "and", "self", ".", "cached_content", ":", "return", "self", ".", "cached_content", "try", ":", "with", "self", ".", "_open_dockerfile", "(", "'rb'", ")", "as", "dockerfile", ":",...
34.8125
0.003497
def _from_dict(cls, _dict): """Initialize a Element object from a json dictionary.""" args = {} if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'types' in _dict: ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'location'", "in", "_dict", ":", "args", "[", "'location'", "]", "=", "Location", ".", "_from_dict", "(", "_dict", ".", "get", "(", "'location'", ")", ")", "if", ...
37.8
0.002581
def rank_member(self, member, score, member_data=None): ''' Rank a member in the leaderboard. @param member [String] Member name. @param score [float] Member score. @param member_data [String] Optional member data. ''' self.rank_member_in(self.leaderboard_name, m...
[ "def", "rank_member", "(", "self", ",", "member", ",", "score", ",", "member_data", "=", "None", ")", ":", "self", ".", "rank_member_in", "(", "self", ".", "leaderboard_name", ",", "member", ",", "score", ",", "member_data", ")" ]
37.555556
0.00578
def Output(self): """Output all sections of the page.""" self.Open() self.Header() self.Body() self.Footer()
[ "def", "Output", "(", "self", ")", ":", "self", ".", "Open", "(", ")", "self", ".", "Header", "(", ")", "self", ".", "Body", "(", ")", "self", ".", "Footer", "(", ")" ]
20.5
0.007813
def safe_delete(filename): """Delete a file safely. If it's not present, no-op.""" try: os.unlink(filename) except OSError as e: if e.errno != errno.ENOENT: raise
[ "def", "safe_delete", "(", "filename", ")", ":", "try", ":", "os", ".", "unlink", "(", "filename", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise" ]
25.142857
0.027473
def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parameters are <feature>value strings """ from . import property component_properties_s = to_seq (component_properties_s) composite_property = property.create_from_string(co...
[ "def", "compose", "(", "composite_property_s", ",", "component_properties_s", ")", ":", "from", ".", "import", "property", "component_properties_s", "=", "to_seq", "(", "component_properties_s", ")", "composite_property", "=", "property", ".", "create_from_string", "(",...
43.153846
0.00959
def _match_serializers_by_query_arg(self, serializers): """Match serializer by query arg.""" # if the format query argument is present, match the serializer arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME') if arg_name: arg_value = request.args.get(arg_name, N...
[ "def", "_match_serializers_by_query_arg", "(", "self", ",", "serializers", ")", ":", "# if the format query argument is present, match the serializer", "arg_name", "=", "current_app", ".", "config", ".", "get", "(", "'REST_MIMETYPE_QUERY_ARG_NAME'", ")", "if", "arg_name", "...
39.117647
0.002937
def configure_api(app): """Configure API Endpoints. """ from heman.api.empowering import resources as empowering_resources from heman.api.cch import resources as cch_resources from heman.api.form import resources as form_resources from heman.api import ApiCatchall # Add Empowering resources...
[ "def", "configure_api", "(", "app", ")", ":", "from", "heman", ".", "api", ".", "empowering", "import", "resources", "as", "empowering_resources", "from", "heman", ".", "api", ".", "cch", "import", "resources", "as", "cch_resources", "from", "heman", ".", "a...
29.454545
0.001495
def get_parent_and_child(self, table_name): """ Get the name of the parent table and the child table for a given MagIC table name. Parameters ---------- table_name : string of MagIC table name ['specimens', 'samples', 'sites', 'locations'] Returns ------...
[ "def", "get_parent_and_child", "(", "self", ",", "table_name", ")", ":", "if", "table_name", "not", "in", "self", ".", "ancestry", ":", "return", "None", ",", "None", "parent_ind", "=", "self", ".", "ancestry", ".", "index", "(", "table_name", ")", "+", ...
33.185185
0.003254
def sub(self, num): """ Subtracts num from the current value """ try: val = self.value() - num except: val = -num self.set(max(0, val))
[ "def", "sub", "(", "self", ",", "num", ")", ":", "try", ":", "val", "=", "self", ".", "value", "(", ")", "-", "num", "except", ":", "val", "=", "-", "num", "self", ".", "set", "(", "max", "(", "0", ",", "val", ")", ")" ]
22.111111
0.014493
def purge_items(app, env, docname): """ Clean, if existing, ``item`` entries in ``traceability_all_items`` environment variable, for all the source docs being purged. This function should be triggered upon ``env-purge-doc`` event. """ keys = list(env.traceability_all_items.keys()) for key ...
[ "def", "purge_items", "(", "app", ",", "env", ",", "docname", ")", ":", "keys", "=", "list", "(", "env", ".", "traceability_all_items", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "if", "env", ".", "traceability_all_items", "[", "key",...
35.916667
0.002262
def confirm(prompt_str, default=False): """Show a confirmation prompt to a command-line user. :param string prompt_str: prompt to give to the user :param bool default: Default value to True or False """ if default: default_str = 'y' prompt = '%s [Y/n]' % prompt_str else: ...
[ "def", "confirm", "(", "prompt_str", ",", "default", "=", "False", ")", ":", "if", "default", ":", "default_str", "=", "'y'", "prompt", "=", "'%s [Y/n]'", "%", "prompt_str", "else", ":", "default_str", "=", "'n'", "prompt", "=", "'%s [y/N]'", "%", "prompt_...
29.555556
0.001821
def plot(self,minval=None,maxval=None,fig=None,log=False, npts=500,**kwargs): """ Plots distribution. Parameters ---------- minval : float,optional minimum value to plot. Required if minval of Distribution is `-np.inf`. maxval : fl...
[ "def", "plot", "(", "self", ",", "minval", "=", "None", ",", "maxval", "=", "None", ",", "fig", "=", "None", ",", "log", "=", "False", ",", "npts", "=", "500", ",", "*", "*", "kwargs", ")", ":", "if", "minval", "is", "None", ":", "minval", "=",...
31.470588
0.013897
def login(self, username=None, password=None, section='default'): """ Created the passport with ``username`` and ``password`` and log in. If either ``username`` or ``password`` is None or omitted, the credentials file will be parsed. :param str username: username t...
[ "def", "login", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ",", "section", "=", "'default'", ")", ":", "if", "self", ".", "has_logged_in", ":", "return", "True", "if", "username", "is", "None", "or", "password", "is", "Non...
39.722222
0.002048
def fit( self, df, duration_col, event_col=None, ancillary_df=None, show_progress=False, timeline=None, weights_col=None, robust=False, initial_point=None, entry_col=None, ): """ Fit the accelerated failure time ...
[ "def", "fit", "(", "self", ",", "df", ",", "duration_col", ",", "event_col", "=", "None", ",", "ancillary_df", "=", "None", ",", "show_progress", "=", "False", ",", "timeline", "=", "None", ",", "weights_col", "=", "None", ",", "robust", "=", "False", ...
36.162162
0.003395
def as_dict(self): """ Dict representation of NEBAnalysis. Returns: JSON serializable dict representation. """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, 'r': jsanitize(self.r), 'en...
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "\"@module\"", ":", "self", ".", "__class__", ".", "__module__", ",", "\"@class\"", ":", "self", ".", "__class__", ".", "__name__", ",", "'r'", ":", "jsanitize", "(", "self", ".", "r", ")", ",", ...
35.538462
0.004219
def do_first(self): """Load generator, set size. We take the generator module name from self.srcfile so that this manipulator will work with different generators in a similar way to how the ordinary generators work with different images """ # Load generator modul...
[ "def", "do_first", "(", "self", ")", ":", "# Load generator module and create instance if we haven't already", "if", "(", "not", "self", ".", "srcfile", ")", ":", "raise", "IIIFError", "(", "text", "=", "(", "\"No generator specified\"", ")", ")", "if", "(", "not"...
45.166667
0.001445
def couldChangeLane(self, vehID, direction): """couldChangeLane(string, int) -> bool Return whether the vehicle could change lanes in the specified direction """ state = self.getLaneChangeState(vehID, direction)[0] return state != tc.LCA_UNKNOWN and (state & tc.LCA_BLOCKED == 0)
[ "def", "couldChangeLane", "(", "self", ",", "vehID", ",", "direction", ")", ":", "state", "=", "self", ".", "getLaneChangeState", "(", "vehID", ",", "direction", ")", "[", "0", "]", "return", "state", "!=", "tc", ".", "LCA_UNKNOWN", "and", "(", "state", ...
52.333333
0.009404
def master(self, name): """Returns a dictionary containing the specified masters state.""" fut = self.execute(b'MASTER', name, encoding='utf-8') return wait_convert(fut, parse_sentinel_master)
[ "def", "master", "(", "self", ",", "name", ")", ":", "fut", "=", "self", ".", "execute", "(", "b'MASTER'", ",", "name", ",", "encoding", "=", "'utf-8'", ")", "return", "wait_convert", "(", "fut", ",", "parse_sentinel_master", ")" ]
53.25
0.009259
def alter(data, system): """Alter data in dm format devices""" device = data[0] action = data[1] if data[2] == '*': data[2] = '.*' regex = re.compile(data[2]) prop = data[3] value = float(data[4]) if action == 'MUL': for item in range(system.__dict__[device].n): ...
[ "def", "alter", "(", "data", ",", "system", ")", ":", "device", "=", "data", "[", "0", "]", "action", "=", "data", "[", "1", "]", "if", "data", "[", "2", "]", "==", "'*'", ":", "data", "[", "2", "]", "=", "'.*'", "regex", "=", "re", ".", "c...
43.054054
0.000614
def _members(self): """ Return a dict of non-private members. """ return { key: value for key, value in self.__dict__.items() # NB: ignore internal SQLAlchemy state and nested relationships if not key.startswith("_") and not isinstance(val...
[ "def", "_members", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "__dict__", ".", "items", "(", ")", "# NB: ignore internal SQLAlchemy state and nested relationships", "if", "not", "key", ".", "starts...
30
0.005882
def issueServiceJob(self, jobNode): """ Issue a service job, putting it on a queue if the maximum number of service jobs to be scheduled has been reached. """ if jobNode.preemptable: self.preemptableServiceJobsToBeIssued.append(jobNode) else: self....
[ "def", "issueServiceJob", "(", "self", ",", "jobNode", ")", ":", "if", "jobNode", ".", "preemptable", ":", "self", ".", "preemptableServiceJobsToBeIssued", ".", "append", "(", "jobNode", ")", "else", ":", "self", ".", "serviceJobsToBeIssued", ".", "append", "(...
38.6
0.007595
def publish_results(self, dist_dir, use_basename_prefix, vt, bundle_dir, archivepath, id, archive_ext): """Publish a copy of the bundle and archive from the results dir in dist.""" # TODO (from mateor) move distdir management somewhere more general purpose. name = vt.target.basename if use_basename_prefix e...
[ "def", "publish_results", "(", "self", ",", "dist_dir", ",", "use_basename_prefix", ",", "vt", ",", "bundle_dir", ",", "archivepath", ",", "id", ",", "archive_ext", ")", ":", "# TODO (from mateor) move distdir management somewhere more general purpose.", "name", "=", "v...
57.75
0.01278
def _get_ut_i(self, seg, sx, sy): """ Returns the U and T coordinate for a specific trace segment :param seg: End points of the segment edge :param sx: Sites longitudes rendered into coordinate system :param sy: Sites latitudes rendered into...
[ "def", "_get_ut_i", "(", "self", ",", "seg", ",", "sx", ",", "sy", ")", ":", "p0x", ",", "p0y", ",", "p1x", ",", "p1y", "=", "seg", "[", "0", ",", "0", "]", ",", "seg", "[", "0", ",", "1", "]", ",", "seg", "[", "1", ",", "0", "]", ",", ...
36.625
0.002217
def ParseApplicationResourceUsage( self, parser_mediator, cache=None, database=None, table=None, **unused_kwargs): """Parses the application resource usage table. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and ...
[ "def", "ParseApplicationResourceUsage", "(", "self", ",", "parser_mediator", ",", "cache", "=", "None", ",", "database", "=", "None", ",", "table", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "self", ".", "_ParseGUIDTable", "(", "parser_mediator", ...
43.117647
0.001335
def encrypt(self, data): """ Encrypt the given data with cipher that is got from AES.cipher call. :param data: data to encrypt :return: bytes """ padding = self.mode().padding() if padding is not None: data = padding.pad(data, WAESMode.__data_padding_length__) return self.cipher().encrypt_block(data)
[ "def", "encrypt", "(", "self", ",", "data", ")", ":", "padding", "=", "self", ".", "mode", "(", ")", ".", "padding", "(", ")", "if", "padding", "is", "not", "None", ":", "data", "=", "padding", ".", "pad", "(", "data", ",", "WAESMode", ".", "__da...
28.181818
0.03125
def get_scheduling_block(sub_array_id, block_id): """Return the list of scheduling blocks instances associated with the sub array""" block_ids = DB.get_sub_array_sbi_ids(sub_array_id) if block_id in block_ids: block = DB.get_block_details([block_id]).__next__() return block, HTTPStatus.O...
[ "def", "get_scheduling_block", "(", "sub_array_id", ",", "block_id", ")", ":", "block_ids", "=", "DB", ".", "get_sub_array_sbi_ids", "(", "sub_array_id", ")", "if", "block_id", "in", "block_ids", ":", "block", "=", "DB", ".", "get_block_details", "(", "[", "bl...
41.333333
0.002632
def groupByHeaderIndex(self): """ Assigns the grouping to the current header index. """ index = self.headerMenuColumn() columnTitle = self.columnOf(index) tableType = self.tableType() if not tableType: return column...
[ "def", "groupByHeaderIndex", "(", "self", ")", ":", "index", "=", "self", ".", "headerMenuColumn", "(", ")", "columnTitle", "=", "self", ".", "columnOf", "(", "index", ")", "tableType", "=", "self", ".", "tableType", "(", ")", "if", "not", "tableType", "...
28.058824
0.010142
def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None: """ Print a plain table with the details of the given trainings. :param trainings: iterable of tuples (train_dir, configuration dict, trace) """ long_table = [] for train_dir, config, trace in trainings: ...
[ "def", "_print_trainings_long", "(", "trainings", ":", "Iterable", "[", "Tuple", "[", "str", ",", "dict", ",", "TrainingTrace", "]", "]", ")", "->", "None", ":", "long_table", "=", "[", "]", "for", "train_dir", ",", "config", ",", "trace", "in", "trainin...
42.846154
0.00439