text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def tokenise_word(string, strict=False, replace=False, tones=False, unknown=False): """ Tokenise the string into a list of tokens or raise ValueError if it cannot be tokenised (relatively) unambiguously. The string should not include whitespace, i.e. it is assumed to be a single word. If strict=False, allow ...
[ "def", "tokenise_word", "(", "string", ",", "strict", "=", "False", ",", "replace", "=", "False", ",", "tones", "=", "False", ",", "unknown", "=", "False", ")", ":", "string", "=", "normalise", "(", "string", ")", "if", "replace", ":", "string", "=", ...
28.030769
24.461538
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Change Adapter Type (requires DPM mode).""" assert wait_for_completion is True # HMC operation is synchronous adapter_uri = uri.split('/operations/')[0] try: adapter ...
[ "def", "post", "(", "method", ",", "hmc", ",", "uri", ",", "uri_parms", ",", "body", ",", "logon_required", ",", "wait_for_completion", ")", ":", "assert", "wait_for_completion", "is", "True", "# HMC operation is synchronous", "adapter_uri", "=", "uri", ".", "sp...
41.98
16.84
def round(self, value_array): """ Rounds a categorical variable by setting to one the max of the given vector and to zero the rest of the entries. Assumes an 1x[number of categories] array (due to one-hot encoding) as an input """ rounded_values = np.zeros(value_array.shape) ...
[ "def", "round", "(", "self", ",", "value_array", ")", ":", "rounded_values", "=", "np", ".", "zeros", "(", "value_array", ".", "shape", ")", "rounded_values", "[", "np", ".", "argmax", "(", "value_array", ")", "]", "=", "1", "return", "rounded_values" ]
43.222222
23.444444
def roc_auc(model, X, y=None, ax=None, **kwargs): """ROCAUC Quick method: Receiver Operating Characteristic (ROC) curves are a measure of a classifier's predictive quality that compares and visualizes the tradeoff between the models' sensitivity and specificity. The ROC curve displays the true posi...
[ "def", "roc_auc", "(", "model", ",", "X", ",", "y", "=", "None", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Instantiate the visualizer", "visualizer", "=", "ROCAUC", "(", "model", ",", "ax", ",", "*", "*", "kwargs", ")", "# Create ...
43.809524
25.92381
def configure(project=LOGGING_PROJECT): """Configures cloud logging This is called for all main calls. If a $LOGGING_PROJECT is environment variable configured, then STDERR and STDOUT are redirected to cloud logging. """ if not project: sys.stderr.write('!! Error: The $LOGGING_PROJECT e...
[ "def", "configure", "(", "project", "=", "LOGGING_PROJECT", ")", ":", "if", "not", "project", ":", "sys", ".", "stderr", ".", "write", "(", "'!! Error: The $LOGGING_PROJECT enviroment '", "'variable is required in order to set up cloud logging. '", "'Cloud logging is disabled...
38.619048
21.285714
def reverse_translate( protein_seq, template_dna=None, leading_seq=None, trailing_seq=None, forbidden_seqs=(), include_stop=True, manufacturer=None): """ Generate a well-behaved DNA sequence from the given protein sequence. If a template DNA sequence is specified, the returned DNA ...
[ "def", "reverse_translate", "(", "protein_seq", ",", "template_dna", "=", "None", ",", "leading_seq", "=", "None", ",", "trailing_seq", "=", "None", ",", "forbidden_seqs", "=", "(", ")", ",", "include_stop", "=", "True", ",", "manufacturer", "=", "None", ")"...
40.5
24.576923
def total_size(self): """ Determine the size (in bytes) of this node. If an array, returns size of the entire array """ if self.inst.is_array: # Total size of arrays is technically supposed to be: # self.inst.array_stride * (self.inst.n_elements-1) + sel...
[ "def", "total_size", "(", "self", ")", ":", "if", "self", ".", "inst", ".", "is_array", ":", "# Total size of arrays is technically supposed to be:", "# self.inst.array_stride * (self.inst.n_elements-1) + self.size", "# However this opens up a whole slew of ugly corner cases that the...
42.466667
20.733333
def _getStickersTemplatesDirectory(self, resource_name): """Returns the paths for the directory containing the css and pt files for the stickers deppending on the filter_by_type. :param resource_name: The name of the resource folder. :type resource_name: string :returns: a strin...
[ "def", "_getStickersTemplatesDirectory", "(", "self", ",", "resource_name", ")", ":", "templates_dir", "=", "queryResourceDirectory", "(", "\"stickers\"", ",", "resource_name", ")", ".", "directory", "if", "self", ".", "filter_by_type", ":", "templates_dir", "=", "t...
43
15.538462
def _match_with_pandas(filtered, matcher): """Find matches in a set using Pandas' library.""" import pandas data = [fl.to_dict() for fl in filtered] if not data: return [] df = pandas.DataFrame(data) df = df.sort_values(['uuid']) cdfs = [] criteria = matcher.matching_criteri...
[ "def", "_match_with_pandas", "(", "filtered", ",", "matcher", ")", ":", "import", "pandas", "data", "=", "[", "fl", ".", "to_dict", "(", ")", "for", "fl", "in", "filtered", "]", "if", "not", "data", ":", "return", "[", "]", "df", "=", "pandas", ".", ...
24.193548
19.225806
def path_types(obj, path): """ Given a list of path name elements, return anew list of [name, type] path components, given the reference object. """ result = [] #for elem in path[:-1]: cur = obj for elem in path[:-1]: if ((issubclass(cur.__class__, MutableMapping) and elem in cur)): ...
[ "def", "path_types", "(", "obj", ",", "path", ")", ":", "result", "=", "[", "]", "#for elem in path[:-1]:", "cur", "=", "obj", "for", "elem", "in", "path", "[", ":", "-", "1", "]", ":", "if", "(", "(", "issubclass", "(", "cur", ".", "__class__", ",...
36.56
20.24
def _convert_1bit_array_to_byte_array(arr): """ Convert bit array to byte array. :param arr: list Bits as a list where each element is an integer of 0 or 1 Returns ------- numpy.array 1D numpy array of type uint8 """ # Padding if necessary while len(arr) < 8 or len(...
[ "def", "_convert_1bit_array_to_byte_array", "(", "arr", ")", ":", "# Padding if necessary", "while", "len", "(", "arr", ")", "<", "8", "or", "len", "(", "arr", ")", "%", "8", ":", "arr", ".", "append", "(", "0", ")", "arr", "=", "_np", ".", "array", ...
31.875
16.3125
def is_valid_port(instance: int): """Validates data is a valid port""" if not isinstance(instance, (int, str)): return True return int(instance) in range(65535)
[ "def", "is_valid_port", "(", "instance", ":", "int", ")", ":", "if", "not", "isinstance", "(", "instance", ",", "(", "int", ",", "str", ")", ")", ":", "return", "True", "return", "int", "(", "instance", ")", "in", "range", "(", "65535", ")" ]
35.2
6.4
def generate_annotations_json_string(source_path, only_simple=False): # type: (str, bool) -> List[FunctionData] """Produce annotation data JSON file from a JSON file with runtime-collected types. Data formats: * The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items. * The ...
[ "def", "generate_annotations_json_string", "(", "source_path", ",", "only_simple", "=", "False", ")", ":", "# type: (str, bool) -> List[FunctionData]", "items", "=", "parse_json", "(", "source_path", ")", "results", "=", "[", "]", "for", "item", "in", "items", ":", ...
37.043478
15.478261
def naive_grouped_rowwise_apply(data, group_labels, func, func_args=(), out=None): """ Simple implementation of grouped row-wise function application. Parameters ---------- ...
[ "def", "naive_grouped_rowwise_apply", "(", "data", ",", "group_labels", ",", "func", ",", "func_args", "=", "(", ")", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "np", ".", "empty_like", "(", "data", ")", "for", "("...
38.0625
15.520833
def _conditions(self, full_path, environ): """Return Etag and Last-Modified values defaults to now for both.""" magic = self._match_magic(full_path) if magic is not None: return magic.conditions(full_path, environ) else: mtime = stat(full_path).st_mtime ...
[ "def", "_conditions", "(", "self", ",", "full_path", ",", "environ", ")", ":", "magic", "=", "self", ".", "_match_magic", "(", "full_path", ")", "if", "magic", "is", "not", "None", ":", "return", "magic", ".", "conditions", "(", "full_path", ",", "enviro...
44.75
9.75
def counter(self, name, description, labels=None, **kwargs): """ Use a Counter to track the total number of invocations of the method. :param name: the name of the metric :param description: the description of the metric :param labels: a dictionary of `{labelname: callable_or_va...
[ "def", "counter", "(", "self", ",", "name", ",", "description", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_track", "(", "Counter", ",", "lambda", "metric", ",", "time", ":", "metric", ".", "inc", "(", ")...
37.4375
19.8125
def cudnnGetConvolutionForwardWorkspaceSize(handle, srcDesc, wDesc, convDesc, destDesc, algo): """" This function returns the amount of GPU memory workspace the user needs to allocate to be able to call cudnnConvolutionForward with the specified algorithm. Pa...
[ "def", "cudnnGetConvolutionForwardWorkspaceSize", "(", "handle", ",", "srcDesc", ",", "wDesc", ",", "convDesc", ",", "destDesc", ",", "algo", ")", ":", "sizeInBytes", "=", "ctypes", ".", "c_size_t", "(", ")", "status", "=", "_libcudnn", ".", "cudnnGetConvolution...
39.685714
22
def get_source(self, index, doc_type, id, **query_params): """ Get the _source of the document `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-get.html>`_ :param index: the index name :param doc_type: the document type :param id: the id of the doc ty...
[ "def", "get_source", "(", "self", ",", "index", ",", "doc_type", ",", "id", ",", "*", "*", "query_params", ")", ":", "self", ".", "_es_parser", ".", "is_not_empty_params", "(", "index", ",", "doc_type", ",", "id", ")", "path", "=", "self", ".", "_es_pa...
51.580645
18.16129
def readQword(self): """ Reads a qword value from the L{ReadData} stream object. @rtype: int @return: The qword value read from the L{ReadData} stream. """ qword = unpack(self.endianness + ('Q' if not self.signed else 'b'), self.readAt(self.offset, 8))[0] ...
[ "def", "readQword", "(", "self", ")", ":", "qword", "=", "unpack", "(", "self", ".", "endianness", "+", "(", "'Q'", "if", "not", "self", ".", "signed", "else", "'b'", ")", ",", "self", ".", "readAt", "(", "self", ".", "offset", ",", "8", ")", ")"...
35
22.6
def is_running(self) -> bool: """Return True if ffmpeg is running.""" if self._proc is None or self._proc.returncode is not None: return False return True
[ "def", "is_running", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_proc", "is", "None", "or", "self", ".", "_proc", ".", "returncode", "is", "not", "None", ":", "return", "False", "return", "True" ]
37.2
15
def local_replace(self, dt, use_dst=True, _recurse=False, **kwds): """Return pywws timestamp (utc, no tzinfo) for the most recent local time before the pywws timestamp dt, with datetime replace applied. """ local_time = dt + self.standard_offset if use_dst: d...
[ "def", "local_replace", "(", "self", ",", "dt", ",", "use_dst", "=", "True", ",", "_recurse", "=", "False", ",", "*", "*", "kwds", ")", ":", "local_time", "=", "dt", "+", "self", ".", "standard_offset", "if", "use_dst", ":", "dst_offset", "=", "self", ...
44.769231
14.192308
def load(trajfiles, features=None, top=None, stride=1, chunksize=None, **kw): r""" Loads coordinate features into memory. If your memory is not big enough consider the use of **pipeline**, or use the stride option to subsample the data. Parameters ---------- trajfiles : str, list of str or nes...
[ "def", "load", "(", "trajfiles", ",", "features", "=", "None", ",", "top", "=", "None", ",", "stride", "=", "1", ",", "chunksize", "=", "None", ",", "*", "*", "kw", ")", ":", "from", "pyemma", ".", "coordinates", ".", "data", ".", "util", ".", "r...
44.245283
26.622642
def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer): """Convert an SimpleRNN layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input ...
[ "def", "convert_simple_rnn", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "hidden_size", "=", "keras_layer", ".", "output_dim", "input_size", "=", "keras_layer", ".", "input_shape"...
32.125
16
def write_url (self, url_data): """Write url_data.base_url.""" self.writeln(u"<tr>") self.writeln(u'<td class="url">%s</td>' % self.part("url")) self.write(u'<td class="url">') self.write(u"`%s'" % cgi.escape(url_data.base_url)) self.writeln(u"</td></tr>")
[ "def", "write_url", "(", "self", ",", "url_data", ")", ":", "self", ".", "writeln", "(", "u\"<tr>\"", ")", "self", ".", "writeln", "(", "u'<td class=\"url\">%s</td>'", "%", "self", ".", "part", "(", "\"url\"", ")", ")", "self", ".", "write", "(", "u'<td ...
42.571429
10.285714
def check_case(institute_id, case_name): """Mark a case that is has been checked. This means to set case['needs_check'] to False """ institute_obj, case_obj = institute_and_case(store, institute_id, case_name) store.case_collection.find_one_and_update({'_id':case_obj['_id']}, {'$set': {'needs_che...
[ "def", "check_case", "(", "institute_id", ",", "case_name", ")", ":", "institute_obj", ",", "case_obj", "=", "institute_and_case", "(", "store", ",", "institute_id", ",", "case_name", ")", "store", ".", "case_collection", ".", "find_one_and_update", "(", "{", "'...
52.142857
17.142857
def acm_certificate_arn(self, lookup, default=None): """ Args: lookup: region/domain on the certificate to be looked up default: the optional value to return if lookup failed; returns None if not set Returns: ARN of a certificate with status "Issued" for the region/domain, if found, or def...
[ "def", "acm_certificate_arn", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "# @todo: Only searches the first 100 certificates in the account", "try", ":", "# This a region-specific client, so we'll make a new client in the right place using existing SESSION", "r...
49.809524
26.857143
def pinc(lat): """ calculate paleoinclination from latitude using dipole formula: tan(I) = 2tan(lat) Parameters ________________ lat : either a single value or an array of latitudes Returns ------- array of inclinations """ tanl = np.tan(np.radians(lat)) inc = np.arctan(2....
[ "def", "pinc", "(", "lat", ")", ":", "tanl", "=", "np", ".", "tan", "(", "np", ".", "radians", "(", "lat", ")", ")", "inc", "=", "np", ".", "arctan", "(", "2.", "*", "tanl", ")", "return", "np", ".", "degrees", "(", "inc", ")" ]
21.25
22.25
def default_52xhandler(response, resource, url, params): """ Default 52x handler that loops every second until a non 52x response is received. :param response: The response of the last executed api request. :param resource: The resource of the last executed api request. :param url: The url of the la...
[ "def", "default_52xhandler", "(", "response", ",", "resource", ",", "url", ",", "params", ")", ":", "time", ".", "sleep", "(", "1", ")", "return", "resource", ".", "execute", "(", "url", ",", "params", ")" ]
52.3
23.5
def _infodict(cls, name): """load the info dictionary for the given name""" info = cls._dataset_info.get(name, None) if info is None: raise ValueError('No such dataset {0} exists, ' 'use list_datasets() to get a list ' 'of ava...
[ "def", "_infodict", "(", "cls", ",", "name", ")", ":", "info", "=", "cls", ".", "_dataset_info", ".", "get", "(", "name", ",", "None", ")", "if", "info", "is", "None", ":", "raise", "ValueError", "(", "'No such dataset {0} exists, '", "'use list_datasets() t...
45.5
16.375
def extract_locals(trcback): """ Extracts the frames locals of given traceback. :param trcback: Traceback. :type trcback: Traceback :return: Frames locals. :rtype: list """ output = [] stack = extract_stack(get_inner_most_frame(trcback)) for frame, file_name, line_number, name,...
[ "def", "extract_locals", "(", "trcback", ")", ":", "output", "=", "[", "]", "stack", "=", "extract_stack", "(", "get_inner_most_frame", "(", "trcback", ")", ")", "for", "frame", ",", "file_name", ",", "line_number", ",", "name", ",", "context", ",", "index...
40.115385
21.423077
def connect(self): """ Returns a new socket connection to this server. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", self._port)) return sock
[ "def", "connect", "(", "self", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "connect", "(", "(", "\"127.0.0.1\"", ",", "self", ".", "_port", ")", ")", "return", "s...
39
14
def get_process_pids(self, process): """Returns PIDs of all processes with process name. If the process doesn't exist, returns an empty list""" pids = [] cmd_line_glob = "/proc/[0-9]*/cmdline" cmd_line_paths = glob.glob(cmd_line_glob) for path in cmd_line_paths: ...
[ "def", "get_process_pids", "(", "self", ",", "process", ")", ":", "pids", "=", "[", "]", "cmd_line_glob", "=", "\"/proc/[0-9]*/cmdline\"", "cmd_line_paths", "=", "glob", ".", "glob", "(", "cmd_line_glob", ")", "for", "path", "in", "cmd_line_paths", ":", "try",...
38.8
9.533333
async def _handle_conversation_delta(self, conversation): """Receive Conversation delta and create or update the conversation. Args: conversation: hangouts_pb2.Conversation instance Raises: NetworkError: A request to fetch the complete conversation failed. """ ...
[ "async", "def", "_handle_conversation_delta", "(", "self", ",", "conversation", ")", ":", "conv_id", "=", "conversation", ".", "conversation_id", ".", "id", "conv", "=", "self", ".", "_conv_dict", ".", "get", "(", "conv_id", ",", "None", ")", "if", "conv", ...
39.411765
19.588235
def install_hook(dialog=SimpleExceptionDialog, invoke_old_hook=False, **extra): """ install the configured exception hook wrapping the old exception hook don't use it twice :oparam dialog: a different exception dialog class :oparam invoke_old_hook: should we invoke the old exception hook? """ ...
[ "def", "install_hook", "(", "dialog", "=", "SimpleExceptionDialog", ",", "invoke_old_hook", "=", "False", ",", "*", "*", "extra", ")", ":", "global", "_old_hook", "assert", "_old_hook", "is", "None", "def", "new_hook", "(", "etype", ",", "eval", ",", "trace"...
31.473684
20.947368
def polygon(self, *coords, color="black", outline=False, outline_color="black"): """ Draws a polygon from an list of co-ordinates :param int *coords: Pairs of x and y positions which make up the polygon. :param str color: The color of the shape. Defaults to `"bl...
[ "def", "polygon", "(", "self", ",", "*", "coords", ",", "color", "=", "\"black\"", ",", "outline", "=", "False", ",", "outline_color", "=", "\"black\"", ")", ":", "return", "self", ".", "tk", ".", "create_polygon", "(", "*", "coords", ",", "outline", "...
33.88
23
def set_bucket_notification(self, bucket_name, notifications): """ Set the given notifications on the bucket. :param bucket_name: Bucket name. :param notifications: Notifications structure """ is_valid_bucket_name(bucket_name) is_valid_bucket_notification_config(...
[ "def", "set_bucket_notification", "(", "self", ",", "bucket_name", ",", "notifications", ")", ":", "is_valid_bucket_name", "(", "bucket_name", ")", "is_valid_bucket_notification_config", "(", "notifications", ")", "content", "=", "xml_marshal_bucket_notifications", "(", "...
33.5
15.416667
def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None): """Creates a new secondary zone. Arguments: account_name -- The name of the account. zone_name -- The name of the zone. master -- Primary name server IP address. Keyword Arg...
[ "def", "create_secondary_zone", "(", "self", ",", "account_name", ",", "zone_name", ",", "master", ",", "tsig_key", "=", "None", ",", "key_value", "=", "None", ")", ":", "zone_properties", "=", "{", "\"name\"", ":", "zone_name", ",", "\"accountName\"", ":", ...
48.666667
25.375
def get_group_headers(self, table_name, group_name): """ Return a list of all headers for a given group """ # get all headers of a particular group df = self.dm[table_name] cond = df['group'] == group_name return df[cond].index
[ "def", "get_group_headers", "(", "self", ",", "table_name", ",", "group_name", ")", ":", "# get all headers of a particular group", "df", "=", "self", ".", "dm", "[", "table_name", "]", "cond", "=", "df", "[", "'group'", "]", "==", "group_name", "return", "df"...
34.5
6.5
def setValue(self, value): """setter function to _lineEdit.text. Sets minimum/maximum as new value if value is out of bounds. Args: value (int/long): new value to set. Returns True if all went fine. """ if value >= self.minimum() and value <= self.maxim...
[ "def", "setValue", "(", "self", ",", "value", ")", ":", "if", "value", ">=", "self", ".", "minimum", "(", ")", "and", "value", "<=", "self", ".", "maximum", "(", ")", ":", "self", ".", "_lineEdit", ".", "setText", "(", "str", "(", "value", ")", "...
35.1875
15.4375
def reset_sequence(app_label): """ Reset the primary key sequence for the tables in an application. This is necessary if any local edits have happened to the table. """ puts("Resetting primary key sequence for {0}".format(app_label)) cursor = connection.cursor() cmd = get_reset_command(app...
[ "def", "reset_sequence", "(", "app_label", ")", ":", "puts", "(", "\"Resetting primary key sequence for {0}\"", ".", "format", "(", "app_label", ")", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cmd", "=", "get_reset_command", "(", "app_label", ")...
31
18.272727
def p_simple_list(p): '''simple_list : simple_list1 | simple_list1 AMPERSAND | simple_list1 SEMICOLON''' tok = p.lexer heredoc.gatherheredocuments(tok) if len(p) == 3 or len(p[1]) > 1: parts = p[1] if len(p) == 3: parts.append(ast.node(k...
[ "def", "p_simple_list", "(", "p", ")", ":", "tok", "=", "p", ".", "lexer", "heredoc", ".", "gatherheredocuments", "(", "tok", ")", "if", "len", "(", "p", ")", "==", "3", "or", "len", "(", "p", "[", "1", "]", ")", ">", "1", ":", "parts", "=", ...
33.65
20.65
def load_configuration(configuration): """Returns a dictionary, accepts a dictionary or a path to a JSON file.""" if isinstance(configuration, dict): return configuration else: with open(configuration) as configfile: return json.load(configfile)
[ "def", "load_configuration", "(", "configuration", ")", ":", "if", "isinstance", "(", "configuration", ",", "dict", ")", ":", "return", "configuration", "else", ":", "with", "open", "(", "configuration", ")", "as", "configfile", ":", "return", "json", ".", "...
39.857143
7.571429
def create_pie_chart(self, snapshot, filename=''): """ Create a pie chart that depicts the distribution of the allocated memory for a given `snapshot`. The chart is saved to `filename`. """ try: from pylab import figure, title, pie, axes, savefig from pyla...
[ "def", "create_pie_chart", "(", "self", ",", "snapshot", ",", "filename", "=", "''", ")", ":", "try", ":", "from", "pylab", "import", "figure", ",", "title", ",", "pie", ",", "axes", ",", "savefig", "from", "pylab", "import", "sum", "as", "pylab_sum", ...
35.96875
16.71875
def date_asn_block(self, ip, announce_date=None): """ Get the ASN and the IP Block announcing the IP at a specific date. :param ip: IP address to search for :param announce_date: Date of the announcement :rtype: tuple .. code-block:: python ...
[ "def", "date_asn_block", "(", "self", ",", "ip", ",", "announce_date", "=", "None", ")", ":", "assignations", ",", "announce_date", ",", "keys", "=", "self", ".", "run", "(", "ip", ",", "announce_date", ")", "pos", "=", "next", "(", "(", "i", "for", ...
35.925926
22.444444
def walker(top, names): """ Walks a directory and records all packages and file extensions. """ global packages, extensions if any(exc in top for exc in excludes): return package = top[top.rfind('holoviews'):].replace(os.path.sep, '.') packages.append(package) for name in names: ...
[ "def", "walker", "(", "top", ",", "names", ")", ":", "global", "packages", ",", "extensions", "if", "any", "(", "exc", "in", "top", "for", "exc", "in", "excludes", ")", ":", "return", "package", "=", "top", "[", "top", ".", "rfind", "(", "'holoviews'...
36.285714
14.142857
def transform(self, img, transformation, params): ''' Apply transformations to the image. New transformations can be defined as methods:: def do__transformationname(self, img, transformation, params): 'returns new image with transformation applied' ....
[ "def", "transform", "(", "self", ",", "img", ",", "transformation", ",", "params", ")", ":", "# Transformations MUST be idempotent.", "# The limitation is caused by implementation of", "# image upload in iktomi.cms.", "# The transformation can be applied twice:", "# on image upload a...
41.954545
22.227273
def get_session(self, sid, namespace=None): """Return the user session for a client. :param sid: The session id of the client. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used. The return value is a dictionar...
[ "def", "get_session", "(", "self", ",", "sid", ",", "namespace", "=", "None", ")", ":", "namespace", "=", "namespace", "or", "'/'", "eio_session", "=", "self", ".", "eio", ".", "get_session", "(", "sid", ")", "return", "eio_session", ".", "setdefault", "...
42.733333
18.533333
def datasets_org_count(self): """Return the number of datasets of user's organizations.""" from udata.models import Dataset # Circular imports. return sum(Dataset.objects(organization=org).visible().count() for org in self.organizations)
[ "def", "datasets_org_count", "(", "self", ")", ":", "from", "udata", ".", "models", "import", "Dataset", "# Circular imports.", "return", "sum", "(", "Dataset", ".", "objects", "(", "organization", "=", "org", ")", ".", "visible", "(", ")", ".", "count", "...
55.4
14.2
def _logsum(a_n): """Compute the log of a sum of exponentiated terms exp(a_n) in a numerically-stable manner. NOTE: this function has been deprecated in favor of logsumexp. Parameters ---------- a_n : np.ndarray, shape=(n_samples) a_n[n] is the nth exponential argument Returns ----...
[ "def", "_logsum", "(", "a_n", ")", ":", "# Compute the maximum argument.", "max_log_term", "=", "np", ".", "max", "(", "a_n", ")", "# Compute the reduced terms.", "terms", "=", "np", ".", "exp", "(", "a_n", "-", "max_log_term", ")", "# Compute the log sum.", "lo...
23.756098
23.560976
def _activate_outbound(self): """switch on newly negotiated encryption parameters for outbound traffic""" m = Message() m.add_byte(cMSG_NEWKEYS) self._send_message(m) block_size = self._cipher_info[self.local_cipher]["block-size"] if self.server_mode: ...
[ "def", "_activate_outbound", "(", "self", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "cMSG_NEWKEYS", ")", "self", ".", "_send_message", "(", "m", ")", "block_size", "=", "self", ".", "_cipher_info", "[", "self", ".", "local_ciphe...
44.357143
17.809524
def xenon_interactive_worker( machine, worker_config, input_queue=None, stderr_sink=None): """Uses Xenon to run a single remote interactive worker. Jobs are read from stdin, and results written to stdout. :param machine: Specification of the machine on which to run. :type machine: nood...
[ "def", "xenon_interactive_worker", "(", "machine", ",", "worker_config", ",", "input_queue", "=", "None", ",", "stderr_sink", "=", "None", ")", ":", "if", "input_queue", "is", "None", ":", "input_queue", "=", "Queue", "(", ")", "registry", "=", "worker_config"...
30.814433
19.536082
def has_assessment_section_begun(self, assessment_section_id): """Tests if this assessment section has started. A section begins from the designated start time if a start time is defined. If no start time is defined the section may begin at any time. Assessment items cannot be accessed ...
[ "def", "has_assessment_section_begun", "(", "self", ",", "assessment_section_id", ")", ":", "return", "get_section_util", "(", "assessment_section_id", ",", "runtime", "=", "self", ".", "_runtime", ")", ".", "_assessment_taken", ".", "has_started", "(", ")" ]
51.173913
22.434783
def getSearchUrl(self, album, artist): """ See CoverSource.getSearchUrl. """ url = "%s/search" % (__class__.BASE_URL) params = collections.OrderedDict() params["search-alias"] = "digital-music" params["field-keywords"] = " ".join((artist, album)) params["sort"] = "relevancerank" return __cla...
[ "def", "getSearchUrl", "(", "self", ",", "album", ",", "artist", ")", ":", "url", "=", "\"%s/search\"", "%", "(", "__class__", ".", "BASE_URL", ")", "params", "=", "collections", ".", "OrderedDict", "(", ")", "params", "[", "\"search-alias\"", "]", "=", ...
42.75
4.625
def have_cycle(graph:dict) -> frozenset: """Perform a topologic sort to detect any cycle. Return the set of unsortable nodes. If at least one item, then there is cycle in given graph. """ # topological sort walked = set() # walked nodes nodes = frozenset(it.chain(it.chain.from_iterable(gr...
[ "def", "have_cycle", "(", "graph", ":", "dict", ")", "->", "frozenset", ":", "# topological sort", "walked", "=", "set", "(", ")", "# walked nodes", "nodes", "=", "frozenset", "(", "it", ".", "chain", "(", "it", ".", "chain", ".", "from_iterable", "(", "...
37.555556
14.388889
def match_msequence(self, tokens, item): """Matches a middle sequence.""" series_type, head_matches, middle, _, last_matches = tokens self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)") self.add_check("_coconut.len(" + item + ") >= " + str(len(head_matches) + len(l...
[ "def", "match_msequence", "(", "self", ",", "tokens", ",", "item", ")", ":", "series_type", ",", "head_matches", ",", "middle", ",", "_", ",", "last_matches", "=", "tokens", "self", ".", "add_check", "(", "\"_coconut.isinstance(\"", "+", "item", "+", "\", _c...
54.388889
20.611111
def _migrate_resource(instance, migrations, version=''): """ Migrate a resource instance Subresources are migrated first, then the resource is recursively migrated :param instance: a perch.Document instance :param migrations: the migrations for a resource :param version: the current resource v...
[ "def", "_migrate_resource", "(", "instance", ",", "migrations", ",", "version", "=", "''", ")", ":", "if", "version", "not", "in", "migrations", ":", "return", "instance", "instance", "=", "_migrate_subresources", "(", "instance", ",", "migrations", "[", "vers...
27.689655
19.62069
def route_handler(context, content, pargs, kwargs): """ Route shortcode works a lot like rendering a page based on the url or route. This allows inserting in rendered HTML within another page. Activate it with the 'shortcodes' template filter. Within the content use the chill route shortcode: "[ch...
[ "def", "route_handler", "(", "context", ",", "content", ",", "pargs", ",", "kwargs", ")", ":", "(", "node", ",", "rule_kw", ")", "=", "node_from_uri", "(", "pargs", "[", "0", "]", ")", "if", "node", "==", "None", ":", "return", "u\"<!-- 404 '{0}' -->\"",...
35.166667
20.833333
def get_batch_header_values(self): """Scrape the "Batch Header" values from the original input file """ lines = self.getOriginalFile().data.splitlines() reader = csv.reader(lines) batch_headers = batch_data = [] for row in reader: if not any(row): ...
[ "def", "get_batch_header_values", "(", "self", ")", ":", "lines", "=", "self", ".", "getOriginalFile", "(", ")", ".", "data", ".", "splitlines", "(", ")", "reader", "=", "csv", ".", "reader", "(", "lines", ")", "batch_headers", "=", "batch_data", "=", "[...
38.826087
11.913043
def validateRegexStr(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value can't be used as a regular expression string. Returns the value argument as a regex object. If you want to check if a string matches a regular expression, ...
[ "def", "validateRegexStr", "(", "value", ",", "blank", "=", "False", ",", "strip", "=", "None", ",", "allowlistRegexes", "=", "None", ",", "blocklistRegexes", "=", "None", ",", "excMsg", "=", "None", ")", ":", "# TODO - I'd be nice to check regexes in other langua...
55.842105
37.289474
def runEditor(self, dir=os.getcwd(), debug=False, args=[]): """ Runs the editor for the Unreal project in the specified directory (or without a project if dir is None) """ projectFile = self.getProjectDescriptor(dir) if dir is not None else '' extraFlags = ['-debug'] + args if debug == True else args Utilit...
[ "def", "runEditor", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "debug", "=", "False", ",", "args", "=", "[", "]", ")", ":", "projectFile", "=", "self", ".", "getProjectDescriptor", "(", "dir", ")", "if", "dir", "is", "not", ...
61.285714
31.285714
def list(self, search_from=None, search_to=None, limit=None): """List all the objects saved elasticsearch. :param search_from: start offset of objects to return. :param search_to: last offset of objects to return. :param limit: max number of values to be returned. :return: li...
[ "def", "list", "(", "self", ",", "search_from", "=", "None", ",", "search_to", "=", "None", ",", "limit", "=", "None", ")", ":", "self", ".", "logger", ".", "debug", "(", "'elasticsearch::list'", ")", "body", "=", "{", "'sort'", ":", "[", "{", "\"_id...
29.382353
16.382353
def login(ctx): """Add an API key (saved in ~/.onecodex)""" base_url = os.environ.get("ONE_CODEX_API_BASE", "https://app.onecodex.com") if not ctx.obj["API_KEY"]: _login(base_url) else: email = _login(base_url, api_key=ctx.obj["API_KEY"]) ocx = Api(api_key=ctx.obj["API_KEY"], tel...
[ "def", "login", "(", "ctx", ")", ":", "base_url", "=", "os", ".", "environ", ".", "get", "(", "\"ONE_CODEX_API_BASE\"", ",", "\"https://app.onecodex.com\"", ")", "if", "not", "ctx", ".", "obj", "[", "\"API_KEY\"", "]", ":", "_login", "(", "base_url", ")", ...
48.533333
28.333333
def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col): """ Read input gene history file into the database. Note that the arguments tax_id_col, id_col and symbol_col have been converted into 0-based column indexes. """ # Make sure that tax_id is not "" or " " if not t...
[ "def", "import_gene_history", "(", "file_handle", ",", "tax_id", ",", "tax_id_col", ",", "id_col", ",", "symbol_col", ")", ":", "# Make sure that tax_id is not \"\" or \" \"", "if", "not", "tax_id", "or", "tax_id", ".", "isspace", "(", ")", ":", "raise", "Excepti...
39.553191
20.106383
def setPANID(self, xPAN): """set Thread Network PAN ID Args: xPAN: a given PAN ID in hex format Returns: True: successful to set the Thread Network PAN ID False: fail to set the Thread Network PAN ID """ print '%s call setPANID' % self.port ...
[ "def", "setPANID", "(", "self", ",", "xPAN", ")", ":", "print", "'%s call setPANID'", "%", "self", ".", "port", "print", "xPAN", "panid", "=", "''", "try", ":", "if", "not", "isinstance", "(", "xPAN", ",", "str", ")", ":", "panid", "=", "str", "(", ...
35.791667
20.916667
def main(): """Primary entry point; we supply '/', but the class brings '/metadata'""" app = apikit.APIFlask(name="Hello", version="0.0.1", repository="http://example.repo", description="Hello World App") # pylint: disable=unu...
[ "def", "main", "(", ")", ":", "app", "=", "apikit", ".", "APIFlask", "(", "name", "=", "\"Hello\"", ",", "version", "=", "\"0.0.1\"", ",", "repository", "=", "\"http://example.repo\"", ",", "description", "=", "\"Hello World App\"", ")", "# pylint: disable=unuse...
31.285714
16.357143
def raise_for_missing_namespace(self, line: str, position: int, namespace: str, name: str) -> None: """Raise an exception if the namespace is not defined.""" if not self.has_namespace(namespace): raise UndefinedNamespaceWarning(self.get_line_number(), line, position, namespace, name)
[ "def", "raise_for_missing_namespace", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "namespace", ":", "str", ",", "name", ":", "str", ")", "->", "None", ":", "if", "not", "self", ".", "has_namespace", "(", "namespace", ")", ":...
77.25
31
def _canon_decode_tag(self, value, mn_tags): """ Decode Canon MakerNote tag based on offset within tag. See http://www.burren.cx/david/canon.html by David Burren """ for i in range(1, len(value)): tag = mn_tags.get(i, ('Unknown', )) name = tag[0] ...
[ "def", "_canon_decode_tag", "(", "self", ",", "value", ",", "mn_tags", ")", ":", "for", "i", "in", "range", "(", "1", ",", "len", "(", "value", ")", ")", ":", "tag", "=", "mn_tags", ".", "get", "(", "i", ",", "(", "'Unknown'", ",", ")", ")", "n...
39.409091
18.136364
def from_csv(cls, path): """ Get box vectors from comma-separated values in file `path`. The csv file must containt only one line, which in turn can contain three values (orthogonal vectors) or nine values (triclinic box). The values should be in nanometers. Parameters...
[ "def", "from_csv", "(", "cls", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "fields", "=", "map", "(", "float", ",", "next", "(", "f", ")", ".", "split", "(", "','", ")", ")", "if", "len", "(", "fields", ")", "==",...
36.15625
20.71875
def ScanForStorageMediaImage(self, source_path_spec): """Scans the path specification for a supported storage media image format. Args: source_path_spec (PathSpec): source path specification. Returns: PathSpec: storage media image path specification or None if no supported storage me...
[ "def", "ScanForStorageMediaImage", "(", "self", ",", "source_path_spec", ")", ":", "try", ":", "type_indicators", "=", "analyzer", ".", "Analyzer", ".", "GetStorageMediaImageTypeIndicators", "(", "source_path_spec", ",", "resolver_context", "=", "self", ".", "_resolve...
36.34
23.38
def url_converter(self, *args, **kwargs): """ Return the custom URL converter for the given file name. """ upstream_converter = super(PatchedManifestStaticFilesStorage, self).url_converter(*args, **kwargs) def converter(matchobj): try: upstream_conver...
[ "def", "url_converter", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "upstream_converter", "=", "super", "(", "PatchedManifestStaticFilesStorage", ",", "self", ")", ".", "url_converter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
39.125
21.25
def json_get(json: JsonValue, path: str, expected_type: Any = ANY) -> Any: """Get a JSON value by path, optionally checking its type. >>> j = {"foo": {"num": 3.4, "s": "Text"}, "arr": [10, 20, 30]} >>> json_get(j, "/foo/num") 3.4 >>> json_get(j, "/arr[1]") 20 Raise ValueError if the path i...
[ "def", "json_get", "(", "json", ":", "JsonValue", ",", "path", ":", "str", ",", "expected_type", ":", "Any", "=", "ANY", ")", "->", "Any", ":", "elements", "=", "_parse_json_path", "(", "path", ")", "current", "=", "json", "current_path", "=", "\"\"", ...
31.731707
18.597561
def put(self, id, project_id=None): """put.""" result = db.session.query(Result).filter_by(id=id).first() if result is None: response = jsonify({ 'result': None, 'message': 'No interface defined for URL.' }) return response, 404 reques...
[ "def", "put", "(", "self", ",", "id", ",", "project_id", "=", "None", ")", ":", "result", "=", "db", ".", "session", ".", "query", "(", "Result", ")", ".", "filter_by", "(", "id", "=", "id", ")", ".", "first", "(", ")", "if", "result", "is", "N...
31.75
18.25
def cmd_help(self, *args): """help [cmd] Get general help, or help for command `cmd`. """ if len(args) > 0: cmdname = args[0].lower() try: method = getattr(self, "cmd_" + cmdname) doc = method.__doc__ if doc is None...
[ "def", "cmd_help", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", ">", "0", ":", "cmdname", "=", "args", "[", "0", "]", ".", "lower", "(", ")", "try", ":", "method", "=", "getattr", "(", "self", ",", "\"cmd_\"", "+", ...
36.689655
12.827586
def this_year(self): """ Get AnnouncementRequests from this school year only. """ start_date, end_date = get_date_range_this_year() return self.filter(start_time__gte=start_date, start_time__lte=end_date)
[ "def", "this_year", "(", "self", ")", ":", "start_date", ",", "end_date", "=", "get_date_range_this_year", "(", ")", "return", "self", ".", "filter", "(", "start_time__gte", "=", "start_date", ",", "start_time__lte", "=", "end_date", ")" ]
56.25
19.25
def get_chi(self, scalar=None): """sqrt(Chi_Squared) statistic (see `mcc`, `phi`, or google 'Matthews Correlation Coefficient'""" phi = self.get_phi(scalar=scalar) return mcc_chi(phi, self._num_samples)
[ "def", "get_chi", "(", "self", ",", "scalar", "=", "None", ")", ":", "phi", "=", "self", ".", "get_phi", "(", "scalar", "=", "scalar", ")", "return", "mcc_chi", "(", "phi", ",", "self", ".", "_num_samples", ")" ]
55.75
4
def v_lift_valve_Crane(rho, D1=None, D2=None, style='swing check angled'): r'''Calculates the approximate minimum velocity required to lift the disk or other controlling element of a check valve to a fully open, stable, position according to the Crane method [1]_. .. math:: v_{min}...
[ "def", "v_lift_valve_Crane", "(", "rho", ",", "D1", "=", "None", ",", "D2", "=", "None", ",", "style", "=", "'swing check angled'", ")", ":", "specific_volume", "=", "1.", "/", "rho", "if", "D1", "is", "not", "None", "and", "D2", "is", "not", "None", ...
38.878261
15.626087
async def handle_request(self, request): """Respond to request if PIN is correct.""" service_name = request.rel_url.query['servicename'] received_code = request.rel_url.query['pairingcode'].lower() _LOGGER.info('Got pairing request from %s with code %s', service_name...
[ "async", "def", "handle_request", "(", "self", ",", "request", ")", ":", "service_name", "=", "request", ".", "rel_url", ".", "query", "[", "'servicename'", "]", "received_code", "=", "request", ".", "rel_url", ".", "query", "[", "'pairingcode'", "]", ".", ...
46.294118
15.764706
def mod_repo(repo, basedir=None, **kwargs): ''' Modify one or more values for a repo. If the repo does not exist, it will be created, so long as the following values are specified: repo name by which the yum refers to the repo name a human-readable name for the repo baseurl ...
[ "def", "mod_repo", "(", "repo", ",", "basedir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Filter out '__pub' arguments, as well as saltenv", "repo_opts", "=", "dict", "(", "(", "x", ",", "kwargs", "[", "x", "]", ")", "for", "x", "in", "kwargs", ...
36.269231
21.051282
def delete(self, workflow_id, email_id): """ Removes an individual Automation workflow email. :param workflow_id: The unique id for the Automation workflow. :type workflow_id: :py:class:`str` :param email_id: The unique id for the Automation workflow email. :type email_i...
[ "def", "delete", "(", "self", ",", "workflow_id", ",", "email_id", ")", ":", "self", ".", "workflow_id", "=", "workflow_id", "self", ".", "email_id", "=", "email_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_bu...
38.846154
17.307692
def SetTimelineName(self, timeline_name): """Sets the timeline name. Args: timeline_name (str): timeline name. """ self._timeline_name = timeline_name logger.info('Timeline name: {0:s}'.format(self._timeline_name))
[ "def", "SetTimelineName", "(", "self", ",", "timeline_name", ")", ":", "self", ".", "_timeline_name", "=", "timeline_name", "logger", ".", "info", "(", "'Timeline name: {0:s}'", ".", "format", "(", "self", ".", "_timeline_name", ")", ")" ]
29.25
12.625
def delete_by_external_id(self, api_objects): """ Delete (DELETE) one or more API objects by external_id. :param api_objects: """ if not isinstance(api_objects, collections.Iterable): api_objects = [api_objects] return CRUDRequest(self).delete(api_objects, de...
[ "def", "delete_by_external_id", "(", "self", ",", "api_objects", ")", ":", "if", "not", "isinstance", "(", "api_objects", ",", "collections", ".", "Iterable", ")", ":", "api_objects", "=", "[", "api_objects", "]", "return", "CRUDRequest", "(", "self", ")", "...
37.444444
15.888889
def get_post_file(self, hdr, f_in, clen, post, files): """Reads from a multipart/form-data.""" lens = { 'clen': clen, 'push': [], } prefix = "boundary=" if not hdr.startswith(prefix): return None boundary = hdr[len(prefix):].strip().enc...
[ "def", "get_post_file", "(", "self", ",", "hdr", ",", "f_in", ",", "clen", ",", "post", ",", "files", ")", ":", "lens", "=", "{", "'clen'", ":", "clen", ",", "'push'", ":", "[", "]", ",", "}", "prefix", "=", "\"boundary=\"", "if", "not", "hdr", "...
35.829268
14.065041
def tree(self, tree_alias, context): """Builds and returns tree structure for 'sitetree_tree' tag. :param str|unicode tree_alias: :param Context context: :rtype: list|str """ tree_alias, sitetree_items = self.init_tree(tree_alias, context) if not sitetree_items:...
[ "def", "tree", "(", "self", ",", "tree_alias", ",", "context", ")", ":", "tree_alias", ",", "sitetree_items", "=", "self", ".", "init_tree", "(", "tree_alias", ",", "context", ")", "if", "not", "sitetree_items", ":", "return", "''", "tree_items", "=", "sel...
33.647059
21.294118
def contacts(self,*args,**kwargs): """ Use assess the cell-to-cell contacts recorded in the celldataframe Returns: Contacts: returns a class that holds cell-to-cell contact information for whatever phenotypes were in the CellDataFrame before execution. """ n = Cont...
[ "def", "contacts", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "n", "=", "Contacts", ".", "read_cellframe", "(", "self", ",", "prune_neighbors", "=", "True", ")", "if", "'measured_regions'", "in", "kwargs", ":", "n", ".", "measure...
51.928571
29.5
def archive_sciobj(pid): """Set the status of an object to archived. Preconditions: - The object with the pid is verified to exist. - The object is not a replica. - The object is not archived. """ sciobj_model = d1_gmn.app.model_util.get_sci_model(pid) sciobj_model.is_archived = True ...
[ "def", "archive_sciobj", "(", "pid", ")", ":", "sciobj_model", "=", "d1_gmn", ".", "app", ".", "model_util", ".", "get_sci_model", "(", "pid", ")", "sciobj_model", ".", "is_archived", "=", "True", "sciobj_model", ".", "save", "(", ")", "_update_modified_timest...
28.846154
14.384615
def spin_in_roche(s, etheta, elongan, eincl): """ Transform the spin s of a star on Kerpler orbit with etheta - true anomaly elongan - longitude of ascending node eincl - inclination from in the plane of sky reference frame into the Roche reference frame. """ # m = Rz(long).Rx(-i...
[ "def", "spin_in_roche", "(", "s", ",", "etheta", ",", "elongan", ",", "eincl", ")", ":", "# m = Rz(long).Rx(-incl).Rz(theta).Rz(pi)", "m", "=", "euler_trans_matrix", "(", "etheta", ",", "elongan", ",", "eincl", ")", "return", "np", ".", "dot", "(", "m", "."...
26.733333
14.6
def _create_class_instance(class_name, _proxy): """ Look for the class in .extensions in case it has already been imported (perhaps as a builtin extensions hard compiled into unity_server). """ try: return _class_instance_from_name('turicreate.extensions.' + class_name, _proxy=_proxy) ex...
[ "def", "_create_class_instance", "(", "class_name", ",", "_proxy", ")", ":", "try", ":", "return", "_class_instance_from_name", "(", "'turicreate.extensions.'", "+", "class_name", ",", "_proxy", "=", "_proxy", ")", "except", ":", "pass", "return", "_class_instance_f...
39.3
23.7
def same_as(self, rows: List[Row], column: Column) -> List[Row]: """ Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row. """ cell_value = rows[0].values[column.name] return_list...
[ "def", "same_as", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "Column", ")", "->", "List", "[", "Row", "]", ":", "cell_value", "=", "rows", "[", "0", "]", ".", "values", "[", "column", ".", "name", "]", "return_lis...
44.545455
15.272727
def _matches_filters(self, msg): """Checks whether the given message matches at least one of the current filters. See :meth:`~can.BusABC.set_filters` for details on how the filters work. This method should not be overridden. :param can.Message msg: the message to ch...
[ "def", "_matches_filters", "(", "self", ",", "msg", ")", ":", "# if no filters are set, all messages are matched", "if", "self", ".", "_filters", "is", "None", ":", "return", "True", "for", "_filter", "in", "self", ".", "_filters", ":", "# check if this filter even ...
33.942857
18.057143
def timezone(self): """ timezone of GSSHA model """ if self._tz is None: # GET CENTROID FROM GSSHA GRID cen_lat, cen_lon = self.centerLatLon() # update time zone tf = TimezoneFinder() tz_name = tf.timezone_at(lng=cen_lon, lat=ce...
[ "def", "timezone", "(", "self", ")", ":", "if", "self", ".", "_tz", "is", "None", ":", "# GET CENTROID FROM GSSHA GRID", "cen_lat", ",", "cen_lon", "=", "self", ".", "centerLatLon", "(", ")", "# update time zone", "tf", "=", "TimezoneFinder", "(", ")", "tz_n...
29.230769
11.538462
def create_char_dataframe(words): """ Give list of input tokenized words, create dataframe of characters where first character of the word is tagged as 1, otherwise 0 Example ======= ['กิน', 'หมด'] to dataframe of [{'char': 'ก', 'type': ..., 'target': 1}, ..., {'char': 'ด', 'type':...
[ "def", "create_char_dataframe", "(", "words", ")", ":", "char_dict", "=", "[", "]", "for", "word", "in", "words", ":", "for", "i", ",", "char", "in", "enumerate", "(", "word", ")", ":", "if", "i", "==", "0", ":", "char_dict", ".", "append", "(", "{...
34.708333
14.125
def _addPredecessor(self, predecessorJob): """ Adds a predecessor job to the set of predecessor jobs. Raises a \ RuntimeError if the job is already a predecessor. """ if predecessorJob in self._directPredecessors: raise RuntimeError("The given job is already a predece...
[ "def", "_addPredecessor", "(", "self", ",", "predecessorJob", ")", ":", "if", "predecessorJob", "in", "self", ".", "_directPredecessors", ":", "raise", "RuntimeError", "(", "\"The given job is already a predecessor of this job\"", ")", "self", ".", "_directPredecessors", ...
48
15.25
def update(self, vips): """ Method to update vip's :param vips: List containing vip's desired to updated :return: None """ data = {'vips': vips} vips_ids = [str(vip.get('id')) for vip in vips] return super(ApiVipRequest, self).put('api/v3/vip-request/%s...
[ "def", "update", "(", "self", ",", "vips", ")", ":", "data", "=", "{", "'vips'", ":", "vips", "}", "vips_ids", "=", "[", "str", "(", "vip", ".", "get", "(", "'id'", ")", ")", "for", "vip", "in", "vips", "]", "return", "super", "(", "ApiVipRequest...
29.538462
21.230769
def p_jsonpath_operator_jsonpath(self, p): """jsonpath : NUMBER operator NUMBER | FLOAT operator FLOAT | ID operator ID | NUMBER operator jsonpath | FLOAT operator jsonpath | jsonpath operator NUMBER ...
[ "def", "p_jsonpath_operator_jsonpath", "(", "self", ",", "p", ")", ":", "# NOTE(sileht): If we have choice between a field or a string we", "# always choice string, because field can be full qualified", "# like $.foo == foo and where string can't.", "for", "i", "in", "[", "1", ",", ...
40.45
12
def delete(self, campaign_id): """ Remove a campaign from your MailChimp account. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` """ self.campaign_id = campaign_id return self._mc_client._delete(url=self._build_path(campaig...
[ "def", "delete", "(", "self", ",", "campaign_id", ")", ":", "self", ".", "campaign_id", "=", "campaign_id", "return", "self", ".", "_mc_client", ".", "_delete", "(", "url", "=", "self", ".", "_build_path", "(", "campaign_id", ")", ")" ]
35.333333
13.333333
def preview_article(self, request, object_id, language): """Redirecting preview function based on draft_id """ article = get_object_or_404(self.model, id=object_id) attrs = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') attrs += '&language=' + language with force_lan...
[ "def", "preview_article", "(", "self", ",", "request", ",", "object_id", ",", "language", ")", ":", "article", "=", "get_object_or_404", "(", "self", ".", "model", ",", "id", "=", "object_id", ")", "attrs", "=", "'?%s'", "%", "get_cms_setting", "(", "'CMS_...
47.777778
9.555556
def run_hooks(obj, hooks, *args): """Run each function in `hooks' with args""" for hook in hooks: if hook(obj, *args): return True pass return False
[ "def", "run_hooks", "(", "obj", ",", "hooks", ",", "*", "args", ")", ":", "for", "hook", "in", "hooks", ":", "if", "hook", "(", "obj", ",", "*", "args", ")", ":", "return", "True", "pass", "return", "False" ]
28.5
12.833333
def _calc_digest(self, origin): """calculate digest for the given file or readable/seekable object Args: origin -- could be the path of a file or a readable/seekable object ( fileobject, stream, stringIO...) Returns: String rapresenting the digest for the given origin ...
[ "def", "_calc_digest", "(", "self", ",", "origin", ")", ":", "if", "hasattr", "(", "origin", ",", "'read'", ")", "and", "hasattr", "(", "origin", ",", "'seek'", ")", ":", "pos", "=", "origin", ".", "tell", "(", ")", "digest", "=", "hashtools", ".", ...
43.533333
25.2
def AgregarComprobanteAAjustar(self, tipo_cbte, pto_vta, nro_cbte): "Agrega comprobante a ajustar" cbte = dict(tipoComprobante=tipo_cbte, puntoVenta=pto_vta, nroComprobante=nro_cbte) self.solicitud['liquidacion']["comprobanteAAjustar"].append(cbte) return True
[ "def", "AgregarComprobanteAAjustar", "(", "self", ",", "tipo_cbte", ",", "pto_vta", ",", "nro_cbte", ")", ":", "cbte", "=", "dict", "(", "tipoComprobante", "=", "tipo_cbte", ",", "puntoVenta", "=", "pto_vta", ",", "nroComprobante", "=", "nro_cbte", ")", "self"...
57.6
26.8
def get_sym_srv_debug_entry_client_key(self, debug_entry_client_key): """GetSymSrvDebugEntryClientKey. [Preview API] Given a client key, returns the best matched debug entry. :param str debug_entry_client_key: A "client key" used by both ends of Microsoft's symbol protocol to identify a debug en...
[ "def", "get_sym_srv_debug_entry_client_key", "(", "self", ",", "debug_entry_client_key", ")", ":", "route_values", "=", "{", "}", "if", "debug_entry_client_key", "is", "not", "None", ":", "route_values", "[", "'debugEntryClientKey'", "]", "=", "self", ".", "_seriali...
68.416667
33.833333