text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _manual_recv(self, method, body, headers={}): """Used in the tests""" headers.setdefault('sent_at', time.time()) return self.recv(self._make_context(), {'method': method, 'body': body, 'headers': headers})
[ "def", "_manual_recv", "(", "self", ",", "method", ",", "body", ",", "headers", "=", "{", "}", ")", ":", "headers", ".", "setdefault", "(", "'sent_at'", ",", "time", ".", "time", "(", ")", ")", "return", "self", ".", "recv", "(", "self", ".", "_mak...
57.5
0.012876
def play_env_problem_randomly(env_problem, num_steps): """Plays the env problem by randomly sampling actions for `num_steps`.""" # Reset all environments. env_problem.reset() # Play all environments, sampling random actions each time. for _ in range(num_steps): # Sample batc...
[ "def", "play_env_problem_randomly", "(", "env_problem", ",", "num_steps", ")", ":", "# Reset all environments.", "env_problem", ".", "reset", "(", ")", "# Play all environments, sampling random actions each time.", "for", "_", "in", "range", "(", "num_steps", ")", ":", ...
40.352941
0.008547
def init_mv_grid(mv_grid_districts=[3545], filename='ding0_tests_grids_1.pkl'): '''Runs ding0 over the districtis selected in mv_grid_districts It also writes the result in filename. If filename = False, then the network is not saved. Parameters ---------- mv_grid_districts: :any:`list` of :ob...
[ "def", "init_mv_grid", "(", "mv_grid_districts", "=", "[", "3545", "]", ",", "filename", "=", "'ding0_tests_grids_1.pkl'", ")", ":", "print", "(", "'\\n########################################'", ")", "print", "(", "' Running ding0 for district'", ",", "mv_grid_districts...
31.325
0.000774
def login(self, sendspec): """Logs the user in with the passed-in password and command. Tracks the login. If used, used logout to log out again. Assumes you are root when logging in, so no password required. If not, override the default command for multi-level logins. If passwords are required, see setup_prom...
[ "def", "login", "(", "self", ",", "sendspec", ")", ":", "user", "=", "sendspec", ".", "user", "command", "=", "sendspec", ".", "send", "prompt_prefix", "=", "sendspec", ".", "prompt_prefix", "shutit", "=", "self", ".", "shutit", "# We don't get the default exp...
54.541284
0.028085
def set_cookie(self, key, value, secret=None, **kargs): ''' Add a cookie or overwrite an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param key: the name of the cookie. :param value: the value of the cookie. :param secre...
[ "def", "set_cookie", "(", "self", ",", "key", ",", "value", ",", "secret", "=", "None", ",", "*", "*", "kargs", ")", ":", "if", "secret", ":", "value", "=", "touni", "(", "cookie_encode", "(", "(", "key", ",", "value", ")", ",", "secret", ")", ")...
50.424242
0.001179
def calculate_power_output(weather, my_turbine, e126, dummy_turbine): r""" Calculates power output of wind turbines using the :class:`~.modelchain.ModelChain`. The :class:`~.modelchain.ModelChain` is a class that provides all necessary steps to calculate the power output of a wind turbine. You can ...
[ "def", "calculate_power_output", "(", "weather", ",", "my_turbine", ",", "e126", ",", "dummy_turbine", ")", ":", "# power output calculation for my_turbine", "# initialize ModelChain with default parameters and use run_model method", "# to calculate power output", "mc_my_turbine", "=...
45.852459
0.00035
def get_all_webhooks(self, **kwargs): # noqa: E501 """Get all webhooks for a customer # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_webhooks(async_r...
[ "def", "get_all_webhooks", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "get_all_webhooks_with_http...
39.681818
0.002237
def barplot(bars, title='', upColor='blue', downColor='red'): """ Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects. """ import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patc...
[ "def", "barplot", "(", "bars", ",", "title", "=", "''", ",", "upColor", "=", "'blue'", ",", "downColor", "=", "'red'", ")", ":", "import", "pandas", "as", "pd", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", "matplotlib", ".", "lines", "im...
29.388889
0.00061
def linreg_ols_lu(y, X): """Linear Regression, OLS, by solving linear equations and LU decomposition Properties ---------- * based on LAPACK's _gesv what applies LU decomposition * avoids using python's inverse functions * should be stable * no overhead or other computations Example: ...
[ "def", "linreg_ols_lu", "(", "y", ",", "X", ")", ":", "import", "numpy", "as", "np", "try", ":", "# solve OLS formula", "return", "np", ".", "linalg", ".", "solve", "(", "np", ".", "dot", "(", "X", ".", "T", ",", "X", ")", ",", "np", ".", "dot", ...
25.84
0.001493
def get_full_pipe(sol, base=()): """ Returns the full pipe of a dispatch run. :param sol: A Solution object. :type sol: schedula.utils.Solution :param base: Base node id. :type base: tuple[str] :return: Full pipe of a dispatch run. :rtype: DspPipe """ ...
[ "def", "get_full_pipe", "(", "sol", ",", "base", "=", "(", ")", ")", ":", "pipe", ",", "i", "=", "DspPipe", "(", ")", ",", "len", "(", "base", ")", "for", "p", "in", "sol", ".", "_pipe", ":", "n", ",", "s", "=", "p", "[", "-", "1", "]", "...
21.782609
0.000955
def keyframe(self, index): """Set current keyframe. Load TiffPage from file if necessary.""" index = int(index) if index < 0: index %= len(self) if self._keyframe.index == index: return if index == 0: self._keyframe = self.pages[0] ...
[ "def", "keyframe", "(", "self", ",", "index", ")", ":", "index", "=", "int", "(", "index", ")", "if", "index", "<", "0", ":", "index", "%=", "len", "(", "self", ")", "if", "self", ".", "_keyframe", ".", "index", "==", "index", ":", "return", "if"...
34.296296
0.002101
def score(self, X, y, sample_weight=None): """Returns the mean accuracy on the given test data and labels. NOTE: In the condition of sklearn.svm.SVC with precomputed kernel when the kernel matrix is computed portion by portion, the function will ignore the first input argument X. ...
[ "def", "score", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ")", ":", "from", "sklearn", ".", "metrics", "import", "accuracy_score", "if", "isinstance", "(", "self", ".", "clf", ",", "sklearn", ".", "svm", ".", "SVC", ")", "an...
40.794872
0.001228
def get_resource_from_handle(self, resource_handle, verify_repo=True): """Get a resource. Args: resource_handle (`ResourceHandle`): Handle of the resource. Returns: `PackageRepositoryResource` instance. """ if verify_repo: # we could fix the ...
[ "def", "get_resource_from_handle", "(", "self", ",", "resource_handle", ",", "verify_repo", "=", "True", ")", ":", "if", "verify_repo", ":", "# we could fix the handle at this point, but handles should", "# always be made from repo.make_resource_handle... for now,", "# at least, er...
46.103448
0.002198
def subDict(self, tags, raw = False): """Creates a dict of values of _tags_ from the Record. The tags are the keys and the values are the values. If the tag is missing the value will be `None`. # Parameters _tags_ : `list[str]` > The list of tags requested _raw_ : `optional [...
[ "def", "subDict", "(", "self", ",", "tags", ",", "raw", "=", "False", ")", ":", "retDict", "=", "{", "}", "for", "tag", "in", "tags", ":", "retDict", "[", "tag", "]", "=", "self", ".", "get", "(", "tag", ",", "raw", "=", "raw", ")", "return", ...
27.608696
0.012177
def gateways_info(): """Returns gateways data. """ data = netifaces.gateways() results = {'default': {}} with suppress(KeyError): results['ipv4'] = data[netifaces.AF_INET] results['default']['ipv4'] = data['default'][netifaces.AF_INET] with suppress(KeyError): results['i...
[ "def", "gateways_info", "(", ")", ":", "data", "=", "netifaces", ".", "gateways", "(", ")", "results", "=", "{", "'default'", ":", "{", "}", "}", "with", "suppress", "(", "KeyError", ")", ":", "results", "[", "'ipv4'", "]", "=", "data", "[", "netifac...
30.857143
0.002247
def simxUnpackFloats(floatsPackedInString): ''' Please have a look at the function description/documentation in the V-REP user manual ''' b=[] for i in range(int(len(floatsPackedInString)/4)): b.append(struct.unpack('<f',floatsPackedInString[4*i:4*(i+1)])[0]) return b
[ "def", "simxUnpackFloats", "(", "floatsPackedInString", ")", ":", "b", "=", "[", "]", "for", "i", "in", "range", "(", "int", "(", "len", "(", "floatsPackedInString", ")", "/", "4", ")", ")", ":", "b", ".", "append", "(", "struct", ".", "unpack", "(",...
36.625
0.013333
def track_exception(self, type_exception: type = None, value : Exception =None, tb : traceback =None, properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None: """ Send information about a single exception that occurred in the application. :para...
[ "def", "track_exception", "(", "self", ",", "type_exception", ":", "type", "=", "None", ",", "value", ":", "Exception", "=", "None", ",", "tb", ":", "traceback", "=", "None", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ...
78.909091
0.022779
def render_q(q, qn, connection): """ Renders the Q object into SQL for the WHEN clause. Uses as much as possible the Django ORM machinery for SQL generation, handling table aliases, field quoting, parameter escaping etc. :param q: Q object representing the filter condition :param qn: db specif...
[ "def", "render_q", "(", "q", ",", "qn", ",", "connection", ")", ":", "joinstr", "=", "u' {} '", ".", "format", "(", "q", ".", "connector", ")", "conditions", "=", "[", "]", "params", "=", "[", "]", "if", "DJANGO_MAJOR", "==", "1", "and", "DJANGO_MINO...
36.285714
0.000548
def get(self, key, r=None, pr=None, timeout=None, include_context=None, basic_quorum=None, notfound_ok=None, head_only=False): """ Retrieve a :class:`~riak.riak_object.RiakObject` or :class:`~riak.datatypes.Datatype`, based on the presence and value of the :attr:`datatype <Bu...
[ "def", "get", "(", "self", ",", "key", ",", "r", "=", "None", ",", "pr", "=", "None", ",", "timeout", "=", "None", ",", "include_context", "=", "None", ",", "basic_quorum", "=", "None", ",", "notfound_ok", "=", "None", ",", "head_only", "=", "False",...
47.465116
0.00144
def _intersection(A,B): """ A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections """ intersection = [] for i in A: if i in B: ...
[ "def", "_intersection", "(", "A", ",", "B", ")", ":", "intersection", "=", "[", "]", "for", "i", "in", "A", ":", "if", "i", "in", "B", ":", "intersection", ".", "append", "(", "i", ")", "return", "intersection" ]
20
0.018568
def main(argv=None): """ Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Prepare arguments parser = argparse.ArgumentParser( prog="pelix.shell.xmpp", parents=[make_common_parser()], description="Pelix XMPP Shell", ...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "# Prepare arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "\"pelix.shell.xmpp\"", ",", "parents", "=", "[", "make_common_parser", "(", ")", "]", ",", "description", "=", "\"P...
27.198198
0.000639
def run(cmd): """Run the given command. Raises OSError is the command returns a non-zero exit status. """ log.debug("running '%s'", cmd) fixed_cmd = cmd if sys.platform == "win32" and cmd.count('"') > 2: fixed_cmd = '"' + cmd + '"' retval = os.system(fixed_cmd) if hasattr(os, "W...
[ "def", "run", "(", "cmd", ")", ":", "log", ".", "debug", "(", "\"running '%s'\"", ",", "cmd", ")", "fixed_cmd", "=", "cmd", "if", "sys", ".", "platform", "==", "\"win32\"", "and", "cmd", ".", "count", "(", "'\"'", ")", ">", "2", ":", "fixed_cmd", "...
29.0625
0.002083
async def build( self, *, remote: str = None, fileobj: BinaryIO = None, path_dockerfile: str = None, tag: str = None, quiet: bool = False, nocache: bool = False, buildargs: Mapping = None, pull: bool = False, rm: bool = True, ...
[ "async", "def", "build", "(", "self", ",", "*", ",", "remote", ":", "str", "=", "None", ",", "fileobj", ":", "BinaryIO", "=", "None", ",", "path_dockerfile", ":", "str", "=", "None", ",", "tag", ":", "str", "=", "None", ",", "quiet", ":", "bool", ...
31.253012
0.001121
def network_create(provider, names, **kwargs): ''' Create private network CLI Example: .. code-block:: bash salt minionname cloud.network_create my-nova names=['salt'] cidr='192.168.100.0/24' ''' client = _get_client() return client.extra_action(provider=provider, names=names, ac...
[ "def", "network_create", "(", "provider", ",", "names", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_client", "(", ")", "return", "client", ".", "extra_action", "(", "provider", "=", "provider", ",", "names", "=", "names", ",", "action", "=", ...
26.153846
0.008523
def _from_binary_objid(cls, binary_stream): """See base class.""" uid_size = ObjectID._UUID_SIZE #some entries might not have all four ids, this line forces #to always create 4 elements, so contruction is easier uids = [UUID(bytes_le=binary_stream[i*uid_size:(i+1)*uid_size].tobytes()) if i * uid_si...
[ "def", "_from_binary_objid", "(", "cls", ",", "binary_stream", ")", ":", "uid_size", "=", "ObjectID", ".", "_UUID_SIZE", "#some entries might not have all four ids, this line forces", "#to always create 4 elements, so contruction is easier", "uids", "=", "[", "UUID", "(", "by...
50.3
0.011719
def _fancy_replace(self, a, alo, ahi, b, blo, bhi): r""" When replacing one block of lines with another, search the blocks for *similar* lines; the best-matching pair (if any) is used as a synch point, and intraline difference marking is done on the similar pair. Lots of work, bu...
[ "def", "_fancy_replace", "(", "self", ",", "a", ",", "alo", ",", "ahi", ",", "b", ",", "blo", ",", "bhi", ")", ":", "# don't synch up unless the lines have a similarity score of at", "# least cutoff; best_ratio tracks the best score seen so far", "best_ratio", ",", "cutof...
41.061856
0.001226
def retry(self, func, partition_id, retry_message, final_failure_message, max_retries, host_id): """ Make attempt_renew_lease async call sync. """ loop = asyncio.new_event_loop() loop.run_until_complete(self.retry_async(func, partition_id, retry_message, ...
[ "def", "retry", "(", "self", ",", "func", ",", "partition_id", ",", "retry_message", ",", "final_failure_message", ",", "max_retries", ",", "host_id", ")", ":", "loop", "=", "asyncio", ".", "new_event_loop", "(", ")", "loop", ".", "run_until_complete", "(", ...
54.714286
0.012853
def send_message(self, stream, msg): """Send an arbitrary message to a particular client. Parameters ---------- stream : :class:`tornado.iostream.IOStream` object The stream to send the message to. msg : Message object The message to send. Notes ...
[ "def", "send_message", "(", "self", ",", "stream", ",", "msg", ")", ":", "assert", "get_thread_ident", "(", ")", "==", "self", ".", "ioloop_thread_id", "try", ":", "if", "stream", ".", "KATCPServer_closing", ":", "raise", "RuntimeError", "(", "'Stream is closi...
39.580645
0.001591
def get_os_version(): """ Returns a named tuple describing the operating system on the remote host. """ # TODO: remove once fabric stops using contextlib.nested. # https://github.com/fabric/fabric/issues/1364 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) ...
[ "def", "get_os_version", "(", ")", ":", "# TODO: remove once fabric stops using contextlib.nested.", "# https://github.com/fabric/fabric/issues/1364", "import", "warnings", "warnings", ".", "filterwarnings", "(", "\"ignore\"", ",", "category", "=", "DeprecationWarning", ")", "c...
34.526316
0.000741
def publish_scene_add(self, scene_id, animation_id, name, color, velocity, config): """publish added scene""" self.sequence_number += 1 self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config)) return self.se...
[ "def", "publish_scene_add", "(", "self", ",", "scene_id", ",", "animation_id", ",", "name", ",", "color", ",", "velocity", ",", "config", ")", ":", "self", ".", "sequence_number", "+=", "1", "self", ".", "publisher", ".", "send_multipart", "(", "msgs", "."...
65.8
0.012012
def findLayer( self, layerName ): """ Looks up the layer for this node based on the inputed layer name. :param layerName | <str> :return <XNodeLayer> """ for layer in self._layers: if ( layer.name() == layerName ): ...
[ "def", "findLayer", "(", "self", ",", "layerName", ")", ":", "for", "layer", "in", "self", ".", "_layers", ":", "if", "(", "layer", ".", "name", "(", ")", "==", "layerName", ")", ":", "return", "layer", "return", "None" ]
28.416667
0.022727
def normalized_index_expression(indices, shape, int_to_slice=False): """Enable indexing with almost Numpy-like capabilities. Implements the following features: - Usage of general slices and sequences of slices - Conversion of `Ellipsis` into an adequate number of ``slice(None)`` objects - Fe...
[ "def", "normalized_index_expression", "(", "indices", ",", "shape", ",", "int_to_slice", "=", "False", ")", ":", "ndim", "=", "len", "(", "shape", ")", "# Support indexing with fewer indices as indexing along the first", "# corresponding axes. In the other cases, normalize the ...
37.385321
0.000239
def get_files_by_img_id(img_id, check_hash=True): """ Шукає файли для img_id. Повертає: { 'main': 'relative path to main image', 'variants': { 'label': 'relative path to variant image by label', ... } } Якщо check_hash=True, тоді файли з невірним х...
[ "def", "get_files_by_img_id", "(", "img_id", ",", "check_hash", "=", "True", ")", ":", "main_rel_path", "=", "get_relative_path_from_img_id", "(", "img_id", ")", "main_path", "=", "media_path", "(", "main_rel_path", ")", "if", "not", "os", ".", "path", ".", "i...
39.404762
0.002358
def cosine_similarity(sent1: str, sent2: str) -> float: """ Calculates cosine similarity between 2 sentences/documents. Thanks to @vpekar, see http://goo.gl/ykibJY """ WORD = re.compile(r'\w+') def get_cosine(vec1, vec2): intersection = set(vec1.keys()) & set(vec2.keys()) numera...
[ "def", "cosine_similarity", "(", "sent1", ":", "str", ",", "sent2", ":", "str", ")", "->", "float", ":", "WORD", "=", "re", ".", "compile", "(", "r'\\w+'", ")", "def", "get_cosine", "(", "vec1", ",", "vec2", ")", ":", "intersection", "=", "set", "(",...
29.482759
0.002265
def clean_surface(surface, span): """Remove spurious characters from a quantity's surface.""" surface = surface.replace('-', ' ') no_start = ['and', ' '] no_end = [' and', ' '] found = True while found: found = False for word in no_start: if surface.lower().startswit...
[ "def", "clean_surface", "(", "surface", ",", "span", ")", ":", "surface", "=", "surface", ".", "replace", "(", "'-'", ",", "' '", ")", "no_start", "=", "[", "'and'", ",", "' '", "]", "no_end", "=", "[", "' and'", ",", "' '", "]", "found", "=", "Tru...
32
0.001011
def _add_group_columns(data, gdf): """ Add group columns to data with a value from the grouped dataframe It is assumed that the grouped dataframe contains a single group >>> data = pd.DataFrame({ ... 'x': [5, 6, 7]}) >>> gdf = GroupedDataFrame({ ... 'g': list('aaa'), ... 'x...
[ "def", "_add_group_columns", "(", "data", ",", "gdf", ")", ":", "n", "=", "len", "(", "data", ")", "if", "isinstance", "(", "gdf", ",", "GroupedDataFrame", ")", ":", "for", "i", ",", "col", "in", "enumerate", "(", "gdf", ".", "plydata_groups", ")", "...
33.410256
0.000746
def getRandomWithMods(inputSpace, maxChanges): """ Returns a random selection from the inputSpace with randomly modified up to maxChanges number of bits. """ size = len(inputSpace) ind = np.random.random_integers(0, size-1, 1)[0] value = copy.deepcopy(inputSpace[ind]) if maxChanges == 0: return valu...
[ "def", "getRandomWithMods", "(", "inputSpace", ",", "maxChanges", ")", ":", "size", "=", "len", "(", "inputSpace", ")", "ind", "=", "np", ".", "random", ".", "random_integers", "(", "0", ",", "size", "-", "1", ",", "1", ")", "[", "0", "]", "value", ...
26.846154
0.019391
def _refine_mode(mode): ''' Return a mode value that is predictable ''' mode = six.text_type(mode).lower() if any([mode.startswith('e'), mode == '1', mode == 'on']): return 'Enforcing' if any([mode.startswith('p'), mode == '0', mode == 'off...
[ "def", "_refine_mode", "(", "mode", ")", ":", "mode", "=", "six", ".", "text_type", "(", "mode", ")", ".", "lower", "(", ")", "if", "any", "(", "[", "mode", ".", "startswith", "(", "'e'", ")", ",", "mode", "==", "'1'", ",", "mode", "==", "'on'", ...
26.25
0.002299
def _load_annotation(self, _coco, coco_ind_to_class_ind, index): """ coco ann: [u'segmentation', u'area', u'iscrowd', u'image_id', u'bbox', u'category_id', u'id'] iscrowd: crowd instances are handled by marking their overlaps with all categories to -1 and later excluded i...
[ "def", "_load_annotation", "(", "self", ",", "_coco", ",", "coco_ind_to_class_ind", ",", "index", ")", ":", "im_ann", "=", "_coco", ".", "loadImgs", "(", "index", ")", "[", "0", "]", "filename", "=", "self", ".", "_image_file_tmpl", ".", "format", "(", "...
36.791667
0.002206
def visible_security_group_mapping(self, filter=None): # @ReservedAssignment """ Return all security groups assigned to VSS container types. This is only available on SMC >= 6.5. :param str filter: filter for searching by name :raises ActionCommandFailed: element not fo...
[ "def", "visible_security_group_mapping", "(", "self", ",", "filter", "=", "None", ")", ":", "# @ReservedAssignment", "if", "'visible_security_group_mapping'", "not", "in", "self", ".", "data", ".", "links", ":", "raise", "ResourceNotFound", "(", "'This entry point is ...
47.666667
0.00823
def remove_params(raw_params, kwargs_default=_kwargs_default_name): u""" Removes all keyword-only args from the params list and a bare star, if any. Does not add the kwargs dict if needed. Returns True if more action is needed, False if not (more action is needed if no kwargs dict exists) """ ...
[ "def", "remove_params", "(", "raw_params", ",", "kwargs_default", "=", "_kwargs_default_name", ")", ":", "assert", "raw_params", "[", "0", "]", ".", "type", "==", "token", ".", "STAR", "if", "raw_params", "[", "1", "]", ".", "type", "==", "token", ".", "...
32.952381
0.001404
def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype="text/html")
[ "def", "execute_command", "(", "self", ",", "request", ",", "command", ",", "frame", ")", ":", "return", "Response", "(", "frame", ".", "console", ".", "eval", "(", "command", ")", ",", "mimetype", "=", "\"text/html\"", ")" ]
56.666667
0.011628
def transSect(theta=None, rho=None, gamma=None): """ Transport matrix of sector dipole :param theta: bending angle in [RAD] :param rho: bending radius in [m] :param gamma: electron energy, gamma value :return: 6x6 numpy array """ m = np.eye(6, 6, dtype=np.float64) if None in (theta, rho...
[ "def", "transSect", "(", "theta", "=", "None", ",", "rho", "=", "None", ",", "gamma", "=", "None", ")", ":", "m", "=", "np", ".", "eye", "(", "6", ",", "6", ",", "dtype", "=", "np", ".", "float64", ")", "if", "None", "in", "(", "theta", ",", ...
32.52
0.002389
def cull(data,index,min=None,max=None): """Sieve an emcee clouds by excluding walkers with search variable 'index' smaller than 'min' or larger than 'max'.""" ret = data if min is not None: ret = ret[ret[:,index] > min,:] if max is not None: ret = ret[ret[:,index] < max,:] ...
[ "def", "cull", "(", "data", ",", "index", ",", "min", "=", "None", ",", "max", "=", "None", ")", ":", "ret", "=", "data", "if", "min", "is", "not", "None", ":", "ret", "=", "ret", "[", "ret", "[", ":", ",", "index", "]", ">", "min", ",", ":...
24.923077
0.029762
def _references_content(ref_files): """Returns dict<str ref_url, str ref_content>.""" example_spec = { "url": tf.FixedLenFeature([], tf.string), "content": tf.FixedLenFeature([], tf.string), } data = {} for ex in generator_utils.tfrecord_iterator( ref_files, gzipped=True, example_spec=exampl...
[ "def", "_references_content", "(", "ref_files", ")", ":", "example_spec", "=", "{", "\"url\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "tf", ".", "string", ")", ",", "\"content\"", ":", "tf", ".", "FixedLenFeature", "(", "[", "]", ",", "...
35.727273
0.01737
def sshclient_from_instance(instance, ssh_key_file, host_key_file='~/.ssh/known_hosts', user_name='root', ssh_pwd=None): """ Create and return an SSHClient object given an instance object. :type instance: :class`boto.ec2.instance.Instance` object ...
[ "def", "sshclient_from_instance", "(", "instance", ",", "ssh_key_file", ",", "host_key_file", "=", "'~/.ssh/known_hosts'", ",", "user_name", "=", "'root'", ",", "ssh_pwd", "=", "None", ")", ":", "s", "=", "FakeServer", "(", "instance", ",", "ssh_key_file", ")", ...
36.857143
0.000944
def OnMouseWheel(self, event): """Event handler for mouse wheel actions Invokes zoom when mouse when Ctrl is also pressed """ if event.ControlDown(): if event.WheelRotation > 0: post_command_event(self.grid, self.grid.ZoomInMsg) else: ...
[ "def", "OnMouseWheel", "(", "self", ",", "event", ")", ":", "if", "event", ".", "ControlDown", "(", ")", ":", "if", "event", ".", "WheelRotation", ">", "0", ":", "post_command_event", "(", "self", ".", "grid", ",", "self", ".", "grid", ".", "ZoomInMsg"...
34.424242
0.001712
def _compute_curve(labels, predictions, num_thresholds, weights=None): """This function is another implementation of functions in https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/pr_curve/summary.py""" if weights is None: weights = 1.0 # Compute bins of true positives ...
[ "def", "_compute_curve", "(", "labels", ",", "predictions", ",", "num_thresholds", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "weights", "=", "1.0", "# Compute bins of true positives and false positives.", "bucket_indices", "=", "np",...
37.866667
0.001717
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
0.000859
def get_trunk_interfaces(auth, url, devid=None, devip=None): """Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass ...
[ "def", "get_trunk_interfaces", "(", "auth", ",", "url", ",", "devid", "=", "None", ",", "devip", "=", "None", ")", ":", "if", "devip", "is", "not", "None", ":", "devid", "=", "get_dev_details", "(", "devip", ",", "auth", ",", "url", ")", "[", "'id'",...
37.684211
0.002269
def Match(pattern, s): """Matches the string with the pattern, caching the compiled regexp.""" # The regexp compilation caching is inlined in both Match and Search for # performance reasons; factoring it out into a separate function turns out # to be noticeably expensive. if pattern not in _regexp_compile_cac...
[ "def", "Match", "(", "pattern", ",", "s", ")", ":", "# The regexp compilation caching is inlined in both Match and Search for", "# performance reasons; factoring it out into a separate function turns out", "# to be noticeably expensive.", "if", "pattern", "not", "in", "_regexp_compile_...
53.875
0.015982
def in_function_call(self): """This function is called whenever the cursor/buffer goes idle for a second. The real workhorse of the intellisense. Decides what kind of intellisense is needed and returns the relevant response.""" #See if we are calling a function inside a module or other f...
[ "def", "in_function_call", "(", "self", ")", ":", "#See if we are calling a function inside a module or other function.", "result", "=", "[", "]", "if", "(", "self", ".", "context", ".", "el_section", "==", "\"body\"", "and", "self", ".", "context", ".", "el_call", ...
42.266667
0.010802
def callproc(self, procname, parameters = (), cursorClass = DictCursor, quiet = False): """Calls a MySQL stored procedure procname. This uses DictCursor by default.""" i = 0 errcode = 0 caughte = None while i < self.numTries: i += 1 try: cursor = self.connection.cursor(cursorClass) if type(para...
[ "def", "callproc", "(", "self", ",", "procname", ",", "parameters", "=", "(", ")", ",", "cursorClass", "=", "DictCursor", ",", "quiet", "=", "False", ")", ":", "i", "=", "0", "errcode", "=", "0", "caughte", "=", "None", "while", "i", "<", "self", "...
32.433333
0.045908
def get_seqprop_to_seqprop_alignment_stats(self, seqprop1, seqprop2): """Get the sequence alignment information for a sequence to a structure's chain.""" alignment = self._get_seqprop_to_seqprop_alignment(seqprop1=seqprop1, seqprop2=seqprop2) return ssbio.protein.sequence.utils.alignment.pairwis...
[ "def", "get_seqprop_to_seqprop_alignment_stats", "(", "self", ",", "seqprop1", ",", "seqprop2", ")", ":", "alignment", "=", "self", ".", "_get_seqprop_to_seqprop_alignment", "(", "seqprop1", "=", "seqprop1", ",", "seqprop2", "=", "seqprop2", ")", "return", "ssbio", ...
94.4
0.012605
def merge_into_nodeset(target, source): """Place all the nodes from the source node-set into the target node-set, preserving document order. Both node-sets must be in document order to begin with. """ if len(target) == 0: target.extend(source) return source = [n for n in sourc...
[ "def", "merge_into_nodeset", "(", "target", ",", "source", ")", ":", "if", "len", "(", "target", ")", "==", "0", ":", "target", ".", "extend", "(", "source", ")", "return", "source", "=", "[", "n", "for", "n", "in", "source", "if", "n", "not", "in"...
36.583333
0.00111
def _decode_temp(byte_1, byte_2): """Decode a signed short temperature as two bytes to a single number.""" temp = (byte_1 << 8) + byte_2 if (temp > 32767): temp = temp - 65536 temp = temp / 10 return temp
[ "def", "_decode_temp", "(", "byte_1", ",", "byte_2", ")", ":", "temp", "=", "(", "byte_1", "<<", "8", ")", "+", "byte_2", "if", "(", "temp", ">", "32767", ")", ":", "temp", "=", "temp", "-", "65536", "temp", "=", "temp", "/", "10", "return", "tem...
35.714286
0.011719
def parseJuiceHeaders(lines): """ Create a JuiceBox from a list of header lines. @param lines: a list of lines. """ b = JuiceBox() bodylen = 0 key = None for L in lines: if L[0] == ' ': # continuation assert key is not None b[key] += '\r\n'+L[...
[ "def", "parseJuiceHeaders", "(", "lines", ")", ":", "b", "=", "JuiceBox", "(", ")", "bodylen", "=", "0", "key", "=", "None", "for", "L", "in", "lines", ":", "if", "L", "[", "0", "]", "==", "' '", ":", "# continuation", "assert", "key", "is", "not",...
26.090909
0.001681
def parse(name, content, releases, get_head_fn): """ Parses the given content for a valid changelog :param name: str, package name :param content: str, content :param releases: list, releases :param get_head_fn: function :return: dict, changelog """ changelog = {} releases = froz...
[ "def", "parse", "(", "name", ",", "content", ",", "releases", ",", "get_head_fn", ")", ":", "changelog", "=", "{", "}", "releases", "=", "frozenset", "(", "releases", ")", "head", "=", "False", "for", "line", "in", "content", ".", "splitlines", "(", ")...
29.916667
0.00135
def make_report_error_api(client): """Create an instance of the gapic Logging API. :type client::class:`google.cloud.error_reporting.Client` :param client: Error Reporting client. :rtype: :class:_ErrorReportingGapicApi :returns: An Error Reporting API instance. """ gax_client = report_erro...
[ "def", "make_report_error_api", "(", "client", ")", ":", "gax_client", "=", "report_errors_service_client", ".", "ReportErrorsServiceClient", "(", "credentials", "=", "client", ".", "_credentials", ",", "client_info", "=", "_CLIENT_INFO", ")", "return", "_ErrorReporting...
37.461538
0.002004
def read(self): # type: () -> str """Read data from the stream.""" s = self._buf + self._raw.read() self._buf = '' return s
[ "def", "read", "(", "self", ")", ":", "# type: () -> str", "s", "=", "self", ".", "_buf", "+", "self", ".", "_raw", ".", "read", "(", ")", "self", ".", "_buf", "=", "''", "return", "s" ]
26.333333
0.018405
def data_to_unicode(self, data): """Recursively convert a list or dictionary to unicode. Args: data: The data to be unicoded. Returns: Unicoded data. """ if isinstance(data, dict): return {self.to_unicode(k): self.to_unicode(v) for k, v in da...
[ "def", "data_to_unicode", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "{", "self", ".", "to_unicode", "(", "k", ")", ":", "self", ".", "to_unicode", "(", "v", ")", "for", "k", ",", "v", "i...
31
0.008351
def sizes(count, offset=0, max_chunk=500): """ Helper to iterate over remote data via count & offset pagination. """ if count is None: chunk = max_chunk while True: yield chunk, offset offset += chunk else: while count: chunk = min(count, m...
[ "def", "sizes", "(", "count", ",", "offset", "=", "0", ",", "max_chunk", "=", "500", ")", ":", "if", "count", "is", "None", ":", "chunk", "=", "max_chunk", "while", "True", ":", "yield", "chunk", ",", "offset", "offset", "+=", "chunk", "else", ":", ...
28.066667
0.002299
def workflow_script_reject(self): """Copy real analyses to RejectAnalysis, with link to real create a new worksheet, with the original analyses, and new duplicates and references to match the rejected worksheet. """ if skip(self, "reject"): return ...
[ "def", "workflow_script_reject", "(", "self", ")", ":", "if", "skip", "(", "self", ",", "\"reject\"", ")", ":", "return", "workflow", "=", "self", ".", "portal_workflow", "def", "copy_src_fields_to_dst", "(", "src", ",", "dst", ")", ":", "# These will be ignor...
46.362573
0.000741
def add_edge(self, source, target): """Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target. """ edge = Edge(len(self.edges)) self.edges.append(edge) source.out_e...
[ "def", "add_edge", "(", "self", ",", "source", ",", "target", ")", ":", "edge", "=", "Edge", "(", "len", "(", "self", ".", "edges", ")", ")", "self", ".", "edges", ".", "append", "(", "edge", ")", "source", ".", "out_edges", ".", "append", "(", "...
25.647059
0.002212
def validate_context(context): """ Set the key for the current context. Args: context: a populated EFVersionContext object """ # Service must exist in service registry if not context.service_registry.service_record(context.service_name): fail("service: {} not found in service registry: {}".for...
[ "def", "validate_context", "(", "context", ")", ":", "# Service must exist in service registry", "if", "not", "context", ".", "service_registry", ".", "service_record", "(", "context", ".", "service_name", ")", ":", "fail", "(", "\"service: {} not found in service registr...
44.217391
0.014437
def get_dependencies(): """Returns list of dicts which indicate installed dependencies""" dependencies = [] # Numpy dep_attrs = { "name": "numpy", "min_version": "1.1.0", "description": "required", } try: import numpy dep_attrs["version"] = numpy.version...
[ "def", "get_dependencies", "(", ")", ":", "dependencies", "=", "[", "]", "# Numpy", "dep_attrs", "=", "{", "\"name\"", ":", "\"numpy\"", ",", "\"min_version\"", ":", "\"1.1.0\"", ",", "\"description\"", ":", "\"required\"", ",", "}", "try", ":", "import", "n...
23.928571
0.000287
def remove_unused_directories(src_folder, categories): """ list all directories. Remove all that are not in categories list (excluding background noise) :param src_folder: :param categories: :return: """ files = os.listdir(src_folder) os.mkdir("unused") for name in files: full_path = os.path.joi...
[ "def", "remove_unused_directories", "(", "src_folder", ",", "categories", ")", ":", "files", "=", "os", ".", "listdir", "(", "src_folder", ")", "os", ".", "mkdir", "(", "\"unused\"", ")", "for", "name", "in", "files", ":", "full_path", "=", "os", ".", "p...
33.117647
0.01209
def hr_diagram_from_data(data, x_range, y_range): """ Given a numpy array create a Bokeh plot figure creating an H-R diagram. """ _, color_mapper = hr_diagram_color_helper([]) data_dict = { 'x': list(data['temperature']), 'y': list(data['luminosity']), 'color': list(data[...
[ "def", "hr_diagram_from_data", "(", "data", ",", "x_range", ",", "y_range", ")", ":", "_", ",", "color_mapper", "=", "hr_diagram_color_helper", "(", "[", "]", ")", "data_dict", "=", "{", "'x'", ":", "list", "(", "data", "[", "'temperature'", "]", ")", ",...
37.555556
0.001443
def ticket_tags(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tags#show-tags" api_path = "/api/v2/tickets/{id}/tags.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "ticket_tags", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/tickets/{id}/tags.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", ...
49
0.008032
def survey_basis(self, keys=None, alias=None, step=None): """ Look at the basis of all the curves in ``well.data`` and return a basis with the minimum start, maximum depth, and minimum step. Args: keys (list): List of strings: the keys of the data items to su...
[ "def", "survey_basis", "(", "self", ",", "keys", "=", "None", ",", "alias", "=", "None", ",", "step", "=", "None", ")", ":", "if", "keys", "is", "None", ":", "keys", "=", "[", "k", "for", "k", ",", "v", "in", "self", ".", "data", ".", "items", ...
36.457143
0.00229
def start_update(self, layer_id): """ A shortcut to create a new version and start importing it. Effectively the same as :py:meth:`koordinates.layers.LayerManager.create_draft` followed by :py:meth:`koordinates.layers.LayerManager.start_import`. """ target_url = self.client.get_u...
[ "def", "start_update", "(", "self", ",", "layer_id", ")", ":", "target_url", "=", "self", ".", "client", ".", "get_url", "(", "'LAYER'", ",", "'POST'", ",", "'update'", ",", "{", "'layer_id'", ":", "layer_id", "}", ")", "r", "=", "self", ".", "client",...
60.375
0.008163
def AddBookkeepingOperators(model): """This adds a few bookkeeping operators that we can inspect later. These operators do not affect the training procedure: they only collect statistics and prints them to file or to logs. """ # Print basically prints out the content of the blob. to_file=1 routes t...
[ "def", "AddBookkeepingOperators", "(", "model", ")", ":", "# Print basically prints out the content of the blob. to_file=1 routes the", "# printed output to a file. The file is going to be stored under", "# root_folder/[blob name]", "model", ".", "Print", "(", "'accuracy'", ",", "[...
48.6875
0.001259
def shutdown(self, restart=True): """ Stop the execution of enqueued jobs, and wait for all running jobs to complete. This method is synchronous and returns as soon as all jobs are terminated (i.e. all threads are stopped). If restart is True, the workqueue is restarted and paus...
[ "def", "shutdown", "(", "self", ",", "restart", "=", "True", ")", ":", "self", ".", "_check_if_ready", "(", ")", "self", ".", "collection", ".", "stop", "(", ")", "self", ".", "collection", ".", "wait", "(", ")", "self", ".", "main_loop", ".", "join"...
34.375
0.002358
def dump(self, obj, context=None): """Serialize object with schema.""" return self.schema_class(context=context).dump(obj).data
[ "def", "dump", "(", "self", ",", "obj", ",", "context", "=", "None", ")", ":", "return", "self", ".", "schema_class", "(", "context", "=", "context", ")", ".", "dump", "(", "obj", ")", ".", "data" ]
47
0.013986
def display_the_graphic_connection(self): """ The following permits to attribute the function "display_the_graphic" to the slider. Because, to make a connection, we can not have parameters for the function, but "display_the_graphic" has some. """ self.display_the_graphic(self.num...
[ "def", "display_the_graphic_connection", "(", "self", ")", ":", "self", ".", "display_the_graphic", "(", "self", ".", "num_line", ",", "self", ".", "wavelength", ",", "self", ".", "data_wanted", ",", "self", ".", "information", ")" ]
62.333333
0.013193
def reset(self): ''' Reset PyMC3 model and all tracked distributions and parameters. ''' self.model = pm.Model() self.mu = None self.par_groups = {}
[ "def", "reset", "(", "self", ")", ":", "self", ".", "model", "=", "pm", ".", "Model", "(", ")", "self", ".", "mu", "=", "None", "self", ".", "par_groups", "=", "{", "}" ]
27.142857
0.010204
def get_collections(module_ident, plpy): """Get all the collections that the module is part of.""" # Make sure to only return one match per collection and only if it is the # latest collection (which may not be the same as what is in # latest_modules) plan = plpy.prepare(''' WITH RECURSIVE t(node, p...
[ "def", "get_collections", "(", "module_ident", ",", "plpy", ")", ":", "# Make sure to only return one match per collection and only if it is the", "# latest collection (which may not be the same as what is in", "# latest_modules)", "plan", "=", "plpy", ".", "prepare", "(", "'''\nWI...
40.321429
0.000865
def Extract_Checkpoints(self): ''' Extract the checkpoints and store in self.tracking_data ''' soup = BeautifulSoup(self.page,'xml') if soup.find('result').string.strip() == 'failed': raise ValueError('The Tracking number is invalid.') status = soup.find('DOCKET_STATUS').string.strip() if status ==...
[ "def", "Extract_Checkpoints", "(", "self", ")", ":", "soup", "=", "BeautifulSoup", "(", "self", ".", "page", ",", "'xml'", ")", "if", "soup", ".", "find", "(", "'result'", ")", ".", "string", ".", "strip", "(", ")", "==", "'failed'", ":", "raise", "V...
29.439024
0.035285
def _init_w_transforms(data, features): """Initialize the mappings (Wi) for the SRM with random orthogonal matrices. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. features : int ...
[ "def", "_init_w_transforms", "(", "data", ",", "features", ")", ":", "w", "=", "[", "]", "subjects", "=", "len", "(", "data", ")", "voxels", "=", "np", ".", "empty", "(", "subjects", ",", "dtype", "=", "int", ")", "# Set Wi to a random orthogonal voxels by...
25.159091
0.001739
def modify_column_if_table_exists(self, tablename: str, fieldname: str, newdef: str) -> Optional[int]: """Alters a column's definition without renaming it.""" if not self.table_exists(tablen...
[ "def", "modify_column_if_table_exists", "(", "self", ",", "tablename", ":", "str", ",", "fieldname", ":", "str", ",", "newdef", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "if", "not", "self", ".", "table_exists", "(", "tablename", ")", ":",...
40
0.008726
def ftr_get_config(website_url, exact_host_match=False): """ Download the Five Filters config from centralized repositories. Repositories can be local if you need to override siteconfigs. The first entry found is returned. If no configuration is found, `None` is returned. If :mod:`cacheops` is install...
[ "def", "ftr_get_config", "(", "website_url", ",", "exact_host_match", "=", "False", ")", ":", "def", "check_requests_result", "(", "result", ")", ":", "return", "(", "u'text/plain'", "in", "result", ".", "headers", ".", "get", "(", "'content-type'", ")", "and"...
38.457364
0.000393
def load_config_yaml(self, flags, config_dict): """ Load config dict and yaml dict and then override both with flags dict. """ if config_dict is None: print('Config File not specified. Using only input flags.') return flags try: config_yaml_dict = self.cfg_fro...
[ "def", "load_config_yaml", "(", "self", ",", "flags", ",", "config_dict", ")", ":", "if", "config_dict", "is", "None", ":", "print", "(", "'Config File not specified. Using only input flags.'", ")", "return", "flags", "try", ":", "config_yaml_dict", "=", "self", "...
52.076923
0.008708
def _raw(self, msg): """ Print any command sent in raw format :param msg: arbitrary code to be printed :type msg: bytes """ self.device.write(msg) if self.auto_flush: self.flush()
[ "def", "_raw", "(", "self", ",", "msg", ")", ":", "self", ".", "device", ".", "write", "(", "msg", ")", "if", "self", ".", "auto_flush", ":", "self", ".", "flush", "(", ")" ]
25.777778
0.008333
def set_mute(self, mute): """Send mute command.""" req_url = ENDPOINTS["setMute"].format(self.ip_address, self.zone_id) params = {"enable": "true" if mute else "false"} return request(req_url, params=params)
[ "def", "set_mute", "(", "self", ",", "mute", ")", ":", "req_url", "=", "ENDPOINTS", "[", "\"setMute\"", "]", ".", "format", "(", "self", ".", "ip_address", ",", "self", ".", "zone_id", ")", "params", "=", "{", "\"enable\"", ":", "\"true\"", "if", "mute...
47
0.008368
def nextConcept(self, concepturi): """Returns the next skos concept in the list of concepts. If it's the last one, returns the first one.""" if concepturi == self.skosConcepts[-1].uri: return self.skosConcepts[0] flag = False for x in self.skosConcepts: if flag ==...
[ "def", "nextConcept", "(", "self", ",", "concepturi", ")", ":", "if", "concepturi", "==", "self", ".", "skosConcepts", "[", "-", "1", "]", ".", "uri", ":", "return", "self", ".", "skosConcepts", "[", "0", "]", "flag", "=", "False", "for", "x", "in", ...
38.636364
0.009195
def sortframe(frame): ''' sorts particles for a frame ''' d = frame['data']; sortedargs = np.lexsort([d['xi'],d['yi'],d['zi']]) d = d[sortedargs]; frame['data']=d; return frame;
[ "def", "sortframe", "(", "frame", ")", ":", "d", "=", "frame", "[", "'data'", "]", "sortedargs", "=", "np", ".", "lexsort", "(", "[", "d", "[", "'xi'", "]", ",", "d", "[", "'yi'", "]", ",", "d", "[", "'zi'", "]", "]", ")", "d", "=", "d", "[...
22.333333
0.038278
def scopes(self, scopes): """Set scopes. :param scopes: The list of scopes. """ validate_scopes(scopes) self._scopes = " ".join(set(scopes)) if scopes else ""
[ "def", "scopes", "(", "self", ",", "scopes", ")", ":", "validate_scopes", "(", "scopes", ")", "self", ".", "_scopes", "=", "\" \"", ".", "join", "(", "set", "(", "scopes", ")", ")", "if", "scopes", "else", "\"\"" ]
27.571429
0.01005
def pack(self, value=None): """Pack the value as a binary representation. :attr:`data` is packed before the calling :meth:`.GenericMessage.pack`. After that, :attr:`data`'s value is restored. Returns: bytes: The binary representation. Raises: :exc:`~.ex...
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "data_backup", "=", "None", "if", "self", ".", "data", "is", "not", "None", "and", "not", "isinstance", "(", "self", ".", "data", ",", "bytes", ")", ...
34.607143
0.002008
def set_index(self, index): """ Sets the pd dataframe index of all dataframes in the system to index """ for df in self.get_DataFrame(data=True, with_population=False): df.index = index
[ "def", "set_index", "(", "self", ",", "index", ")", ":", "for", "df", "in", "self", ".", "get_DataFrame", "(", "data", "=", "True", ",", "with_population", "=", "False", ")", ":", "df", ".", "index", "=", "index" ]
43.4
0.013575
def _check_cors_origin(origin, allowed_origins): ''' Check if an origin match cors allowed origins ''' if isinstance(allowed_origins, list): if origin in allowed_origins: return origin elif allowed_origins == '*': return allowed_origins elif allowed_origins == origin:...
[ "def", "_check_cors_origin", "(", "origin", ",", "allowed_origins", ")", ":", "if", "isinstance", "(", "allowed_origins", ",", "list", ")", ":", "if", "origin", "in", "allowed_origins", ":", "return", "origin", "elif", "allowed_origins", "==", "'*'", ":", "ret...
32.75
0.002475
def get_repositories_by_composition(self, *args, **kwargs): """Pass through to provider CompositionRepositorySession.get_repositories_by_composition""" # Implemented from kitosid template for - # osid.resource.ResourceBinSession.get_bins_by_resource catalogs = self._get_provider_session(...
[ "def", "get_repositories_by_composition", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.ResourceBinSession.get_bins_by_resource", "catalogs", "=", "self", ".", "_get_provider_session", "(", "'...
64.666667
0.008475
def replace_one(self, filter, replacement, upsert=False, bypass_document_validation=False, collation=None): """Replace a single document matching the filter. >>> for doc in db.test.find({}): ... print(doc) ... {u'x': 1, u'_id': ObjectId('54f4c5bef...
[ "def", "replace_one", "(", "self", ",", "filter", ",", "replacement", ",", "upsert", "=", "False", ",", "bypass_document_validation", "=", "False", ",", "collation", "=", "None", ")", ":", "common", ".", "validate_is_mapping", "(", "\"filter\"", ",", "filter",...
38.234375
0.001594
def segments_overlapping(ab, cd): ''' segments_overlapping((a, b), (c, d)) yields True if the line segments (a,b) and (c,d) are both colinear and have a non-finite overlap. If (a,b) and (c,d) touch at a single point, they are not considered overlapping. ''' (a,b) = ab (c,d) = cd ss = [po...
[ "def", "segments_overlapping", "(", "ab", ",", "cd", ")", ":", "(", "a", ",", "b", ")", "=", "ab", "(", "c", ",", "d", ")", "=", "cd", "ss", "=", "[", "point_in_segment", "(", "ab", ",", "c", ")", ",", "point_in_segment", "(", "ab", ",", "d", ...
44.285714
0.018957
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ ...
[ "def", "get_handlers", "(", "self", ",", "component_context", ",", "instance", ")", ":", "# Extract information from the context", "requirements", "=", "component_context", ".", "get_handler", "(", "ipopo_constants", ".", "HANDLER_REQUIRES_BEST", ")", "requires_filters", ...
34.538462
0.002167
def connect_put_node_proxy(self, name, **kwargs): # noqa: E501 """connect_put_node_proxy # noqa: E501 connect PUT requests to proxy of Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
[ "def", "connect_put_node_proxy", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "con...
46.545455
0.001914
def insert_level(df, label, level=0, copy=0, axis=0, level_name=None): """Add a new level to the index with the specified label. The newly created index will be a MultiIndex. :param df: DataFrame :param label: label to insert :param copy: If True, copy the DataFrame before assigning new index ...
[ "def", "insert_level", "(", "df", ",", "label", ",", "level", "=", "0", ",", "copy", "=", "0", ",", "axis", "=", "0", ",", "level_name", "=", "None", ")", ":", "df", "=", "df", "if", "not", "copy", "else", "df", ".", "copy", "(", ")", "src", ...
39.2
0.002491
def collect(self): """ After adding the desired aggregation columns, `collect` finalizes the groupby operation by converting the GroupbyTable into a DataTable. The first columns of the resulting table are the groupfields, followed by the aggregation columns specified in ...
[ "def", "collect", "(", "self", ")", ":", "# The final order of columns is determined by the", "# group keys and the aggregation columns", "final_field_order", "=", "list", "(", "self", ".", "__groupfields", ")", "+", "self", ".", "__grouptable", ".", "fields", "# Transfor...
38.538462
0.001947
def load(self, ladderName): """retrieve the ladder settings from saved disk file""" self.name = ladderName # preset value to load self.filename with open(self.filename, "rb") as f: data = f.read() self.__dict__.update( json.loads(data) )
[ "def", "load", "(", "self", ",", "ladderName", ")", ":", "self", ".", "name", "=", "ladderName", "# preset value to load self.filename", "with", "open", "(", "self", ".", "filename", ",", "\"rb\"", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(",...
46.666667
0.017544
def url(self): """ Get the ``xlink:href`` of this file. """ el_FLocat = self._el.find(TAG_METS_FLOCAT) if el_FLocat is not None: return el_FLocat.get("{%s}href" % NS["xlink"]) return ''
[ "def", "url", "(", "self", ")", ":", "el_FLocat", "=", "self", ".", "_el", ".", "find", "(", "TAG_METS_FLOCAT", ")", "if", "el_FLocat", "is", "not", "None", ":", "return", "el_FLocat", ".", "get", "(", "\"{%s}href\"", "%", "NS", "[", "\"xlink\"", "]", ...
29.75
0.008163
def normalizeGlyphLeftMargin(value): """ Normalizes glyph left margin. * **value** must be a :ref:`type-int-float` or `None`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)) and value is not None: raise TypeError("Glyph left margin must b...
[ "def", "normalizeGlyphLeftMargin", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")", "and", "value", "is", "not", "None", ":", "raise", "TypeError", "(", "\"Glyph left margin must be an :ref:`type-int-float...
37.636364
0.002358