text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def google(rest): "Look up a phrase on google" API_URL = 'https://www.googleapis.com/customsearch/v1?' try: key = pmxbot.config['Google API key'] except KeyError: return "Configure 'Google API key' in config" # Use a custom search that searches everything normally # http://stackoverflow.com/a/11206266/70170 ...
[ "def", "google", "(", "rest", ")", ":", "API_URL", "=", "'https://www.googleapis.com/customsearch/v1?'", "try", ":", "key", "=", "pmxbot", ".", "config", "[", "'Google API key'", "]", "except", "KeyError", ":", "return", "\"Configure 'Google API key' in config\"", "# ...
27.291667
0.035398
def channels_info(self, room_id=None, channel=None, **kwargs): """Gets a channel’s information.""" if room_id: return self.__call_api_get('channels.info', roomId=room_id, kwargs=kwargs) elif channel: return self.__call_api_get('channels.info', roomName=channel, kwargs=kwa...
[ "def", "channels_info", "(", "self", ",", "room_id", "=", "None", ",", "channel", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "room_id", ":", "return", "self", ".", "__call_api_get", "(", "'channels.info'", ",", "roomId", "=", "room_id", ",", ...
50.875
0.009662
def _readGroupSetsGenerator(self, request, numObjects, getByIndexMethod): """ Returns a generator over the results for the specified request, which is over a set of objects of the specified size. The objects are returned by call to the specified method, which must take a single i...
[ "def", "_readGroupSetsGenerator", "(", "self", ",", "request", ",", "numObjects", ",", "getByIndexMethod", ")", ":", "currentIndex", "=", "0", "if", "request", ".", "page_token", ":", "currentIndex", ",", "=", "paging", ".", "_parsePageToken", "(", "request", ...
47.527778
0.001145
def GET_parameteritemvalues(self) -> None: """Get the values of all |ChangeItem| objects handling |Parameter| objects.""" for item in state.parameteritems: self._outputs[item.name] = item.value
[ "def", "GET_parameteritemvalues", "(", "self", ")", "->", "None", ":", "for", "item", "in", "state", ".", "parameteritems", ":", "self", ".", "_outputs", "[", "item", ".", "name", "]", "=", "item", ".", "value" ]
45
0.008734
def submit(self, btn=None): "Process form submission" data = self.build_data_set() if btn and btn.name: data[btn.name] = btn.name evt = FormSubmitEvent(self, data) self.container.ProcessEvent(evt)
[ "def", "submit", "(", "self", ",", "btn", "=", "None", ")", ":", "data", "=", "self", ".", "build_data_set", "(", ")", "if", "btn", "and", "btn", ".", "name", ":", "data", "[", "btn", ".", "name", "]", "=", "btn", ".", "name", "evt", "=", "Form...
34.571429
0.008065
def median_interval(data, alpha=_alpha): """ Median including bayesian credible interval. """ q = [100*alpha/2., 50, 100*(1-alpha/2.)] lo,med,hi = np.percentile(data,q) return interval(med,lo,hi)
[ "def", "median_interval", "(", "data", ",", "alpha", "=", "_alpha", ")", ":", "q", "=", "[", "100", "*", "alpha", "/", "2.", ",", "50", ",", "100", "*", "(", "1", "-", "alpha", "/", "2.", ")", "]", "lo", ",", "med", ",", "hi", "=", "np", "....
30.428571
0.027397
def find_python(finder, line=None): """ Given a `pythonfinder.Finder` instance and an optional line, find a corresponding python :param finder: A :class:`pythonfinder.Finder` instance to use for searching :type finder: :class:pythonfinder.Finder` :param str line: A version, path, name, or nothing, ...
[ "def", "find_python", "(", "finder", ",", "line", "=", "None", ")", ":", "if", "line", "and", "not", "isinstance", "(", "line", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "\"Invalid python search type: expected string, received {0!r}\"",...
37.05
0.001972
def linearization_error(nodes): """Image for :func:`.linearization_error` docstring.""" if NO_IMAGES: return curve = bezier.Curve.from_nodes(nodes) line = bezier.Curve.from_nodes(nodes[:, (0, -1)]) midpoints = np.hstack([curve.evaluate(0.5), line.evaluate(0.5)]) ax = curve.plot(256) ...
[ "def", "linearization_error", "(", "nodes", ")", ":", "if", "NO_IMAGES", ":", "return", "curve", "=", "bezier", ".", "Curve", ".", "from_nodes", "(", "nodes", ")", "line", "=", "bezier", ".", "Curve", ".", "from_nodes", "(", "nodes", "[", ":", ",", "("...
33.2
0.001953
def seq(*sequence): """Runs a series of parsers in sequence optionally storing results in a returned dictionary. For example: seq(whitespace, ('phone', digits), whitespace, ('name', remaining)) """ results = {} for p in sequence: if callable(p): p() continue...
[ "def", "seq", "(", "*", "sequence", ")", ":", "results", "=", "{", "}", "for", "p", "in", "sequence", ":", "if", "callable", "(", "p", ")", ":", "p", "(", ")", "continue", "k", ",", "v", "=", "p", "results", "[", "k", "]", "=", "v", "(", ")...
26.285714
0.010499
def agent(agent_id): ''' Show the information about the given agent. ''' fields = [ ('ID', 'id'), ('Status', 'status'), ('Region', 'region'), ('First Contact', 'first_contact'), ('CPU Usage (%)', 'cpu_cur_pct'), ('Used Memory (MiB)', 'mem_cur_bytes'), ...
[ "def", "agent", "(", "agent_id", ")", ":", "fields", "=", "[", "(", "'ID'", ",", "'id'", ")", ",", "(", "'Status'", ",", "'status'", ")", ",", "(", "'Region'", ",", "'region'", ")", ",", "(", "'First Contact'", ",", "'first_contact'", ")", ",", "(", ...
32.083333
0.00084
def write(self, content=None): """ Write report to file. Parameters ---------- content: str 'summary', 'extended', 'powerflow' """ if self.system.files.no_output is True: return t, _ = elapsed() if not content: ...
[ "def", "write", "(", "self", ",", "content", "=", "None", ")", ":", "if", "self", ".", "system", ".", "files", ".", "no_output", "is", "True", ":", "return", "t", ",", "_", "=", "elapsed", "(", ")", "if", "not", "content", ":", "logger", ".", "wa...
33.344828
0.000753
def __extract_bbox(arr, bb_old): "Extracts the bounding box of an binary objects hole (assuming only one in existence)." hole = ndimage.binary_fill_holes(arr)- arr bb_list = ndimage.find_objects(ndimage.binary_dilation(hole, iterations = 1)) if 0 == len(bb_list): return bb_old else: bb = bb_list[0] ...
[ "def", "__extract_bbox", "(", "arr", ",", "bb_old", ")", ":", "hole", "=", "ndimage", ".", "binary_fill_holes", "(", "arr", ")", "-", "arr", "bb_list", "=", "ndimage", ".", "find_objects", "(", "ndimage", ".", "binary_dilation", "(", "hole", ",", "iteratio...
40.230769
0.020561
def add_highdepth_genome_exclusion(items): """Add exclusions to input items to avoid slow runtimes on whole genomes. """ out = [] for d in items: d = utils.deepish_copy(d) if dd.get_coverage_interval(d) == "genome": e = dd.get_exclude_regions(d) if "highdepth" not...
[ "def", "add_highdepth_genome_exclusion", "(", "items", ")", ":", "out", "=", "[", "]", "for", "d", "in", "items", ":", "d", "=", "utils", ".", "deepish_copy", "(", "d", ")", "if", "dd", ".", "get_coverage_interval", "(", "d", ")", "==", "\"genome\"", "...
33.692308
0.002222
def render_embed_css(self, css_embed: Iterable[bytes]) -> bytes: """Default method used to render the final embedded css for the rendered webpage. Override this method in a sub-classed controller to change the output. """ return b'<style type="text/css">\n' + b"\n".join(css_embe...
[ "def", "render_embed_css", "(", "self", ",", "css_embed", ":", "Iterable", "[", "bytes", "]", ")", "->", "bytes", ":", "return", "b'<style type=\"text/css\">\\n'", "+", "b\"\\n\"", ".", "join", "(", "css_embed", ")", "+", "b\"\\n</style>\"" ]
47.428571
0.008876
def from_file(filename, password='', keytype=None): """ Returns a new PrivateKey instance with the given attributes. If keytype is None, we attempt to automatically detect the type. :type filename: string :param filename: The key file name. :type password: string ...
[ "def", "from_file", "(", "filename", ",", "password", "=", "''", ",", "keytype", "=", "None", ")", ":", "if", "keytype", "is", "None", ":", "try", ":", "key", "=", "RSAKey", ".", "from_private_key_file", "(", "filename", ")", "keytype", "=", "'rsa'", "...
35.965517
0.001867
def _validate_key(self, key): """Returns a boolean indicating if the attribute name is valid or not""" return not any([key.startswith(i) for i in self.EXCEPTIONS])
[ "def", "_validate_key", "(", "self", ",", "key", ")", ":", "return", "not", "any", "(", "[", "key", ".", "startswith", "(", "i", ")", "for", "i", "in", "self", ".", "EXCEPTIONS", "]", ")" ]
59
0.01676
def getWeights(self, term_i=None): """ Return weights for fixed effect term term_i Args: term_i: fixed effect term index Returns: weights of the spefied fixed effect term. The output will be a KxL matrix of weights will be returned, wh...
[ "def", "getWeights", "(", "self", ",", "term_i", "=", "None", ")", ":", "assert", "self", ".", "init", ",", "'GP not initialised'", "if", "term_i", "==", "None", ":", "if", "self", ".", "gp", ".", "mean", ".", "n_terms", "==", "1", ":", "term_i", "="...
38.263158
0.009396
def echo_results_file(results_file, no_color, verbose=False): """Print test results in nagios style format.""" try: data = collect_results(results_file) except ValueError: echo_style( 'The results file is not the proper json format.', no_color, fg='red' ...
[ "def", "echo_results_file", "(", "results_file", ",", "no_color", ",", "verbose", "=", "False", ")", ":", "try", ":", "data", "=", "collect_results", "(", "results_file", ")", "except", "ValueError", ":", "echo_style", "(", "'The results file is not the proper json ...
27.65
0.001748
def substitute(self, target, replacement): """Return a list of selectors obtained by replacing the `target` selector with `replacement`. Herein lie the guts of the Sass @extend directive. In general, for a selector ``a X b Y c``, a target ``X Y``, and a replacement ``q Z``, ret...
[ "def", "substitute", "(", "self", ",", "target", ",", "replacement", ")", ":", "# Find the target in the parent selector, and split it into", "# before/after", "p_before", ",", "p_extras", ",", "p_after", "=", "self", ".", "break_around", "(", "target", ".", "simple_s...
43.09375
0.002128
def configuration(*args, **kwargs): """this function just instantiates a ConfigurationManager and returns the configuration dictionary. It accepts all the same parameters as the constructor for the ConfigurationManager class.""" try: config_kwargs = {'mapping_class': kwargs.pop('mapping_class')...
[ "def", "configuration", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "config_kwargs", "=", "{", "'mapping_class'", ":", "kwargs", ".", "pop", "(", "'mapping_class'", ")", "}", "except", "KeyError", ":", "config_kwargs", "=", "{", "}",...
44.9
0.002183
def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringu...
[ "def", "base64_encodestring", "(", "instr", ")", ":", "return", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "base64", ".", "encodestring", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_bytes", "(", "instr", ")", ")", ",", ...
39.166667
0.002079
def arnoldi_res(A, V, H, ip_B=None): """Measure Arnoldi residual. :param A: a linear operator that can be used with scipy's aslinearoperator with ``shape==(N,N)``. :param V: Arnoldi basis matrix with ``shape==(N,n)``. :param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with ``s...
[ "def", "arnoldi_res", "(", "A", ",", "V", ",", "H", ",", "ip_B", "=", "None", ")", ":", "N", "=", "V", ".", "shape", "[", "0", "]", "invariant", "=", "H", ".", "shape", "[", "0", "]", "==", "H", ".", "shape", "[", "1", "]", "A", "=", "get...
39.5
0.001124
def is_stop_here(self, frame, event, arg): """ Does the magic to determine if we stop here and run a command processor or not. If so, return True and set self.stop_reason; if not, return False. Determining factors can be whether a breakpoint was encountered, whether we are stepp...
[ "def", "is_stop_here", "(", "self", ",", "frame", ",", "event", ",", "arg", ")", ":", "# Add an generic event filter here?", "# FIXME TODO: Check for", "# - thread switching (under set option)", "# Check for \"next\" and \"finish\" stopping via stop_level", "# Do we want a different...
36.375
0.001673
def from_csv(cls, path:PathOrStr, csv_name:str, cols:IntsOrStrs=0, delimiter:str=None, header:str='infer', processor:PreProcessors=None, **kwargs)->'ItemList': """Create an `ItemList` in `path` from the inputs in the `cols` of `path/csv_name`""" df = pd.read_csv(Path(path)/csv_name, del...
[ "def", "from_csv", "(", "cls", ",", "path", ":", "PathOrStr", ",", "csv_name", ":", "str", ",", "cols", ":", "IntsOrStrs", "=", "0", ",", "delimiter", ":", "str", "=", "None", ",", "header", ":", "str", "=", "'infer'", ",", "processor", ":", "PreProc...
86.4
0.050459
def txt_read_in(self): """Read in txt files. Method for reading in text or csv files. This uses ascii class from astropy.io for flexible input. It is slower than numpy, but has greater flexibility with less input. """ # read in data = ascii.read(self.WORKING_DIRECTORY ...
[ "def", "txt_read_in", "(", "self", ")", ":", "# read in", "data", "=", "ascii", ".", "read", "(", "self", ".", "WORKING_DIRECTORY", "+", "'/'", "+", "self", ".", "file_name", ")", "# find number of distinct x and y points.", "num_x_pts", "=", "len", "(", "np",...
39.809524
0.008178
def args(self): """Tuple containing `label_or_index` as its only element.""" if self.space.has_basis or isinstance(self.label, SymbolicLabelBase): return (self.label, ) else: return (self.index, )
[ "def", "args", "(", "self", ")", ":", "if", "self", ".", "space", ".", "has_basis", "or", "isinstance", "(", "self", ".", "label", ",", "SymbolicLabelBase", ")", ":", "return", "(", "self", ".", "label", ",", ")", "else", ":", "return", "(", "self", ...
39.833333
0.008197
def build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: """Build an edge predicate that passes for edges for which one of the given nodes is the subject.""" nodes = set(nodes) def downstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool: """Pass fo...
[ "def", "build_downstream_edge_predicate", "(", "nodes", ":", "Iterable", "[", "BaseEntity", "]", ")", "->", "EdgePredicate", ":", "nodes", "=", "set", "(", "nodes", ")", "def", "downstream_filter", "(", "graph", ":", "BELGraph", ",", "u", ":", "BaseEntity", ...
53.333333
0.010246
def create_folder(self, name, parent): '''Create a new folder. Args: name (srt): The name of the folder. parent (str): The UUID of the parent entity. The parent must be a project or a folder. Returns: A dictionary of details of the created fo...
[ "def", "create_folder", "(", "self", ",", "name", ",", "parent", ")", ":", "if", "not", "is_valid_uuid", "(", "parent", ")", ":", "raise", "StorageArgumentException", "(", "'Invalid UUID for parent: {0}'", ".", "format", "(", "parent", ")", ")", "return", "sel...
37.631579
0.001363
def save_params( self, f=None, f_params=None, f_optimizer=None, f_history=None): """Saves the module's parameters, history, and optimizer, not the whole object. To save the whole object, use pickle. ``f_params`` and ``f_optimizer`` uses PyTorchs' :func:`~torch.save`...
[ "def", "save_params", "(", "self", ",", "f", "=", "None", ",", "f_params", "=", "None", ",", "f_optimizer", "=", "None", ",", "f_history", "=", "None", ")", ":", "# TODO: Remove warning in a future release", "if", "f", "is", "not", "None", ":", "warnings", ...
39.203125
0.000778
def _methodInTraceback(self, name, traceback): ''' Returns boolean whether traceback contains method from this instance ''' foundMethod = False for frame in self._frames(traceback): this = frame.f_locals.get('self') if this is self and frame.f_code.co_name == name: foundMethod = ...
[ "def", "_methodInTraceback", "(", "self", ",", "name", ",", "traceback", ")", ":", "foundMethod", "=", "False", "for", "frame", "in", "self", ".", "_frames", "(", "traceback", ")", ":", "this", "=", "frame", ".", "f_locals", ".", "get", "(", "'self'", ...
31.909091
0.00831
def replicaStatus(self, url): """gets the replica status when exported async set to True""" params = {"f" : "json"} url = url + "/status" return self._get(url=url, param_dict=params, securityHandler=self._securityHandler, ...
[ "def", "replicaStatus", "(", "self", ",", "url", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "url", "=", "url", "+", "\"/status\"", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "securi...
45.888889
0.016627
def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): """tickOptionComputation(EWrapper self, TickerId tickerId, TickType tickType, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, ...
[ "def", "tickOptionComputation", "(", "self", ",", "tickerId", ",", "tickType", ",", "impliedVol", ",", "delta", ",", "optPrice", ",", "pvDividend", ",", "gamma", ",", "vega", ",", "theta", ",", "undPrice", ")", ":", "return", "_swigibpy", ".", "EWrapper_tick...
163.333333
0.010163
def set_ratio(self, new_ratio): """Set a new conversion ratio immediately.""" from samplerate.lowlevel import src_set_ratio return src_set_ratio(self._state, new_ratio)
[ "def", "set_ratio", "(", "self", ",", "new_ratio", ")", ":", "from", "samplerate", ".", "lowlevel", "import", "src_set_ratio", "return", "src_set_ratio", "(", "self", ".", "_state", ",", "new_ratio", ")" ]
47.25
0.010417
def bin1d(x, bins): """ Place values of a 1-d array into bins and determine counts of values in each bin Parameters ---------- x : array (n, 1), values to bin bins : array (k,1), upper bounds of each bin (monotonic) Returns ------- binIds : array ...
[ "def", "bin1d", "(", "x", ",", "bins", ")", ":", "left", "=", "[", "-", "float", "(", "\"inf\"", ")", "]", "left", ".", "extend", "(", "bins", "[", "0", ":", "-", "1", "]", ")", "right", "=", "bins", "cuts", "=", "list", "(", "zip", "(", "l...
28.3125
0.000711
def _request_login(self, login, password): """Sends Login request""" return self._request_internal("Login", login=login, password=password)
[ "def", "_request_login", "(", "self", ",", "login", ",", "password", ")", ":", "return", "self", ".", "_request_internal", "(", "\"Login\"", ",", "login", "=", "login", ",", "password", "=", "password", ")" ]
45.4
0.008658
def create_switch(apps, schema_editor): """Create and activate the SAP_USE_ENTERPRISE_ENROLLMENT_PAGE switch if it does not already exist.""" Switch = apps.get_model('waffle', 'Switch') Switch.objects.get_or_create(name='SAP_USE_ENTERPRISE_ENROLLMENT_PAGE', defaults={'active': False})
[ "def", "create_switch", "(", "apps", ",", "schema_editor", ")", ":", "Switch", "=", "apps", ".", "get_model", "(", "'waffle'", ",", "'Switch'", ")", "Switch", ".", "objects", ".", "get_or_create", "(", "name", "=", "'SAP_USE_ENTERPRISE_ENROLLMENT_PAGE'", ",", ...
73.5
0.010101
def location_2_json(self): """ transform ariane_clip3 location object to Ariane server JSON obj :return: Ariane JSON obj """ LOGGER.debug("Location.location_2_json") json_obj = { 'locationID': self.id, 'locationName': self.name, 'locati...
[ "def", "location_2_json", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Location.location_2_json\"", ")", "json_obj", "=", "{", "'locationID'", ":", "self", ".", "id", ",", "'locationName'", ":", "self", ".", "name", ",", "'locationDescription'", ":",...
38.095238
0.002439
def getOperationName(self, ps, action): '''Returns operation name. action -- soapAction value ''' method = self.root.get(_get_element_nsuri_name(ps.body_root)) or \ self.soapAction.get(action) if method is None: raise UnknownRequestException, \ ...
[ "def", "getOperationName", "(", "self", ",", "ps", ",", "action", ")", ":", "method", "=", "self", ".", "root", ".", "get", "(", "_get_element_nsuri_name", "(", "ps", ".", "body_root", ")", ")", "or", "self", ".", "soapAction", ".", "get", "(", "action...
44.4
0.013245
def set_user_password(self, uid, mode='set_password', password=None): """Set user password and (modes) :param uid: id number of user. see: get_names_uid()['name'] :param mode: disable = disable user connections enable = enable user connections ...
[ "def", "set_user_password", "(", "self", ",", "uid", ",", "mode", "=", "'set_password'", ",", "password", "=", "None", ")", ":", "mode_mask", "=", "{", "'disable'", ":", "0", ",", "'enable'", ":", "1", ",", "'set_password'", ":", "2", ",", "'test_passwor...
35.326087
0.001198
def rebuildPolygons(self, path): """ Rebuilds the polygons that will be used on this path. :param path | <QPainterPath> :return <list> [ <QPolygonF>, .. ] """ output = [] # create the input arrow if self.showInputArrow(): ...
[ "def", "rebuildPolygons", "(", "self", ",", "path", ")", ":", "output", "=", "[", "]", "# create the input arrow", "if", "self", ".", "showInputArrow", "(", ")", ":", "if", "self", ".", "inputArrowStyle", "(", ")", "&", "self", ".", "ArrowStyle", ".", "I...
30.12069
0.002217
def combine_count_files(files, out_file=None, ext=".fpkm"): """ combine a set of count files into a single combined file """ files = list(files) if not files: return None assert all([file_exists(x) for x in files]), \ "Some count files in %s do not exist." % files for f in fi...
[ "def", "combine_count_files", "(", "files", ",", "out_file", "=", "None", ",", "ext", "=", "\".fpkm\"", ")", ":", "files", "=", "list", "(", "files", ")", "if", "not", "files", ":", "return", "None", "assert", "all", "(", "[", "file_exists", "(", "x", ...
34.923077
0.000714
def ndto2d(x, axis=-1): """Convert a multi-dimensional array into a 2d array, with the axes specified by the `axis` parameter flattened into an index along rows, and the remaining axes flattened into an index along the columns. This operation can not be properly achieved by a simple reshape operatio...
[ "def", "ndto2d", "(", "x", ",", "axis", "=", "-", "1", ")", ":", "# Convert int axis into a tuple", "if", "isinstance", "(", "axis", ",", "int", ")", ":", "axis", "=", "(", "axis", ",", ")", "# Handle negative axis indices", "axis", "=", "tuple", "(", "[...
37.680851
0.00055
def setup(): """ Creates shared and upload directory then fires setup to recipes. """ init_tasks() run_hook("before_setup") # Create shared folder env.run("mkdir -p %s" % (paths.get_shared_path())) env.run("chmod 755 %s" % (paths.get_shared_path())) # Create backup folder env...
[ "def", "setup", "(", ")", ":", "init_tasks", "(", ")", "run_hook", "(", "\"before_setup\"", ")", "# Create shared folder", "env", ".", "run", "(", "\"mkdir -p %s\"", "%", "(", "paths", ".", "get_shared_path", "(", ")", ")", ")", "env", ".", "run", "(", "...
25.73913
0.001629
def from_text(cls, text: str): """ Construct an AnalysisGraph object from text, using Eidos to perform machine reading. """ eidosProcessor = process_text(text) return cls.from_statements(eidosProcessor.statements)
[ "def", "from_text", "(", "cls", ",", "text", ":", "str", ")", ":", "eidosProcessor", "=", "process_text", "(", "text", ")", "return", "cls", ".", "from_statements", "(", "eidosProcessor", ".", "statements", ")" ]
40.166667
0.00813
def determine_num_chunks(chunk_size, file_size): """ Figure out how many pieces we are sending the file in. NOTE: duke-data-service requires an empty chunk to be uploaded for empty files. """ if file_size == 0: return 1 return int(math.ceil(float(file_size) / ...
[ "def", "determine_num_chunks", "(", "chunk_size", ",", "file_size", ")", ":", "if", "file_size", "==", "0", ":", "return", "1", "return", "int", "(", "math", ".", "ceil", "(", "float", "(", "file_size", ")", "/", "float", "(", "chunk_size", ")", ")", "...
41.5
0.00885
def delete_all_thumbnails(path, recursive=True): """ Delete all files within a path which match the thumbnails pattern. By default, matching files from all sub-directories are also removed. To only remove from the path directory, set recursive=False. """ total = 0 for thumbs in all_thumbnai...
[ "def", "delete_all_thumbnails", "(", "path", ",", "recursive", "=", "True", ")", ":", "total", "=", "0", "for", "thumbs", "in", "all_thumbnails", "(", "path", ",", "recursive", "=", "recursive", ")", ".", "values", "(", ")", ":", "total", "+=", "_delete_...
37.909091
0.002342
def _run_command(self, env): """ Run command(s) and return output and urgency. """ output = "" urgent = False # run the block/command for command in self.commands: try: process = Popen( command, s...
[ "def", "_run_command", "(", "self", ",", "env", ")", ":", "output", "=", "\"\"", "urgent", "=", "False", "# run the block/command", "for", "command", "in", "self", ".", "commands", ":", "try", ":", "process", "=", "Popen", "(", "command", ",", "stdout", ...
38.5625
0.002107
def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None): """ Perform trajectory based re-sampling. Parameters ---------- dtrajs : list of discrete trajectories lag : int lag time N_full : int Number of states in discrete trajectories. nbs : int, optio...
[ "def", "bootstrapping_dtrajs", "(", "dtrajs", ",", "lag", ",", "N_full", ",", "nbs", "=", "10000", ",", "active_set", "=", "None", ")", ":", "# Get the number of simulations:", "Q", "=", "len", "(", "dtrajs", ")", "# Get the number of states in the active set:", "...
29.328358
0.000985
def is45(msg): """Check if a message is likely to be BDS code 4,5. Meteorological hazard report Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False """ if allzeros(msg): return False d = hex2bin(data(msg)) # status bit 1, 4, ...
[ "def", "is45", "(", "msg", ")", ":", "if", "allzeros", "(", "msg", ")", ":", "return", "False", "d", "=", "hex2bin", "(", "data", "(", "msg", ")", ")", "# status bit 1, 4, 7, 10, 13, 16, 27, 39", "if", "wrongstatus", "(", "d", ",", "1", ",", "2", ",", ...
17.673077
0.001031
def set_initial_status(self, response): """Process first response after initiating long running operation and set self.status attribute. :param requests.Response response: initial REST call response. """ self._raise_if_bad_http_status_and_method(response) if self._is_em...
[ "def", "set_initial_status", "(", "self", ",", "response", ")", ":", "self", ".", "_raise_if_bad_http_status_and_method", "(", "response", ")", "if", "self", ".", "_is_empty", "(", "response", ")", ":", "self", ".", "resource", "=", "None", "else", ":", "try...
39.647059
0.002172
def parse_cigar(cigar): """ parse cigar string into list of operations e.g.: 28M1I29M2I6M1I46M -> [['28', 'M'], ['1', 'I'], ['29', 'M'], ['2', 'I'], ['6', 'M'], ['1', 'I'], ['46', 'M']] """ cigar = cigar.replace('M', 'M ').replace('I', 'I ').replace('D', 'D ').split() cigar = [c.replac...
[ "def", "parse_cigar", "(", "cigar", ")", ":", "cigar", "=", "cigar", ".", "replace", "(", "'M'", ",", "'M '", ")", ".", "replace", "(", "'I'", ",", "'I '", ")", ".", "replace", "(", "'D'", ",", "'D '", ")", ".", "split", "(", ")", "cigar", "=", ...
48
0.009091
async def disconnect(self): """Disconnect this interface.""" self._data = await self._handler.disconnect( system_id=self.node.system_id, id=self.id)
[ "async", "def", "disconnect", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "disconnect", "(", "system_id", "=", "self", ".", "node", ".", "system_id", ",", "id", "=", "self", ".", "id", ")" ]
43.25
0.011364
def plotMDS(inputFileName, outPrefix, populationFileName, options): """Plots the MDS value. :param inputFileName: the name of the ``mds`` file. :param outPrefix: the prefix of the output files. :param populationFileName: the name of the population file. :param options: the options :type inputF...
[ "def", "plotMDS", "(", "inputFileName", ",", "outPrefix", ",", "populationFileName", ",", "options", ")", ":", "# The options", "plotMDS_options", "=", "Dummy", "(", ")", "plotMDS_options", ".", "file", "=", "inputFileName", "plotMDS_options", ".", "out", "=", "...
36.472727
0.000485
def get(self, request, bot_id, id, format=None): """ Get hook by id --- serializer: HookSerializer responseMessages: - code: 401 message: Not authenticated """ return super(HookDetail, self).get(request, bot_id, id, format)
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "HookDetail", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
30.4
0.009585
def constcase(text, acronyms=None): """Return text in CONST_CASE style (aka SCREAMING_SNAKE_CASE). Args: text: input string to convert case detect_acronyms: should attempt to detect acronyms acronyms: a list of acronyms to detect >>> constcase("hello world") 'HELLO_WORLD' >...
[ "def", "constcase", "(", "text", ",", "acronyms", "=", "None", ")", ":", "words", ",", "_case", ",", "_sep", "=", "case_parse", ".", "parse_case", "(", "text", ",", "acronyms", ")", "return", "'_'", ".", "join", "(", "[", "w", ".", "upper", "(", ")...
32.933333
0.001969
def forward(self, input): """Feed-forward through the network.""" return th.nn.functional.linear(input, self.weight.div(self.weight.pow(2).sum(0).sqrt()))
[ "def", "forward", "(", "self", ",", "input", ")", ":", "return", "th", ".", "nn", ".", "functional", ".", "linear", "(", "input", ",", "self", ".", "weight", ".", "div", "(", "self", ".", "weight", ".", "pow", "(", "2", ")", ".", "sum", "(", "0...
56
0.017647
def detection(reference_tempi, reference_weight, estimated_tempi, tol=0.08): """Compute the tempo detection accuracy metric. Parameters ---------- reference_tempi : np.ndarray, shape=(2,) Two non-negative reference tempi reference_weight : float > 0 The relative strength of ``refer...
[ "def", "detection", "(", "reference_tempi", ",", "reference_weight", ",", "estimated_tempi", ",", "tol", "=", "0.08", ")", ":", "validate", "(", "reference_tempi", ",", "reference_weight", ",", "estimated_tempi", ")", "if", "tol", "<", "0", "or", "tol", ">", ...
29.101449
0.000482
def initialize_hooks(self): """ Create SessionRunHooks for all callbacks, and hook it onto `self.sess` to create `self.hooked_sess`. A new trainer may override this method to create multiple groups of hooks, which can be useful when the training is not done by a single `train_op`. ...
[ "def", "initialize_hooks", "(", "self", ")", ":", "hooks", "=", "self", ".", "_callbacks", ".", "get_hooks", "(", ")", "self", ".", "hooked_sess", "=", "tfv1", ".", "train", ".", "MonitoredSession", "(", "session_creator", "=", "ReuseSessionCreator", "(", "s...
49
0.01002
def is_webdriver_ios(webdriver): """ Check if a web driver if mobile. Args: webdriver (WebDriver): Selenium webdriver. """ browser = webdriver.capabilities['browserName'] if (browser == u('iPhone') or browser == u('iPad')): return T...
[ "def", "is_webdriver_ios", "(", "webdriver", ")", ":", "browser", "=", "webdriver", ".", "capabilities", "[", "'browserName'", "]", "if", "(", "browser", "==", "u", "(", "'iPhone'", ")", "or", "browser", "==", "u", "(", "'iPad'", ")", ")", ":", "return",...
23.2
0.01105
def append(self, tag): ''' append - Append an item to this tag collection @param tag - an AdvancedTag ''' list.append(self, tag) self.uids.add(tag.uid)
[ "def", "append", "(", "self", ",", "tag", ")", ":", "list", ".", "append", "(", "self", ",", "tag", ")", "self", ".", "uids", ".", "add", "(", "tag", ".", "uid", ")" ]
25.125
0.009615
def run(quiet, args): """Run a local command. Examples: $ django run manage.py runserver ... """ if not args: raise ClickException('pass a command to run') cmd = ' '.join(args) application = get_current_application() name = application.name settings = os.environ.get('...
[ "def", "run", "(", "quiet", ",", "args", ")", ":", "if", "not", "args", ":", "raise", "ClickException", "(", "'pass a command to run'", ")", "cmd", "=", "' '", ".", "join", "(", "args", ")", "application", "=", "get_current_application", "(", ")", "name", ...
21.2
0.001805
def write_sample(binary, payload, path, filename): # pragma: no cover """ This function writes a sample on file system. Args: binary (bool): True if it's a binary file payload: payload of sample, in base64 if it's a binary path (string): path of file filename (string): name...
[ "def", "write_sample", "(", "binary", ",", "payload", ",", "path", ",", "filename", ")", ":", "# pragma: no cover", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "makedirs", "(", "path", ")", "sample", "=", "os", "....
28.545455
0.001541
def parse(self): """ This method parses the raw email and makes the tokens. Returns: Instance of MailParser with raw email parsed """ if not self.message: return self # reset and start parsing self._reset() parts = [] # Normal p...
[ "def", "parse", "(", "self", ")", ":", "if", "not", "self", ".", "message", ":", "return", "self", "# reset and start parsing", "self", ".", "_reset", "(", ")", "parts", "=", "[", "]", "# Normal parts plus defects", "# walk all mail parts to search defects", "for"...
42.346939
0.000471
def resource_request_encode(self, request_id, uri_type, uri, transfer_type, storage): ''' The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI con...
[ "def", "resource_request_encode", "(", "self", ",", "request_id", ",", "uri_type", ",", "uri", ",", "transfer_type", ",", "storage", ")", ":", "return", "MAVLink_resource_request_message", "(", "request_id", ",", "uri_type", ",", "uri", ",", "transfer_type", ",", ...
83.769231
0.009083
def get_tournament(self, tag: crtag, timeout=0): """Get a tournament information Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV \*\*timeout: Optional[int] = None Custom timeout that ov...
[ "def", "get_tournament", "(", "self", ",", "tag", ":", "crtag", ",", "timeout", "=", "0", ")", ":", "url", "=", "self", ".", "api", ".", "TOURNAMENT", "+", "'/'", "+", "tag", "return", "self", ".", "_get_model", "(", "url", ",", "PartialTournament", ...
35.461538
0.008457
def get_user_settings_module(project_root: str): """Return project-specific user settings module, if it exists. :param project_root: Absolute path to project root directory. A project settings file is a file named `YSETTINGS_FILE` found at the top level of the project root dir. Return `None` if p...
[ "def", "get_user_settings_module", "(", "project_root", ":", "str", ")", ":", "if", "project_root", ":", "project_settings_file", "=", "os", ".", "path", ".", "join", "(", "project_root", ",", "YSETTINGS_FILE", ")", "if", "os", ".", "path", ".", "isfile", "(...
44.53125
0.000687
def remove_element(self, e): """Remove element `e` from model """ if e.label is not None: self.elementdict.pop(e.label) self.elementlist.remove(e)
[ "def", "remove_element", "(", "self", ",", "e", ")", ":", "if", "e", ".", "label", "is", "not", "None", ":", "self", ".", "elementdict", ".", "pop", "(", "e", ".", "label", ")", "self", ".", "elementlist", ".", "remove", "(", "e", ")" ]
30.333333
0.02139
def evaluate_parameter_sets(self): """ This takes the parameter sets of the model instance and evaluates any formulas using the parameter values to create a fixed, full set of parameters for each parameter set in the model """ #parameter_interpreter = ParameterInterpreter(self....
[ "def", "evaluate_parameter_sets", "(", "self", ")", ":", "#parameter_interpreter = ParameterInterpreter(self.modelInstance)", "#parameter_interpreter.evaluate_parameter_sets()", "self", ".", "parameter_interpreter", "=", "LcoptParameterSet", "(", "self", ".", "modelInstance", ")", ...
59.545455
0.013534
def __get_cmd_table_options(cmd_line_options): """ Get all table options from the command line :type cmd_line_options: dict :param cmd_line_options: Dictionary with all command line options :returns: dict -- E.g. {'table_name': {}} """ table_name = cmd_line_options['table_name'] options = {...
[ "def", "__get_cmd_table_options", "(", "cmd_line_options", ")", ":", "table_name", "=", "cmd_line_options", "[", "'table_name'", "]", "options", "=", "{", "table_name", ":", "{", "}", "}", "for", "option", "in", "DEFAULT_OPTIONS", "[", "'table'", "]", ".", "ke...
33.470588
0.001709
def _evalWeekday(self, datetimeString, sourceTime): """ Evaluate text passed by L{_partialParseWeekday()} """ s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is a weekday yr, mth, dy, hr, mn, sec, wd, yd, isdst = so...
[ "def", "_evalWeekday", "(", "self", ",", "datetimeString", ",", "sourceTime", ")", ":", "s", "=", "datetimeString", ".", "strip", "(", ")", "sourceTime", "=", "self", ".", "_evalDT", "(", "datetimeString", ",", "sourceTime", ")", "# Given string is a weekday", ...
39.36
0.001984
def is_edge(obj, shape): """ Check if a 2d object is on the edge of the array. Parameters ---------- obj : tuple(slice, slice) Pair of slices (e.g. from scipy.ndimage.measurements.find_objects) shape : tuple(int, int) Array shape. Returns ------- b : boolean ...
[ "def", "is_edge", "(", "obj", ",", "shape", ")", ":", "if", "obj", "[", "0", "]", ".", "start", "==", "0", ":", "return", "True", "if", "obj", "[", "1", "]", ".", "start", "==", "0", ":", "return", "True", "if", "obj", "[", "0", "]", ".", "...
25.045455
0.008741
def weights_multi_problem_input(labels, taskid=-1): """Assign weight 1.0 to only the inputs for the given task.""" taskid = check_nonnegative(taskid) weights_all_tokens = weights_multi_problem_all(labels, taskid) weights_target = weights_multi_problem(labels, taskid) return weights_all_tokens - weights_target
[ "def", "weights_multi_problem_input", "(", "labels", ",", "taskid", "=", "-", "1", ")", ":", "taskid", "=", "check_nonnegative", "(", "taskid", ")", "weights_all_tokens", "=", "weights_multi_problem_all", "(", "labels", ",", "taskid", ")", "weights_target", "=", ...
52.5
0.01875
def print_message(self, message, verbosity_needed=1): """ Prints the message, if verbosity is high enough. """ if self.args.verbosity >= verbosity_needed: print(message)
[ "def", "print_message", "(", "self", ",", "message", ",", "verbosity_needed", "=", "1", ")", ":", "if", "self", ".", "args", ".", "verbosity", ">=", "verbosity_needed", ":", "print", "(", "message", ")" ]
48.5
0.010152
def parse_command(bot: NoneBot, cmd_string: str) -> Tuple[Optional[Command], Optional[str]]: """ Parse a command string (typically from a message). :param bot: NoneBot instance :param cmd_string: command string :return: (Command object, current arg string) """ logger.debug...
[ "def", "parse_command", "(", "bot", ":", "NoneBot", ",", "cmd_string", ":", "str", ")", "->", "Tuple", "[", "Optional", "[", "Command", "]", ",", "Optional", "[", "str", "]", "]", ":", "logger", ".", "debug", "(", "f'Parsing command: {cmd_string}'", ")", ...
35.171429
0.000395
def make_psrrates(pkllist, nbins=60, period=0.156): """ Visualize cands in set of pkl files from pulsar observations. Input pkl list assumed to start with on-axis pulsar scan, followed by off-axis scans. nbins for output histogram. period is pulsar period in seconds (used to find single peak for cluster of ...
[ "def", "make_psrrates", "(", "pkllist", ",", "nbins", "=", "60", ",", "period", "=", "0.156", ")", ":", "# get metadata", "state", "=", "pickle", ".", "load", "(", "open", "(", "pkllist", "[", "0", "]", ",", "'r'", ")", ")", "# assume single state for al...
37.716216
0.008031
def _name_scope(self, name=None, default_name=None, values=None): """Helper function to standardize op scope.""" with tf.compat.v1.name_scope(self.name): with tf.compat.v1.name_scope( name, default_name, values=values or []) as scope: yield scope
[ "def", "_name_scope", "(", "self", ",", "name", "=", "None", ",", "default_name", "=", "None", ",", "values", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v1", ".", "name_scope", "(", "self", ".", "name", ")", ":", "with", "tf", ".", ...
45.5
0.010791
def get_daterange(self, dataset): """The method is getting information about date range of dataset""" path = '/api/1.0/meta/dataset/{}/daterange' return self._api_get(definition.DateRange, path.format(dataset))
[ "def", "get_daterange", "(", "self", ",", "dataset", ")", ":", "path", "=", "'/api/1.0/meta/dataset/{}/daterange'", "return", "self", ".", "_api_get", "(", "definition", ".", "DateRange", ",", "path", ".", "format", "(", "dataset", ")", ")" ]
47
0.008368
def identify_segments(self): """ Find all the segments in the triangulation and return an array of vertices (n1,n2) where n1 < n2 """ lst = self.lst lend = self.lend lptr = self.lptr segments_array = np.empty((len(lptr),2),dtype=np.int) segments...
[ "def", "identify_segments", "(", "self", ")", ":", "lst", "=", "self", ".", "lst", "lend", "=", "self", ".", "lend", "lptr", "=", "self", ".", "lptr", "segments_array", "=", "np", ".", "empty", "(", "(", "len", "(", "lptr", ")", ",", "2", ")", ",...
30.166667
0.017857
def get_canvas_xy(self, data_x, data_y, center=None): """Reverse of :meth:`get_data_xy`. """ if center is not None: self.logger.warning("`center` keyword is ignored and will be deprecated") arr_pts = np.asarray((data_x, data_y)).T return self.tform['data_to_native']...
[ "def", "get_canvas_xy", "(", "self", ",", "data_x", ",", "data_y", ",", "center", "=", "None", ")", ":", "if", "center", "is", "not", "None", ":", "self", ".", "logger", ".", "warning", "(", "\"`center` keyword is ignored and will be deprecated\"", ")", "arr_p...
36.777778
0.00885
def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True return self.freshness() - freshness <= self.expire_after
[ "def", "is_fresh", "(", "self", ",", "freshness", ")", ":", "if", "self", ".", "expire_after", "is", "None", ":", "return", "True", "return", "self", ".", "freshness", "(", ")", "-", "freshness", "<=", "self", ".", "expire_after" ]
45.8
0.008584
def babel_compile(source, **kwargs): """Compiles the given ``source`` from ES6 to ES5 using Babeljs""" presets = kwargs.get('presets') if not presets: kwargs['presets'] = ["es2015"] with open(BABEL_COMPILER, 'rb') as babel_js: return evaljs( (babel_js.read().decode('utf-8'), ...
[ "def", "babel_compile", "(", "source", ",", "*", "*", "kwargs", ")", ":", "presets", "=", "kwargs", ".", "get", "(", "'presets'", ")", "if", "not", "presets", ":", "kwargs", "[", "'presets'", "]", "=", "[", "\"es2015\"", "]", "with", "open", "(", "BA...
38.571429
0.001808
def appliances_path(self): """ Get the image storage directory """ server_config = Config.instance().get_section_config("Server") appliances_path = os.path.expanduser(server_config.get("appliances_path", "~/GNS3/projects")) os.makedirs(appliances_path, exist_ok=True) ...
[ "def", "appliances_path", "(", "self", ")", ":", "server_config", "=", "Config", ".", "instance", "(", ")", ".", "get_section_config", "(", "\"Server\"", ")", "appliances_path", "=", "os", ".", "path", ".", "expanduser", "(", "server_config", ".", "get", "("...
42.375
0.008671
def transform_txn_for_ledger(txn): """ Some transactions need to be transformed before they can be stored in the ledger, eg. storing certain payload in another data store and only its hash in the ledger """ if get_type(txn) == ATTRIB: txn = DomainReqHandler.tr...
[ "def", "transform_txn_for_ledger", "(", "txn", ")", ":", "if", "get_type", "(", "txn", ")", "==", "ATTRIB", ":", "txn", "=", "DomainReqHandler", ".", "transform_attrib_for_ledger", "(", "txn", ")", "return", "txn" ]
40.111111
0.00813
def get_components(self, other): """ Break this vector into one vector that is perpendicular to the given vector and another that is parallel to it. """ tangent = self.get_projection(other) normal = self - tangent return normal, tangent
[ "def", "get_components", "(", "self", ",", "other", ")", ":", "tangent", "=", "self", ".", "get_projection", "(", "other", ")", "normal", "=", "self", "-", "tangent", "return", "normal", ",", "tangent" ]
45.333333
0.01083
def reboot(env, identifier, hard): """Reboot an active server.""" hardware_server = env.client['Hardware_Server'] mgr = SoftLayer.HardwareManager(env.client) hw_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'hardware') if not (env.skip_confirmations or formatting.confirm('This wi...
[ "def", "reboot", "(", "env", ",", "identifier", ",", "hard", ")", ":", "hardware_server", "=", "env", ".", "client", "[", "'Hardware_Server'", "]", "mgr", "=", "SoftLayer", ".", "HardwareManager", "(", "env", ".", "client", ")", "hw_id", "=", "helpers", ...
37.352941
0.001536
def db_get(table, record, column, if_exists=False): ''' Gets a column's value for a specific record. Args: table: A string - name of the database table. record: A string - identifier of the record. column: A string - name of the column. if_exists: A boolean - if True, it is ...
[ "def", "db_get", "(", "table", ",", "record", ",", "column", ",", "if_exists", "=", "False", ")", ":", "cmd", "=", "[", "'ovs-vsctl'", ",", "'--format=json'", ",", "'--columns={0}'", ".", "format", "(", "column", ")", "]", "if", "if_exists", ":", "cmd", ...
30.225806
0.001034
def file_transfer_protocol_encode(self, target_network, target_system, target_component, payload): ''' File transfer message target_network : Network ID (0 for broadcast) (uint8_t) target_system : System ID (0 for broadcast) (uint8_...
[ "def", "file_transfer_protocol_encode", "(", "self", ",", "target_network", ",", "target_system", ",", "target_component", ",", "payload", ")", ":", "return", "MAVLink_file_transfer_protocol_message", "(", "target_network", ",", "target_system", ",", "target_component", "...
85.727273
0.008395
def set_timezone(data, tz=None, from_local=False): """ change the timeozone to specified one without converting """ # pandas object? if isinstance(data, pd.DataFrame) | isinstance(data, pd.Series): try: try: data.index = data.index.tz_convert(tz) except Except...
[ "def", "set_timezone", "(", "data", ",", "tz", "=", "None", ",", "from_local", "=", "False", ")", ":", "# pandas object?", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", "|", "isinstance", "(", "data", ",", "pd", ".", "Series", ")",...
32.586207
0.001028
def on_change_zijd_mouse_cursor(self, event): """ If mouse is over data point making it selectable change the shape of the cursor Parameters ---------- event : the wx Mouseevent for that click """ if not array(self.CART_rot).any(): return ...
[ "def", "on_change_zijd_mouse_cursor", "(", "self", ",", "event", ")", ":", "if", "not", "array", "(", "self", ".", "CART_rot", ")", ".", "any", "(", ")", ":", "return", "pos", "=", "event", ".", "GetPosition", "(", ")", "width", ",", "height", "=", "...
38.151515
0.001549
def mpfr_floordiv(rop, x, y, rnd): """ Given two MPFR numbers x and y, compute floor(x / y), rounded if necessary using the given rounding mode. The result is placed in 'rop'. """ # Algorithm notes # --------------- # A simple and obvious approach is to compute floor(x / y) exactly, and ...
[ "def", "mpfr_floordiv", "(", "rop", ",", "x", ",", "y", ",", "rnd", ")", ":", "# Algorithm notes", "# ---------------", "# A simple and obvious approach is to compute floor(x / y) exactly, and", "# then round to the nearest representable value using the given rounding", "# mode. Thi...
38.020408
0.000262
def get_scaled_cutout_wdhtdp_view(shp, p1, p2, new_dims): """ Like get_scaled_cutout_wdht, but returns the view/slice to extract from an image instead of the extraction itself. """ x1, y1, z1 = p1 x2, y2, z2 = p2 new_wd, new_ht, new_dp = new_dims x1, y1, x2, y2 = int(x1), int(y1), int(x...
[ "def", "get_scaled_cutout_wdhtdp_view", "(", "shp", ",", "p1", ",", "p2", ",", "new_dims", ")", ":", "x1", ",", "y1", ",", "z1", "=", "p1", "x2", ",", "y2", ",", "z2", "=", "p2", "new_wd", ",", "new_ht", ",", "new_dp", "=", "new_dims", "x1", ",", ...
42.314815
0.001711
def get_edge_evidence(self, u: BaseEntity, v: BaseEntity, key: str) -> Optional[str]: """Get the evidence for a given edge.""" return self._get_edge_attr(u, v, key, EVIDENCE)
[ "def", "get_edge_evidence", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "return", "self", ".", "_get_edge_attr", "(", "u", ",", "v", ",", "key", ",", "E...
62.666667
0.015789
def propagate(w, b, X, Y): """ Implement the cost function and its gradient for the propagation Arguments: w weights, a numpy array of size (dim, 1) b bias, a scalar X data of size (dim, number of examples) Y true "label" vector of size (1, number of examples) R...
[ "def", "propagate", "(", "w", ",", "b", ",", "X", ",", "Y", ")", ":", "m", "=", "X", ".", "shape", "[", "1", "]", "A", "=", "sigmoid", "(", "np", ".", "dot", "(", "w", ".", "T", ",", "X", ")", "+", "b", ")", "cost", "=", "-", "1", "/"...
28.69697
0.001021
def generate_targets(self, local_go_targets=None): """Generate Go targets in memory to form a complete Go graph. :param local_go_targets: The local Go targets to fill in a complete target graph for. If `None`, then all local Go targets under the Go source root are used. :type ...
[ "def", "generate_targets", "(", "self", ",", "local_go_targets", "=", "None", ")", ":", "# TODO(John Sirois): support multiple source roots like GOPATH does?", "# The GOPATH's 1st element is read-write, the rest are read-only; ie: their sources build to", "# the 1st element's pkg/ and bin/ d...
54.746479
0.00834
def parse(readDataInstance): """ Returns a new L{ImageBaseRelocationEntry} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to parse as a L{ImageBaseRelocationEntry} object. @rtype: L{ImageBaseRelocationEntry} ...
[ "def", "parse", "(", "readDataInstance", ")", ":", "reloc", "=", "ImageBaseRelocationEntry", "(", ")", "reloc", ".", "virtualAddress", ".", "value", "=", "readDataInstance", ".", "readDword", "(", ")", "reloc", ".", "sizeOfBlock", ".", "value", "=", "readDataI...
45.75
0.008032
def infer(self, context=None, **kwargs): """Get a generator of the inferred values. This is the main entry point to the inference system. .. seealso:: :ref:`inference` If the instance has some explicit inference function set, it will be called instead of the default interface....
[ "def", "infer", "(", "self", ",", "context", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "context", "is", "not", "None", ":", "context", "=", "context", ".", "extra_context", ".", "get", "(", "self", ",", "context", ")", "if", "self", "."...
36.78125
0.002483
def list(self, page: int = None, pageSize: int = None, search: str = None, workspaceId: str = None) -> dict: """ Retrieves a list of JSON descriptions for all forms in your Typeform account (public and private). Forms are listed in reverse-chronological order based on the last date they were mod...
[ "def", "list", "(", "self", ",", "page", ":", "int", "=", "None", ",", "pageSize", ":", "int", "=", "None", ",", "search", ":", "str", "=", "None", ",", "workspaceId", ":", "str", "=", "None", ")", "->", "dict", ":", "return", "self", ".", "__cli...
48.454545
0.009208
def set_error(scope, error_re=None): """ Defines a pattern that, whenever detected in the response of the remote host, causes an error to be raised. In other words, whenever Exscript waits for a prompt, it searches the response of the host for the given pattern and raises an error if the patter...
[ "def", "set_error", "(", "scope", ",", "error_re", "=", "None", ")", ":", "conn", "=", "scope", ".", "get", "(", "'__connection__'", ")", "conn", ".", "set_error_prompt", "(", "error_re", ")", "return", "True" ]
32.266667
0.002008
def on_backward_end(self, iteration:int, **kwargs)->None: "Callback function that writes backward end appropriate data to Tensorboard." if iteration == 0: return self._update_batches_if_needed() if iteration % self.stats_iters == 0: self._write_model_stats(iteration=iteration)
[ "def", "on_backward_end", "(", "self", ",", "iteration", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "iteration", "==", "0", ":", "return", "self", ".", "_update_batches_if_needed", "(", ")", "if", "iteration", "%", "self", ".", ...
61
0.02589
def scale_down(self, workers, pods=None): """ Remove the pods for the requested list of workers When scale_down is called by the _adapt async loop, the workers are assumed to have been cleanly closed first and in-memory data has been migrated to the remaining workers. Note that...
[ "def", "scale_down", "(", "self", ",", "workers", ",", "pods", "=", "None", ")", ":", "# Get the existing worker pods", "pods", "=", "pods", "or", "self", ".", "_cleanup_terminated_pods", "(", "self", ".", "pods", "(", ")", ")", "# Work out the list of pods that...
40.321429
0.00173