text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def volume_montecarlo(found_d, missed_d, found_mchirp, missed_mchirp, distribution_param, distribution, limits_param, min_param=None, max_param=None): """ Compute sensitive volume and standard error via direct Monte Carlo integral Injections should be made over a...
[ "def", "volume_montecarlo", "(", "found_d", ",", "missed_d", ",", "found_mchirp", ",", "missed_mchirp", ",", "distribution_param", ",", "distribution", ",", "limits_param", ",", "min_param", "=", "None", ",", "max_param", "=", "None", ")", ":", "d_power", "=", ...
41.493243
19.331081
def authorize_url(self): """ Build the authorization url and save the state. Return the authorization url """ url, self.state = self.oauth.authorization_url( '%sauthorize' % OAUTH_URL) return url
[ "def", "authorize_url", "(", "self", ")", ":", "url", ",", "self", ".", "state", "=", "self", ".", "oauth", ".", "authorization_url", "(", "'%sauthorize'", "%", "OAUTH_URL", ")", "return", "url" ]
31
12
def save(self, path): """Save waveform to file path as a WAV file. :returns: Path to the saved file. """ (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" path ...
[ "def", "save", "(", "self", ",", "path", ")", ":", "(", "folder", ",", "filename", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "(", "name", ",", "extension", ")", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "...
24.833333
19.666667
def _clamp_rgb_coordinate(self, coord): """ Clamps an RGB coordinate, taking into account whether or not the color is upscaled or not. :param float coord: The coordinate value. :rtype: float :returns: The clamped value. """ if not self.is_upscaled: ...
[ "def", "_clamp_rgb_coordinate", "(", "self", ",", "coord", ")", ":", "if", "not", "self", ".", "is_upscaled", ":", "return", "min", "(", "max", "(", "coord", ",", "0.0", ")", ",", "1.0", ")", "else", ":", "return", "min", "(", "max", "(", "coord", ...
31
11.769231
def _merge_args_with_kwargs(args_dict, kwargs_dict): """Merge args with kwargs.""" ret = args_dict.copy() ret.update(kwargs_dict) return ret
[ "def", "_merge_args_with_kwargs", "(", "args_dict", ",", "kwargs_dict", ")", ":", "ret", "=", "args_dict", ".", "copy", "(", ")", "ret", ".", "update", "(", "kwargs_dict", ")", "return", "ret" ]
30.4
13
def group_membership_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/group_memberships#delete-membership" api_path = "/api/v2/group_memberships/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "group_membership_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/group_memberships/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "("...
60
20
def convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """ if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_type = False if ty is None and default is not None: ty = type(def...
[ "def", "convert_type", "(", "ty", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "ty", ",", "tuple", ")", ":", "return", "Tuple", "(", "ty", ")", "if", "isinstance", "(", "ty", ",", "ParamType", ")", ":", "return", "ty", "guessed_typ...
31.361111
17.583333
def read_block_idb(self, block, _): """Interface Description Block""" options = block[16:] tsresol = 1000000 while len(options) >= 4: code, length = struct.unpack(self.endian + "HH", options[:4]) # PCAP Next Generation (pcapng) Capture File Format # 4....
[ "def", "read_block_idb", "(", "self", ",", "block", ",", "_", ")", ":", "options", "=", "block", "[", "16", ":", "]", "tsresol", "=", "1000000", "while", "len", "(", "options", ")", ">=", "4", ":", "code", ",", "length", "=", "struct", ".", "unpack...
54.285714
23.47619
def _update_resume_for_completed(self): # type: (Descriptor) -> None """Update resume for completion :param Descriptor self: this """ if not self.is_resumable: return with self._meta_lock: self._resume_mgr.add_or_update_record( self...
[ "def", "_update_resume_for_completed", "(", "self", ")", ":", "# type: (Descriptor) -> None", "if", "not", "self", ".", "is_resumable", ":", "return", "with", "self", ".", "_meta_lock", ":", "self", ".", "_resume_mgr", ".", "add_or_update_record", "(", "self", "."...
35
10.166667
def _nama(self): """Mengembalikan representasi string untuk nama entri ini. :returns: String representasi nama entri :rtype: str """ hasil = self.nama if self.nomor: hasil += " [{}]".format(self.nomor) if self.kata_dasar: hasil = " » ".jo...
[ "def", "_nama", "(", "self", ")", ":", "hasil", "=", "self", ".", "nama", "if", "self", ".", "nomor", ":", "hasil", "+=", "\" [{}]\"", ".", "format", "(", "self", ".", "nomor", ")", "if", "self", ".", "kata_dasar", ":", "hasil", "=", "\" » \".", "j...
28
17.615385
def addsitedir(sitedir, known_paths=None): """Add 'sitedir' argument to sys.path if missing and handle .pth files in 'sitedir'""" if known_paths is None: known_paths = _init_pathinfo() reset = 1 else: reset = 0 sitedir, sitedircase = makepath(sitedir) if not sitedircase i...
[ "def", "addsitedir", "(", "sitedir", ",", "known_paths", "=", "None", ")", ":", "if", "known_paths", "is", "None", ":", "known_paths", "=", "_init_pathinfo", "(", ")", "reset", "=", "1", "else", ":", "reset", "=", "0", "sitedir", ",", "sitedircase", "=",...
29.772727
14.454545
def blog_recent_posts(limit=5, tag=None, username=None, category=None): """ Put a list of recently published blog posts into the template context. A tag title or slug, category title or slug or author's username can also be specified to filter the recent posts returned. Usage:: {% blog_rec...
[ "def", "blog_recent_posts", "(", "limit", "=", "5", ",", "tag", "=", "None", ",", "username", "=", "None", ",", "category", "=", "None", ")", ":", "blog_posts", "=", "BlogPost", ".", "objects", ".", "published", "(", ")", ".", "select_related", "(", "\...
39
20.714286
def _calc_specpp_hiE(self, Egamma): """ Spectrum computed as in Eq. 42 for Egamma >= 0.1 TeV """ # Fixed quad with n=40 is about 15 times faster and is always within # 0.5% of the result of adaptive quad for Egamma>0.1 # WARNING: It also produces artifacts for steep distr...
[ "def", "_calc_specpp_hiE", "(", "self", ",", "Egamma", ")", ":", "# Fixed quad with n=40 is about 15 times faster and is always within", "# 0.5% of the result of adaptive quad for Egamma>0.1", "# WARNING: It also produces artifacts for steep distributions (e.g.", "# Maxwellian) at ~500 GeV. Re...
33.777778
18
def get_next_assessment_section(self, assessment_section_id): """Gets the next assessemnt section following the given assesment section. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` return: (osid.assessment.AssessmentSection) - the next section...
[ "def", "get_next_assessment_section", "(", "self", ",", "assessment_section_id", ")", ":", "assessment_taken", "=", "self", ".", "get_assessment_section", "(", "assessment_section_id", ")", ".", "_assessment_taken", "return", "assessment_taken", ".", "_get_next_assessment_s...
54.176471
24.941176
def is_break_tag(self, el): """Check if tag is an element we should break on.""" name = el.name return name in self.break_tags or name in self.user_break_tags
[ "def", "is_break_tag", "(", "self", ",", "el", ")", ":", "name", "=", "el", ".", "name", "return", "name", "in", "self", ".", "break_tags", "or", "name", "in", "self", ".", "user_break_tags" ]
35.8
20.2
def adopt(self, grab): """ Copy the state of another `Grab` instance. Use case: create backup of current state to the cloned instance and then restore the state from it. """ self.load_config(grab.config) self.doc = grab.doc.copy(new_grab=self) for key ...
[ "def", "adopt", "(", "self", ",", "grab", ")", ":", "self", ".", "load_config", "(", "grab", ".", "config", ")", "self", ".", "doc", "=", "grab", ".", "doc", ".", "copy", "(", "new_grab", "=", "self", ")", "for", "key", "in", "self", ".", "clonab...
28.733333
16.866667
def sliding_t(wrap, size, step): """ Transformation for Sequence.sliding :param wrap: wrap children values with this :param size: size of window :param step: step size :return: transformation """ return Transformation( 'sliding({0}, {1})'.format(size, step), partial(slidi...
[ "def", "sliding_t", "(", "wrap", ",", "size", ",", "step", ")", ":", "return", "Transformation", "(", "'sliding({0}, {1})'", ".", "format", "(", "size", ",", "step", ")", ",", "partial", "(", "sliding_impl", ",", "wrap", ",", "size", ",", "step", ")", ...
29.461538
9
def _degrees_to_direction(self, degrees): """Convert wind direction from degrees to compass direction.""" try: degrees = float(degrees) except ValueError: return None if degrees < 0 or degrees > 360: return None if degrees <= 11.25 or degrees >...
[ "def", "_degrees_to_direction", "(", "self", ",", "degrees", ")", ":", "try", ":", "degrees", "=", "float", "(", "degrees", ")", "except", "ValueError", ":", "return", "None", "if", "degrees", "<", "0", "or", "degrees", ">", "360", ":", "return", "None",...
28.357143
12.857143
def process_target(self): """Return target with transformations, if any""" if isinstance(self.target, str): # Replace single and double quotes with escaped single-quote self.target = self.target.replace("'", "\'").replace('"', "\'") return "\"{target}\"".format(target...
[ "def", "process_target", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "target", ",", "str", ")", ":", "# Replace single and double quotes with escaped single-quote", "self", ".", "target", "=", "self", ".", "target", ".", "replace", "(", "\"'\"",...
50.571429
16.571429
def __getIp6Address(self, addressType): """get specific type of IPv6 address configured on thread device Args: addressType: the specific type of IPv6 address link local: link local unicast IPv6 address that's within one-hop scope global: global unicast IPv6 address ...
[ "def", "__getIp6Address", "(", "self", ",", "addressType", ")", ":", "addrType", "=", "[", "'link local'", ",", "'global'", ",", "'rloc'", ",", "'mesh EID'", "]", "addrs", "=", "[", "]", "globalAddr", "=", "[", "]", "linkLocal64Addr", "=", "''", "rlocAddr"...
32.160714
14.857143
def set_image(self, image = None): """This method is used to set the image number. image must be an unsigned int. """ if image is None or type(image) is not int: raise KPError("Need a new image number") else: self.image = image self....
[ "def", "set_image", "(", "self", ",", "image", "=", "None", ")", ":", "if", "image", "is", "None", "or", "type", "(", "image", ")", "is", "not", "int", ":", "raise", "KPError", "(", "\"Need a new image number\"", ")", "else", ":", "self", ".", "image",...
29.230769
17.076923
def validate_token_age(callback_token): """ Returns True if a given token is within the age expiration limit. """ try: token = CallbackToken.objects.get(key=callback_token, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = api_setti...
[ "def", "validate_token_age", "(", "callback_token", ")", ":", "try", ":", "token", "=", "CallbackToken", ".", "objects", ".", "get", "(", "key", "=", "callback_token", ",", "is_active", "=", "True", ")", "seconds", "=", "(", "timezone", ".", "now", "(", ...
31.2
18.1
def check_venv(self): """ Ensure we're inside a virtualenv. """ if self.zappa: venv = self.zappa.get_current_venv() else: # Just for `init`, when we don't have settings yet. venv = Zappa.get_current_venv() if not venv: raise ClickException(...
[ "def", "check_venv", "(", "self", ")", ":", "if", "self", ".", "zappa", ":", "venv", "=", "self", ".", "zappa", ".", "get_current_venv", "(", ")", "else", ":", "# Just for `init`, when we don't have settings yet.", "venv", "=", "Zappa", ".", "get_current_venv", ...
55.545455
31.272727
def getScriptNames(self): """This function returns the list of layouts for the current db.""" if self._db == '': raise FMError, 'No database was selected' request = [] request.append(uu({'-db': self._db })) request.append(uu({'-scriptnames': '' })) result = self._doRequest(request) result = FMResult...
[ "def", "getScriptNames", "(", "self", ")", ":", "if", "self", ".", "_db", "==", "''", ":", "raise", "FMError", ",", "'No database was selected'", "request", "=", "[", "]", "request", ".", "append", "(", "uu", "(", "{", "'-db'", ":", "self", ".", "_db",...
26.055556
19
def make_request( ins, method, url, stripe_account=None, params=None, headers=None, **kwargs ): """ Return a deferred or handle error. For overriding in various classes. """ if txstripe.api_key is None: raise error.AuthenticationError( 'No API key provided. (HINT: set your A...
[ "def", "make_request", "(", "ins", ",", "method", ",", "url", ",", "stripe_account", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "txstripe", ".", "api_key", "is", "None", ":", "raise"...
29.559322
20.813559
def generate_code(meta, prefix=None, node=False, min=False): """ Generate res.js Args: meta: tuple(url_prefix, auth_header, resources) or metadata of API Returns: res.js source code """ if isinstance(meta, dict): url_prefix, auth_header, resources = parse_meta(meta) ...
[ "def", "generate_code", "(", "meta", ",", "prefix", "=", "None", ",", "node", "=", "False", ",", "min", "=", "False", ")", ":", "if", "isinstance", "(", "meta", ",", "dict", ")", ":", "url_prefix", ",", "auth_header", ",", "resources", "=", "parse_meta...
28.416667
18
def by_causes(queryset, cause_string=None): """ Filter queryset by a comma delimeted cause list """ if cause_string: operator, items = get_operator_and_items(cause_string) q_obj = SQ() for c in items: if len(c) > 0: q_obj.add(SQ(causes=c), operator) queryset = queryset.filter(q_obj) ...
[ "def", "by_causes", "(", "queryset", ",", "cause_string", "=", "None", ")", ":", "if", "cause_string", ":", "operator", ",", "items", "=", "get_operator_and_items", "(", "cause_string", ")", "q_obj", "=", "SQ", "(", ")", "for", "c", "in", "items", ":", "...
32.6
13.5
def reverseCommit(self): """ Remove the inserted character(s). """ # Move the cursor to the right of the text to delete. tc = self.qteWidget.textCursor() # Delete as many characters as necessary. For an image that would # be exactly 1 even though the HTML code t...
[ "def", "reverseCommit", "(", "self", ")", ":", "# Move the cursor to the right of the text to delete.", "tc", "=", "self", ".", "qteWidget", ".", "textCursor", "(", ")", "# Delete as many characters as necessary. For an image that would", "# be exactly 1 even though the HTML code t...
33.916667
19.5
def make_elements(tokens, text, start=0, end=None, fallback=None): """Make elements from a list of parsed tokens. It will turn all unmatched holes into fallback elements. :param tokens: a list of parsed tokens. :param text: the original tet. :param start: the offset of where parsing starts. Default...
[ "def", "make_elements", "(", "tokens", ",", "text", ",", "start", "=", "0", ",", "end", "=", "None", ",", "fallback", "=", "None", ")", ":", "result", "=", "[", "]", "end", "=", "end", "or", "len", "(", "text", ")", "prev_end", "=", "start", "for...
38.409091
15.818182
def check_for_interest(self, client, recipient, message): """Determine whether this line is addressing us.""" for prefix in self.prefixes: if message.startswith(prefix): return True, message[len(prefix):] # Don't require a prefix if addressed in PM. # This co...
[ "def", "check_for_interest", "(", "self", ",", "client", ",", "recipient", ",", "message", ")", ":", "for", "prefix", "in", "self", ".", "prefixes", ":", "if", "message", ".", "startswith", "(", "prefix", ")", ":", "return", "True", ",", "message", "[", ...
38.428571
13.071429
def create(self, tag, **kwds): """ Endpoint: /tag/create.json Creates a new tag. Returns True if successful. Raises a TroveboxError if not. """ return self._client.post("/tag/create.json", tag=tag, **kwds)["result"]
[ "def", "create", "(", "self", ",", "tag", ",", "*", "*", "kwds", ")", ":", "return", "self", ".", "_client", ".", "post", "(", "\"/tag/create.json\"", ",", "tag", "=", "tag", ",", "*", "*", "kwds", ")", "[", "\"result\"", "]" ]
29.333333
12.888889
def get_all_subnets_cidr(self, no_mask=False): """Returns all the subnets. """ body = {} subnet_cidrs = [] try: subnet_list = self.neutronclient.list_subnets(body=body) subnet_dat = subnet_list.get('subnets') for sub in subnet_dat: if n...
[ "def", "get_all_subnets_cidr", "(", "self", ",", "no_mask", "=", "False", ")", ":", "body", "=", "{", "}", "subnet_cidrs", "=", "[", "]", "try", ":", "subnet_list", "=", "self", ".", "neutronclient", ".", "list_subnets", "(", "body", "=", "body", ")", ...
39.2
15.933333
def advanced_indexing_op(inputs, index): """Advanced Indexing for Sequences, returns the outputs by given sequence lengths. When return the last output :class:`DynamicRNNLayer` uses it to get the last outputs with the sequence lengths. Parameters ----------- inputs : tensor for data With sh...
[ "def", "advanced_indexing_op", "(", "inputs", ",", "index", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "inputs", ")", "[", "0", "]", "# max_length = int(inputs.get_shape()[1]) # for fixed length rnn, length is given", "max_length", "=", "tf", ".", "shape...
41.061224
22.591837
def UsersChangePassword (self, current_password, new_password): """ Change the password for the current user @param current_password (string) - md5 hash of the current password of the user @param new_password (string) - md5 hash of the new password of the us...
[ "def", "UsersChangePassword", "(", "self", ",", "current_password", ",", "new_password", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/change_password'", ",", "\"POST\"", ",", "{", "\"current_password\"", ":", "current_password", ",", "\"new_password\"", ...
50.214286
30.214286
def _update_Frxy(self): """Update `Frxy` from `piAx_piAy_beta`, `omega`, `omega2`, and `beta`.""" self.Frxy.fill(1.0) self.Frxy_no_omega.fill(1.0) with scipy.errstate(divide='raise', under='raise', over='raise', invalid='ignore'): scipy.copyto(self.Frxy_no_ome...
[ "def", "_update_Frxy", "(", "self", ")", ":", "self", ".", "Frxy", ".", "fill", "(", "1.0", ")", "self", ".", "Frxy_no_omega", ".", "fill", "(", "1.0", ")", "with", "scipy", ".", "errstate", "(", "divide", "=", "'raise'", ",", "under", "=", "'raise'"...
53.266667
18
def get_mx(self, tree: Union[ast.Symbol, ast.ComponentRef, ast.Expression]) -> ca.MX: """ We pull components and symbols from the AST on demand. This is to ensure that parametrized vector dimensions can be resolved. Vector dimensions need to be known at CasADi MX creation time. ...
[ "def", "get_mx", "(", "self", ",", "tree", ":", "Union", "[", "ast", ".", "Symbol", ",", "ast", ".", "ComponentRef", ",", "ast", ".", "Expression", "]", ")", "->", "ca", ".", "MX", ":", "if", "tree", "not", "in", "self", ".", "src", ":", "if", ...
43.882353
18.588235
def distok(self): """ Boolean array showing which stars pass all distribution constraints. A "distribution constraint" is a constraint that affects the distribution of stars, rather than just the number. """ ok = np.ones(len(self.stars)).astype(bool) for name in ...
[ "def", "distok", "(", "self", ")", ":", "ok", "=", "np", ".", "ones", "(", "len", "(", "self", ".", "stars", ")", ")", ".", "astype", "(", "bool", ")", "for", "name", "in", "self", ".", "constraints", ":", "c", "=", "self", ".", "constraints", ...
35.538462
16.153846
def spop(self, key, count=None): """Removes and returns one or more random elements from the set value store at key. This operation is similar to :meth:`~tredis.RedisClient.srandmember`, that returns one or more random elements from a set but does not remove it. The cou...
[ "def", "spop", "(", "self", ",", "key", ",", "count", "=", "None", ")", ":", "command", "=", "[", "b'SPOP'", ",", "key", "]", "if", "count", ":", "# pragma: nocover", "command", ".", "append", "(", "ascii", "(", "count", ")", ".", "encode", "(", "'...
39.5
23.8125
def get_ii_text(node): """ Get the text for IndicatorItem node. :param node: IndicatorItem node. :return: """ if node.tag != 'IndicatorItem': raise IOCParseError('Invalid tag: {}'.format(node.tag)) condition = node.attrib.get('condition') pres...
[ "def", "get_ii_text", "(", "node", ")", ":", "if", "node", ".", "tag", "!=", "'IndicatorItem'", ":", "raise", "IOCParseError", "(", "'Invalid tag: {}'", ".", "format", "(", "node", ".", "tag", ")", ")", "condition", "=", "node", ".", "attrib", ".", "get"...
43.607143
20.321429
def find_component(co_id): """ find a component from the Ariane server cache depending on its id :param co_id: the component id to find :return: the component if found and None if not """ LOGGER.debug("InjectorCachedComponentService.find_component") ret = None ...
[ "def", "find_component", "(", "co_id", ")", ":", "LOGGER", ".", "debug", "(", "\"InjectorCachedComponentService.find_component\"", ")", "ret", "=", "None", "if", "co_id", "is", "not", "None", ":", "args", "=", "{", "'properties'", ":", "{", "'OPERATION'", ":",...
52.625
25.958333
def mapFromChart( self, x, y ): """ Maps a chart point to a pixel position within the grid based on the rulers. :param x | <variant> y | <variant> :return <QPointF> """ grid = self.gridRect() h...
[ "def", "mapFromChart", "(", "self", ",", "x", ",", "y", ")", ":", "grid", "=", "self", ".", "gridRect", "(", ")", "hruler", "=", "self", ".", "horizontalRuler", "(", ")", "vruler", "=", "self", ".", "verticalRuler", "(", ")", "xperc", "=", "hruler", ...
29.291667
12.458333
def wm_msg(self, module_name, command): """ Execute the message with i3-msg or swaymsg and log its output. """ wm_msg = self.config["wm"]["msg"] pipe = Popen([wm_msg, command], stdout=PIPE) self.py3_wrapper.log( '{} module="{}" command="{}" stdout={}'.format( ...
[ "def", "wm_msg", "(", "self", ",", "module_name", ",", "command", ")", ":", "wm_msg", "=", "self", ".", "config", "[", "\"wm\"", "]", "[", "\"msg\"", "]", "pipe", "=", "Popen", "(", "[", "wm_msg", ",", "command", "]", ",", "stdout", "=", "PIPE", ")...
36.181818
14.181818
def gchart(self, s = 0, size = [], candle = 20): """ Chart for serious stocks 輸出 Google Chart 圖表。 s = 資料筆數 size = 圖表寬度、高度 [寬度,高度] candle = K 棒的寬度 """ if s == 0: s = len(self.raw_data) if len(size) == 2: sw,sh = size else: sh = 300 sw = 25 * s ...
[ "def", "gchart", "(", "self", ",", "s", "=", "0", ",", "size", "=", "[", "]", ",", "candle", "=", "20", ")", ":", "if", "s", "==", "0", ":", "s", "=", "len", "(", "self", ".", "raw_data", ")", "if", "len", "(", "size", ")", "==", "2", ":"...
25.545455
22.8
def _compile_arithmetic_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None...
[ "def", "_compile_arithmetic_expression", "(", "self", ",", "expr", ":", "Expression", ",", "scope", ":", "Dict", "[", "str", ",", "TensorFluent", "]", ",", "batch_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "noise", ":", "Optional", "[", "...
37.265306
24.408163
def build_epsf(self, stars, init_epsf=None): """ Iteratively build an ePSF from star cutouts. Parameters ---------- stars : `EPSFStars` object The stars used to build the ePSF. init_epsf : `EPSFModel` object, optional The initial ePSF model. If ...
[ "def", "build_epsf", "(", "self", ",", "stars", ",", "init_epsf", "=", "None", ")", ":", "iter_num", "=", "0", "center_dist_sq", "=", "self", ".", "center_accuracy_sq", "+", "1.", "centers", "=", "stars", ".", "cutout_center_flat", "n_stars", "=", "stars", ...
36.267442
19.686047
def get_for_targets(self, targets): """Gets the classpath products for the given targets. Products are returned in order, respecting target excludes. :param targets: The targets to lookup classpath products for. :returns: The ordered (conf, path) tuples, with paths being either classfile directories o...
[ "def", "get_for_targets", "(", "self", ",", "targets", ")", ":", "cp_entries", "=", "self", ".", "get_classpath_entries_for_targets", "(", "targets", ")", "return", "[", "(", "conf", ",", "cp_entry", ".", "path", ")", "for", "conf", ",", "cp_entry", "in", ...
42.333333
22
def _update_bgbrush(self, bgcolor): """Updates background color""" brush_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW) brush_color.SetRGB(bgcolor) self.bgcolor_choice.SetColour(brush_color)
[ "def", "_update_bgbrush", "(", "self", ",", "bgcolor", ")", ":", "brush_color", "=", "wx", ".", "SystemSettings_GetColour", "(", "wx", ".", "SYS_COLOUR_WINDOW", ")", "brush_color", ".", "SetRGB", "(", "bgcolor", ")", "self", ".", "bgcolor_choice", ".", "SetCol...
32.714286
18.714286
def WriteHeader(self): """Writes the header to the output.""" output_text = self._field_delimiter.join(self._fields) output_text = '{0:s}\n'.format(output_text) self._output_writer.Write(output_text)
[ "def", "WriteHeader", "(", "self", ")", ":", "output_text", "=", "self", ".", "_field_delimiter", ".", "join", "(", "self", ".", "_fields", ")", "output_text", "=", "'{0:s}\\n'", ".", "format", "(", "output_text", ")", "self", ".", "_output_writer", ".", "...
42.2
9
def _set_nsx_controller(self, v, load=False): """ Setter method for nsx_controller, mapped from YANG variable /nsx_controller (list) If this variable is read-only (config: false) in the source YANG file, then _set_nsx_controller is considered as a private method. Backends looking to populate this va...
[ "def", "_set_nsx_controller", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
130.863636
62.636364
def url(self, var, default=NOTSET): """ :rtype: urlparse.ParseResult """ return self.get_value(var, cast=urlparse, default=default, parse_default=True)
[ "def", "url", "(", "self", ",", "var", ",", "default", "=", "NOTSET", ")", ":", "return", "self", ".", "get_value", "(", "var", ",", "cast", "=", "urlparse", ",", "default", "=", "default", ",", "parse_default", "=", "True", ")" ]
35.8
11
def queries(self, rcSuffix='', rcNeeded=False, padChar='-', queryInsertionChar='N', unknownQualityChar='!', allowDuplicateIds=False, addAlignment=False): """ Produce padded (with gaps) queries according to the CIGAR string and reference sequence length for each ma...
[ "def", "queries", "(", "self", ",", "rcSuffix", "=", "''", ",", "rcNeeded", "=", "False", ",", "padChar", "=", "'-'", ",", "queryInsertionChar", "=", "'N'", ",", "unknownQualityChar", "=", "'!'", ",", "allowDuplicateIds", "=", "False", ",", "addAlignment", ...
51.814634
22.868293
def coindex_around_coords(self, lat, lon, start=None, interval=None): """ Queries the OWM Weather API for Carbon Monoxide values sampled in the surroundings of the provided geocoordinates and in the specified time interval. A *COIndex* object instance is returned, encapsulating a...
[ "def", "coindex_around_coords", "(", "self", ",", "lat", ",", "lon", ",", "start", "=", "None", ",", "interval", "=", "None", ")", ":", "geo", ".", "assert_is_lon", "(", "lon", ")", "geo", ".", "assert_is_lat", "(", "lat", ")", "params", "=", "{", "'...
51.763158
23.657895
def _postgresql(self, dbhost, dbport, dbname, dbuser, dbpass, dsn_style=None): # noqa """PostgreSQL psycopg2 driver accepts two syntaxes Plus a string for .pgpass file """ dsn = [] if dsn_style is None or dsn_style == 'all' or dsn_style == 'keyvalue': dsnstr = "ho...
[ "def", "_postgresql", "(", "self", ",", "dbhost", ",", "dbport", ",", "dbname", ",", "dbuser", ",", "dbpass", ",", "dsn_style", "=", "None", ")", ":", "# noqa", "dsn", "=", "[", "]", "if", "dsn_style", "is", "None", "or", "dsn_style", "==", "'all'", ...
37.714286
20.047619
def alias_create(indices, alias, hosts=None, body=None, profile=None, source=None): ''' Create an alias for a specific index/indices indices Single or multiple indices separated by comma, use _all to perform the operation on all indices. alias Alias name body Optional defini...
[ "def", "alias_create", "(", "indices", ",", "alias", ",", "hosts", "=", "None", ",", "body", "=", "None", ",", "profile", "=", "None", ",", "source", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "if", "source"...
44.2
33.866667
def report(self, req_handler): "Send a response corresponding to this error to the client" if self.exc: req_handler.send_exception(self.code, self.exc, self.headers) return text = (self.text or BaseHTTPRequestHandler.responses[self.code][1] ...
[ "def", "report", "(", "self", ",", "req_handler", ")", ":", "if", "self", ".", "exc", ":", "req_handler", ".", "send_exception", "(", "self", ".", "code", ",", "self", ".", "exc", ",", "self", ".", "headers", ")", "return", "text", "=", "(", "self", ...
40
27.636364
def is_text(bytesio): """Return whether the first KB of contents seems to be binary. This is roughly based on libmagic's binary/text detection: https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228 """ text_chars = ( bytearray([7, 8, 9, 10, 11, ...
[ "def", "is_text", "(", "bytesio", ")", ":", "text_chars", "=", "(", "bytearray", "(", "[", "7", ",", "8", ",", "9", ",", "10", ",", "11", ",", "12", ",", "13", ",", "27", "]", ")", "+", "bytearray", "(", "range", "(", "0x20", ",", "0x7F", ")"...
39.5
20.25
def get_objects_from_from_queues(self): """ Get objects from "from" queues and add them. :return: True if we got something in the queue, False otherwise. :rtype: bool """ _t0 = time.time() had_some_objects = False for module in self.modules_manager.get_external_i...
[ "def", "get_objects_from_from_queues", "(", "self", ")", ":", "_t0", "=", "time", ".", "time", "(", ")", "had_some_objects", "=", "False", "for", "module", "in", "self", ".", "modules_manager", ".", "get_external_instances", "(", ")", ":", "queue", "=", "mod...
41.272727
18.757576
def json_obj_to_cursor(self, json): """(Deprecated) Converts a JSON object to a mongo db cursor :param str json: A json string :returns: dictionary with ObjectId type :rtype: dict """ cursor = json_util.loads(json) if "id" in json: cursor["_id"] = Obj...
[ "def", "json_obj_to_cursor", "(", "self", ",", "json", ")", ":", "cursor", "=", "json_util", ".", "loads", "(", "json", ")", "if", "\"id\"", "in", "json", ":", "cursor", "[", "\"_id\"", "]", "=", "ObjectId", "(", "cursor", "[", "\"id\"", "]", ")", "d...
29.153846
13.307692
def contains(self, other): """ Returns True if offset vector @other can be found in @self, False otherwise. An offset vector is "found in" another offset vector if the latter contains all of the former's instruments and the relative offsets among those instruments are equal (the absolute offsets need not b...
[ "def", "contains", "(", "self", ",", "other", ")", ":", "return", "offsetvector", "(", "(", "key", ",", "offset", ")", "for", "key", ",", "offset", "in", "self", ".", "items", "(", ")", "if", "key", "in", "other", ")", ".", "deltas", "==", "other",...
30.52381
24.142857
def relative_strength_index(data, period): """ Relative Strength Index. Formula: RSI = 100 - (100 / 1 + (prevGain/prevLoss)) """ catch_errors.check_for_period_error(data, period) period = int(period) changes = [data_tup[1] - data_tup[0] for data_tup in zip(data[::1], data[1::1])] ...
[ "def", "relative_strength_index", "(", "data", ",", "period", ")", ":", "catch_errors", ".", "check_for_period_error", "(", "data", ",", "period", ")", "period", "=", "int", "(", "period", ")", "changes", "=", "[", "data_tup", "[", "1", "]", "-", "data_tup...
29.906977
21.534884
def shannon_entropy(data, iterator): """ Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html """ if not data: return 0 entropy = 0 for x in iterator: p_x = float(data.count(x))/len(data) if p_x > 0: entropy += - p_x*math.log(p_...
[ "def", "shannon_entropy", "(", "data", ",", "iterator", ")", ":", "if", "not", "data", ":", "return", "0", "entropy", "=", "0", "for", "x", "in", "iterator", ":", "p_x", "=", "float", "(", "data", ".", "count", "(", "x", ")", ")", "/", "len", "("...
27.75
16.25
def overextends(parser, token): """ Extended version of Django's ``extends`` tag that allows circular inheritance to occur, eg a template can both be overridden and extended at once. """ if DJANGO_VERSION >= (1, 9): warnings.warn( "The `overextends` template tag is deprecated...
[ "def", "overextends", "(", "parser", ",", "token", ")", ":", "if", "DJANGO_VERSION", ">=", "(", "1", ",", "9", ")", ":", "warnings", ".", "warn", "(", "\"The `overextends` template tag is deprecated in favour of \"", "\"Django's built-in `extends` tag, which supports recu...
40.956522
17.826087
def read_pr_report(self, filename): """Reads in a PlanarRad generated report Saves the single line reported parameters as a python dictionary :param filename: The name and path of the PlanarRad generated file :returns self.data_dictionary: python dictionary with the key and values from...
[ "def", "read_pr_report", "(", "self", ",", "filename", ")", ":", "done", "=", "False", "f", "=", "open", "(", "filename", ")", "while", "f", ":", "#for line in open(filename):", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ":", "do...
38.925373
26.731343
def better(old_value, new_value, mode): """ Check if new value is better than the old value""" if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)): return True if mode == 'min': return new_value < old_value elif mode == 'max': re...
[ "def", "better", "(", "old_value", ",", "new_value", ",", "mode", ")", ":", "if", "(", "old_value", "is", "None", "or", "np", ".", "isnan", "(", "old_value", ")", ")", "and", "(", "new_value", "is", "not", "None", "and", "not", "np", ".", "isnan", ...
37.636364
20.909091
def instance_of(*args): """ This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * provi...
[ "def", "instance_of", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "# Standard mode", "value", ",", "ref_type", "=", "args", "if", "not", "isinstance", "(", "ref_type", ",", "set", ")", ":", "# ref_type is a single type", "i...
38.078125
20.265625
def tag_id(self, name): """ Get the unique tag identifier for a given tag. :param name: The tag :type name: str :rtype: str """ return self._store.get(self.tag_key(name)) or self.reset_tag(name)
[ "def", "tag_id", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_store", ".", "get", "(", "self", ".", "tag_key", "(", "name", ")", ")", "or", "self", ".", "reset_tag", "(", "name", ")" ]
24.3
19.5
def _calculate(self, startingPercentage, endPercentage, startDate, endDate): """This is the error calculation function that gets called by :py:meth:`BaseErrorMeasure.get_error`. Both parameters will be correct at this time. :param float startingPercentage: Defines the start of the interval. Th...
[ "def", "_calculate", "(", "self", ",", "startingPercentage", ",", "endPercentage", ",", "startDate", ",", "endDate", ")", ":", "# get the defined subset of error values", "errorValues", "=", "self", ".", "_get_error_values", "(", "startingPercentage", ",", "endPercentag...
46.257143
29.6
def _set_residue_map(self): """ map each residue to the corresponding molecule. """ self.map_residue_to_mol = {} lookup = {} for idx, mol in enumerate(self.mols): if not mol.formula in lookup: mol.translate_sites(indices=range(len(mol)), ...
[ "def", "_set_residue_map", "(", "self", ")", ":", "self", ".", "map_residue_to_mol", "=", "{", "}", "lookup", "=", "{", "}", "for", "idx", ",", "mol", "in", "enumerate", "(", "self", ".", "mols", ")", ":", "if", "not", "mol", ".", "formula", "in", ...
41.416667
12.583333
def assign_line_results(grid, line_data): """ Write results obtained from PF to graph Parameters ----------- grid: ding0.network line_data: pandas.DataFrame DataFrame containing active/reactive at nodes obtained from PF analysis """ package_path = ding0.__path__[0] edges =...
[ "def", "assign_line_results", "(", "grid", ",", "line_data", ")", ":", "package_path", "=", "ding0", ".", "__path__", "[", "0", "]", "edges", "=", "[", "edge", "for", "edge", "in", "grid", ".", "graph_edges", "(", ")", "if", "(", "edge", "[", "'adj_nod...
43.55814
23.697674
def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. """ if len(self._valid_lines) == 0: re...
[ "def", "cmd_requests_per_minute", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_valid_lines", ")", "==", "0", ":", "return", "current_minute", "=", "self", ".", "_valid_lines", "[", "0", "]", ".", "accept_date", "current_minute_counter", "=", "0", ...
32.553191
15.382979
def collect(self): """ Collect metrics from all registered metric sets :return: """ logger.debug("Collecting metrics") for name, metricset in compat.iteritems(self._metricsets): data = metricset.collect() if data: self._queue_func(...
[ "def", "collect", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Collecting metrics\"", ")", "for", "name", ",", "metricset", "in", "compat", ".", "iteritems", "(", "self", ".", "_metricsets", ")", ":", "data", "=", "metricset", ".", "collect", "...
30.545455
15.454545
def adapt(self, other: 'BinningBase'): """Adapt this binning so that it contains all bins of another binning. Parameters ---------- other: BinningBase """ # TODO: in-place arg if np.array_equal(self.bins, other.bins): return None, None elif no...
[ "def", "adapt", "(", "self", ",", "other", ":", "'BinningBase'", ")", ":", "# TODO: in-place arg", "if", "np", ".", "array_equal", "(", "self", ".", "bins", ",", "other", ".", "bins", ")", ":", "return", "None", ",", "None", "elif", "not", "self", ".",...
32.071429
13.857143
def magictype(text, prompt_template="default", speed=1): """Echo each character in ``text`` as keyboard characters are pressed. Characters are echo'd ``speed`` characters at a time. """ echo_prompt(prompt_template) cursor_position = 0 return_to_regular_type = False with raw_mode(): w...
[ "def", "magictype", "(", "text", ",", "prompt_template", "=", "\"default\"", ",", "speed", "=", "1", ")", ":", "echo_prompt", "(", "prompt_template", ")", "cursor_position", "=", "0", "return_to_regular_type", "=", "False", "with", "raw_mode", "(", ")", ":", ...
40.875
9.95
def CoefficientOfNetworkComplexity_metric(bpmn_graph): """ Returns the value of the Coefficient of Network Complexity metric ("Ratio of the total number of arcs in a process model to its total number of nodes.") for the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph r...
[ "def", "CoefficientOfNetworkComplexity_metric", "(", "bpmn_graph", ")", ":", "return", "float", "(", "len", "(", "bpmn_graph", ".", "get_flows", "(", ")", ")", ")", "/", "float", "(", "len", "(", "bpmn_graph", ".", "get_nodes", "(", ")", ")", ")" ]
42.6
25.6
def conv_lstm(x, kernel_size, filters, padding="SAME", dilation_rate=(1, 1), name=None, reuse=None): """Convolutional LSTM in 1 dimension.""" with tf.variable_scope( name, default_name="conv_lstm", values=[x], reuse=reuse): ...
[ "def", "conv_lstm", "(", "x", ",", "kernel_size", ",", "filters", ",", "padding", "=", "\"SAME\"", ",", "dilation_rate", "=", "(", "1", ",", "1", ")", ",", "name", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope",...
32.157895
16.263158
def get_wwpns(self, partitions): """ Return the WWPNs of the host ports (of the :term:`HBAs <HBA>`) of the specified :term:`Partitions <Partition>` of this CPC. This method performs the HMC operation "Export WWPN List". Authorization requirements: * Object-access permi...
[ "def", "get_wwpns", "(", "self", ",", "partitions", ")", ":", "body", "=", "{", "'partitions'", ":", "[", "p", ".", "uri", "for", "p", "in", "partitions", "]", "}", "result", "=", "self", ".", "manager", ".", "session", ".", "post", "(", "self", "....
39.638298
23.93617
def update_expiry(self, commit=True): """Update token's expiration datetime on every auth action.""" self.expires = update_expiry(self.created) if commit: self.save()
[ "def", "update_expiry", "(", "self", ",", "commit", "=", "True", ")", ":", "self", ".", "expires", "=", "update_expiry", "(", "self", ".", "created", ")", "if", "commit", ":", "self", ".", "save", "(", ")" ]
39.6
10.4
def is_capable_terminal(file=sys.stderr) -> bool: """ Determine whether we are connected to a capable terminal. """ if not os.isatty(file.fileno()): return False terminal = os.getenv("TERM", "dumb") # Hardcoded list of non-capable terminals. return terminal not in ["dumb", "emacs"]
[ "def", "is_capable_terminal", "(", "file", "=", "sys", ".", "stderr", ")", "->", "bool", ":", "if", "not", "os", ".", "isatty", "(", "file", ".", "fileno", "(", ")", ")", ":", "return", "False", "terminal", "=", "os", ".", "getenv", "(", "\"TERM\"", ...
34.444444
7.111111
def add_residue_mindist(self, residue_pairs='all', scheme='closest-heavy', ignore_nonprotein=True, threshold=None, periodic=True): r""" Adds the minimum distance be...
[ "def", "add_residue_mindist", "(", "self", ",", "residue_pairs", "=", "'all'", ",", "scheme", "=", "'closest-heavy'", ",", "ignore_nonprotein", "=", "True", ",", "threshold", "=", "None", ",", "periodic", "=", "True", ")", ":", "from", ".", "distances", "imp...
48.944444
32.037037
def tokenize(s, locale, update=None): """ Tokenize `s` according to corresponding locale dictionary. Don't use this for serious text processing. """ zhdict = getdict(locale) pfset = pfsdict[locale] if update: zhdict = zhdict.copy() zhdict.update(update) newset = set()...
[ "def", "tokenize", "(", "s", ",", "locale", ",", "update", "=", "None", ")", ":", "zhdict", "=", "getdict", "(", "locale", ")", "pfset", "=", "pfsdict", "[", "locale", "]", "if", "update", ":", "zhdict", "=", "zhdict", ".", "copy", "(", ")", "zhdic...
25.027778
14.75
def on_site(self, site_id=None): """Return a :class:`QuerySet` of pages that are published on the site defined by the ``SITE_ID`` setting. :param site_id: specify the id of the site object to filter with. """ if settings.PAGES_USE_SITE_ID: if not site_id: ...
[ "def", "on_site", "(", "self", ",", "site_id", "=", "None", ")", ":", "if", "settings", ".", "PAGES_USE_SITE_ID", ":", "if", "not", "site_id", ":", "site_id", "=", "settings", ".", "SITE_ID", "return", "self", ".", "get_queryset", "(", ")", ".", "filter"...
38.909091
12.363636
def xauth(base_url_template=DEFAULT_READER_URL_TEMPLATE, **xargs): """ Returns an OAuth token tuple that can be used with clients.ReaderClient. :param base_url_template: Template for generating Readability API urls. :param consumer_key: Readability consumer key, otherwise read from READABILITY_CONSUME...
[ "def", "xauth", "(", "base_url_template", "=", "DEFAULT_READER_URL_TEMPLATE", ",", "*", "*", "xargs", ")", ":", "consumer_key", "=", "xargs", ".", "get", "(", "'consumer_key'", ")", "or", "required_from_env", "(", "'READABILITY_CONSUMER_KEY'", ")", "consumer_secret"...
43.395349
27.627907
def getipmacarp(self): """ Function operates on the IMCDev object and updates the ipmacarp attribute :return: """ self.ipmacarp = get_ip_mac_arp_list(self.auth, self.url, devid = self.devid)
[ "def", "getipmacarp", "(", "self", ")", ":", "self", ".", "ipmacarp", "=", "get_ip_mac_arp_list", "(", "self", ".", "auth", ",", "self", ".", "url", ",", "devid", "=", "self", ".", "devid", ")" ]
37.5
21.166667
def update(self, friendly_name=values.unset, unique_name=values.unset, attributes=values.unset): """ Update the ChannelInstance :param unicode friendly_name: A human-readable name for the Channel. :param unicode unique_name: A unique, addressable name for the Channel. ...
[ "def", "update", "(", "self", ",", "friendly_name", "=", "values", ".", "unset", ",", "unique_name", "=", "values", ".", "unset", ",", "attributes", "=", "values", ".", "unset", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'FriendlyName'", ":...
32.4
19.666667
def getSystemIps(): """ will not return the localhost one """ IPs = [] for interface in NetInfo.getSystemIfs(): if not interface.startswith('lo'): ip = netinfo.get_ip(interface) IPs.append(ip) return IPs
[ "def", "getSystemIps", "(", ")", ":", "IPs", "=", "[", "]", "for", "interface", "in", "NetInfo", ".", "getSystemIfs", "(", ")", ":", "if", "not", "interface", ".", "startswith", "(", "'lo'", ")", ":", "ip", "=", "netinfo", ".", "get_ip", "(", "interf...
34
12.125
def report(request, comment_id): """ Flags a comment on GET. Redirects to whatever is provided in request.REQUEST['next']. """ comment = get_object_or_404( django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) if comment.parent is not None: messages.info(reques...
[ "def", "report", "(", "request", ",", "comment_id", ")", ":", "comment", "=", "get_object_or_404", "(", "django_comments", ".", "get_model", "(", ")", ",", "pk", "=", "comment_id", ",", "site__pk", "=", "settings", ".", "SITE_ID", ")", "if", "comment", "."...
33.823529
20.176471
def get_license(self, key=github.GithubObject.NotSet): """ :calls: `GET /license/:license <https://developer.github.com/v3/licenses/#get-an-individual-license>`_ :param key: string :rtype: :class:`github.License.License` """ assert isinstance(key, (str, unicode)), key ...
[ "def", "get_license", "(", "self", ",", "key", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "isinstance", "(", "key", ",", "(", "str", ",", "unicode", ")", ")", ",", "key", "headers", ",", "data", "=", "self", ".", "__reques...
39.538462
22
def var_replace(self, text): """Replaces all instances of @VAR with their values in the specified text. """ result = text for var in self._vardict: result = result.replace("@{}".format(var), self._vardict[var]) return result
[ "def", "var_replace", "(", "self", ",", "text", ")", ":", "result", "=", "text", "for", "var", "in", "self", ".", "_vardict", ":", "result", "=", "result", ".", "replace", "(", "\"@{}\"", ".", "format", "(", "var", ")", ",", "self", ".", "_vardict", ...
38.571429
13
def update_particle(self, part, chi=0.729843788, c=2.05): """Constriction factor update particle method. Notes ----- Looks for a list of neighbours attached to a particle and uses the particle's best position and that of the best neighbour. """ neighbour_...
[ "def", "update_particle", "(", "self", ",", "part", ",", "chi", "=", "0.729843788", ",", "c", "=", "2.05", ")", ":", "neighbour_pool", "=", "[", "self", ".", "population", "[", "i", "]", "for", "i", "in", "part", ".", "neighbours", "]", "best_neighbour...
45.068966
17.241379
def __eliminate_unused_constraits (self, objects): """ Eliminate constraints which mention objects not in 'objects'. In graph-theory terms, this is finding subgraph induced by ordered vertices. """ result = [] for c in self.constraints_: if c [0] in ob...
[ "def", "__eliminate_unused_constraits", "(", "self", ",", "objects", ")", ":", "result", "=", "[", "]", "for", "c", "in", "self", ".", "constraints_", ":", "if", "c", "[", "0", "]", "in", "objects", "and", "c", "[", "1", "]", "in", "objects", ":", ...
35.818182
14.181818
def member_status(): ''' Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status ''' ret = {'membership': {}, 'summary': {'Valid': 0, 'Leaving': 0, 'Exiting': 0, ...
[ "def", "member_status", "(", ")", ":", "ret", "=", "{", "'membership'", ":", "{", "}", ",", "'summary'", ":", "{", "'Valid'", ":", "0", ",", "'Leaving'", ":", "0", ",", "'Exiting'", ":", "0", ",", "'Joining'", ":", "0", ",", "'Down'", ":", "0", "...
25.190476
18.714286
def get_score_system(self): """Gets a grade system for the score. return: (osid.grading.GradeSystem) - the grade system raise: IllegalState - ``is_scored()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemen...
[ "def", "get_score_system", "(", "self", ")", ":", "# Implemented from template for osid.resource.Resource.get_avatar_template", "if", "not", "bool", "(", "self", ".", "_my_map", "[", "'scoreSystemId'", "]", ")", ":", "raise", "errors", ".", "IllegalState", "(", "'this...
52.052632
24.578947
def submitEntry(self): """Process user inputs and subit logbook entry when user clicks Submit button""" # logType = self.logui.logType.currentText() mcclogs, physlogs = self.selectedLogs() success = True if mcclogs != []: if not self.acceptedUser("MC...
[ "def", "submitEntry", "(", "self", ")", ":", "# logType = self.logui.logType.currentText()", "mcclogs", ",", "physlogs", "=", "self", ".", "selectedLogs", "(", ")", "success", "=", "True", "if", "mcclogs", "!=", "[", "]", ":", "if", "not", "self", ".", "acce...
37.75
18.0625
def ystep(self): r"""Minimise Augmented Lagrangian with respect to :math:`\mathbf{y}`. """ AXU = self.AX + self.U Y0 = (self.rho*(self.block_sep0(AXU) - self.S)) / (self.W**2 + self.rho) Y1 = self.Pcn(self.block_...
[ "def", "ystep", "(", "self", ")", ":", "AXU", "=", "self", ".", "AX", "+", "self", ".", "U", "Y0", "=", "(", "self", ".", "rho", "*", "(", "self", ".", "block_sep0", "(", "AXU", ")", "-", "self", ".", "S", ")", ")", "/", "(", "self", ".", ...
36.1
14.9
def selectPolicy(self, origin, request_method=None): "Based on the matching strategy and the origin and optionally the requested method a tuple of policyname and origin to pass back is returned." ret_origin = None policyname = None if self.matchstrategy in ("firstmatch", "verbmatch"): ...
[ "def", "selectPolicy", "(", "self", ",", "origin", ",", "request_method", "=", "None", ")", ":", "ret_origin", "=", "None", "policyname", "=", "None", "if", "self", ".", "matchstrategy", "in", "(", "\"firstmatch\"", ",", "\"verbmatch\"", ")", ":", "for", "...
47.666667
15.5
def translate_changes(initial_change): """Translate rope.base.change.Change instances to dictionaries. See Refactor.get_changes for an explanation of the resulting dictionary. """ agenda = [initial_change] result = [] while agenda: change = agenda.pop(0) if isinstance(chang...
[ "def", "translate_changes", "(", "initial_change", ")", ":", "agenda", "=", "[", "initial_change", "]", "result", "=", "[", "]", "while", "agenda", ":", "change", "=", "agenda", ".", "pop", "(", "0", ")", "if", "isinstance", "(", "change", ",", "rope_cha...
45.395349
15.860465
def cholorth(S): "Cholesky orthogonalization" return np.linalg.inv(np.linalg.cholesky(S)).T
[ "def", "cholorth", "(", "S", ")", ":", "return", "np", ".", "linalg", ".", "inv", "(", "np", ".", "linalg", ".", "cholesky", "(", "S", ")", ")", ".", "T" ]
32.333333
13.666667
def likes(user, *models): """ Usage: {% likes user as var %} Or {% likes user [model1, model2] as var %} """ content_types = [] model_list = models or settings.PINAX_LIKES_LIKABLE_MODELS.keys() for model in model_list: if not _allowed(model): continue ...
[ "def", "likes", "(", "user", ",", "*", "models", ")", ":", "content_types", "=", "[", "]", "model_list", "=", "models", "or", "settings", ".", "PINAX_LIKES_LIKABLE_MODELS", ".", "keys", "(", ")", "for", "model", "in", "model_list", ":", "if", "not", "_al...
31.411765
17.882353
def get_document(self, doc_uri): """Return a managed document if-present, else create one pointing at disk. See https://github.com/Microsoft/language-server-protocol/issues/177 """ return self._docs.get(doc_uri) or self._create_document(doc_uri)
[ "def", "get_document", "(", "self", ",", "doc_uri", ")", ":", "return", "self", ".", "_docs", ".", "get", "(", "doc_uri", ")", "or", "self", ".", "_create_document", "(", "doc_uri", ")" ]
45.5
19.333333
def toDiv(self, style='document'): """ Returns the text as paragaphed HTML vs. a full HTML document page. :return <str> """ if not self.editor().toPlainText(): return '' html = self.editor().document().toHtml(self.encoding()) ...
[ "def", "toDiv", "(", "self", ",", "style", "=", "'document'", ")", ":", "if", "not", "self", ".", "editor", "(", ")", ".", "toPlainText", "(", ")", ":", "return", "''", "html", "=", "self", ".", "editor", "(", ")", ".", "document", "(", ")", ".",...
35.333333
19.151515