text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def CacheStorage_requestEntries(self, cacheId, skipCount, pageSize): """ Function path: CacheStorage.requestEntries Domain: CacheStorage Method name: requestEntries Parameters: Required arguments: 'cacheId' (type: CacheId) -> ID of cache to get entries from. 'skipCount' (type: integer) -> ...
[ "def", "CacheStorage_requestEntries", "(", "self", ",", "cacheId", ",", "skipCount", ",", "pageSize", ")", ":", "assert", "isinstance", "(", "skipCount", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'skipCount' must be of type '['int']'. Received type: '%s'\"", "%...
40.615385
22.538462
def uniq(items): """Remove duplicates in given list with its order kept. >>> uniq([]) [] >>> uniq([1, 4, 5, 1, 2, 3, 5, 10]) [1, 4, 5, 2, 3, 10] """ acc = items[:1] for item in items[1:]: if item not in acc: acc += [item] return acc
[ "def", "uniq", "(", "items", ")", ":", "acc", "=", "items", "[", ":", "1", "]", "for", "item", "in", "items", "[", "1", ":", "]", ":", "if", "item", "not", "in", "acc", ":", "acc", "+=", "[", "item", "]", "return", "acc" ]
19.785714
19.214286
def _is_retryable_exception(e): """Returns True if the exception is always safe to retry. This is True if the client was never able to establish a connection to the server (for example, name resolution failed or the connection could otherwise not be initialized). Conservatively, if we can't tell w...
[ "def", "_is_retryable_exception", "(", "e", ")", ":", "if", "isinstance", "(", "e", ",", "urllib3", ".", "exceptions", ".", "ProtocolError", ")", ":", "e", "=", "e", ".", "args", "[", "1", "]", "if", "isinstance", "(", "e", ",", "(", "socket", ".", ...
36.75
20.85
def end_at(self, document_fields): """End query at a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.end_at` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSn...
[ "def", "end_at", "(", "self", ",", "document_fields", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "end_at", "(", "document_fields", ")" ]
38.684211
20.947368
def push_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) ...
[ "def", "push_image", "(", "registry", ",", "image", ")", ":", "# type: (str, Dict[str, Any]) -> None", "values", "=", "{", "'registry'", ":", "registry", ",", "'image'", ":", "image", "[", "'name'", "]", ",", "}", "log", ".", "info", "(", "\"Pushing <33>{regis...
36.842105
21.736842
def from_byte_array(cls, bytes_): """Decodes a run-length encoded ByteArray and returns a Bitmap. The ByteArray decompresses to a sequence of 32-bit values, which are stored as a byte string. (The specific encoding depends on Form.depth.) """ runs = cls._length_run_coding.parse(b...
[ "def", "from_byte_array", "(", "cls", ",", "bytes_", ")", ":", "runs", "=", "cls", ".", "_length_run_coding", ".", "parse", "(", "bytes_", ")", "pixels", "=", "(", "run", ".", "pixels", "for", "run", "in", "runs", ".", "data", ")", "data", "=", "\"\"...
50.666667
15.555556
def tmpl_asciify(text): """ * synopsis: ``%asciify{text}`` * description: Translate non-ASCII characters to their ASCII \ equivalents. For example, “café” becomes “cafe”. Uses the mapping \ provided by the unidecode module. """ ger_umlaute = {'ae': u'ä', ...
[ "def", "tmpl_asciify", "(", "text", ")", ":", "ger_umlaute", "=", "{", "'ae'", ":", "u'ä',", "", "'oe'", ":", "u'ö',", "", "'ue'", ":", "u'ü',", "", "'Ae'", ":", "u'Ä',", "", "'Oe'", ":", "u'Ö',", "", "'Ue'", ":", "u'Ü'}", "", "for", "replace", "...
39.625
10.125
def copy_data_from_scenario(resource_attrs, source_scenario_id, target_scenario_id, **kwargs): """ For a given list of resource attribute IDS copy the dataset_ids from the resource scenarios in the source scenario to those in the 'target' scenario. """ #Get all the resource scenarios we wis...
[ "def", "copy_data_from_scenario", "(", "resource_attrs", ",", "source_scenario_id", ",", "target_scenario_id", ",", "*", "*", "kwargs", ")", ":", "#Get all the resource scenarios we wish to update", "target_resourcescenarios", "=", "db", ".", "DBSession", ".", "query", "(...
44.138889
24.138889
def _get_crud_params(compiler, stmt, **kw): """ extract values from crud parameters taken from SQLAlchemy's crud module (since 1.0.x) and adapted for Crate dialect""" compiler.postfetch = [] compiler.insert_prefetch = [] compiler.update_prefetch = [] compiler.re...
[ "def", "_get_crud_params", "(", "compiler", ",", "stmt", ",", "*", "*", "kw", ")", ":", "compiler", ".", "postfetch", "=", "[", "]", "compiler", ".", "insert_prefetch", "=", "[", "]", "compiler", ".", "update_prefetch", "=", "[", "]", "compiler", ".", ...
38.370968
20.741935
def fetch_build_eggs(self, requires): """Resolve pre-setup requirements""" resolved_dists = pkg_resources.working_set.resolve( pkg_resources.parse_requirements(requires), installer=self.fetch_build_egg, replace_conflicting=True, ) for dist in resolved_...
[ "def", "fetch_build_eggs", "(", "self", ",", "requires", ")", ":", "resolved_dists", "=", "pkg_resources", ".", "working_set", ".", "resolve", "(", "pkg_resources", ".", "parse_requirements", "(", "requires", ")", ",", "installer", "=", "self", ".", "fetch_build...
40.9
11.1
def parse_selection_set(lexer: Lexer) -> SelectionSetNode: """SelectionSet: {Selection+}""" start = lexer.token return SelectionSetNode( selections=many_nodes( lexer, TokenKind.BRACE_L, parse_selection, TokenKind.BRACE_R ), loc=loc(lexer, start), )
[ "def", "parse_selection_set", "(", "lexer", ":", "Lexer", ")", "->", "SelectionSetNode", ":", "start", "=", "lexer", ".", "token", "return", "SelectionSetNode", "(", "selections", "=", "many_nodes", "(", "lexer", ",", "TokenKind", ".", "BRACE_L", ",", "parse_s...
32.444444
18.222222
def _init_subtokens_from_list(self, subtoken_strings, reserved_tokens=None): """Initialize token information from a list of subtoken strings. Args: subtoken_strings: a list of subtokens reserved_tokens: List of reserved tokens. We must have `reserved_tokens` as None or the empty list, or el...
[ "def", "_init_subtokens_from_list", "(", "self", ",", "subtoken_strings", ",", "reserved_tokens", "=", "None", ")", ":", "if", "reserved_tokens", "is", "None", ":", "reserved_tokens", "=", "[", "]", "if", "reserved_tokens", ":", "self", ".", "_all_subtoken_strings...
38.1875
21.78125
def slurp_properties(source, destination, ignore=[], srckeys=None): """Copy properties from *source* (assumed to be a module) to *destination* (assumed to be a dict). *ignore* lists properties that should not be thusly copied. *srckeys* is a list of keys to copy, if the source's __all__ is untrustw...
[ "def", "slurp_properties", "(", "source", ",", "destination", ",", "ignore", "=", "[", "]", ",", "srckeys", "=", "None", ")", ":", "if", "srckeys", "is", "None", ":", "srckeys", "=", "source", ".", "__all__", "destination", ".", "update", "(", "dict", ...
42.857143
17.214286
def observe_reward_value(self, state_key, action_key): ''' Compute the reward value. Args: state_key: The key of state. action_key: The key of action. Returns: Reward value. ''' x, y = state_k...
[ "def", "observe_reward_value", "(", "self", ",", "state_key", ",", "action_key", ")", ":", "x", ",", "y", "=", "state_key", "if", "self", ".", "__map_arr", "[", "y", "]", "[", "x", "]", "==", "self", ".", "__end_point_label", ":", "return", "100.0", "e...
31.333333
21.416667
def set_style(self, style): """ Sets the style to the specified Pygments style. """ style = SolarizedStyle # get_style_by_name(style) self._style = style self._clear_caches()
[ "def", "set_style", "(", "self", ",", "style", ")", ":", "style", "=", "SolarizedStyle", "# get_style_by_name(style)", "self", ".", "_style", "=", "style", "self", ".", "_clear_caches", "(", ")" ]
35
9.333333
def check_topics(client, req_topics): """Check for existence of provided topics in Kafka.""" client.update_cluster() logger.debug('Found topics: %r', client.topics.keys()) for req_topic in req_topics: if req_topic not in client.topics.keys(): err_topic_not_found = 'Topic not found: ...
[ "def", "check_topics", "(", "client", ",", "req_topics", ")", ":", "client", ".", "update_cluster", "(", ")", "logger", ".", "debug", "(", "'Found topics: %r'", ",", "client", ".", "topics", ".", "keys", "(", ")", ")", "for", "req_topic", "in", "req_topics...
40.777778
16.666667
def __apply_mask(address_packed, mask_packed, nr_bytes): """ Perform a bitwise AND operation on all corresponding bytes between the mask and the provided address. Mask parts set to 0 will become 0 in the anonymized IP address as well :param bytes address_packed: Binary representation of the IP addre...
[ "def", "__apply_mask", "(", "address_packed", ",", "mask_packed", ",", "nr_bytes", ")", ":", "anon_packed", "=", "bytearray", "(", ")", "for", "i", "in", "range", "(", "0", ",", "nr_bytes", ")", ":", "anon_packed", ".", "append", "(", "ord", "(", "mask_p...
40.368421
22.263158
def datetime_to_time(date, time): """Take the date and time 4-tuples and return the time in seconds since the epoch as a floating point number.""" if (255 in date) or (255 in time): raise RuntimeError("specific date and time required") time_tuple = ( date[0]+1900, date[1], date[2], ...
[ "def", "datetime_to_time", "(", "date", ",", "time", ")", ":", "if", "(", "255", "in", "date", ")", "or", "(", "255", "in", "time", ")", ":", "raise", "RuntimeError", "(", "\"specific date and time required\"", ")", "time_tuple", "=", "(", "date", "[", "...
33.166667
13.583333
def set_auto_commit(self, auto_commit): """Sets auto-commit mode for this connection. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by...
[ "def", "set_auto_commit", "(", "self", ",", "auto_commit", ")", ":", "auto_commit", "=", "bool", "(", "auto_commit", ")", "if", "auto_commit", "==", "self", ".", "_auto_commit", ":", "return", "self", ".", "_auto_commit", "=", "auto_commit", "if", "self", "....
49.55
33.95
def getAverageBuildDuration(self, package, **kwargs): """ Return a timedelta that Koji considers to be average for this package. Calls "getAverageBuildDuration" XML-RPC. :param package: ``str``, for example "ceph" :returns: deferred that when fired returns a datetime object for...
[ "def", "getAverageBuildDuration", "(", "self", ",", "package", ",", "*", "*", "kwargs", ")", ":", "seconds", "=", "yield", "self", ".", "call", "(", "'getAverageBuildDuration'", ",", "package", ",", "*", "*", "kwargs", ")", "if", "seconds", "is", "None", ...
42.066667
20.2
def parse(name, content, releases, get_head_fn): """ Parses the given content for a valid changelog :param name: str, package name :param content: str, content :param releases: list, releases :param get_head_fn: function :return: dict, changelog """ changelog = {} releases = froz...
[ "def", "parse", "(", "name", ",", "content", ",", "releases", ",", "get_head_fn", ")", ":", "changelog", "=", "{", "}", "releases", "=", "frozenset", "(", "releases", ")", "head", "=", "False", "for", "line", "in", "content", ".", "splitlines", "(", ")...
29.916667
11.416667
def create_tomodir(self, directory): """Create a tomodir subdirectory structure in the given directory """ pwd = os.getcwd() if not os.path.isdir(directory): os.makedirs(directory) os.chdir(directory) directories = ( 'config', 'exe', ...
[ "def", "create_tomodir", "(", "self", ",", "directory", ")", ":", "pwd", "=", "os", ".", "getcwd", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "directory", ")", "os", ".", "chdir",...
25.318182
15.227273
def close(self): """If a connection is open, close its transport.""" if self._local.conn: self._local.conn.transport.close() self._local.conn = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_local", ".", "conn", ":", "self", ".", "_local", ".", "conn", ".", "transport", ".", "close", "(", ")", "self", ".", "_local", ".", "conn", "=", "None" ]
36
10.2
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0): """ Query records from underlying repository """ # run the raw query and get total # we want to exclude layers which are not valid, as it is done in the search engine if 'where' in ...
[ "def", "query", "(", "self", ",", "constraint", ",", "sortby", "=", "None", ",", "typenames", "=", "None", ",", "maxrecords", "=", "10", ",", "startposition", "=", "0", ")", ":", "# run the raw query and get total", "# we want to exclude layers which are not valid, ...
46.666667
21.5
async def reconnect(self): """Reconnect to the modem.""" _LOGGER.debug('starting Connection.reconnect') await self._connect() while self._closed: await self._retry_connection() _LOGGER.debug('ending Connection.reconnect')
[ "async", "def", "reconnect", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "'starting Connection.reconnect'", ")", "await", "self", ".", "_connect", "(", ")", "while", "self", ".", "_closed", ":", "await", "self", ".", "_retry_connection", "(", ")", ...
38.142857
9.428571
def update(self, friendly_name=None, description=None): """ Selectively updates Dataset information. Args: friendly_name: if not None, the new friendly name. description: if not None, the new description. Returns: """ self._get_info() if self._info: if friendly_name: ...
[ "def", "update", "(", "self", ",", "friendly_name", "=", "None", ",", "description", "=", "None", ")", ":", "self", ".", "_get_info", "(", ")", "if", "self", ".", "_info", ":", "if", "friendly_name", ":", "self", ".", "_info", "[", "'friendlyName'", "]...
26.045455
20.363636
def draw_panel(self, data, panel_params, coord, ax, **params): """ Plot all groups For effeciency, geoms that do not need to partition different groups before plotting should override this method and avoid the groupby. Parameters ---------- data : datafr...
[ "def", "draw_panel", "(", "self", ",", "data", ",", "panel_params", ",", "coord", ",", "ax", ",", "*", "*", "params", ")", ":", "for", "_", ",", "gdata", "in", "data", ".", "groupby", "(", "'group'", ")", ":", "gdata", ".", "reset_index", "(", "inp...
34.205882
17.970588
def n_executions(self): """ Queries and returns the number of past task executions. """ pipeline = self.tiger.connection.pipeline() pipeline.exists(self.tiger._key('task', self.id)) pipeline.llen(self.tiger._key('task', self.id, 'executions')) exists, n_executions...
[ "def", "n_executions", "(", "self", ")", ":", "pipeline", "=", "self", ".", "tiger", ".", "connection", ".", "pipeline", "(", ")", "pipeline", ".", "exists", "(", "self", ".", "tiger", ".", "_key", "(", "'task'", ",", "self", ".", "id", ")", ")", "...
36.846154
15.307692
def create_platform(platform): ''' .. versionadded:: 2019.2.0 Create a new device platform platform String of device platform, e.g., ``junos`` CLI Example: .. code-block:: bash salt myminion netbox.create_platform junos ''' nb_platform = get_('dcim', 'platforms', slu...
[ "def", "create_platform", "(", "platform", ")", ":", "nb_platform", "=", "get_", "(", "'dcim'", ",", "'platforms'", ",", "slug", "=", "slugify", "(", "platform", ")", ")", "if", "nb_platform", ":", "return", "False", "else", ":", "payload", "=", "{", "'n...
23.56
23.64
def main(): """Main function calls the test functs""" print("Python version %s" % sys.version) print("Testing compatibility for function defined with *args") test_func_args(func_old_args) test_func_args(func_new) print("Testing compatibility for function defined with **kwargs") test_func_...
[ "def", "main", "(", ")", ":", "print", "(", "\"Python version %s\"", "%", "sys", ".", "version", ")", "print", "(", "\"Testing compatibility for function defined with *args\"", ")", "test_func_args", "(", "func_old_args", ")", "test_func_args", "(", "func_new", ")", ...
29.5
22.1875
def start_current_script(): """upload current python script to EV3""" current_editor = get_workbench().get_editor_notebook().get_current_editor() code = current_editor.get_text_widget().get("1.0", "end") try: ast.parse(code) #Return None, if script is not saved and user closed file savin...
[ "def", "start_current_script", "(", ")", ":", "current_editor", "=", "get_workbench", "(", ")", ".", "get_editor_notebook", "(", ")", ".", "get_current_editor", "(", ")", "code", "=", "current_editor", ".", "get_text_widget", "(", ")", ".", "get", "(", "\"1.0\...
42.5
21.714286
def count_citation_years(graph: BELGraph) -> typing.Counter[int]: """Count the number of citations from each year.""" result = defaultdict(set) for _, _, data in graph.edges(data=True): if CITATION not in data or CITATION_DATE not in data[CITATION]: continue try: dt...
[ "def", "count_citation_years", "(", "graph", ":", "BELGraph", ")", "->", "typing", ".", "Counter", "[", "int", "]", ":", "result", "=", "defaultdict", "(", "set", ")", "for", "_", ",", "_", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", ...
36.133333
24.2
def import_new_atlas_pointings( self, recent=False): """ *Import any new ATLAS pointings from the atlas3/atlas4 databases into the ``atlas_exposures`` table of the Atlas Movers database* **Key Arguments:** - ``recent`` -- only sync the most recent 2 weeks of ...
[ "def", "import_new_atlas_pointings", "(", "self", ",", "recent", "=", "False", ")", ":", "self", ".", "log", ".", "info", "(", "'starting the ``import_new_atlas_pointings`` method'", ")", "if", "recent", ":", "mjd", "=", "mjdnow", "(", "log", "=", "self", ".",...
32.709677
19.274194
def webhooks(self): """Instance depends on the API version: * 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.operations.WebhooksOperations>` * 2018-02-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.Webhoo...
[ "def", "webhooks", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'webhooks'", ")", "if", "api_version", "==", "'2017-10-01'", ":", "from", ".", "v2017_10_01", ".", "operations", "import", "WebhooksOperations", "as", "Operation...
68.176471
39.941176
def on_event(self, message, handler, namespace=None): """Register a SocketIO event handler. ``on_event`` is the non-decorator version of ``'on'``. Example:: def on_foo_event(json): print('received json: ' + str(json)) socketio.on_event('my event', on_f...
[ "def", "on_event", "(", "self", ",", "message", ",", "handler", ",", "namespace", "=", "None", ")", ":", "self", ".", "on", "(", "message", ",", "namespace", "=", "namespace", ")", "(", "handler", ")" ]
45.583333
26.333333
def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_info is None: ...
[ "def", "prepare_for_reraise", "(", "error", ",", "exc_info", "=", "None", ")", ":", "if", "not", "hasattr", "(", "error", ",", "\"_type_\"", ")", ":", "if", "exc_info", "is", "None", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "error", ".",...
33.461538
14.230769
def create_from_fits(cls, fitsfile, norm_type='eflux', hdu_scan="SCANDATA", hdu_energies="EBOUNDS", irow=None): """Create a CastroData object from a tscube FITS file. Parameters ---------- fitsfile : str ...
[ "def", "create_from_fits", "(", "cls", ",", "fitsfile", ",", "norm_type", "=", "'eflux'", ",", "hdu_scan", "=", "\"SCANDATA\"", ",", "hdu_energies", "=", "\"EBOUNDS\"", ",", "irow", "=", "None", ")", ":", "if", "irow", "is", "not", "None", ":", "tab_s", ...
33.208333
20.770833
def tag_to_dict(html): """Extract tag's attributes into a `dict`.""" element = document_fromstring(html).xpath("//html/body/child::*")[0] attributes = dict(element.attrib) attributes["text"] = element.text_content() return attributes
[ "def", "tag_to_dict", "(", "html", ")", ":", "element", "=", "document_fromstring", "(", "html", ")", ".", "xpath", "(", "\"//html/body/child::*\"", ")", "[", "0", "]", "attributes", "=", "dict", "(", "element", ".", "attrib", ")", "attributes", "[", "\"te...
35.428571
17
def new(cls, variable, **kwargs): """Return a new |IndexMask| object of the same shape as the parameter referenced by |property| |IndexMask.refindices|. Entries are only |True|, if the integer values of the respective entries of the referenced parameter are contained in the |Inde...
[ "def", "new", "(", "cls", ",", "variable", ",", "*", "*", "kwargs", ")", ":", "indices", "=", "cls", ".", "get_refindices", "(", "variable", ")", "if", "numpy", ".", "min", "(", "getattr", "(", "indices", ",", "'values'", ",", "0", ")", ")", "<", ...
52.055556
14.611111
def process_from_json_file(filename, doc_id_type=None): """Process RLIMSP extractions from a bulk-download JSON file. Parameters ---------- filename : str Path to the JSON file. doc_id_type : Optional[str] In some cases the RLIMS-P paragraph info doesn't contain 'pmid' or 'p...
[ "def", "process_from_json_file", "(", "filename", ",", "doc_id_type", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "'rt'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "json_list", "=", "[", "]", "for", "line", ...
36.481481
20.407407
def _dep_changed(self, dep, code_changed=False, value_changed=False): """ Called when a dependency's expression has changed. """ self.changed(code_changed, value_changed)
[ "def", "_dep_changed", "(", "self", ",", "dep", ",", "code_changed", "=", "False", ",", "value_changed", "=", "False", ")", ":", "self", ".", "changed", "(", "code_changed", ",", "value_changed", ")" ]
47.75
9.5
def _child(self, path): """ Return a ConfigNode object representing a child node with the specified relative path. """ if self._path: path = '{}.{}'.format(self._path, path) return ConfigNode(root=self._root, path=path)
[ "def", "_child", "(", "self", ",", "path", ")", ":", "if", "self", ".", "_path", ":", "path", "=", "'{}.{}'", ".", "format", "(", "self", ".", "_path", ",", "path", ")", "return", "ConfigNode", "(", "root", "=", "self", ".", "_root", ",", "path", ...
34
14.5
def get_user(self, user_id): """ Details for a specific user. Will pull from cached users first, or get and add to cached users. :param username: the username or userId of the user :return: VoicebaseUser """ if user_id in self._users: return self._user...
[ "def", "get_user", "(", "self", ",", "user_id", ")", ":", "if", "user_id", "in", "self", ".", "_users", ":", "return", "self", ".", "_users", ".", "get", "(", "user_id", ")", "else", ":", "# Load user", "# Save user in cache", "return" ]
31.692308
12.461538
def get_long_description(): """ Returns the long description of HaTeMiLe for Python. :return: The long description of HaTeMiLe for Python. :rtype: str """ with open( os.path.join(BASE_DIRECTORY, 'README.md'), 'r', encoding='utf-8' ) as readme_file: return re...
[ "def", "get_long_description", "(", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "BASE_DIRECTORY", ",", "'README.md'", ")", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "readme_file", ":", "return", "readme_file", ".", "...
23.071429
18.357143
def course_discovery(request): """ Search for courses Args: request (required) - django request object Returns: http json response with the following fields "took" - how many seconds the operation took "total" - how many results were found "max_score...
[ "def", "course_discovery", "(", "request", ")", ":", "results", "=", "{", "\"error\"", ":", "_", "(", "\"Nothing to search\"", ")", "}", "status_code", "=", "500", "search_term", "=", "request", ".", "POST", ".", "get", "(", "\"search_string\"", ",", "None",...
30.488636
23.943182
def find_resource(r, *, pkg='cyther'): """ Finds a given cyther resource in the 'test' subdirectory in 'cyther' package """ file_path = pkg_resources.resource_filename(pkg, os.path.join('test', r)) if not os.path.isfile(file_path): msg = "Resource '{}' does not exist" raise FileN...
[ "def", "find_resource", "(", "r", ",", "*", ",", "pkg", "=", "'cyther'", ")", ":", "file_path", "=", "pkg_resources", ".", "resource_filename", "(", "pkg", ",", "os", ".", "path", ".", "join", "(", "'test'", ",", "r", ")", ")", "if", "not", "os", "...
36.7
12.3
def xor_fault(a, b, out, fault): """Returns True if XOR(a, b) == out and fault == 0 or XOR(a, b) != out and fault == 1.""" if (a != b) == out: return fault == 0 else: return fault == 1
[ "def", "xor_fault", "(", "a", ",", "b", ",", "out", ",", "fault", ")", ":", "if", "(", "a", "!=", "b", ")", "==", "out", ":", "return", "fault", "==", "0", "else", ":", "return", "fault", "==", "1" ]
34.5
14.333333
def add_new_source(self, source_token, stripe_js_response=None): """Add new source (for example: a new card) to the customer The new source will be automatically set as customer's default payment source. Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be u...
[ "def", "add_new_source", "(", "self", ",", "source_token", ",", "stripe_js_response", "=", "None", ")", ":", "customer", "=", "self", ".", "retrieve_from_stripe", "(", ")", "customer", ".", "source", "=", "source_token", "customer", ".", "save", "(", ")", "i...
48
19.666667
def get_dag(self, dag_id): """ Gets the DAG out of the dictionary, and refreshes it if expired """ from airflow.models.dag import DagModel # Avoid circular import # If asking for a known subdag, we want to refresh the parent root_dag_id = dag_id if dag_id in sel...
[ "def", "get_dag", "(", "self", ",", "dag_id", ")", ":", "from", "airflow", ".", "models", ".", "dag", "import", "DagModel", "# Avoid circular import", "# If asking for a known subdag, we want to refresh the parent", "root_dag_id", "=", "dag_id", "if", "dag_id", "in", ...
38.625
17.8125
def relation_factory(relation_name): """Get the RelationFactory for the given relation name. Looks for a RelationFactory in the first file matching: ``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py`` """ role, interface = hookenv.relation_to_role_and_interface(relation_name) ...
[ "def", "relation_factory", "(", "relation_name", ")", ":", "role", ",", "interface", "=", "hookenv", ".", "relation_to_role_and_interface", "(", "relation_name", ")", "if", "not", "(", "role", "and", "interface", ")", ":", "hookenv", ".", "log", "(", "'Unable ...
47.083333
20.416667
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The resize event. """ self._update_transforms() if self._central_widget is not None: self._central_widget.size = self.size ...
[ "def", "on_resize", "(", "self", ",", "event", ")", ":", "self", ".", "_update_transforms", "(", ")", "if", "self", ".", "_central_widget", "is", "not", "None", ":", "self", ".", "_central_widget", ".", "size", "=", "self", ".", "size", "if", "len", "(...
27.133333
14.866667
def dopri853core(n, func, x, t, hmax, h, rtol, atol, nmax, safe, beta, fac1, fac2, pos_neg, args): """ Core of DOP8(5, 3) integration """ # array to store the result result = np.zeros((len(t), n)) # initial preparations facold = 1.0e-4 expo1 = 1.0 / 8.0 - beta * 0.2 facc1 = 1.0 / fa...
[ "def", "dopri853core", "(", "n", ",", "func", ",", "x", ",", "t", ",", "hmax", ",", "h", ",", "rtol", ",", "atol", ",", "nmax", ",", "safe", ",", "beta", ",", "fac1", ",", "fac2", ",", "pos_neg", ",", "args", ")", ":", "# array to store the result"...
40.352201
27.081761
def hook(self, m:nn.Module, i:Tensors, o:Tensors)->Tuple[Rank0Tensor,Rank0Tensor]: "Take the mean and std of `o`." return o.mean().item(),o.std().item()
[ "def", "hook", "(", "self", ",", "m", ":", "nn", ".", "Module", ",", "i", ":", "Tensors", ",", "o", ":", "Tensors", ")", "->", "Tuple", "[", "Rank0Tensor", ",", "Rank0Tensor", "]", ":", "return", "o", ".", "mean", "(", ")", ".", "item", "(", ")...
55.333333
16
def q(self, q): """ Set the quaternion :param q: list or array of quaternion values [w, x, y, z] """ self._q = np.array(q) # mark other representations as outdated, will get generated on next # read self._euler = None self._dcm = None
[ "def", "q", "(", "self", ",", "q", ")", ":", "self", ".", "_q", "=", "np", ".", "array", "(", "q", ")", "# mark other representations as outdated, will get generated on next", "# read", "self", ".", "_euler", "=", "None", "self", ".", "_dcm", "=", "None" ]
27
18.818182
def remove(self, *terminals): # type: (Iterable[Any]) -> None """ Remove terminals from the set. Removes also rules using this terminal. :param terminals: Terminals to remove. :raise KeyError if the object is not in the set. """ for term in set(terminals):...
[ "def", "remove", "(", "self", ",", "*", "terminals", ")", ":", "# type: (Iterable[Any]) -> None", "for", "term", "in", "set", "(", "terminals", ")", ":", "if", "term", "not", "in", "self", ":", "raise", "KeyError", "(", "'Terminal '", "+", "str", "(", "t...
40.571429
10
def split(text): """ Split text into arguments accounting for muti-word arguments which are double quoted """ # Cleanup text text = text.strip() text = re.sub('\s+', ' ', text) # collpse multiple spaces space, quote, parts = ' ', '"', [] part, quoted = '', False for char in text: ...
[ "def", "split", "(", "text", ")", ":", "# Cleanup text", "text", "=", "text", ".", "strip", "(", ")", "text", "=", "re", ".", "sub", "(", "'\\s+'", ",", "' '", ",", "text", ")", "# collpse multiple spaces", "space", ",", "quote", ",", "parts", "=", "...
23.413043
18.869565
def discoverdevs(self): ''' Find all the pcap-eligible devices on the local system. ''' if len(self._interfaces): raise PcapException("Device discovery should only be done once.") ppintf = self._ffi.new("pcap_if_t * *") errbuf = self._ffi.new("cha...
[ "def", "discoverdevs", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_interfaces", ")", ":", "raise", "PcapException", "(", "\"Device discovery should only be done once.\"", ")", "ppintf", "=", "self", ".", "_ffi", ".", "new", "(", "\"pcap_if_t * *\"", ...
38.744681
20.319149
def parse_fade_requirement(text): """Return a requirement and repo from the given text, already parsed and converted.""" text = text.strip() if "::" in text: repo_raw, requirement = text.split("::", 1) try: repo = {'pypi': REPO_PYPI, 'vcs': REPO_VCS}[repo_raw] except Key...
[ "def", "parse_fade_requirement", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "\"::\"", "in", "text", ":", "repo_raw", ",", "requirement", "=", "text", ".", "split", "(", "\"::\"", ",", "1", ")", "try", ":", "repo", "=", ...
31.347826
19.434783
def CSS_setEffectivePropertyValueForNode(self, nodeId, propertyName, value): """ Function path: CSS.setEffectivePropertyValueForNode Domain: CSS Method name: setEffectivePropertyValueForNode WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'nodeId' (type: D...
[ "def", "CSS_setEffectivePropertyValueForNode", "(", "self", ",", "nodeId", ",", "propertyName", ",", "value", ")", ":", "assert", "isinstance", "(", "propertyName", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'propertyName' must be of type '['str']'. Received type:...
38.851852
22.703704
def thumbs(self): """Returns the URLs of all thumbnails in the thread.""" if self.topic.has_file: yield self.topic.file.thumbnail_url for reply in self.replies: if reply.has_file: yield reply.file.thumbnail_url
[ "def", "thumbs", "(", "self", ")", ":", "if", "self", ".", "topic", ".", "has_file", ":", "yield", "self", ".", "topic", ".", "file", ".", "thumbnail_url", "for", "reply", "in", "self", ".", "replies", ":", "if", "reply", ".", "has_file", ":", "yield...
38.285714
8.714286
def _get_default_locs(self, vmin, vmax): "Returns the default locations of ticks." if self.plot_obj.date_axis_info is None: self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) locator = self.plot_obj.date_axis_info if self.isminor: return np.compr...
[ "def", "_get_default_locs", "(", "self", ",", "vmin", ",", "vmax", ")", ":", "if", "self", ".", "plot_obj", ".", "date_axis_info", "is", "None", ":", "self", ".", "plot_obj", ".", "date_axis_info", "=", "self", ".", "finder", "(", "vmin", ",", "vmax", ...
36.727273
21.454545
def matches(property_name, regex, *, present_optional=False, message=None): """Returns a Validation that checks a property against a regex.""" def check(val): """Checks that a value matches a scope-enclosed regex.""" if not val: return present_optional else: return True if rege...
[ "def", "matches", "(", "property_name", ",", "regex", ",", "*", ",", "present_optional", "=", "False", ",", "message", "=", "None", ")", ":", "def", "check", "(", "val", ")", ":", "\"\"\"Checks that a value matches a scope-enclosed regex.\"\"\"", "if", "not", "v...
38.9
18
def get_cluster_graph(self, engine="fdp", graph_attr=None, node_attr=None, edge_attr=None): """ Generate directory graph in the DOT language. Directories are shown as clusters .. warning:: This function scans the entire directory tree starting from top so the resulting ...
[ "def", "get_cluster_graph", "(", "self", ",", "engine", "=", "\"fdp\"", ",", "graph_attr", "=", "None", ",", "node_attr", "=", "None", ",", "edge_attr", "=", "None", ")", ":", "# https://www.graphviz.org/doc/info/", "from", "graphviz", "import", "Digraph", "g", ...
45.873563
22.471264
def _find_id(self, id_): """Moves to row where formula is (if found, otherwise does nothing)""" for i, row in enumerate(self._data): if row["id"] == id_: t = self.tableWidget # idx = t.itemFromIndex() t.setCurrentCell(i, 0) ...
[ "def", "_find_id", "(", "self", ",", "id_", ")", ":", "for", "i", ",", "row", "in", "enumerate", "(", "self", ".", "_data", ")", ":", "if", "row", "[", "\"id\"", "]", "==", "id_", ":", "t", "=", "self", ".", "tableWidget", "# idx = t.itemFromIndex()\...
40.125
6.5
def enable_backups(self, table_name, model): """Calls UpdateContinuousBackups on the table according to model.Meta["continuous_backups"] :param table_name: The name of the table to enable Continuous Backups on :param model: The model to get Continuous Backups settings from """ s...
[ "def", "enable_backups", "(", "self", ",", "table_name", ",", "model", ")", ":", "self", ".", "_tables", ".", "pop", "(", "table_name", ",", "None", ")", "request", "=", "{", "\"TableName\"", ":", "table_name", ",", "\"PointInTimeRecoverySpecification\"", ":",...
48.6
23.133333
def create_ml_configuration_from_datasets(self, dataset_ids): """ Creates an ml configuration from dataset_ids and extract_as_keys :param dataset_ids: Array of dataset identifiers to make search template from :return: An identifier used to request the status of the builder job (get_ml_c...
[ "def", "create_ml_configuration_from_datasets", "(", "self", ",", "dataset_ids", ")", ":", "available_columns", "=", "self", ".", "search_template_client", ".", "get_available_columns", "(", "dataset_ids", ")", "# Create a search template from dataset ids", "search_template", ...
55.916667
34.083333
def operator(self, text): """Push an operator onto the token queue.""" cls = self.OPERATORS[text] self.push_token(cls(text, self.lineno, self.offset))
[ "def", "operator", "(", "self", ",", "text", ")", ":", "cls", "=", "self", ".", "OPERATORS", "[", "text", "]", "self", ".", "push_token", "(", "cls", "(", "text", ",", "self", ".", "lineno", ",", "self", ".", "offset", ")", ")" ]
42.75
10.25
def clear_zones(self): """stub""" if self.get_zones_metadata().is_read_only(): raise NoAccess() self.my_osid_object_form._my_map['zones'] = \ self._zones_metadata['default_object_values'][0]
[ "def", "clear_zones", "(", "self", ")", ":", "if", "self", ".", "get_zones_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise", "NoAccess", "(", ")", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'zones'", "]", "=", "self", ".", ...
38.833333
12.5
def enrichr(gene_list, gene_sets, organism='human', description='', outdir='Enrichr', background='hsapiens_gene_ensembl', cutoff=0.05, format='pdf', figsize=(8,6), top_term=10, no_plot=False, verbose=False): """Enrichr API. :param gene_list: Flat file with list of genes, one gene id per...
[ "def", "enrichr", "(", "gene_list", ",", "gene_sets", ",", "organism", "=", "'human'", ",", "description", "=", "''", ",", "outdir", "=", "'Enrichr'", ",", "background", "=", "'hsapiens_gene_ensembl'", ",", "cutoff", "=", "0.05", ",", "format", "=", "'pdf'",...
58.282051
36.333333
def locate(self, path): """ Find a config item along a path; leading slash is optional and ignored. """ return Zconfig(lib.zconfig_locate(self._as_parameter_, path), False)
[ "def", "locate", "(", "self", ",", "path", ")", ":", "return", "Zconfig", "(", "lib", ".", "zconfig_locate", "(", "self", ".", "_as_parameter_", ",", "path", ")", ",", "False", ")" ]
40
18.4
def has_role_collective(self, role_s, logical_operator=all): """ :param role_s: 1..N role identifier :type role_s: a Set of Strings :param logical_operator: indicates whether all or at least one permission check is true (any) :type: any OR all...
[ "def", "has_role_collective", "(", "self", ",", "role_s", ",", "logical_operator", "=", "all", ")", ":", "if", "self", ".", "authorized", ":", "return", "self", ".", "security_manager", ".", "has_role_collective", "(", "self", ".", "identifiers", ",", "role_s"...
41.888889
20.777778
def create(self, validated_data): """Override ``create`` to provide a user via request.user by default. This is required since the read_only ``user`` field is not included by default anymore since https://github.com/encode/django-rest-framework/pull/5886. """ if 'user' n...
[ "def", "create", "(", "self", ",", "validated_data", ")", ":", "if", "'user'", "not", "in", "validated_data", ":", "validated_data", "[", "'user'", "]", "=", "self", ".", "context", "[", "'request'", "]", ".", "user", "return", "super", "(", "RefreshTokenS...
47.2
18
def read(self, ifile): """ Reads an input header from an input file. The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the input header is signalled by an empty line or an end-of-file. :param ifile: File-like object that supports ...
[ "def", "read", "(", "self", ",", "ifile", ")", ":", "name", ",", "value", "=", "None", ",", "None", "for", "line", "in", "ifile", ":", "if", "line", "==", "'\\n'", ":", "break", "item", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "if"...
38.16
22.56
def accepts(self): # type: Union[Iterable[Type[T]], Type[Any]] """The types of objects the data sink can store.""" types = set() any_dispatch = False try: types.update(getattr(self.__class__, "put")._accepts) any_dispatch = True except AttributeError: ...
[ "def", "accepts", "(", "self", ")", ":", "# type: Union[Iterable[Type[T]], Type[Any]]", "types", "=", "set", "(", ")", "any_dispatch", "=", "False", "try", ":", "types", ".", "update", "(", "getattr", "(", "self", ".", "__class__", ",", "\"put\"", ")", ".", ...
35.933333
17.733333
def create_body(self, shape, name=None, **kwargs): '''Create a new body. Parameters ---------- shape : str The "shape" of the body to be created. This should name a type of body object, e.g., "box" or "cap". name : str, optional The name to us...
[ "def", "create_body", "(", "self", ",", "shape", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "shape", "=", "shape", ".", "lower", "(", ")", "if", "name", "is", "None", ":", "for", "i", "in", "range", "(", "1", "+", "len", "(", ...
34.44
19.4
def read(self, file_path: str) -> Iterable[Instance]: """ Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self...
[ "def", "read", "(", "self", ",", "file_path", ":", "str", ")", "->", "Iterable", "[", "Instance", "]", ":", "lazy", "=", "getattr", "(", "self", ",", "'lazy'", ",", "None", ")", "if", "lazy", "is", "None", ":", "logger", ".", "warning", "(", "\"Dat...
45.436364
24.309091
def _from_jsonlines(cls, lines, selector_handler=None, strict=False, debug=False): """ Interpret input lines as a JSON Parsley script. Python-style comment lines are skipped. """ return cls(json.loads( "\n".join([l for l in lines if not cls.REGEX_COMMENT_LINE.mat...
[ "def", "_from_jsonlines", "(", "cls", ",", "lines", ",", "selector_handler", "=", "None", ",", "strict", "=", "False", ",", "debug", "=", "False", ")", ":", "return", "cls", "(", "json", ".", "loads", "(", "\"\\n\"", ".", "join", "(", "[", "l", "for"...
44.111111
21.666667
def prox_components(X, step, prox=None, axis=0): """Split X along axis and apply prox to each chunk. prox can be a list. """ K = X.shape[axis] if not hasattr(prox_list, '__iter__'): prox = [prox] * K assert len(prox_list) == K if axis == 0: Pk = [prox_list[k](X[k], step) f...
[ "def", "prox_components", "(", "X", ",", "step", ",", "prox", "=", "None", ",", "axis", "=", "0", ")", ":", "K", "=", "X", ".", "shape", "[", "axis", "]", "if", "not", "hasattr", "(", "prox_list", ",", "'__iter__'", ")", ":", "prox", "=", "[", ...
27.1875
17.4375
def status(url="http://127.0.0.1/status"): """ Return the data from an Nginx status page as a dictionary. http://wiki.nginx.org/HttpStubStatusModule url The URL of the status page. Defaults to 'http://127.0.0.1/status' CLI Example: .. code-block:: bash salt '*' nginx.status ...
[ "def", "status", "(", "url", "=", "\"http://127.0.0.1/status\"", ")", ":", "resp", "=", "_urlopen", "(", "url", ")", "status_data", "=", "resp", ".", "read", "(", ")", "resp", ".", "close", "(", ")", "lines", "=", "status_data", ".", "splitlines", "(", ...
27.162162
16.945946
def tile_fonts(self, fontstack, stack_range, out_folder=None): """This resource returns glyphs in PBF format. The template url for this fonts resource is represented in Vector Tile Style resource.""" url = "{url}/resources/fonts/{fontstack}/{stack_range}.pbf".format( url=self._url, ...
[ "def", "tile_fonts", "(", "self", ",", "fontstack", ",", "stack_range", ",", "out_folder", "=", "None", ")", ":", "url", "=", "\"{url}/resources/fonts/{fontstack}/{stack_range}.pbf\"", ".", "format", "(", "url", "=", "self", ".", "_url", ",", "fontstack", "=", ...
48
11.5625
def normalize_target_params(self, request, controller_args, controller_kwargs): """get params ready for calling target this method exists because child classes might only really need certain params passed to the method, this allows the child classes to decided what their target methods ...
[ "def", "normalize_target_params", "(", "self", ",", "request", ",", "controller_args", ",", "controller_kwargs", ")", ":", "return", "[", "]", ",", "dict", "(", "request", "=", "request", ",", "controller_args", "=", "controller_args", ",", "controller_kwargs", ...
49.052632
26.263158
async def getLiftRows(self, lops): ''' Returns: Iterable[Tuple[bytes, Dict[str, Any]]]: yield a stream of tuple (buid, propdict) ''' for oper in lops: func = self._lift_funcs.get(oper[0]) if func is None: raise s_exc.NoSuchLift(name=o...
[ "async", "def", "getLiftRows", "(", "self", ",", "lops", ")", ":", "for", "oper", "in", "lops", ":", "func", "=", "self", ".", "_lift_funcs", ".", "get", "(", "oper", "[", "0", "]", ")", "if", "func", "is", "None", ":", "raise", "s_exc", ".", "No...
31.666667
19.8
def dot_path(obj: t.Union[t.Dict, object], path: str, default: t.Any = None, separator: str = '.'): """ Provides an access to elements of a mixed dict/object type by a delimiter-separated path. :: class O1: my_dict = {'a': {'b': 1}} class ...
[ "def", "dot_path", "(", "obj", ":", "t", ".", "Union", "[", "t", ".", "Dict", ",", "object", "]", ",", "path", ":", "str", ",", "default", ":", "t", ".", "Any", "=", "None", ",", "separator", ":", "str", "=", "'.'", ")", ":", "path_items", "=",...
24.795455
18.431818
def report(self, fraction=None): """report the total progress for the current stack, optionally given the local fraction completed. fraction=None: if given, used as the fraction of the local method so far completed. runtimes=None: if given, used as the expected runtimes for the current stack. """ r = Dict() ...
[ "def", "report", "(", "self", ",", "fraction", "=", "None", ")", ":", "r", "=", "Dict", "(", ")", "local_key", "=", "self", ".", "stack_key", "if", "local_key", "is", "None", ":", "return", "{", "}", "runtimes", "=", "self", ".", "runtimes", "(", "...
39.555556
15.5
def handle_request(self): """Handle one request, possibly blocking. Respects self.timeout. """ # Support people who used socket.settimeout() to escape # handle_request before self.timeout was available. timeout = self.socket.gettimeout() if timeout is None: ...
[ "def", "handle_request", "(", "self", ")", ":", "# Support people who used socket.settimeout() to escape", "# handle_request before self.timeout was available.", "timeout", "=", "self", ".", "socket", ".", "gettimeout", "(", ")", "if", "timeout", "is", "None", ":", "timeo...
35.117647
11.705882
def render_ditaa(self, code, options, prefix='ditaa'): """Render ditaa code into a PNG output file.""" hashkey = code.encode('utf-8') + str(options) + \ str(self.builder.config.ditaa) + \ str(self.builder.config.ditaa_args) infname = '%s-%s.%s' % (prefix, sha(hashkey).hexdigest()...
[ "def", "render_ditaa", "(", "self", ",", "code", ",", "options", ",", "prefix", "=", "'ditaa'", ")", ":", "hashkey", "=", "code", ".", "encode", "(", "'utf-8'", ")", "+", "str", "(", "options", ")", "+", "str", "(", "self", ".", "builder", ".", "co...
36.261538
18.769231
def normalize(opts): """ Performs various normalization functions on opts, the provided namespace. It is assumed that opts has already been validated with anchorhub.validation_opts.validate(). :param opts: a namespace containing options for AnchorHub :return: a namespace with the attributes mod...
[ "def", "normalize", "(", "opts", ")", ":", "opts_dict", "=", "vars", "(", "opts", ")", "add_is_dir", "(", "opts_dict", ")", "ensure_directories_end_in_separator", "(", "opts_dict", ")", "add_abs_path_directories", "(", "opts_dict", ")", "add_open_close_wrappers", "(...
35.125
13.375
def sort_amounts(proteins, sort_index): """Generic function for sorting peptides and psms. Assumes a higher number is better for what is passed at sort_index position in protein.""" amounts = {} for protein in proteins: amount_x_for_protein = protein[sort_index] try: amounts[...
[ "def", "sort_amounts", "(", "proteins", ",", "sort_index", ")", ":", "amounts", "=", "{", "}", "for", "protein", "in", "proteins", ":", "amount_x_for_protein", "=", "protein", "[", "sort_index", "]", "try", ":", "amounts", "[", "amount_x_for_protein", "]", "...
44.636364
13.181818
def ImpulseNoise(p=0, name=None, deterministic=False, random_state=None): """ Creates an augmenter to apply impulse noise to an image. This is identical to ``SaltAndPepper``, except that per_channel is always set to True. dtype support:: See ``imgaug.augmenters.arithmetic.SaltAndPepper``. ...
[ "def", "ImpulseNoise", "(", "p", "=", "0", ",", "name", "=", "None", ",", "deterministic", "=", "False", ",", "random_state", "=", "None", ")", ":", "return", "SaltAndPepper", "(", "p", "=", "p", ",", "per_channel", "=", "True", ",", "name", "=", "na...
35.75
31.416667
def addsshkeyuser(self, user_id, title, key): """ Add a new ssh key for the user identified by id :param user_id: id of the user to add the key to :param title: title of the new key :param key: the key itself :return: true if added, false if it didn't add it (it could be...
[ "def", "addsshkeyuser", "(", "self", ",", "user_id", ",", "title", ",", "key", ")", ":", "data", "=", "{", "'title'", ":", "title", ",", "'key'", ":", "key", "}", "request", "=", "requests", ".", "post", "(", "'{0}/{1}/keys'", ".", "format", "(", "se...
36.947368
20.631579
def search(self, evaluation, data): """ Performs the search and returns the indices of the selected attributes. :param evaluation: the evaluation algorithm to use :type evaluation: ASEvaluation :param data: the data to use :type data: Instances :return: the selec...
[ "def", "search", "(", "self", ",", "evaluation", ",", "data", ")", ":", "array", "=", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"search\"", ",", "\"(Lweka/attributeSelection/ASEvaluation;Lweka/core/Instances;)[I\"", ",", "evaluation", ".", "jo...
37.777778
17.222222
def ib_group_member_add(self, group_id, userids): ''' ib group member add ''' req_hook = 'pod/v1/admin/group/' + group_id + '/membership/add' req_args = {'usersListId': userids} req_args = json.dumps(req_args) status_code, response = self.__rest__.POST_query(req_hook, req_args) ...
[ "def", "ib_group_member_add", "(", "self", ",", "group_id", ",", "userids", ")", ":", "req_hook", "=", "'pod/v1/admin/group/'", "+", "group_id", "+", "'/membership/add'", "req_args", "=", "{", "'usersListId'", ":", "userids", "}", "req_args", "=", "json", ".", ...
51.25
13.75
def apply_sfr_obs(): """apply the sfr observation process - pairs with setup_sfr_obs(). requires sfr_obs.config. Writes <sfr_out_file>.processed, where <sfr_out_file> is defined in "sfr_obs.config" Parameters ---------- None Returns ------- df : pd.DataFrame a dataframe o...
[ "def", "apply_sfr_obs", "(", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "\"sfr_obs.config\"", ")", "df_key", "=", "pd", ".", "read_csv", "(", "\"sfr_obs.config\"", ",", "index_col", "=", "0", ")", "assert", "df_key", ".", "iloc", "[", "0"...
34.85
21.125
def _migrate(data: Mapping[str, Any]) -> SettingsData: """ Check the version integer of the JSON file data a run any necessary migrations to get us to the latest file format. Returns dictionary of settings and version migrated to """ next = dict(data) version = next.pop('_version', 0) ta...
[ "def", "_migrate", "(", "data", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "SettingsData", ":", "next", "=", "dict", "(", "data", ")", "version", "=", "next", ".", "pop", "(", "'_version'", ",", "0", ")", "target_version", "=", "len", ...
30.5
16.8
def unregister(self, event): """ Remove all registered handlers for an event. Silent return when event was not registered. Usage: dispatch.unregister("my_event") dispatch.unregister("my_event") # no-op """ if self.running: raise Run...
[ "def", "unregister", "(", "self", ",", "event", ")", ":", "if", "self", ".", "running", ":", "raise", "RuntimeError", "(", "\"Can't unregister while running\"", ")", "self", ".", "_handlers", ".", "pop", "(", "event", ",", "None", ")" ]
27.857143
17
def decay(ax, p0, pf, A, n, format=None, **kwds): r"""Draw a spontaneous decay as a wavy line.""" if format is None: format = 'k-' T = sqrt((p0[0]-pf[0])**2+(p0[1]-pf[1])**2) alpha = atan2(pf[1]-p0[1], pf[0]-p0[0]) x = [i*T/400.0 for i in range(401)] y = [A*sin(xi * 2*pi*n/T) for xi in x...
[ "def", "decay", "(", "ax", ",", "p0", ",", "pf", ",", "A", ",", "n", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'", "T", "=", "sqrt", "(", "(", "p0", "[", "0", "]", "...
33.714286
14.285714
def combine_urls(path1, path2): """ Returns the combination of two urls and checks that there are no double slashes at the seam. TODO: Extend to check for other anomalies as well. :param path1: First part of the url :param path2: Second part of the url :return: Combination of the paths with dou...
[ "def", "combine_urls", "(", "path1", ",", "path2", ")", ":", "if", "path1", ".", "endswith", "(", "\"/\"", ")", "and", "path2", ".", "startswith", "(", "\"/\"", ")", ":", "path2", "=", "path2", ".", "replace", "(", "\"/\"", ",", "\"\"", ",", "1", "...
39.785714
15.785714
def validate_slice_increment(dicoms): """ Validate that the distance between all slices is equal (or very close to) :param dicoms: list of dicoms """ first_image_position = numpy.array(dicoms[0].ImagePositionPatient) previous_image_position = numpy.array(dicoms[1].ImagePositionPatient) inc...
[ "def", "validate_slice_increment", "(", "dicoms", ")", ":", "first_image_position", "=", "numpy", ".", "array", "(", "dicoms", "[", "0", "]", ".", "ImagePositionPatient", ")", "previous_image_position", "=", "numpy", ".", "array", "(", "dicoms", "[", "1", "]",...
55.782609
27.434783
def recover_buildpack(app_folder): """ Given the path to an app folder where an app was just built, return a BuildPack object pointing to the dir for the buildpack used during the build. Relies on the builder.sh script storing the buildpack location in /.buildpack inside the container. """ ...
[ "def", "recover_buildpack", "(", "app_folder", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "app_folder", ",", "'.buildpack'", ")", "with", "open", "(", "filepath", ")", "as", "f", ":", "buildpack_picked", "=", "f", ".", "read", "(", ...
39.6875
15.9375
def parse_response_adu(resp_adu, req_adu=None): """ Parse response ADU and return response data. Some functions require request ADU to fully understand request ADU. :param resp_adu: Resonse ADU. :param req_adu: Request ADU, default None. :return: Response data. """ resp_pdu = resp_adu[7:] ...
[ "def", "parse_response_adu", "(", "resp_adu", ",", "req_adu", "=", "None", ")", ":", "resp_pdu", "=", "resp_adu", "[", "7", ":", "]", "function", "=", "create_function_from_response_pdu", "(", "resp_pdu", ",", "req_adu", ")", "return", "function", ".", "data" ...
33.416667
14.75