text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
async def close_all_connections(self) -> None: """Close all open connections and asynchronously wait for them to finish. This method is used in combination with `~.TCPServer.stop` to support clean shutdowns (especially for unittests). Typical usage would call ``stop()`` first to stop ac...
[ "async", "def", "close_all_connections", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_connections", ":", "# Peek at an arbitrary element of the set", "conn", "=", "next", "(", "iter", "(", "self", ".", "_connections", ")", ")", "await", "conn", ...
42.222222
21.444444
def reduce_sort(self, js_cmp=None, options=None): """ Adds the Javascript built-in ``Riak.reduceSort`` to the query as a reduce phase. :param js_cmp: A Javascript comparator function as specified by Array.sort() :type js_cmp: string :param options: phase option...
[ "def", "reduce_sort", "(", "self", ",", "js_cmp", "=", "None", ",", "options", "=", "None", ")", ":", "if", "options", "is", "None", ":", "options", "=", "dict", "(", ")", "if", "js_cmp", ":", "options", "[", "'arg'", "]", "=", "js_cmp", "return", ...
30.578947
18.894737
def checkUserManage(self): """ Checks if the current user has granted access to this worksheet and if has also privileges for managing it. """ granted = False can_access = self.checkUserAccess() if can_access is True: pm = getToolByName(self, 'portal_memb...
[ "def", "checkUserManage", "(", "self", ")", ":", "granted", "=", "False", "can_access", "=", "self", ".", "checkUserAccess", "(", ")", "if", "can_access", "is", "True", ":", "pm", "=", "getToolByName", "(", "self", ",", "'portal_membership'", ")", "edit_allo...
39.363636
15.272727
def get_env_setting(setting): """ Get the environment setting or return exception """ try: return os.environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg)
[ "def", "get_env_setting", "(", "setting", ")", ":", "try", ":", "return", "os", ".", "environ", "[", "setting", "]", "except", "KeyError", ":", "error_msg", "=", "\"Set the %s env variable\"", "%", "setting", "raise", "ImproperlyConfigured", "(", "error_msg", ")...
35.714286
12.714286
def get(self, request): '''Get user information, with a list of permissions for that user.''' user = request.user serializer = PermissionsUserSerializer( instance=user, context={'request': request}) return Response(data=serializer.data)
[ "def", "get", "(", "self", ",", "request", ")", ":", "user", "=", "request", ".", "user", "serializer", "=", "PermissionsUserSerializer", "(", "instance", "=", "user", ",", "context", "=", "{", "'request'", ":", "request", "}", ")", "return", "Response", ...
45.833333
15.833333
def ahrs_send(self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw, force_mavlink1=False): ''' Status of DCM attitude estimator omegaIx : X gyro drift estimate rad/s (float) omegaIy : Y gyro dr...
[ "def", "ahrs_send", "(", "self", ",", "omegaIx", ",", "omegaIy", ",", "omegaIz", ",", "accel_weight", ",", "renorm_val", ",", "error_rp", ",", "error_yaw", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "a...
64.571429
42
def deleteFromStore(self): """ Delete all the Items which are found by this query. """ if (self.limit is None and not isinstance(self.sort, attributes.UnspecifiedOrdering)): # The ORDER BY is pointless here, and SQLite complains about it. return self.c...
[ "def", "deleteFromStore", "(", "self", ")", ":", "if", "(", "self", ".", "limit", "is", "None", "and", "not", "isinstance", "(", "self", ".", "sort", ",", "attributes", ".", "UnspecifiedOrdering", ")", ")", ":", "# The ORDER BY is pointless here, and SQLite comp...
41.682927
20.95122
def rcs(J,P,R,T,p,c,a,RUB): """rcs -- model for the resource constrained scheduling problem Parameters: - J: set of jobs - P: set of precedence constraints between jobs - R: set of resources - T: number of periods - p[j]: processing time of job j - c[j,t]: cost in...
[ "def", "rcs", "(", "J", ",", "P", ",", "R", ",", "T", ",", "p", ",", "c", ",", "a", ",", "RUB", ")", ":", "model", "=", "Model", "(", "\"resource constrained scheduling\"", ")", "s", ",", "x", "=", "{", "}", ",", "{", "}", "# s - start time varia...
38.511628
23.488372
def use_winlegacy(): """ Forces use of the legacy Windows CryptoAPI. This should only be used on Windows XP or for testing. It is less full-featured than the Cryptography Next Generation (CNG) API, and as a result the elliptic curve and PSS padding features are implemented in pure Python. This isn't...
[ "def", "use_winlegacy", "(", ")", ":", "if", "sys", ".", "platform", "!=", "'win32'", ":", "plat", "=", "platform", ".", "system", "(", ")", "or", "sys", ".", "platform", "if", "plat", "==", "'Darwin'", ":", "plat", "=", "'OS X'", "raise", "Environment...
44.461538
28.153846
def unpack(self, token): """ Unpack a received signed or signed and encrypted Json Web Token :param token: The Json Web Token :return: If decryption and signature verification work the payload will be returned as a Message instance if possible. """ if not tok...
[ "def", "unpack", "(", "self", ",", "token", ")", ":", "if", "not", "token", ":", "raise", "KeyError", "_jwe_header", "=", "_jws_header", "=", "None", "# Check if it's an encrypted JWT", "darg", "=", "{", "}", "if", "self", ".", "allowed_enc_encs", ":", "darg...
33.369048
16.297619
def sum_abs_distance(labels, preds): """ Compute the sum of abs distances. :param labels: A float tensor of shape [batch_size, ..., X] representing the labels. :param preds: A float tensor of shape [batch_size, ..., X] representing the predictions. :return: A float tensor of shape [batch_size, ...]...
[ "def", "sum_abs_distance", "(", "labels", ",", "preds", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"sum_abs_distance\"", ")", ":", "return", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "preds", "-", "labels", ")", ",", "axis", "=", ...
47.2
23.2
def lemmas(self): """Returns the synset's lemmas/variants' literal represantions. Returns ------- list of Lemmas List of its variations' literals as Lemma objects. """ return [lemma("%s.%s"%(self.name,variant.literal)) for variant in self._raw_...
[ "def", "lemmas", "(", "self", ")", ":", "return", "[", "lemma", "(", "\"%s.%s\"", "%", "(", "self", ".", "name", ",", "variant", ".", "literal", ")", ")", "for", "variant", "in", "self", ".", "_raw_synset", ".", "variants", "]" ]
32.7
23.1
def cut(args): """ %prog cut agpfile bedfile Cut at the boundaries of the ranges in the bedfile. """ p = OptionParser(cut.__doc__) p.add_option("--sep", default=".", help="Separator for splits") opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) ...
[ "def", "cut", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "cut", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sep\"", ",", "default", "=", "\".\"", ",", "help", "=", "\"Separator for splits\"", ")", "opts", ",", "args", "=", "p", ...
25.911765
18.323529
def server(value=None): """Get the hostname of the server or set the server using hostname or aliases. Supported aliases: 'localhost', 'staging', 'labs'. Also set via environment variable GRAPHISTRY_HOSTNAME.""" if value is None: return PyGraphistry._config['hostname'] ...
[ "def", "server", "(", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "PyGraphistry", ".", "_config", "[", "'hostname'", "]", "# setter", "shortcuts", "=", "{", "'dev'", ":", "'localhost:3000'", ",", "'staging'", ":", "'staging....
43.235294
14.823529
def from_buffer(string, serverEndpoint=ServerEndpoint): ''' Parse from buffered content :param string: buffered content :param serverEndpoint: Tika server URL (Optional) :return: parsed content ''' status, response = callServer('put', serverEndpoint, '/unpack/all', string, ...
[ "def", "from_buffer", "(", "string", ",", "serverEndpoint", "=", "ServerEndpoint", ")", ":", "status", ",", "response", "=", "callServer", "(", "'put'", ",", "serverEndpoint", ",", "'/unpack/all'", ",", "string", ",", "{", "'Accept'", ":", "'application/x-tar'",...
38
20.5
def stack_layer(self, layer, no_setup=False): """ Stack a neural layer. :type layer: NeuralLayer :param no_setup: whether the layer is already initialized """ if layer.name: layer.name += "%d" % (len(self.layers) + 1) if not self.layers: la...
[ "def", "stack_layer", "(", "self", ",", "layer", ",", "no_setup", "=", "False", ")", ":", "if", "layer", ".", "name", ":", "layer", ".", "name", "+=", "\"%d\"", "%", "(", "len", "(", "self", ".", "layers", ")", "+", "1", ")", "if", "not", "self",...
40
14
def orderExecuted(self, orderDict): ''' call back for executed order ''' for orderId, order in orderDict.items(): if order.symbol in self.__trakers.keys(): self.__trakers[order.symbol].orderExecuted(orderId)
[ "def", "orderExecuted", "(", "self", ",", "orderDict", ")", ":", "for", "orderId", ",", "order", "in", "orderDict", ".", "items", "(", ")", ":", "if", "order", ".", "symbol", "in", "self", ".", "__trakers", ".", "keys", "(", ")", ":", "self", ".", ...
49.4
11.4
def find_jamfile (self, dir, parent_root=0, no_errors=0): """Find the Jamfile at the given location. This returns the exact names of all the Jamfiles in the given directory. The optional parent-root argument causes this to search not the given directory but the ones above it up to the di...
[ "def", "find_jamfile", "(", "self", ",", "dir", ",", "parent_root", "=", "0", ",", "no_errors", "=", "0", ")", ":", "assert", "isinstance", "(", "dir", ",", "basestring", ")", "assert", "isinstance", "(", "parent_root", ",", "(", "int", ",", "bool", ")...
43.377358
15.716981
def batch_put_attributes(self, domain_or_name, items, replace=True): """ Store attributes for multiple items in a domain. :type domain_or_name: string or :class:`boto.sdb.domain.Domain` object. :param domain_or_name: Either the name of a domain or a Domain object :type ...
[ "def", "batch_put_attributes", "(", "self", ",", "domain_or_name", ",", "items", ",", "replace", "=", "True", ")", ":", "domain", ",", "domain_name", "=", "self", ".", "get_domain_and_name", "(", "domain_or_name", ")", "params", "=", "{", "'DomainName'", ":", ...
46.923077
23.538462
async def disable(self): """Disable this user. """ await self.controller.disable_user(self.username) self._user_info.disabled = True
[ "async", "def", "disable", "(", "self", ")", ":", "await", "self", ".", "controller", ".", "disable_user", "(", "self", ".", "username", ")", "self", ".", "_user_info", ".", "disabled", "=", "True" ]
32
6.8
def _get_next_available_channel_id(self): """Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int """ for index in compatibility.RANGE(self._last_channel_id or 1, ...
[ "def", "_get_next_available_channel_id", "(", "self", ")", ":", "for", "index", "in", "compatibility", ".", "RANGE", "(", "self", ".", "_last_channel_id", "or", "1", ",", "self", ".", "max_allowed_channels", "+", "1", ")", ":", "if", "index", "in", "self", ...
38.578947
14.789474
def count_lines(fname, mode='rU'): '''Count the number of lines in a file Only faster way would be to utilize multiple processor cores to perform parallel reads. http://stackoverflow.com/q/845058/623735 ''' with open(fname, mode) as f: for i, l in enumerate(f): pass return ...
[ "def", "count_lines", "(", "fname", ",", "mode", "=", "'rU'", ")", ":", "with", "open", "(", "fname", ",", "mode", ")", "as", "f", ":", "for", "i", ",", "l", "in", "enumerate", "(", "f", ")", ":", "pass", "return", "i", "+", "1" ]
28.636364
21.727273
def spell_correct(string): """ Uses aspell to spell correct an input string. Requires aspell to be installed and added to the path. Returns the spell corrected string if aspell is found, original string if not. string - string """ # Create a temp file so that aspell could be used # By d...
[ "def", "spell_correct", "(", "string", ")", ":", "# Create a temp file so that aspell could be used", "# By default, tempfile will delete this file when the file handle is closed.", "f", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w'", ")", "f", ".", "writ...
36.180328
19.295082
def sun_zenith_angle(utc_time, lon, lat): """Sun-zenith angle for *lon*, *lat* at *utc_time*. lon,lat in degrees. The angle returned is given in degrees """ return np.rad2deg(np.arccos(cos_zen(utc_time, lon, lat)))
[ "def", "sun_zenith_angle", "(", "utc_time", ",", "lon", ",", "lat", ")", ":", "return", "np", ".", "rad2deg", "(", "np", ".", "arccos", "(", "cos_zen", "(", "utc_time", ",", "lon", ",", "lat", ")", ")", ")" ]
38.166667
6.833333
def rename(self, **kwargs): '''Rename series in the group.''' for old, new in kwargs.iteritems(): if old in self.groups: self.groups[new] = self.groups[old] del self.groups[old]
[ "def", "rename", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "old", ",", "new", "in", "kwargs", ".", "iteritems", "(", ")", ":", "if", "old", "in", "self", ".", "groups", ":", "self", ".", "groups", "[", "new", "]", "=", "self", ".",...
38.666667
6.333333
def getUnitCost(self, CorpNum, ItemCode): """ 전자명세서 발행단가 확인. args CorpNum : 팝빌회원 사업자번호 ItemCode : 명세서 종류 코드 [121 - 거래명세서], [122 - 청구서], [123 - 견적서], [124 - 발주서], [125 - 입금표], [126 - 영수증] return ...
[ "def", "getUnitCost", "(", "self", ",", "CorpNum", ",", "ItemCode", ")", ":", "if", "ItemCode", "==", "None", "or", "ItemCode", "==", "\"\"", ":", "raise", "PopbillException", "(", "-", "99999999", ",", "\"명세서 종류 코드가 입력되지 않았습니다.\")\r", "", "result", "=", "se...
37.470588
15.294118
def createEditor(self, delegate, parent, option): """ Creates a ColorCtiEditor. For the parameters see the AbstractCti constructor documentation. """ return ColorCtiEditor(self, delegate, parent=parent)
[ "def", "createEditor", "(", "self", ",", "delegate", ",", "parent", ",", "option", ")", ":", "return", "ColorCtiEditor", "(", "self", ",", "delegate", ",", "parent", "=", "parent", ")" ]
46.8
13.2
def clinvar_objs(self, submission_id, key_id): """Collects a list of objects from the clinvar collection (variants of case data) as specified by the key_id in the clinvar submission Args: submission_id(str): the _id key of a clinvar submission key_id(str) : either 'v...
[ "def", "clinvar_objs", "(", "self", ",", "submission_id", ",", "key_id", ")", ":", "# Get a submission object", "submission", "=", "self", ".", "clinvar_submission_collection", ".", "find_one", "(", "{", "'_id'", ":", "ObjectId", "(", "submission_id", ")", "}", ...
50.318182
30.636364
def after_unassign(reference_analysis): """Removes the reference analysis from the system """ analysis_events.after_unassign(reference_analysis) ref_sample = reference_analysis.aq_parent ref_sample.manage_delObjects([reference_analysis.getId()])
[ "def", "after_unassign", "(", "reference_analysis", ")", ":", "analysis_events", ".", "after_unassign", "(", "reference_analysis", ")", "ref_sample", "=", "reference_analysis", ".", "aq_parent", "ref_sample", ".", "manage_delObjects", "(", "[", "reference_analysis", "."...
43.333333
7
def TRCCp(T, a0, a1, a2, a3, a4, a5, a6, a7): r'''Calculates ideal gas heat capacity using the model developed in [1]_. The ideal gas heat capacity is given by: .. math:: C_p = R\left(a_0 + (a_1/T^2) \exp(-a_2/T) + a_3 y^2 + (a_4 - a_5/(T-a_7)^2 )y^j \right) y = \frac{T-a_7}{T+a_6...
[ "def", "TRCCp", "(", "T", ",", "a0", ",", "a1", ",", "a2", ",", "a3", ",", "a4", ",", "a5", ",", "a6", ",", "a7", ")", ":", "if", "T", "<=", "a7", ":", "y", "=", "0.", "else", ":", "y", "=", "(", "T", "-", "a7", ")", "/", "(", "T", ...
25.418605
27.837209
def parse_ipv6_hostname(cls, hostname): '''Parse and normalize a IPv6 address.''' if not hostname.startswith('[') or not hostname.endswith(']'): raise ValueError('Invalid IPv6 address: {}' .format(ascii(hostname))) hostname = ipaddress.IPv6Address(hostna...
[ "def", "parse_ipv6_hostname", "(", "cls", ",", "hostname", ")", ":", "if", "not", "hostname", ".", "startswith", "(", "'['", ")", "or", "not", "hostname", ".", "endswith", "(", "']'", ")", ":", "raise", "ValueError", "(", "'Invalid IPv6 address: {}'", ".", ...
39.666667
21.444444
def on_train_end(self, **kwargs): "Load the best model." if self.save_model: # Adapted from fast.ai "SaveModelCallback" if self.model_path.is_file(): with self.model_path.open('rb') as model_file: self.learn.load(model_file, purge=False) ...
[ "def", "on_train_end", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "save_model", ":", "# Adapted from fast.ai \"SaveModelCallback\"", "if", "self", ".", "model_path", ".", "is_file", "(", ")", ":", "with", "self", ".", "model_path", "....
42.555556
18.111111
def delete_event(self, id, **kwargs): # noqa: E501 """Delete a specific event # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_event(id, async_req=True)...
[ "def", "delete_event", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_event_wi...
39.857143
17.333333
def normalize_hex(hex_value): """ Normalize a hexadecimal color value to the following form and return the result:: #[a-f0-9]{6} In other words, the following transformations are applied as needed: * If the value contains only three hexadecimal digits, it is expanded to six. ...
[ "def", "normalize_hex", "(", "hex_value", ")", ":", "try", ":", "hex_digits", "=", "HEX_COLOR_RE", ".", "match", "(", "hex_value", ")", ".", "groups", "(", ")", "[", "0", "]", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"'%s' is not a vali...
26.707317
22.121951
def get_time(self, force_uptime=False): """Get the current UTC time or uptime. By default, this method will return UTC time if possible and fall back to uptime if not. If you specify, force_uptime=True, it will always return uptime even if utc time is available. Args: ...
[ "def", "get_time", "(", "self", ",", "force_uptime", "=", "False", ")", ":", "if", "force_uptime", ":", "return", "self", ".", "uptime", "time", "=", "self", ".", "uptime", "+", "self", ".", "time_offset", "if", "self", ".", "is_utc", ":", "time", "|="...
27.391304
23.782609
def adapt(self): r"""Update the proposal using the points stored in ``self.samples[-1]`` and the parameters which can be set via :py:meth:`.set_adapt_params`. In the above referenced function's docstring, the algorithm is described in detail. If the resulting matrix is not a vali...
[ "def", "adapt", "(", "self", ")", ":", "last_run", "=", "self", ".", "samples", "[", "-", "1", "]", "accept_rate", "=", "float", "(", "self", ".", "_last_accept_count", ")", "/", "len", "(", "last_run", ")", "# careful with rowvar!", "# in this form it is ex...
47.06383
24.829787
async def wait(self, need_pts=False) -> dict: """Send long poll request :param need_pts: need return the pts field """ if not self.base_url: await self._get_long_poll_server(need_pts) params = { 'ts': self.ts, 'key': self.key, } ...
[ "async", "def", "wait", "(", "self", ",", "need_pts", "=", "False", ")", "->", "dict", ":", "if", "not", "self", ".", "base_url", ":", "await", "self", ".", "_get_long_poll_server", "(", "need_pts", ")", "params", "=", "{", "'ts'", ":", "self", ".", ...
27.904762
18.285714
def is_probabilistic_classifier(clf): # type: (Any) -> bool """ Return True if a classifier can return probabilities """ if not hasattr(clf, 'predict_proba'): return False if isinstance(clf, OneVsRestClassifier): # It currently has a predict_proba method, but does not check if # ...
[ "def", "is_probabilistic_classifier", "(", "clf", ")", ":", "# type: (Any) -> bool", "if", "not", "hasattr", "(", "clf", ",", "'predict_proba'", ")", ":", "return", "False", "if", "isinstance", "(", "clf", ",", "OneVsRestClassifier", ")", ":", "# It currently has ...
42.7
12.9
def _get_writable(stream_or_path, mode): """This method returns a tuple containing the stream and a flag to indicate if the stream should be automatically closed. The `stream_or_path` parameter is returned if it is an open writable stream. Otherwise, it treats the `stream_or_path` parameter as a file p...
[ "def", "_get_writable", "(", "stream_or_path", ",", "mode", ")", ":", "is_stream", "=", "hasattr", "(", "stream_or_path", ",", "'write'", ")", "if", "not", "is_stream", ":", "# No stream provided, treat \"stream_or_path\" as path", "stream_or_path", "=", "open", "(", ...
40.578947
17.105263
def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ methods = {} ...
[ "def", "get_extra_functions", "(", "self", ")", "->", "Dict", "[", "str", ",", "Callable", "]", ":", "methods", "=", "{", "}", "for", "mName", "in", "dir", "(", "self", ")", ":", "m", "=", "getattr", "(", "self", ",", "mName", ")", "if", "callable"...
37.615385
18.153846
def _menuItem(self, menuitem, *args): """Return the specified menu item. Example - refer to items by name: app._menuItem(app.AXMenuBar, 'File', 'New').Press() app._menuItem(app.AXMenuBar, 'Edit', 'Insert', 'Line Break').Press() Refer to items by index: app._menuitem(a...
[ "def", "_menuItem", "(", "self", ",", "menuitem", ",", "*", "args", ")", ":", "self", ".", "_activate", "(", ")", "for", "item", "in", "args", ":", "# If the item has an AXMenu as a child, navigate into it.", "# This seems like a silly abstraction added by apple's a11y ap...
36.9
20.666667
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry...
[ "def", "add_to_manifest", "(", "self", ",", "manifest", ")", ":", "# Add this service to list of services", "manifest", ".", "add_service", "(", "self", ".", "service", ".", "name", ")", "# Add environment variables", "manifest", ".", "add_env_var", "(", "predix", "...
48.684211
26.473684
def get_details(self): """ The function called to get the details appended to the help message when self.append_details is True """ # create the exception main message according to the type of result if isinstance(self.validation_outcome, Exception): prefix = 'Validation function [...
[ "def", "get_details", "(", "self", ")", ":", "# create the exception main message according to the type of result", "if", "isinstance", "(", "self", ".", "validation_outcome", ",", "Exception", ")", ":", "prefix", "=", "'Validation function [{val}] raised '", "if", "self", ...
56.136364
36.5
def pulse_drawer(samples, duration, dt=None, interp_method='None', filename=None, interactive=False, dpi=150, nop=1000, size=(6, 5)): """Plot the interpolated envelope of pulse Args: samples (ndarray): Data points of complex pulse envelope. duration (int): Puls...
[ "def", "pulse_drawer", "(", "samples", ",", "duration", ",", "dt", "=", "None", ",", "interp_method", "=", "'None'", ",", "filename", "=", "None", ",", "interactive", "=", "False", ",", "dpi", "=", "150", ",", "nop", "=", "1000", ",", "size", "=", "(...
34.547619
20.440476
def T_stock(self, V_stock): """Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float """ return Stock...
[ "def", "T_stock", "(", "self", ",", "V_stock", ")", ":", "return", "Stock", ".", "T_stock", "(", "self", ",", "V_stock", ",", "self", ".", "Q_stock", "(", ")", ")", ".", "to", "(", "u", ".", "hr", ")" ]
32.545455
18.818182
def generate(basename, xml_list): '''generate complete MAVLink Objective-C implemenation''' generate_shared(basename, xml_list) for xml in xml_list: generate_message_definitions(basename, xml)
[ "def", "generate", "(", "basename", ",", "xml_list", ")", ":", "generate_shared", "(", "basename", ",", "xml_list", ")", "for", "xml", "in", "xml_list", ":", "generate_message_definitions", "(", "basename", ",", "xml", ")" ]
34.666667
16
def get_parser(): """ Return argument parser. """ parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description=__doc__, ) # connection to redis server parser.add_argument('--host', default='localhost') parser.add_argument('--port', default=6379, t...
[ "def", "get_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "formatter_class", "=", "argparse", ".", "RawTextHelpFormatter", ",", "description", "=", "__doc__", ",", ")", "# connection to redis server", "parser", ".", "add_argument", ...
33.888889
22.277778
def get_work_item_next_states_on_checkin_action(self, ids, action=None): """GetWorkItemNextStatesOnCheckinAction. [Preview API] Returns the next state on the given work item IDs. :param [int] ids: list of work item ids :param str action: possible actions. Currently only supports checkin ...
[ "def", "get_work_item_next_states_on_checkin_action", "(", "self", ",", "ids", ",", "action", "=", "None", ")", ":", "query_parameters", "=", "{", "}", "if", "ids", "is", "not", "None", ":", "ids", "=", "\",\"", ".", "join", "(", "map", "(", "str", ",", ...
56.333333
21.277778
def put(contract_name, abi): ''' save the contract's ABI :param contract_name: string - name of the contract :param abi: the contract's abi JSON file :return: None, None if saved okay None, error is an error ''' if not Catalog.path: ...
[ "def", "put", "(", "contract_name", ",", "abi", ")", ":", "if", "not", "Catalog", ".", "path", ":", "return", "None", ",", "\"path to catalog must be set before saving to it\"", "if", "not", "contract_name", ":", "return", "None", ",", "\"contract name must be provi...
32.2
19.8
def _prep_mod_opts(self): ''' Returns a copy of the opts with key bits stripped out ''' mod_opts = {} for key, val in six.iteritems(self.opts): if key == 'logger': continue mod_opts[key] = val return mod_opts
[ "def", "_prep_mod_opts", "(", "self", ")", ":", "mod_opts", "=", "{", "}", "for", "key", ",", "val", "in", "six", ".", "iteritems", "(", "self", ".", "opts", ")", ":", "if", "key", "==", "'logger'", ":", "continue", "mod_opts", "[", "key", "]", "="...
28.7
17.3
def get_form(self, request, obj=None, **kwargs): """ Pass the current language to the form. """ form_class = super(TranslatableAdmin, self).get_form(request, obj, **kwargs) if self._has_translatable_model(): form_class.language_code = self.get_form_language(request, o...
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "form_class", "=", "super", "(", "TranslatableAdmin", ",", "self", ")", ".", "get_form", "(", "request", ",", "obj", ",", "*", "*", "kwargs", ...
38
16.666667
def get_mfa(self, auth_resp): """Gets MFA code from user and returns response which includes the client token""" devices = auth_resp['data']['devices'] if len(devices) == 1: # If there's only one option, don't show selection prompt selection = "0" x = 1 ...
[ "def", "get_mfa", "(", "self", ",", "auth_resp", ")", ":", "devices", "=", "auth_resp", "[", "'data'", "]", "[", "'devices'", "]", "if", "len", "(", "devices", ")", "==", "1", ":", "# If there's only one option, don't show selection prompt", "selection", "=", ...
39.405405
23.027027
def _checkDragDropEvent(self, ev): """Checks if event contains a file URL, accepts if it does, ignores if it doesn't""" mimedata = ev.mimeData() if mimedata.hasUrls(): urls = [str(url.toLocalFile()) for url in mimedata.urls() if url.toLocalFile()] else: urls = [] ...
[ "def", "_checkDragDropEvent", "(", "self", ",", "ev", ")", ":", "mimedata", "=", "ev", ".", "mimeData", "(", ")", "if", "mimedata", ".", "hasUrls", "(", ")", ":", "urls", "=", "[", "str", "(", "url", ".", "toLocalFile", "(", ")", ")", "for", "url",...
35.5
16.785714
def update(cls, args): """Call the method to update the Web UI.""" kytos_api = KytosConfig().config.get('kytos', 'api') url = f"{kytos_api}api/kytos/core/web/update" version = args["<version>"] if version: url += f"/{version}" try: result = reques...
[ "def", "update", "(", "cls", ",", "args", ")", ":", "kytos_api", "=", "KytosConfig", "(", ")", ".", "config", ".", "get", "(", "'kytos'", ",", "'api'", ")", "url", "=", "f\"{kytos_api}api/kytos/core/web/update\"", "version", "=", "args", "[", "\"<version>\""...
35.388889
18.555556
def get(self, item): """ Get item through ``__getitem__`` and cache the result. Args: item (str): name of package or module. Returns: Package/Module: the corresponding object. """ if item not in self._item_cache: try: ...
[ "def", "get", "(", "self", ",", "item", ")", ":", "if", "item", "not", "in", "self", ".", "_item_cache", ":", "try", ":", "item", "=", "self", ".", "__getitem__", "(", "item", ")", "except", "KeyError", ":", "item", "=", "None", "self", ".", "_item...
27.647059
14.941176
def url(self, key, includeToken=None): """ Build a URL string with proper token argument. Token will be appended to the URL if either includeToken is True or CONFIG.log.show_secrets is 'true'. """ if self._token and (includeToken or self._showSecrets): delim = '&' if '?'...
[ "def", "url", "(", "self", ",", "key", ",", "includeToken", "=", "None", ")", ":", "if", "self", ".", "_token", "and", "(", "includeToken", "or", "self", ".", "_showSecrets", ")", ":", "delim", "=", "'&'", "if", "'?'", "in", "key", "else", "'?'", "...
57.5
15
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) An...
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# convert to radians and unpack", "translation_x", ",", "translation_y", "=", "self", ".", "translation", "translation_matrix", "=", "np", ".", "array", "(", "[", "[", ...
34.275
18.825
def delete_external_nodes(sender, **kwargs): """ sync by deleting nodes from external layers when needed """ node = kwargs['instance'] if node.layer.is_external is False or not hasattr(node.layer, 'external') or node.layer.external.synchronizer_path is None: return False if hasattr(node, 'exte...
[ "def", "delete_external_nodes", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "node", "=", "kwargs", "[", "'instance'", "]", "if", "node", ".", "layer", ".", "is_external", "is", "False", "or", "not", "hasattr", "(", "node", ".", "layer", ",", "'ex...
40.384615
21.692308
def program_pixel_reg(self, enable_receiver=True): """ Send the pixel register to the chip and store the output. Loads the values of self['PIXEL_REG'] onto the chip. Includes enabling the clock, and loading the Control (CTR) and DAC shadow registers. if(enable_receiver)...
[ "def", "program_pixel_reg", "(", "self", ",", "enable_receiver", "=", "True", ")", ":", "self", ".", "_clear_strobes", "(", ")", "# enable receiver it work only if pixel register is enabled/clocked", "self", "[", "'PIXEL_RX'", "]", ".", "set_en", "(", "enable_receiver",...
37.304348
26.26087
def is_json_file(abspath): """Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file """ abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".json", ".js"]: is_json = True elif ext == ".gz": ...
[ "def", "is_json_file", "(", "abspath", ")", ":", "abspath", "=", "abspath", ".", "lower", "(", ")", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "abspath", ")", "if", "ext", "in", "[", "\".json\"", ",", "\".js\"", "]", ":", "i...
29.4
13.25
def estimates(symbol, token='', version=''): '''Provides the latest consensus estimate for the next fiscal period https://iexcloud.io/docs/api/#estimates Updates at 9am, 11am, 12pm UTC every day Args: symbol (string); Ticker to request token (string); Access token version (stri...
[ "def", "estimates", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "return", "_getJson", "(", "'stock/'", "+", "symbol", "+", "'/estimates'", ",", "token", ",", "version", ")" ]
28.8125
20.4375
def dbg_print(self): """ Print out debugging information """ for region_id, region in self.regions.items(): print("Region [%s]:" % region_id) region.dbg_print(indent=2)
[ "def", "dbg_print", "(", "self", ")", ":", "for", "region_id", ",", "region", "in", "self", ".", "regions", ".", "items", "(", ")", ":", "print", "(", "\"Region [%s]:\"", "%", "region_id", ")", "region", ".", "dbg_print", "(", "indent", "=", "2", ")" ]
31.142857
6
def char_ngrams(s, n=3, token_fn=tokens.on_whitespace): """ Character-level n-grams from within the words in a string. By default, the word boundary is assumed to be whitespace. n-grams are not taken across word boundaries, only within words. If a word's length is less than or equ...
[ "def", "char_ngrams", "(", "s", ",", "n", "=", "3", ",", "token_fn", "=", "tokens", ".", "on_whitespace", ")", ":", "tokens", "=", "token_fn", "(", "s", ")", "ngram_tuples", "=", "[", "__ngrams", "(", "t", ",", "n", "=", "min", "(", "len", "(", "...
33.741935
22.064516
def simpleabut (source, addon): """ Concatenates two lists as columns and returns the result. '2D' lists are also accomodated for either argument (source or addon). This DOES NOT repeat either list to make the 2 lists of equal length. Beware of list pairs with different lengths ... the resulting list will be the...
[ "def", "simpleabut", "(", "source", ",", "addon", ")", ":", "if", "type", "(", "source", ")", "not", "in", "[", "ListType", ",", "TupleType", "]", ":", "source", "=", "[", "source", "]", "if", "type", "(", "addon", ")", "not", "in", "[", "ListType"...
43.441176
20.617647
def status(self): """ Poll YubiKey for status. """ data = self._read() self._status = YubiKeyUSBHIDStatus(data) return self._status
[ "def", "status", "(", "self", ")", ":", "data", "=", "self", ".", "_read", "(", ")", "self", ".", "_status", "=", "YubiKeyUSBHIDStatus", "(", "data", ")", "return", "self", ".", "_status" ]
24.714286
9.285714
def inicializar_y_capturar_excepciones(func): "Decorador para inicializar y capturar errores (version para webservices)" @functools.wraps(func) def capturar_errores_wrapper(self, *args, **kwargs): try: # inicializo (limpio variables) self.Errores = [] # listas de st...
[ "def", "inicializar_y_capturar_excepciones", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "capturar_errores_wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# inicializo (limpio variabl...
41.016667
14.15
def check_valid_format(figformat): """Check if the specified figure format is valid. If format is invalid the default is returned. Probably installation-dependent """ fig = plt.figure() if figformat in list(fig.canvas.get_supported_filetypes().keys()): logging.info("Nanoplotter: valid o...
[ "def", "check_valid_format", "(", "figformat", ")", ":", "fig", "=", "plt", ".", "figure", "(", ")", "if", "figformat", "in", "list", "(", "fig", ".", "canvas", ".", "get_supported_filetypes", "(", ")", ".", "keys", "(", ")", ")", ":", "logging", ".", ...
40
20.857143
def send_tunnelling_request(self, cemi, auto_connect=True): """Sends a tunneling request based on the given CEMI data. This method does not wait for an acknowledge or result frame. """ if not self.connected: if auto_connect: if not self.connect(): ...
[ "def", "send_tunnelling_request", "(", "self", ",", "cemi", ",", "auto_connect", "=", "True", ")", ":", "if", "not", "self", ".", "connected", ":", "if", "auto_connect", ":", "if", "not", "self", ".", "connect", "(", ")", ":", "raise", "KNXException", "(...
37.219512
20.121951
def upload_gif(gif): """Uploads an image file to Imgur""" client_id = os.environ.get('IMGUR_API_ID') client_secret = os.environ.get('IMGUR_API_SECRET') if client_id is None or client_secret is None: click.echo('Cannot upload - could not find IMGUR_API_ID or IMGUR_API_SECRET environment variabl...
[ "def", "upload_gif", "(", "gif", ")", ":", "client_id", "=", "os", ".", "environ", ".", "get", "(", "'IMGUR_API_ID'", ")", "client_secret", "=", "os", ".", "environ", ".", "get", "(", "'IMGUR_API_SECRET'", ")", "if", "client_id", "is", "None", "or", "cli...
33.588235
27.235294
def dependent_images(self): """ Determine the dependent images from these commands This includes all the FROM statements and any external image from a complex ADD instruction that copies from another container """ found = [] for command in self.commands: ...
[ "def", "dependent_images", "(", "self", ")", ":", "found", "=", "[", "]", "for", "command", "in", "self", ".", "commands", ":", "dep", "=", "command", ".", "dependent_image", "if", "dep", ":", "if", "dep", "not", "in", "found", ":", "yield", "dep", "...
33.214286
14.071429
def set_sns(style="white", context="paper", font_scale=1.5, color_codes=True, rc={}): """Set default plot style using seaborn. Font size is set to match the size of the tick labels, rather than the axes labels. """ rcd = {"lines.markersize": 8, "lines.markeredgewidth": 1.25, ...
[ "def", "set_sns", "(", "style", "=", "\"white\"", ",", "context", "=", "\"paper\"", ",", "font_scale", "=", "1.5", ",", "color_codes", "=", "True", ",", "rc", "=", "{", "}", ")", ":", "rcd", "=", "{", "\"lines.markersize\"", ":", "8", ",", "\"lines.mar...
41.266667
21.6
def _state_to_task(cls, tstate, shard_state, eta=None, countdown=None): """Generate task for slice according to current states. Args: tstate: An instance of TransientShardState. shard_state: An instance of ShardStat...
[ "def", "_state_to_task", "(", "cls", ",", "tstate", ",", "shard_state", ",", "eta", "=", "None", ",", "countdown", "=", "None", ")", ":", "base_path", "=", "tstate", ".", "base_path", "task_name", "=", "MapperWorkerCallbackHandler", ".", "get_task_name", "(", ...
32.473684
19.789474
def _parse_authors(element): """ Returns a well formatted list of users that can be matched against posts. """ authors = [] items = element.findall("./{%s}author" % WP_NAMESPACE) for item in items: login = item.find("./{%s}author_login" % WP_NAMESPACE).text email = item.find("....
[ "def", "_parse_authors", "(", "element", ")", ":", "authors", "=", "[", "]", "items", "=", "element", ".", "findall", "(", "\"./{%s}author\"", "%", "WP_NAMESPACE", ")", "for", "item", "in", "items", ":", "login", "=", "item", ".", "find", "(", "\"./{%s}a...
32.48
21.04
def similarity_cost(inputs_encoded, targets_encoded): """Loss telling to be more similar to your own targets than to others.""" # This is a first very simple version: handle variable-length by padding # to same length and putting everything into batch. In need of a better way. x, y = common_layers.pad_to_same_l...
[ "def", "similarity_cost", "(", "inputs_encoded", ",", "targets_encoded", ")", ":", "# This is a first very simple version: handle variable-length by padding", "# to same length and putting everything into batch. In need of a better way.", "x", ",", "y", "=", "common_layers", ".", "pa...
59.75
20.125
def fix_dashes(string): """Fix bad Unicode special dashes in string.""" string = string.replace(u'\u05BE', '-') string = string.replace(u'\u1806', '-') string = string.replace(u'\u2E3A', '-') string = string.replace(u'\u2E3B', '-') string = unidecode(string) return re.sub(r'--+', '-', string...
[ "def", "fix_dashes", "(", "string", ")", ":", "string", "=", "string", ".", "replace", "(", "u'\\u05BE'", ",", "'-'", ")", "string", "=", "string", ".", "replace", "(", "u'\\u1806'", ",", "'-'", ")", "string", "=", "string", ".", "replace", "(", "u'\\u...
39.25
5.125
def plot_vgp(map_axis, vgp_lon=None, vgp_lat=None, di_block=None, label='', color='k', marker='o', edge='black', markersize=20, legend=False): """ This function plots a paleomagnetic pole position on a cartopy map axis. Before this function is called, a plot needs to be initialized with code ...
[ "def", "plot_vgp", "(", "map_axis", ",", "vgp_lon", "=", "None", ",", "vgp_lat", "=", "None", ",", "di_block", "=", "None", ",", "label", "=", "''", ",", "color", "=", "'k'", ",", "marker", "=", "'o'", ",", "edge", "=", "'black'", ",", "markersize", ...
46.5
26.772727
def from_ymd_to_excel(year, month, day): """ converts date as `(year, month, day)` tuple into Microsoft Excel representation style :param tuple(int, int, int): int tuple `year, month, day` :return int: """ if not is_valid_ymd(year, month, day): raise ValueError("Invalid date {0}.{1}.{2}...
[ "def", "from_ymd_to_excel", "(", "year", ",", "month", ",", "day", ")", ":", "if", "not", "is_valid_ymd", "(", "year", ",", "month", ",", "day", ")", ":", "raise", "ValueError", "(", "\"Invalid date {0}.{1}.{2}\"", ".", "format", "(", "year", ",", "month",...
38.2
23.6
def product(self, factorset, inplace=True): r""" Return the factor sets product with the given factor sets Suppose :math:`\vec\phi_1` and :math:`\vec\phi_2` are two factor sets then their product is a another factors set :math:`\vec\phi_3 = \vec\phi_1 \cup \vec\phi_2`. Paramete...
[ "def", "product", "(", "self", ",", "factorset", ",", "inplace", "=", "True", ")", ":", "factor_set", "=", "self", "if", "inplace", "else", "self", ".", "copy", "(", ")", "factor_set1", "=", "factorset", ".", "copy", "(", ")", "factor_set", ".", "add_f...
46.057692
25.692308
def verify_initdict(initdict: InitDict) -> None: """ Ensures that its parameter is a proper ``InitDict``, or raises ``ValueError``. """ if (not isinstance(initdict, dict) or ARGS_LABEL not in initdict or KWARGS_LABEL not in initdict): raise ValueError("Not an InitDict...
[ "def", "verify_initdict", "(", "initdict", ":", "InitDict", ")", "->", "None", ":", "if", "(", "not", "isinstance", "(", "initdict", ",", "dict", ")", "or", "ARGS_LABEL", "not", "in", "initdict", "or", "KWARGS_LABEL", "not", "in", "initdict", ")", ":", "...
36.111111
8.111111
def report_read_counts(self, filename, grp_wise=False, reorder='as-is', notes=None): """ Exports expected read counts :param filename: File name for output :param grp_wise: whether the report is at isoform level or gene level :param reorder: whether the report should be either '...
[ "def", "report_read_counts", "(", "self", ",", "filename", ",", "grp_wise", "=", "False", ",", "reorder", "=", "'as-is'", ",", "notes", "=", "None", ")", ":", "expected_read_counts", "=", "self", ".", "probability", ".", "sum", "(", "axis", "=", "APM", "...
46.916667
18.805556
def find_lines(filename, **pattern): """Find a line (JSON-formatted) in the given file where all keys in `pattern` are present as keys in the line's JSON, and where their values equal the corresponding values in `pattern`. Additional keys in the line are ignored. If no matching line is found, or if ...
[ "def", "find_lines", "(", "filename", ",", "*", "*", "pattern", ")", ":", "if", "exists", "(", "filename", ")", ":", "with", "file", "(", "filename", ",", "'r'", ")", "as", "fp", ":", "for", "line", "in", "fp", ":", "try", ":", "data", "=", "json...
39.15
11.75
def _build_proxy_contract_creation_constructor(self, master_copy: str, initializer: bytes, funder: str, payment_toke...
[ "def", "_build_proxy_contract_creation_constructor", "(", "self", ",", "master_copy", ":", "str", ",", "initializer", ":", "bytes", ",", "funder", ":", "str", ",", "payment_token", ":", "str", ",", "payment", ":", "int", ")", "->", "ContractConstructor", ":", ...
45.583333
21.416667
def setup_objective(obj, free_variables, on_step=None, disp=True, make_dense=False): ''' obj here can be a list of ch objects or a dict of label: ch objects. Either way, the ch objects will be merged into one objective using a ChInputsStacked. The labels are just used for printing out values per objecti...
[ "def", "setup_objective", "(", "obj", ",", "free_variables", ",", "on_step", "=", "None", ",", "disp", "=", "True", ",", "make_dense", "=", "False", ")", ":", "# Validate free variables", "num_unique_ids", "=", "len", "(", "np", ".", "unique", "(", "np", "...
49.125
26.375
def _GetDirectory(self): """Retrieves a directory. Returns: ZipDirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return ZipDirectory(self._file_system, self.path_spec)
[ "def", "_GetDirectory", "(", "self", ")", ":", "if", "self", ".", "entry_type", "!=", "definitions", ".", "FILE_ENTRY_TYPE_DIRECTORY", ":", "return", "None", "return", "ZipDirectory", "(", "self", ".", "_file_system", ",", "self", ".", "path_spec", ")" ]
29.777778
18.444444
def release_api_class(self): """Github Release API class.""" cls = current_app.config['GITHUB_RELEASE_CLASS'] if isinstance(cls, string_types): cls = import_string(cls) assert issubclass(cls, GitHubRelease) return cls
[ "def", "release_api_class", "(", "self", ")", ":", "cls", "=", "current_app", ".", "config", "[", "'GITHUB_RELEASE_CLASS'", "]", "if", "isinstance", "(", "cls", ",", "string_types", ")", ":", "cls", "=", "import_string", "(", "cls", ")", "assert", "issubclas...
37.571429
8.571429
def key_expand(self, key): """ Derive public key and account number from **private key** :param key: Private key to generate account and public key of :type key: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.key_expand( key="781186FB9EF17DB6E3D105655...
[ "def", "key_expand", "(", "self", ",", "key", ")", ":", "key", "=", "self", ".", "_process_value", "(", "key", ",", "'privatekey'", ")", "payload", "=", "{", "\"key\"", ":", "key", "}", "resp", "=", "self", ".", "call", "(", "'key_expand'", ",", "pay...
29.555556
27.925926
def chgroups(name, groups, append=True): ''' Change the groups this user belongs to, add append=False to make the user a member of only the specified groups Args: name (str): The user name for which to change groups groups (str, list): A single group or a list of groups to assign to th...
[ "def", "chgroups", "(", "name", ",", "groups", ",", "append", "=", "True", ")", ":", "if", "six", ".", "PY2", ":", "name", "=", "_to_unicode", "(", "name", ")", "if", "isinstance", "(", "groups", ",", "string_types", ")", ":", "groups", "=", "groups"...
29.983333
23.383333
def merge_with_published(self): """Merge changes with latest published version.""" pid, first = self.fetch_published() lca = first.revisions[self['_deposit']['pid']['revision_id']] # ignore _deposit and $schema field args = [lca.dumps(), first.dumps(), self.dumps()] for a...
[ "def", "merge_with_published", "(", "self", ")", ":", "pid", ",", "first", "=", "self", ".", "fetch_published", "(", ")", "lca", "=", "first", ".", "revisions", "[", "self", "[", "'_deposit'", "]", "[", "'pid'", "]", "[", "'revision_id'", "]", "]", "# ...
38.133333
12
def get_least_common_subsumer(self,from_tid,to_tid): """ Returns the deepest common subsumer among two terms @type from_tid: string @param from_tid: one term id @type to_tid: string @param to_tid: another term id @rtype: string @return: the term identifier...
[ "def", "get_least_common_subsumer", "(", "self", ",", "from_tid", ",", "to_tid", ")", ":", "termid_from", "=", "self", ".", "terminal_for_term", ".", "get", "(", "from_tid", ")", "termid_to", "=", "self", ".", "terminal_for_term", ".", "get", "(", "to_tid", ...
39
12.259259
def do_response(self, response_args=None, request=None, **kwargs): """ **Placeholder for the time being** :param response_args: :param request: :param kwargs: request arguments :return: Response information """ links = [Link(href=h, rel=OIC_ISSUER) for h...
[ "def", "do_response", "(", "self", ",", "response_args", "=", "None", ",", "request", "=", "None", ",", "*", "*", "kwargs", ")", ":", "links", "=", "[", "Link", "(", "href", "=", "h", ",", "rel", "=", "OIC_ISSUER", ")", "for", "h", "in", "kwargs", ...
27.35
20.95
def gen_uposix(table, posix_table): """Generate the posix table and write out to file.""" # `Alnum: [\p{L&}\p{Nd}]` s = set(table['l']['c'] + table['n']['d']) posix_table["posixalnum"] = list(s) # `Alpha: [\p{L&}]` s = set(table['l']['c']) posix_table["posixalpha"] = list(s) # `ASCII:...
[ "def", "gen_uposix", "(", "table", ",", "posix_table", ")", ":", "# `Alnum: [\\p{L&}\\p{Nd}]`", "s", "=", "set", "(", "table", "[", "'l'", "]", "[", "'c'", "]", "+", "table", "[", "'n'", "]", "[", "'d'", "]", ")", "posix_table", "[", "\"posixalnum\"", ...
30.013699
15.287671
def __clear_references(self, request, remove_request=True): """Remove any internal references to the given request""" # remove request itself if remove_request: with self.__requests: self.__requests.pop(request.id_) # remove request type specific references ...
[ "def", "__clear_references", "(", "self", ",", "request", ",", "remove_request", "=", "True", ")", ":", "# remove request itself", "if", "remove_request", ":", "with", "self", ".", "__requests", ":", "self", ".", "__requests", ".", "pop", "(", "request", ".", ...
45
9.916667
def allreduce_grads(self): """For each parameter, reduce the gradients from different contexts. Should be called after `autograd.backward()`, outside of `record()` scope, and before `trainer.update()`. For normal parameter updates, `step()` should be used, which internally calls ...
[ "def", "allreduce_grads", "(", "self", ")", ":", "if", "not", "self", ".", "_kv_initialized", ":", "self", ".", "_init_kvstore", "(", ")", "if", "self", ".", "_params_to_init", ":", "self", ".", "_init_params", "(", ")", "assert", "not", "(", "self", "."...
47.619048
23.857143
def not_in(self, table): """ Select nuclei not in table Parameters ---------- table: Table, Table object from where nuclei should be removed Example: ---------- Find the new nuclei in AME2003 with Z,N >= 8: >>> Table('AME2003').not_in(Table('AME...
[ "def", "not_in", "(", "self", ",", "table", ")", ":", "idx", "=", "self", ".", "df", ".", "index", "-", "table", ".", "df", ".", "index", "return", "Table", "(", "df", "=", "self", ".", "df", "[", "idx", "]", ",", "name", "=", "self", ".", "n...
26.294118
20.411765
def build_update(self, alias=None, assigned_to=None, blocks_add=None, blocks_remove=None, blocks_set=None, depends_on_add=None, depends_on_remove=None, ...
[ "def", "build_update", "(", "self", ",", "alias", "=", "None", ",", "assigned_to", "=", "None", ",", "blocks_add", "=", "None", ",", "blocks_remove", "=", "None", ",", "blocks_set", "=", "None", ",", "depends_on_add", "=", "None", ",", "depends_on_remove", ...
35.741259
11.433566
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: StepContext for this StepInstance :rtype: twilio.rest.studio.v1.flow.engagement.step.StepContext ...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "StepContext", "(", "self", ".", "_version", ",", "flow_sid", "=", "self", ".", "_solution", "[", "'flow_sid'", "]", ",", "engagemen...
39.125
17.625
def get_qualifier_dict(vocabularies, qualifier_vocab): """Get the qualifier dictionary based on the element's qualifier vocabulary. """ # Raise exception if the vocabulary can't be found. if vocabularies.get(qualifier_vocab, None) is None: raise UNTLFormException( 'Could not retr...
[ "def", "get_qualifier_dict", "(", "vocabularies", ",", "qualifier_vocab", ")", ":", "# Raise exception if the vocabulary can't be found.", "if", "vocabularies", ".", "get", "(", "qualifier_vocab", ",", "None", ")", "is", "None", ":", "raise", "UNTLFormException", "(", ...
38
14.538462
def patch(self, id_or_uri, operation, path, value, timeout=-1, custom_headers=None): """ Uses the PATCH to update a resource. Only one operation can be performed in each PATCH call. Args: id_or_uri: Can be either the resource ID or the resource URI. operation: P...
[ "def", "patch", "(", "self", ",", "id_or_uri", ",", "operation", ",", "path", ",", "value", ",", "timeout", "=", "-", "1", ",", "custom_headers", "=", "None", ")", ":", "patch_request_body", "=", "[", "{", "'op'", ":", "operation", ",", "'path'", ":", ...
39.956522
24.913043
def add_transition_model(self, variable, transition_model): """ Adds a transition model for a particular variable. Parameters: ----------- variable: any hashable python object must be an existing variable of the model. transition_model: dict or 2d array ...
[ "def", "add_transition_model", "(", "self", ",", "variable", ",", "transition_model", ")", ":", "if", "isinstance", "(", "transition_model", ",", "list", ")", ":", "transition_model", "=", "np", ".", "array", "(", "transition_model", ")", "# check if the transitio...
48.693548
26.145161
def get_notification(self, notification_id, **params): """https://developers.coinbase.com/api/v2#show-a-notification""" response = self._get('v2', 'notifications', notification_id, params=params) return self._make_api_object(response, Notification)
[ "def", "get_notification", "(", "self", ",", "notification_id", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'notifications'", ",", "notification_id", ",", "params", "=", "params", ")", "return", "self", ".", ...
67.25
19.25