text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_default_ref(repo): """Return a `github.GitRef` object for the HEAD of the default branch. Parameters ---------- repo: github.Repository.Repository repo to get default branch head ref from Returns ------- head : :class:`github.GitRef` instance Raises ------ gith...
[ "def", "get_default_ref", "(", "repo", ")", ":", "assert", "isinstance", "(", "repo", ",", "github", ".", "Repository", ".", "Repository", ")", ",", "type", "(", "repo", ")", "# XXX this probably should be resolved via repos.yaml", "default_branch", "=", "repo", "...
30.030303
21.151515
def _add_include_arg(arg_parser): """ Adds optional repeatable include parameter to a parser. :param arg_parser: ArgumentParser parser to add this argument to. """ arg_parser.add_argument("--include", metavar='Path', action='append', ...
[ "def", "_add_include_arg", "(", "arg_parser", ")", ":", "arg_parser", ".", "add_argument", "(", "\"--include\"", ",", "metavar", "=", "'Path'", ",", "action", "=", "'append'", ",", "type", "=", "to_unicode", ",", "dest", "=", "'include_paths'", ",", "help", ...
44.666667
11.5
def split_params(sym, params): """Helper function to split params dictionary into args and aux params Parameters ---------- sym : :class:`~mxnet.symbol.Symbol` MXNet symbol object params : dict of ``str`` to :class:`~mxnet.ndarray.NDArray` Dict of convert...
[ "def", "split_params", "(", "sym", ",", "params", ")", ":", "arg_params", "=", "{", "}", "aux_params", "=", "{", "}", "for", "args", "in", "sym", ".", "list_arguments", "(", ")", ":", "if", "args", "in", "params", ":", "arg_params", ".", "update", "(...
41.346154
20.307692
def calledThrice(cls, spy): #pylint: disable=invalid-name """ Checking the inspector is called thrice Args: SinonSpy """ cls.__is_spy(spy) if not (spy.calledThrice): raise cls.failException(cls.message)
[ "def", "calledThrice", "(", "cls", ",", "spy", ")", ":", "#pylint: disable=invalid-name", "cls", ".", "__is_spy", "(", "spy", ")", "if", "not", "(", "spy", ".", "calledThrice", ")", ":", "raise", "cls", ".", "failException", "(", "cls", ".", "message", "...
31.875
8.875
def Fstar(self, value): """ set fixed effect design for predictions """ if value is None: self._use_to_predict = False else: assert value.shape[1] == self._K, 'Dimension mismatch' self._use_to_predict = True self._Fstar = value self.clear_cache...
[ "def", "Fstar", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "self", ".", "_use_to_predict", "=", "False", "else", ":", "assert", "value", ".", "shape", "[", "1", "]", "==", "self", ".", "_K", ",", "'Dimension mismatch'", "s...
35.888889
11.555556
def is_directory(self): """ :return: whether this task is associated with a directory. :rtype: bool """ if self.cid is None: msg = 'Cannot determine whether this task is a directory.' if not self.is_transferred: msg += ' This task has not b...
[ "def", "is_directory", "(", "self", ")", ":", "if", "self", ".", "cid", "is", "None", ":", "msg", "=", "'Cannot determine whether this task is a directory.'", "if", "not", "self", ".", "is_transferred", ":", "msg", "+=", "' This task has not been transferred.'", "ra...
38.181818
14
def load_config(path=None): """Choose and return the config path and it's contents as dict.""" # NOTE: Initially I wanted to inherit Path to encapsulate Git access # there but there's no easy way to subclass pathlib.Path :( head_sha = get_sha1_from("HEAD") revision = head_sha saved_config_path =...
[ "def", "load_config", "(", "path", "=", "None", ")", ":", "# NOTE: Initially I wanted to inherit Path to encapsulate Git access", "# there but there's no easy way to subclass pathlib.Path :(", "head_sha", "=", "get_sha1_from", "(", "\"HEAD\"", ")", "revision", "=", "head_sha", ...
31.464286
17.464286
def main(*args, **kwargs): """ `kwargs`: `configuration_filepath`: filepath for the `ini` configuration """ kwargs = {**kwargs, **_get_kwargs()} # FIXME: This filepath handeling is messed up and not transparent as it should be default_filepath = get_config_filepath() configuration_f...
[ "def", "main", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "{", "*", "*", "kwargs", ",", "*", "*", "_get_kwargs", "(", ")", "}", "# FIXME: This filepath handeling is messed up and not transparent as it should be", "default_filepath", "=", ...
38.458333
15.958333
def get_reserved_ip_address(self, name): ''' Retrieves information about the specified reserved IP address. name: Required. Name of the reserved IP address. ''' _validate_not_none('name', name) return self._perform_get(self._get_reserved_ip_path(name), Reserv...
[ "def", "get_reserved_ip_address", "(", "self", ",", "name", ")", ":", "_validate_not_none", "(", "'name'", ",", "name", ")", "return", "self", ".", "_perform_get", "(", "self", ".", "_get_reserved_ip_path", "(", "name", ")", ",", "ReservedIP", ")" ]
35.222222
23
def download_bundle_view(self, request, pk): """A view that allows the user to download a certificate bundle in PEM format.""" return self._download_response(request, pk, bundle=True)
[ "def", "download_bundle_view", "(", "self", ",", "request", ",", "pk", ")", ":", "return", "self", ".", "_download_response", "(", "request", ",", "pk", ",", "bundle", "=", "True", ")" ]
49.25
17
def correlation_model(prediction, fm): """ wraps numpy.corrcoef functionality for model evaluation input: prediction: 2D Matrix the model salience map fm: fixmat Used to compute a FDM to which the prediction is compared. """ (_, r_x) = calc_resize_factor(pred...
[ "def", "correlation_model", "(", "prediction", ",", "fm", ")", ":", "(", "_", ",", "r_x", ")", "=", "calc_resize_factor", "(", "prediction", ",", "fm", ".", "image_size", ")", "fdm", "=", "compute_fdm", "(", "fm", ",", "scale_factor", "=", "r_x", ")", ...
33.923077
16.076923
def duplicate_files(self): ''' Search for duplicates of submission file uploads for this assignment. This includes the search in other course, whether inactive or not. Returns a list of lists, where each latter is a set of duplicate submissions with at least on of them for this a...
[ "def", "duplicate_files", "(", "self", ")", ":", "result", "=", "list", "(", ")", "files", "=", "SubmissionFile", ".", "valid_ones", ".", "order_by", "(", "'md5'", ")", "for", "key", ",", "dup_group", "in", "groupby", "(", "files", ",", "lambda", "f", ...
43.222222
22.111111
def has_output(state, text, pattern=True, no_output_msg=None): """Search student output for a pattern. Among the student and solution process, the student submission and solution code as a string, the ``Ex()`` state also contains the output that a student generated with his or her submission. With ``h...
[ "def", "has_output", "(", "state", ",", "text", ",", "pattern", "=", "True", ",", "no_output_msg", "=", "None", ")", ":", "if", "not", "no_output_msg", ":", "no_output_msg", "=", "\"You did not output the correct things.\"", "_msg", "=", "state", ".", "build_mes...
41.179487
31.538462
def start_activity(self, appPackage, appActivity, **opts): """Opens an arbitrary activity during a test. If the activity belongs to another application, that application is started and the activity is opened. Android only. - _appPackage_ - The package containing the activity to start. ...
[ "def", "start_activity", "(", "self", ",", "appPackage", ",", "appActivity", ",", "*", "*", "opts", ")", ":", "# Almost the same code as in appium's start activity,", "# just to keep the same keyword names as in open application", "arguments", "=", "{", "'app_wait_package'", ...
41.275
24.2
def boxify(message, border_color=None): """Put a message inside a box. Args: message (unicode): message to decorate. border_color (unicode): name of the color to outline the box with. """ lines = message.split("\n") max_width = max(_visual_width(line) for line in lines) padding...
[ "def", "boxify", "(", "message", ",", "border_color", "=", "None", ")", ":", "lines", "=", "message", ".", "split", "(", "\"\\n\"", ")", "max_width", "=", "max", "(", "_visual_width", "(", "line", ")", "for", "line", "in", "lines", ")", "padding_horizont...
30.133333
23.177778
def _transientSchedule(self, when, now): """ If the service is currently running, schedule a tick to happen no later than C{when}. @param when: The time at which to tick. @type when: L{epsilon.extime.Time} @param now: The current time. @type now: L{epsilon.extim...
[ "def", "_transientSchedule", "(", "self", ",", "when", ",", "now", ")", ":", "if", "not", "self", ".", "running", ":", "return", "if", "self", ".", "timer", "is", "not", "None", ":", "if", "self", ".", "timer", ".", "getTime", "(", ")", "<", "when"...
38.807692
17.653846
def f_remove(self, recursive=True, predicate=None): """Recursively removes all children of the trajectory :param recursive: Only here for consistency with signature of parent method. Cannot be set to `False` because the trajectory root node cannot be removed. :param pr...
[ "def", "f_remove", "(", "self", ",", "recursive", "=", "True", ",", "predicate", "=", "None", ")", ":", "if", "not", "recursive", ":", "raise", "ValueError", "(", "'Nice try ;-)'", ")", "for", "child", "in", "list", "(", "self", ".", "_children", ".", ...
37.789474
28.210526
def to_dict(self): """ Convert current Task into a dictionary :return: python dictionary """ task_desc_as_dict = { 'uid': self._uid, 'name': self._name, 'state': self._state, 'state_history': self._state_history, 'pre...
[ "def", "to_dict", "(", "self", ")", ":", "task_desc_as_dict", "=", "{", "'uid'", ":", "self", ".", "_uid", ",", "'name'", ":", "self", ".", "_name", ",", "'state'", ":", "self", ".", "_state", ",", "'state_history'", ":", "self", ".", "_state_history", ...
31.146341
14.902439
def get_write_fields(self): """ Get the list of fields used to write the header, separating record and signal specification fields. Returns the default required fields, the user defined fields, and their dependencies. Does NOT include `d_signal` or `e_d_signal`. ...
[ "def", "get_write_fields", "(", "self", ")", ":", "# Record specification fields", "rec_write_fields", "=", "self", ".", "get_write_subset", "(", "'record'", ")", "# Add comments if any", "if", "self", ".", "comments", "!=", "None", ":", "rec_write_fields", ".", "ap...
31.081081
19.837838
def format_nd_slice(item, ndim): """Preformat a getitem argument as an N-tuple """ if not isinstance(item, tuple): item = (item,) return item[:ndim] + (None,) * (ndim - len(item))
[ "def", "format_nd_slice", "(", "item", ",", "ndim", ")", ":", "if", "not", "isinstance", "(", "item", ",", "tuple", ")", ":", "item", "=", "(", "item", ",", ")", "return", "item", "[", ":", "ndim", "]", "+", "(", "None", ",", ")", "*", "(", "nd...
33
7.333333
def extend(self, table, keys=None): """Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the row index is used. ...
[ "def", "extend", "(", "self", ",", "table", ",", "keys", "=", "None", ")", ":", "if", "keys", ":", "for", "k", "in", "keys", ":", "if", "k", "not", "in", "self", ".", "_Header", "(", ")", ":", "raise", "IndexError", "(", "\"Unknown key: '%s'\"", ",...
28.386364
17.522727
def charindex(self, line, char, context): """Determines the absolute character index for the specified line and char using the *buffer's* code string.""" #Make sure that we have chars and lines to work from if len(context.bufferstr) > 0 and len(self._chars) == 0: #Add one for...
[ "def", "charindex", "(", "self", ",", "line", ",", "char", ",", "context", ")", ":", "#Make sure that we have chars and lines to work from", "if", "len", "(", "context", ".", "bufferstr", ")", ">", "0", "and", "len", "(", "self", ".", "_chars", ")", "==", ...
47.157895
15.473684
def L_diffuser_outer(sed_inputs=sed_dict): """Return the outer length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns -------...
[ "def", "L_diffuser_outer", "(", "sed_inputs", "=", "sed_dict", ")", ":", "return", "(", "(", "sed_inputs", "[", "'manifold'", "]", "[", "'diffuser'", "]", "[", "'A'", "]", "/", "(", "2", "*", "sed_inputs", "[", "'manifold'", "]", "[", "'diffuser'", "]", ...
34.421053
20.894737
def toints(self): """\ Returns an iterable of integers interpreting the content of `seq` as sequence of binary numbers of length 8. """ def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x')...
[ "def", "toints", "(", "self", ")", ":", "def", "grouper", "(", "iterable", ",", "n", ",", "fillvalue", "=", "None", ")", ":", "\"Collect data into fixed-length chunks or blocks\"", "# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx", "return", "zip_longest", "(", "*", "[",...
49.1
19.4
def plot_poles_colorbar(map_axis, plons, plats, A95s, colorvalues, vmin, vmax, colormap='viridis', edgecolor='k', marker='o', markersize='20', alpha=1.0, colorbar=True, colorbar_label='pole age (Ma)'): """ This function plots multiple paleomagnetic pole and A95 er...
[ "def", "plot_poles_colorbar", "(", "map_axis", ",", "plons", ",", "plats", ",", "A95s", ",", "colorvalues", ",", "vmin", ",", "vmax", ",", "colormap", "=", "'viridis'", ",", "edgecolor", "=", "'k'", ",", "marker", "=", "'o'", ",", "markersize", "=", "'20...
45.642857
29.142857
def __get_segment_types(self, element): """ given a <segment> or <group> element, returns its segment type and the segment type of its parent (i.e. its dominating node) Parameters ---------- element : ??? etree Element Returns ------- segment_typ...
[ "def", "__get_segment_types", "(", "self", ",", "element", ")", ":", "if", "not", "'parent'", "in", "element", ".", "attrib", ":", "if", "element", ".", "tag", "==", "'segment'", ":", "segment_type", "=", "'isolated'", "parent_segment_type", "=", "None", "el...
41.58
16.5
def serve(self, port=62000): """ Start LanguageBoard web application Parameters ---------- port: int port to serve web application """ from http.server import HTTPServer, CGIHTTPRequestHandler os.chdir(self.log_folder) httpd = HTTPServer((''...
[ "def", "serve", "(", "self", ",", "port", "=", "62000", ")", ":", "from", "http", ".", "server", "import", "HTTPServer", ",", "CGIHTTPRequestHandler", "os", ".", "chdir", "(", "self", ".", "log_folder", ")", "httpd", "=", "HTTPServer", "(", "(", "''", ...
31.1875
19.6875
def delete(self, directory_updated=False): # pylint: disable=W0212 """ Delete this configuration :param directory_updated: If True, tell ConfigurationAdmin to not recall the directory of this deletion (internal use only...
[ "def", "delete", "(", "self", ",", "directory_updated", "=", "False", ")", ":", "# pylint: disable=W0212", "with", "self", ".", "__lock", ":", "if", "self", ".", "__deleted", ":", "# Nothing to do", "return", "# Update status", "self", ".", "__deleted", "=", "...
31.066667
18.2
def select(self, txn, from_key=None, to_key=None, return_keys=True, return_values=True, reverse=False, limit=None): """ Select all records (key-value pairs) in table, optionally within a given key range. :param txn: The transaction in which to run. :type txn: :class:`zlmdb.Transaction` ...
[ "def", "select", "(", "self", ",", "txn", ",", "from_key", "=", "None", ",", "to_key", "=", "None", ",", "return_keys", "=", "True", ",", "return_values", "=", "True", ",", "reverse", "=", "False", ",", "limit", "=", "None", ")", ":", "assert", "type...
39.675676
22.972973
def deprecated_func(func): """Deprecates a function, printing a warning on the first usage.""" # We use a mutable container here to work around Py2's lack of # the `nonlocal` keyword. first_usage = [True] @functools.wraps(func) def wrapper(*args, **kwargs): if first_usage[0]: ...
[ "def", "deprecated_func", "(", "func", ")", ":", "# We use a mutable container here to work around Py2's lack of", "# the `nonlocal` keyword.", "first_usage", "=", "[", "True", "]", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ...
29.722222
18.444444
def show_grid(data_frame, show_toolbar=None, precision=None, grid_options=None, column_options=None, column_definitions=None, row_edit_callback=None): """ Renders a DataFrame or Series as an interactive qgrid, represented by ...
[ "def", "show_grid", "(", "data_frame", ",", "show_toolbar", "=", "None", ",", "precision", "=", "None", ",", "grid_options", "=", "None", ",", "column_options", "=", "None", ",", "column_definitions", "=", "None", ",", "row_edit_callback", "=", "None", ")", ...
40.989474
21.284211
def get_cookie_header(queue_item): """Convert a requests cookie jar to a HTTP request cookie header value. Args: queue_item (:class:`nyawc.QueueItem`): The parent queue item of the new request. Returns: str: The HTTP cookie header value. """ header = [...
[ "def", "get_cookie_header", "(", "queue_item", ")", ":", "header", "=", "[", "]", "path", "=", "URLHelper", ".", "get_path", "(", "queue_item", ".", "request", ".", "url", ")", "for", "cookie", "in", "queue_item", ".", "request", ".", "cookies", ":", "ro...
31.5
23.7
def on_commit(self, changes): """Method that gets called when a model is changed. This serves to do the actual index writing. """ if _get_config(self)['enable_indexing'] is False: return None for wh in self.whoosheers: if not wh.auto_update: ...
[ "def", "on_commit", "(", "self", ",", "changes", ")", ":", "if", "_get_config", "(", "self", ")", "[", "'enable_indexing'", "]", "is", "False", ":", "return", "None", "for", "wh", "in", "self", ".", "whoosheers", ":", "if", "not", "wh", ".", "auto_upda...
42.409091
16.590909
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
[ "def", "data_url", "(", "contents", ",", "domain", "=", "DEFAULT_DOMAIN", ")", ":", "url", "=", "(", "domain", "+", "'#data=data:application/json,'", "+", "urllib", ".", "parse", ".", "quote", "(", "contents", ")", ")", "return", "url" ]
25.923077
16.538462
def gen_bag_feats(self, e_set): """ Generates bag of words features from an input essay set and trained FeatureExtractor Generally called by gen_feats Returns an array of features e_set - EssaySet object """ if(hasattr(self, '_stem_dict')): sfeats = se...
[ "def", "gen_bag_feats", "(", "self", ",", "e_set", ")", ":", "if", "(", "hasattr", "(", "self", ",", "'_stem_dict'", ")", ")", ":", "sfeats", "=", "self", ".", "_stem_dict", ".", "transform", "(", "e_set", ".", "_clean_stem_text", ")", "nfeats", "=", "...
47.857143
20.714286
def guess_tags(filename): """ Function to get potential tags for files using the file names. :param filename: This field is the name of file. """ tags = [] stripped_filename = strip_zip_suffix(filename) if stripped_filename.endswith('.vcf'): tags.append('vcf') if stripped_filena...
[ "def", "guess_tags", "(", "filename", ")", ":", "tags", "=", "[", "]", "stripped_filename", "=", "strip_zip_suffix", "(", "filename", ")", "if", "stripped_filename", ".", "endswith", "(", "'.vcf'", ")", ":", "tags", ".", "append", "(", "'vcf'", ")", "if", ...
29.4
13.533333
async def SetVolumeAttachmentInfo(self, volume_attachments): ''' volume_attachments : typing.Sequence[~VolumeAttachment] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='StorageProvisioner', ...
[ "async", "def", "SetVolumeAttachmentInfo", "(", "self", ",", "volume_attachments", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'StorageProvisioner'", ",", "request", "=", "'SetVolumeAttachmentInf...
37.642857
14.785714
def _print_unique_links_with_status_codes(page_url, soup): """ Finds all unique links in the html of the page source and then prints out those links with their status codes. Format: ["link" -> "status_code"] (per line) Page links include those obtained from: "a"->"href", "img"->"...
[ "def", "_print_unique_links_with_status_codes", "(", "page_url", ",", "soup", ")", ":", "links", "=", "_get_unique_links", "(", "page_url", ",", "soup", ")", "for", "link", "in", "links", ":", "status_code", "=", "_get_link_status_code", "(", "link", ")", "print...
47.272727
11.636364
def check_roles(self, account, aws_policies, aws_roles): """Iterate through the roles of a specific account and create or update the roles if they're missing or does not match the roles from Git. Args: account (:obj:`Account`): The account to check roles on aws_policies ...
[ "def", "check_roles", "(", "self", ",", "account", ",", "aws_policies", ",", "aws_roles", ")", ":", "self", ".", "log", ".", "debug", "(", "'Checking roles for {}'", ".", "format", "(", "account", ".", "account_name", ")", ")", "max_session_duration", "=", "...
47.435115
22.839695
def badge_form(model): '''A form factory for a given model badges''' class BadgeForm(ModelForm): model_class = Badge kind = fields.RadioField( _('Kind'), [validators.DataRequired()], choices=model.__badges__.items(), description=_('Kind of badge (certified, e...
[ "def", "badge_form", "(", "model", ")", ":", "class", "BadgeForm", "(", "ModelForm", ")", ":", "model_class", "=", "Badge", "kind", "=", "fields", ".", "RadioField", "(", "_", "(", "'Kind'", ")", ",", "[", "validators", ".", "DataRequired", "(", ")", "...
30.727273
17.454545
def BVV(value, size=None, **kwargs): """ Creates a bit-vector value (i.e., a concrete value). :param value: The value. Either an integer or a string. If it's a string, it will be interpreted as the bytes of a big-endian constant. :param size: The size (in bits) of the bit-vecto...
[ "def", "BVV", "(", "value", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "value", ")", "in", "(", "bytes", ",", "str", ")", ":", "if", "type", "(", "value", ")", "is", "str", ":", "l", ".", "warning", "(", ...
38.3
24.8
def export(self, template_file_name, output_file_name, sort="public", data=None, limit=0): """Export ranking to a file. Args: template_file_name (str): where is the template (moustache template) output_file_name (str): where create the file with th...
[ "def", "export", "(", "self", ",", "template_file_name", ",", "output_file_name", ",", "sort", "=", "\"public\"", ",", "data", "=", "None", ",", "limit", "=", "0", ")", ":", "exportedData", "=", "{", "}", "exportedUsers", "=", "self", ".", "getSortedUsers"...
32.59375
17.875
def request_system_disarm(blink, network): """ Disarm system. :param blink: Blink instance. :param network: Sync module network id. """ url = "{}/network/{}/disarm".format(blink.urls.base_url, network) return http_post(blink, url)
[ "def", "request_system_disarm", "(", "blink", ",", "network", ")", ":", "url", "=", "\"{}/network/{}/disarm\"", ".", "format", "(", "blink", ".", "urls", ".", "base_url", ",", "network", ")", "return", "http_post", "(", "blink", ",", "url", ")" ]
27.888889
12.333333
def check_for_required_columns(problems, table, df): """ Check that the given ProtoFeed table has the required columns. Parameters ---------- problems : list A four-tuple containing 1. A problem type (string) equal to ``'error'`` or ``'warning'``; ``'error'`` means the P...
[ "def", "check_for_required_columns", "(", "problems", ",", "table", ",", "df", ")", ":", "r", "=", "cs", ".", "PROTOFEED_REF", "req_columns", "=", "r", ".", "loc", "[", "(", "r", "[", "'table'", "]", "==", "table", ")", "&", "r", "[", "'column_required...
31.139535
22.395349
def mount_share(name=None, remote_share=None, remote_file=None, mount_type="nfs", username=None, password=None): ''' Mounts a remote file through a remote share. Currently, this feature is supported in version 1.5 or greater. Th...
[ "def", "mount_share", "(", "name", "=", "None", ",", "remote_share", "=", "None", ",", "remote_file", "=", "None", ",", "mount_type", "=", "\"nfs\"", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "not", "name", ":", "raise...
39.955224
32.313433
def filter_by_milestone(self, filtered_issues, tag_name, all_issues): """ :param list(dict) filtered_issues: Filtered issues. :param str tag_name: Name (title) of tag. :param list(dict) all_issues: All issues. :rtype: list(dict) :return: Filtered issues according mileston...
[ "def", "filter_by_milestone", "(", "self", ",", "filtered_issues", ",", "tag_name", ",", "all_issues", ")", ":", "filtered_issues", "=", "self", ".", "remove_issues_in_milestones", "(", "filtered_issues", ")", "if", "tag_name", ":", "# add missed issues (according miles...
41.866667
16.933333
def register_app(app_name, app_setting, web_application_setting, mainfile, package_space): """insert current project root path into sys path """ from turbo import log app_config.app_name = app_name app_config.app_setting = app_setting app_config.project_name = os.path.basename(get_base_dir(mainf...
[ "def", "register_app", "(", "app_name", ",", "app_setting", ",", "web_application_setting", ",", "mainfile", ",", "package_space", ")", ":", "from", "turbo", "import", "log", "app_config", ".", "app_name", "=", "app_name", "app_config", ".", "app_setting", "=", ...
47.583333
14.916667
def event(self, event): """ Qt override. This is needed to be able to intercept the Tab key press event. """ if event.type() == QEvent.KeyPress: if (event.key() == Qt.Key_Tab or event.key() == Qt.Key_Space): text = self.text() ...
[ "def", "event", "(", "self", ",", "event", ")", ":", "if", "event", ".", "type", "(", ")", "==", "QEvent", ".", "KeyPress", ":", "if", "(", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Tab", "or", "event", ".", "key", "(", ")", "==", ...
40.52381
14.142857
def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ if order == MSBFIRST: self.lsbfirst = 0 elif order == LSBFIRST: ...
[ "def", "set_bit_order", "(", "self", ",", "order", ")", ":", "if", "order", "==", "MSBFIRST", ":", "self", ".", "lsbfirst", "=", "0", "elif", "order", "==", "LSBFIRST", ":", "self", ".", "lsbfirst", "=", "1", "else", ":", "raise", "ValueError", "(", ...
37.727273
12.818182
def defaults(d1, d2): """ Update a copy of d1 with the contents of d2 that are not in d1. d1 and d2 are dictionary like objects. Parameters ---------- d1 : dict | dataframe dict with the preferred values d2 : dict | dataframe dict with the default values Returns ---...
[ "def", "defaults", "(", "d1", ",", "d2", ")", ":", "d1", "=", "d1", ".", "copy", "(", ")", "tolist", "=", "isinstance", "(", "d2", ",", "pd", ".", "DataFrame", ")", "keys", "=", "(", "k", "for", "k", "in", "d2", "if", "k", "not", "in", "d1", ...
22.777778
17.814815
def diag_post_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") diag = ET.SubElement(config, "diag", xmlns="urn:brocade.com:mgmt:brocade-diagnostics") post = ET.SubElement(diag, "post") enable = ET.SubElement(post, "enable") callbac...
[ "def", "diag_post_enable", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "diag", "=", "ET", ".", "SubElement", "(", "config", ",", "\"diag\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade...
38.5
13.4
def _convert_type(data_type): # @NoSelf ''' Converts CDF data types into python types ''' if data_type in (1, 41): dt_string = 'b' elif data_type == 2: dt_string = 'h' elif data_type == 4: dt_string = 'i' elif data_type in (8, ...
[ "def", "_convert_type", "(", "data_type", ")", ":", "# @NoSelf", "if", "data_type", "in", "(", "1", ",", "41", ")", ":", "dt_string", "=", "'b'", "elif", "data_type", "==", "2", ":", "dt_string", "=", "'h'", "elif", "data_type", "==", "4", ":", "dt_str...
27.266667
13.333333
def example_exc_handler(tries_remaining, exception, delay): """Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised. """ print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s second...
[ "def", "example_exc_handler", "(", "tries_remaining", ",", "exception", ",", "delay", ")", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Caught '%s', %d tries remaining, sleeping for %s seconds\"", "%", "(", "exception", ",", "tries_remaining", ",", "delay", ")" ]
45.25
16.75
def patch(self, endpoint, json=None, params=None, **kwargs): """ PATCH to DHIS2 :param endpoint: DHIS2 API endpoint :param json: HTTP payload :param params: HTTP parameters (dict) :return: requests.Response object """ json = kwargs['data'] if 'data' in kwa...
[ "def", "patch", "(", "self", ",", "endpoint", ",", "json", "=", "None", ",", "params", "=", "None", ",", "*", "*", "kwargs", ")", ":", "json", "=", "kwargs", "[", "'data'", "]", "if", "'data'", "in", "kwargs", "else", "json", "return", "self", ".",...
40.3
11.1
def map_over_glob(fn, path, pattern): """map a function over a glob pattern, relative to a directory""" return [fn(x) for x in glob.glob(os.path.join(path, pattern))]
[ "def", "map_over_glob", "(", "fn", ",", "path", ",", "pattern", ")", ":", "return", "[", "fn", "(", "x", ")", "for", "x", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "path", ",", "pattern", ")", ")", "]" ]
57.333333
9.666667
def get_value_from_content(key): """Get a value from the path specifed. :param key: Array that defines the path of the value inside the message. """ def value_from_content_function(service, message): """Actual implementation of get_value_from_content function. :param service: SelenolSe...
[ "def", "get_value_from_content", "(", "key", ")", ":", "def", "value_from_content_function", "(", "service", ",", "message", ")", ":", "\"\"\"Actual implementation of get_value_from_content function.\n\n :param service: SelenolService object.\n :param message: SelenolMessag...
36
12.307692
def is_number(obj): """Check if obj is number.""" return isinstance(obj, (int, float, np.int_, np.float_))
[ "def", "is_number", "(", "obj", ")", ":", "return", "isinstance", "(", "obj", ",", "(", "int", ",", "float", ",", "np", ".", "int_", ",", "np", ".", "float_", ")", ")" ]
37.333333
13.666667
def Bernstein(n, k): """Bernstein polynomial. """ coeff = binom(n, k) def _bpoly(x): return coeff * x ** k * (1 - x) ** (n - k) return _bpoly
[ "def", "Bernstein", "(", "n", ",", "k", ")", ":", "coeff", "=", "binom", "(", "n", ",", "k", ")", "def", "_bpoly", "(", "x", ")", ":", "return", "coeff", "*", "x", "**", "k", "*", "(", "1", "-", "x", ")", "**", "(", "n", "-", "k", ")", ...
16.3
21.2
def timeSeries(self, tag = None, outputFile = None, giveYears = True, greatestFirst = True, limitTo = False, pandasMode = True): """Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list c...
[ "def", "timeSeries", "(", "self", ",", "tag", "=", "None", ",", "outputFile", "=", "None", ",", "giveYears", "=", "True", ",", "greatestFirst", "=", "True", ",", "limitTo", "=", "False", ",", "pandasMode", "=", "True", ")", ":", "seriesDict", "=", "{",...
40.409639
23.951807
def find_attacker_slider(dest_list, occ_bb, piece_bb, target_bb, pos, domain): """ Find a slider attacker Parameters ---------- dest_list : list To store the results. occ_bb : int, bitboard Occupancy bitboard. piece_bb : int, bitboard Bitboar...
[ "def", "find_attacker_slider", "(", "dest_list", ",", "occ_bb", ",", "piece_bb", ",", "target_bb", ",", "pos", ",", "domain", ")", ":", "pos_map", ",", "domain_trans", ",", "pos_inv_map", "=", "domain", "r", "=", "reach", "[", "pos_map", "(", "pos", ")", ...
34.029412
17.764706
def dump_all(data_list, stream=None, **kwargs): """ Serialize YAMLDict into a YAML stream. If stream is None, return the produced string instead. """ return yaml.dump_all( data_list, stream=stream, Dumper=YAMLDictDumper, **kwargs )
[ "def", "dump_all", "(", "data_list", ",", "stream", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "yaml", ".", "dump_all", "(", "data_list", ",", "stream", "=", "stream", ",", "Dumper", "=", "YAMLDictDumper", ",", "*", "*", "kwargs", ")" ]
25.181818
13.727273
def exclude_file(sp, f): """ Exclude discovered files if they match the special exclude_ search pattern keys """ # Make everything a list if it isn't already for k in sp: if k in ['exclude_fn', 'exclude_fn_re' 'exclude_contents', 'exclude_contents_re']: if not isinstance(sp[k...
[ "def", "exclude_file", "(", "sp", ",", "f", ")", ":", "# Make everything a list if it isn't already", "for", "k", "in", "sp", ":", "if", "k", "in", "[", "'exclude_fn'", ",", "'exclude_fn_re'", "'exclude_contents'", ",", "'exclude_contents_re'", "]", ":", "if", "...
37.410256
14.589744
def make_sentences(self, stream_item): 'assemble Sentence and Token objects' self.make_label_index(stream_item) sentences = [] token_num = 0 new_mention_id = 0 for sent_start, sent_end, sent_str in self._sentences( stream_item.body.clean_visible): ...
[ "def", "make_sentences", "(", "self", ",", "stream_item", ")", ":", "self", ".", "make_label_index", "(", "stream_item", ")", "sentences", "=", "[", "]", "token_num", "=", "0", "new_mention_id", "=", "0", "for", "sent_start", ",", "sent_end", ",", "sent_str"...
41.8
16.16
def check_valid_temperature(var, units): r"""Check that variable is air temperature.""" check_valid(var, 'standard_name', 'air_temperature') check_valid(var, 'units', units) assert_daily(var)
[ "def", "check_valid_temperature", "(", "var", ",", "units", ")", ":", "check_valid", "(", "var", ",", "'standard_name'", ",", "'air_temperature'", ")", "check_valid", "(", "var", ",", "'units'", ",", "units", ")", "assert_daily", "(", "var", ")" ]
33.833333
13.166667
def check_version(version, fallback="master"): """ Check that a version string is PEP440 compliant and there are no unreleased changes. For example, ``version = "0.1"`` will be returned as is but ``version = "0.1+10.8dl8dh9"`` will return the fallback. This is the convention used by `versioneer <ht...
[ "def", "check_version", "(", "version", ",", "fallback", "=", "\"master\"", ")", ":", "parse", "=", "Version", "(", "version", ")", "if", "parse", ".", "local", "is", "not", "None", ":", "return", "fallback", "return", "version" ]
26.522727
24.886364
def plot_sn_discovery_ratio_map(log, snSurveyDiscoveryTimes, redshifts, peakAppMagList, snCampaignLengthList, extraSurveyConstraints, ...
[ "def", "plot_sn_discovery_ratio_map", "(", "log", ",", "snSurveyDiscoveryTimes", ",", "redshifts", ",", "peakAppMagList", ",", "snCampaignLengthList", ",", "extraSurveyConstraints", ",", "pathToOutputPlotFolder", ")", ":", "################ > IMPORTS ################", "## STAN...
38.029412
18.441176
def handle_joined(self, connection, event): """ Store join times for current nicknames when we first join. """ nicknames = [s.lstrip("@+") for s in event.arguments()[-1].split()] for nickname in nicknames: self.joined[nickname] = datetime.now()
[ "def", "handle_joined", "(", "self", ",", "connection", ",", "event", ")", ":", "nicknames", "=", "[", "s", ".", "lstrip", "(", "\"@+\"", ")", "for", "s", "in", "event", ".", "arguments", "(", ")", "[", "-", "1", "]", ".", "split", "(", ")", "]",...
41.428571
11.428571
def dim_iter(self, *dim_strides, **kwargs): """ Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning a tuple of dictionaries describing a dimension update. For example, the following call effectively produces 2 loops over the 'ntime...
[ "def", "dim_iter", "(", "self", ",", "*", "dim_strides", ",", "*", "*", "kwargs", ")", ":", "# Extract dimension names", "dims", "=", "[", "ds", "[", "0", "]", "for", "ds", "in", "dim_strides", "]", "def", "_create_dim_dicts", "(", "*", "args", ")", ":...
31.45
18.95
def _adjusted_mutual_info_score(reference_indices, estimated_indices): """Compute the mutual information between two sequence labelings, adjusted for chance. Parameters ---------- reference_indices : np.ndarray Array of reference indices estimated_indices : np.ndarray Array of ...
[ "def", "_adjusted_mutual_info_score", "(", "reference_indices", ",", "estimated_indices", ")", ":", "n_samples", "=", "len", "(", "reference_indices", ")", "ref_classes", "=", "np", ".", "unique", "(", "reference_indices", ")", "est_classes", "=", "np", ".", "uniq...
42.289157
17.963855
def ji_windows(self, ij_win): # what can be given to ij_win NOT intuitive/right name by now!!! """For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions. Arguments: ij_win {int} -- The index specifying the window for which to return the resoluti...
[ "def", "ji_windows", "(", "self", ",", "ij_win", ")", ":", "# what can be given to ij_win NOT intuitive/right name by now!!!", "ji_windows", "=", "{", "}", "transform_src", "=", "self", ".", "_layer_meta", "[", "self", ".", "_res_indices", "[", "self", ".", "_window...
59.714286
30.571429
def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. ...
[ "def", "integer_key_convert", "(", "dictin", ",", "dropfailedkeys", "=", "False", ")", ":", "# type: (DictUpperBound, bool) -> Dict", "return", "key_value_convert", "(", "dictin", ",", "keyfn", "=", "int", ",", "dropfailedkeys", "=", "dropfailedkeys", ")" ]
35.692308
25.384615
def endpoint_delete(endpoint_id): """ Executor for `globus endpoint delete` """ client = get_client() res = client.delete_endpoint(endpoint_id) formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message")
[ "def", "endpoint_delete", "(", "endpoint_id", ")", ":", "client", "=", "get_client", "(", ")", "res", "=", "client", ".", "delete_endpoint", "(", "endpoint_id", ")", "formatted_print", "(", "res", ",", "text_format", "=", "FORMAT_TEXT_RAW", ",", "response_key", ...
33.571429
9.285714
def unhumanize_delay(delaystr): ''' Accept a string representing link propagation delay (e.g., '100 milliseconds' or '100 msec' or 100 millisec') and return a floating point number representing the delay in seconds. Recognizes: - us, usec, micros* all as microseconds - ms, msec, mil...
[ "def", "unhumanize_delay", "(", "delaystr", ")", ":", "if", "isinstance", "(", "delaystr", ",", "float", ")", ":", "return", "delaystr", "mobj", "=", "re", ".", "match", "(", "'^\\s*([\\d\\.]+)\\s*(\\w*)'", ",", "delaystr", ")", "if", "not", "mobj", ":", "...
30.935484
20.225806
def _set_overlay_service_policy(self, v, load=False): """ Setter method for overlay_service_policy, mapped from YANG variable /overlay_transit/overlay_service_policy (list) If this variable is read-only (config: false) in the source YANG file, then _set_overlay_service_policy is considered as a private ...
[ "def", "_set_overlay_service_policy", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
142.863636
69.181818
def poll_parser(poll): """ Parses a poll object """ if __is_deleted(poll): return deleted_parser(poll) if poll['type'] not in poll_types: raise Exception('Not a poll type') return Poll( poll['id'], poll['by'], __check_key('kids', poll), # poll and pollopt...
[ "def", "poll_parser", "(", "poll", ")", ":", "if", "__is_deleted", "(", "poll", ")", ":", "return", "deleted_parser", "(", "poll", ")", "if", "poll", "[", "'type'", "]", "not", "in", "poll_types", ":", "raise", "Exception", "(", "'Not a poll type'", ")", ...
27.263158
16.947368
def validate_instance_username(self, username): ''' Validate instance username ''' # 1-16 alphanumeric characters - first character must be a letter - # cannot be a reserved MySQL word if re.match('[\w-]+$', username) is not None: if len(username) <= 16 and len(username) >= 1...
[ "def", "validate_instance_username", "(", "self", ",", "username", ")", ":", "# 1-16 alphanumeric characters - first character must be a letter -", "# cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "username", ")", "is", "not", "None", ...
53.272727
14.181818
def submit_statement_request(meth, end_point, query_str='', data=None, tries=2, **params): """Even lower level function to make the request.""" full_end_point = 'statements/' + end_point.lstrip('/') return make_db_rest_request(meth, full_end_point, query_str, data, params, tries...
[ "def", "submit_statement_request", "(", "meth", ",", "end_point", ",", "query_str", "=", "''", ",", "data", "=", "None", ",", "tries", "=", "2", ",", "*", "*", "params", ")", ":", "full_end_point", "=", "'statements/'", "+", "end_point", ".", "lstrip", "...
63.4
20.2
def main(): """ Change labels of the "minikube" node: - Add label "foo" with value "bar". This will overwrite the "foo" label if it already exists. - Remove the label "baz" from the node. """ config.load_kube_config() api_instance = client.CoreV1Api() body = { "metada...
[ "def", "main", "(", ")", ":", "config", ".", "load_kube_config", "(", ")", "api_instance", "=", "client", ".", "CoreV1Api", "(", ")", "body", "=", "{", "\"metadata\"", ":", "{", "\"labels\"", ":", "{", "\"foo\"", ":", "\"bar\"", ",", "\"baz\"", ":", "N...
21.347826
21.086957
def list_tar (archive, compression, cmd, verbosity, interactive): """List a TAR archive.""" cmdlist = [cmd, '-n'] add_star_opts(cmdlist, compression, verbosity) cmdlist.append("file=%s" % archive) return cmdlist
[ "def", "list_tar", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ")", ":", "cmdlist", "=", "[", "cmd", ",", "'-n'", "]", "add_star_opts", "(", "cmdlist", ",", "compression", ",", "verbosity", ")", "cmdlist", ".", "...
37.666667
12.166667
def interpolate(self, gmvs): """ :param gmvs: array of intensity measure levels :returns: (interpolated loss ratios, interpolated covs, indices > min) """ # gmvs are clipped to max(iml) gmvs_curve = numpy.piecewise( gmvs, [gmvs > self.iml...
[ "def", "interpolate", "(", "self", ",", "gmvs", ")", ":", "# gmvs are clipped to max(iml)", "gmvs_curve", "=", "numpy", ".", "piecewise", "(", "gmvs", ",", "[", "gmvs", ">", "self", ".", "imls", "[", "-", "1", "]", "]", ",", "[", "self", ".", "imls", ...
40.538462
14.692308
def run_python_module(modulename, args): """Run a python module, as though with ``python -m name args...``. `modulename` is the name of the module, possibly a dot-separated name. `args` is the argument array to present as sys.argv, including the first element naming the module being executed. """ ...
[ "def", "run_python_module", "(", "modulename", ",", "args", ")", ":", "openfile", "=", "None", "glo", ",", "loc", "=", "globals", "(", ")", ",", "locals", "(", ")", "try", ":", "try", ":", "# Search for the module - inside its parent package, if any - using", "#...
40.8125
19.916667
def gcj02tobd09(lng, lat): """ 火星坐标系(GCJ-02)转百度坐标系(BD-09) 谷歌、高德——>百度 :param lng:火星坐标经度 :param lat:火星坐标纬度 :return: """ z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi) theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi) bd_lng = z * math.cos(theta) ...
[ "def", "gcj02tobd09", "(", "lng", ",", "lat", ")", ":", "z", "=", "math", ".", "sqrt", "(", "lng", "*", "lng", "+", "lat", "*", "lat", ")", "+", "0.00002", "*", "math", ".", "sin", "(", "lat", "*", "x_pi", ")", "theta", "=", "math", ".", "ata...
29.615385
14.538462
def diff_config(base, target): '''Find the differences between two configurations. This finds a delta configuration from `base` to `target`, such that calling :func:`overlay_config` with `base` and the result of this function yields `target`. This works as follows: * If both are identical (of any...
[ "def", "diff_config", "(", "base", ",", "target", ")", ":", "if", "not", "isinstance", "(", "base", ",", "collections", ".", "Mapping", ")", ":", "if", "base", "==", "target", ":", "return", "{", "}", "return", "target", "if", "not", "isinstance", "(",...
33
19.136364
def table(name=None, mode='create', use_cache=True, priority='interactive', allow_large_results=False): """ Construct a query output object where the result is a table Args: name: the result table name as a string or TableName; if None (the default), then a temporary table will be u...
[ "def", "table", "(", "name", "=", "None", ",", "mode", "=", "'create'", ",", "use_cache", "=", "True", ",", "priority", "=", "'interactive'", ",", "allow_large_results", "=", "False", ")", ":", "output", "=", "QueryOutput", "(", ")", "output", ".", "_out...
50.4
23.44
def find_file_format(file_name): """ Returns a tuple with the file path and format found, or (None, None) """ for file_format in Format.ALLOWED: file_path = '.'.join((file_name, file_format)) if os.path.exists(file_path): return file_path, file_for...
[ "def", "find_file_format", "(", "file_name", ")", ":", "for", "file_format", "in", "Format", ".", "ALLOWED", ":", "file_path", "=", "'.'", ".", "join", "(", "(", "file_name", ",", "file_format", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "f...
37.888889
9.444444
def create_nio(self, node, nio_settings): """ Creates a new NIO. :param node: Dynamips node instance :param nio_settings: information to create the NIO :returns: a NIO object """ nio = None if nio_settings["type"] == "nio_udp": lport = nio_s...
[ "def", "create_nio", "(", "self", ",", "node", ",", "nio_settings", ")", ":", "nio", "=", "None", "if", "nio_settings", "[", "\"type\"", "]", "==", "\"nio_udp\"", ":", "lport", "=", "nio_settings", "[", "\"lport\"", "]", "rhost", "=", "nio_settings", "[", ...
50.294118
21.205882
def _visit_functiondef(self, cls, node, parent): """visit an FunctionDef node to become astroid""" self._global_names.append({}) node, doc = self._get_doc(node) newnode = cls(node.name, doc, node.lineno, node.col_offset, parent) if node.decorator_list: decorators = se...
[ "def", "_visit_functiondef", "(", "self", ",", "cls", ",", "node", ",", "parent", ")", ":", "self", ".", "_global_names", ".", "append", "(", "{", "}", ")", "node", ",", "doc", "=", "self", ".", "_get_doc", "(", "node", ")", "newnode", "=", "cls", ...
40.142857
16.321429
def save(yaml_dict, filepath): ''' Save YAML settings to the specified file path. ''' yamldict.dump(yaml_dict, open(filepath, 'w'), default_flow_style=False)
[ "def", "save", "(", "yaml_dict", ",", "filepath", ")", ":", "yamldict", ".", "dump", "(", "yaml_dict", ",", "open", "(", "filepath", ",", "'w'", ")", ",", "default_flow_style", "=", "False", ")" ]
33.8
24.2
def _get_resource_id_from_stack(cfn_client, stack_name, logical_id): """ Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the resource within the specified stack. Parameters ---------- cfn_client CloudFormation client provided ...
[ "def", "_get_resource_id_from_stack", "(", "cfn_client", ",", "stack_name", ",", "logical_id", ")", ":", "LOG", ".", "debug", "(", "\"Getting resource's PhysicalId from AWS CloudFormation stack. StackName=%s, LogicalId=%s\"", ",", "stack_name", ",", "logical_id", ")", "try", ...
34.857143
28.380952
def dump(self): '''Regurgitate the tables and rows''' for table in self.tables: print("*** %s ***" % table.name) table.dump()
[ "def", "dump", "(", "self", ")", ":", "for", "table", "in", "self", ".", "tables", ":", "print", "(", "\"*** %s ***\"", "%", "table", ".", "name", ")", "table", ".", "dump", "(", ")" ]
32.2
11.4
def setup(self, environ): '''Called once only to setup the WSGI application handler. Check :ref:`lazy wsgi handler <wsgi-lazy-handler>` section for further information. ''' request = wsgi_request(environ) cfg = request.cache.cfg loop = request.cache._loop ...
[ "def", "setup", "(", "self", ",", "environ", ")", ":", "request", "=", "wsgi_request", "(", "environ", ")", "cfg", "=", "request", ".", "cache", ".", "cfg", "loop", "=", "request", ".", "cache", ".", "_loop", "self", ".", "store", "=", "create_store", ...
48
18.526316
def evaluate_at(self, *args, **parameter_specification): # pragma: no cover """ Evaluate the function at the given x(,y,z) for the provided parameters, explicitly provided as part of the parameter_specification keywords. :param *args: :param **parameter_specification: :...
[ "def", "evaluate_at", "(", "self", ",", "*", "args", ",", "*", "*", "parameter_specification", ")", ":", "# pragma: no cover", "# Set the parameters to the provided values", "for", "parameter", "in", "parameter_specification", ":", "self", ".", "_get_child", "(", "par...
33.625
24.375
def image(request, obj_id): """Handles a request based on method and calls the appropriate function""" obj = Image.objects.get(pk=obj_id) if request.method == 'POST': return post(request, obj) elif request.method == 'PUT': getPutData(request) return put(request, obj) elif req...
[ "def", "image", "(", "request", ",", "obj_id", ")", ":", "obj", "=", "Image", ".", "objects", ".", "get", "(", "pk", "=", "obj_id", ")", "if", "request", ".", "method", "==", "'POST'", ":", "return", "post", "(", "request", ",", "obj", ")", "elif",...
36.181818
7.272727
def remove_images(self, images): """ Remove images from the album. :param images: A list of the images we want to remove from the album. Can be Image objects, ids or a combination of the two. Images that you cannot remove (non-existing, not owned by you or not part of ...
[ "def", "remove_images", "(", "self", ",", "images", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/album/{0}/\"", "\"remove_images\"", ".", "format", "(", "self", ".", "_delete_or_id_hash", ")", ")", "# NOTE: Returns True and ever...
49.2
20.933333
def name(self, *args): ''' get/set the descriptive name text of this object. ''' if len(args): self.__name = args[0] else: return self.__name
[ "def", "name", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", ":", "self", ".", "__name", "=", "args", "[", "0", "]", "else", ":", "return", "self", ".", "__name" ]
24.75
19.5
def _createConnection(self, connections): """ Create GSSHAPY Connection Objects Method """ for c in connections: # Create GSSHAPY Connection object connection = Connection(slinkNumber=c['slinkNumber'], upSjuncNumber=c['upSjunc'...
[ "def", "_createConnection", "(", "self", ",", "connections", ")", ":", "for", "c", "in", "connections", ":", "# Create GSSHAPY Connection object", "connection", "=", "Connection", "(", "slinkNumber", "=", "c", "[", "'slinkNumber'", "]", ",", "upSjuncNumber", "=", ...
37.769231
16.230769
def get_vulnerabilities(self, teams=None, applications=None, channel_types=None, start_date=None, end_date=None, generic_severities=None, generic_vulnerabilities=None, number_merged=None, number_vulnerabilities=None, parameter=None, path=None, show_open=None, show...
[ "def", "get_vulnerabilities", "(", "self", ",", "teams", "=", "None", ",", "applications", "=", "None", ",", "channel_types", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "generic_severities", "=", "None", ",", "generic_vul...
53.142857
25.057143
def construct_mapping(self, node, deep=False): ''' Build the mapping for YAML ''' if not isinstance(node, MappingNode): raise ConstructorError( None, None, 'expected a mapping node, but found {0}'.format(node.id), ...
[ "def", "construct_mapping", "(", "self", ",", "node", ",", "deep", "=", "False", ")", ":", "if", "not", "isinstance", "(", "node", ",", "MappingNode", ")", ":", "raise", "ConstructorError", "(", "None", ",", "None", ",", "'expected a mapping node, but found {0...
34.970588
14.205882
def concentric_circles_path(size): """ Yields a set of paths that are concentric circles, moving outwards, about the center of the image. :param size: The (width, height) of the image :return: Yields individual circles, where each circle is a generator that yields pixel coordinates. """ width, ...
[ "def", "concentric_circles_path", "(", "size", ")", ":", "width", ",", "height", "=", "size", "x0", ",", "y0", "=", "width", "//", "2", ",", "height", "//", "2", "max_radius", "=", "int", "(", "sqrt", "(", "2", ")", "*", "max", "(", "height", ",", ...
49.8
21.6
def purge(self): """ Purge cache by removing obsolete items. """ purged_count = 0 if self.__expiration is not None: with self.__connection: if self.__caching_strategy is CachingStrategy.FIFO: # dump least recently added rows for post in (False, True): purged_cou...
[ "def", "purge", "(", "self", ")", ":", "purged_count", "=", "0", "if", "self", ".", "__expiration", "is", "not", "None", ":", "with", "self", ".", "__connection", ":", "if", "self", ".", "__caching_strategy", "is", "CachingStrategy", ".", "FIFO", ":", "#...
58.4
26.15