Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
379,800
def modifiedaminoacids(df, kind=): colors = [,,] total_aas, quants = analysis.modifiedaminoacids(df) df = pd.DataFrame() for a, n in quants.items(): df[a] = [n] df.sort_index(axis=1, inplace=True) if kind == or kind == : ax1 = df.plot(kind=, figsize=(7,7), col...
Generate a plot of relative numbers of modified amino acids in source DataFrame. Plot a pie or bar chart showing the number and percentage of modified amino acids in the supplied data frame. The amino acids displayed will be determined from the supplied data/modification type. :param df: processed Dat...
379,801
def assert_angles_allclose(x, y, **kwargs): c2 = (np.sin(x)-np.sin(y))**2 + (np.cos(x)-np.cos(y))**2 diff = np.arccos((2.0 - c2)/2.0) assert np.allclose(diff, 0.0, **kwargs)
Like numpy's assert_allclose, but for angles (in radians).
379,802
def twoDimensionalScatter(title, title_x, title_y, x, y, lim_x = None, lim_y = None, color = , size = 20, alpha=None): plt.figure() plt.scatter(x, y, c=color, s=size, alpha=alpha, edgecolors=) plt.xlabel(title_x) pl...
Create a two-dimensional scatter plot. INPUTS
379,803
def _compute_projection_filters(G, sf, estimated_source): eps = np.finfo(np.float).eps (nsampl, nchan) = estimated_source.shape if len(G.shape) == 4: G = G[None, None, ...] sf = sf[None, ...] nsrc = G.shape[0] filters_len = G.shape[-1] estimat...
Least-squares projection of estimated source on the subspace spanned by delayed versions of reference sources, with delays between 0 and filters_len-1
379,804
def field(ctx, text, index, delimiter=): splits = text.split(delimiter) splits = [f for f in splits if f != delimiter and len(f.strip()) > 0] index = conversions.to_integer(index, ctx) if index < 1: raise ValueError() if index <= len(splits): return splits[index-1] e...
Reference a field in string separated by a delimiter
379,805
def work_get(self, wallet, account): wallet = self._process_value(wallet, ) account = self._process_value(account, ) payload = {"wallet": wallet, "account": account} resp = self.call(, payload) return resp[]
Retrieves work for **account** in **wallet** .. enable_control required .. version 8.0 required :param wallet: Wallet to get account work for :type wallet: str :param account: Account to get work for :type account: str :raises: :py:exc:`nano.rpc.RPCException` ...
379,806
def chunks(arr, size): for i in _range(0, len(arr), size): yield arr[i:i+size]
Splits a list into chunks :param arr: list to split :type arr: :class:`list` :param size: number of elements in each chunk :type size: :class:`int` :return: generator object :rtype: :class:`generator`
379,807
def post(self, request, *args, **kwargs): now = timezone.now() data = { : request.POST.get(), : slugify(request.POST.get()), : DRAFT if in request.POST else PUBLISHED, : [Site.objects.get_current().pk], : [request.user.pk], ...
Handle the datas for posting a quick entry, and redirect to the admin in case of error or to the entry's page in case of success.
379,808
def getCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): cbCtx[] = errorIndication cbCtx[] = errorStatus cbCtx[]...
Creates a generator to perform one or more SNMP GET queries. On each iteration, new SNMP GET request is send (:RFC:`1905#section-4.2.1`). The iterator blocks waiting for response to arrive or error to occur. Parameters ---------- snmpEngine : :py:class:`~pysnmp.hlapi.SnmpEngine` Class inst...
379,809
def wrap_requests(requests_func): def call(url, *args, **kwargs): blacklist_hostnames = execution_context.get_opencensus_attr( ) parsed_url = urlparse(url) if parsed_url.port is None: dest_url = parsed_url.hostname else: dest_url = .format(par...
Wrap the requests function to trace it.
379,810
def getcols(sheetMatch=None,colMatch="Decay"): book=BOOK() if sheetMatch is None: matchingSheets=book.sheetNames print(%(len(matchingSheets))) else: matchingSheets=[x for x in book.sheetNames if sheetMatch in x] print(%(len(matchingSheets),len(book.sheetNames),sheetMatch...
find every column in every sheet and put it in a new sheet or book.
379,811
def asxc(cls, obj): if isinstance(obj, cls): return obj if is_string(obj): return cls.from_name(obj) raise TypeError("Don't know how to convert <%s:%s> to Xcfunc" % (type(obj), str(obj)))
Convert object into Xcfunc.
379,812
def assertTimeZoneIsNotNone(self, dt, msg=None): if not isinstance(dt, datetime): raise TypeError() self.assertIsNotNone(dt.tzinfo, msg=msg)
Fail unless ``dt`` has a non-null ``tzinfo`` attribute. Parameters ---------- dt : datetime msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Raises ------ TypeError If ``dt...
379,813
def remove_pardir_symbols(path, sep=os.sep, pardir=os.pardir): bits = path.split(sep) bits = (x for x in bits if x != pardir) return sep.join(bits)
Remove relative path symobls such as '..' Args: path (str): A target path string sep (str): A strint to refer path delimiter (Default: `os.sep`) pardir (str): A string to refer parent directory (Default: `os.pardir`) Returns: str
379,814
def shell(self, name=, site=None, use_root=0, **kwargs): r = self.database_renderer(name=name, site=site) if int(use_root): kwargs = dict( db_user=r.env.db_root_username, db_password=r.env.db_root_password, db_host=r.env.db_host, ...
Opens a SQL shell to the given database, assuming the configured database and user supports this feature.
379,815
def explode(self, obj): if obj in self._done: return False result = False for item in self._explode: if hasattr(item, ): if obj._moId == item._moId: result = True else: ...
Determine if the object should be exploded.
379,816
def extract_command(outputdir, domain_methods, text_domain, keywords, comment_tags, base_dir, project, version, msgid_bugs_address): monkeypatch_i18n()
Extracts strings into .pot files :arg domain: domains to generate strings for or 'all' for all domains :arg outputdir: output dir for .pot files; usually locale/templates/LC_MESSAGES/ :arg domain_methods: DOMAIN_METHODS setting :arg text_domain: TEXT_DOMAIN settings :arg keywords: KEYWORDS ...
379,817
def create_concept_scheme(rdf, ns, lname=): ont = None if not ns: if p.startswith(prot): rdf.remove((ont, p, o)) replace_uri(rdf, ont, cs) return cs
Create a skos:ConceptScheme in the model and return it.
379,818
def restore(self, bAsync = True): if bAsync: win32.ShowWindowAsync( self.get_handle(), win32.SW_RESTORE ) else: win32.ShowWindow( self.get_handle(), win32.SW_RESTORE )
Unmaximize and unminimize the window. @see: L{maximize}, L{minimize} @type bAsync: bool @param bAsync: Perform the request asynchronously. @raise WindowsError: An error occured while processing this request.
379,819
def data(self, data, part=False, dataset=): links = self.parser(self.scanner(data, part), part, dataset) self.storage.add_links(links)
Parse data and update links. Parameters ---------- data Data to parse. part : `bool`, optional True if data is partial (default: `False`). dataset : `str`, optional Dataset key prefix (default: '').
379,820
def get_handler(self, *args, **options): handler = super(Command, self).get_handler(*args, **options) insecure_serving = options.get(, False) if self.should_use_static_handler(options): return StaticFilesHandler(handler) return handler
Returns the static files serving handler wrapping the default handler, if static files should be served. Otherwise just returns the default handler.
379,821
def delete(self): if self.dynamic_version_of is None: self._delete_dynamic_versions() else: super(DynamicFieldMixin, self).delete() self._inventory.srem(self.dynamic_part)
If a dynamic version, delete it the standard way and remove it from the inventory, else delete all dynamic versions.
379,822
def normalize_feature_objects(feature_objs): for obj in feature_objs: if hasattr(obj, "__geo_interface__") and \ in obj.__geo_interface__.keys() and \ obj.__geo_interface__[] == : yield obj.__geo_interface__ elif isinstance(obj, dict) and in obj and \ ...
Takes an iterable of GeoJSON-like Feature mappings or an iterable of objects with a geo interface and normalizes it to the former.
379,823
def calendar(type=, direction=, last=1, startDate=None, token=, version=): if startDate: startDate = _strOrDate(startDate) return _getJson(.format(type=type, direction=direction, last=last, date=startDate), token, version) return _getJson( + type + + direction + + str(last), token, versio...
This call allows you to fetch a number of trade dates or holidays from a given date. For example, if you want the next trading day, you would call /ref-data/us/dates/trade/next/1. https://iexcloud.io/docs/api/#u-s-exchanges 8am, 9am, 12pm, 1pm UTC daily Args: type (string); "holiday" or "trade" ...
379,824
def install_binary_dist(self, members, virtualenv_compatible=True, prefix=None, python=None, track_installed_files=False): module_search_path = set(map(os.path.normpath, sys.path)) prefix = os.path.normpath(prefix...
Install a binary distribution into the given prefix. :param members: An iterable of tuples with two values each: 1. A :class:`tarfile.TarInfo` object. 2. A file-like object. :param prefix: The "prefix" under which the requirements should be ...
379,825
def as_dict(self): d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "molecule": self.molecule.as_dict(), "graphs": json_graph.adjacency_data(self.graph)} return d
As in :Class: `pymatgen.core.Molecule` except with using `to_dict_of_dicts` from NetworkX to store graph information.
379,826
def _set_defined_policy(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=defined_policy.defined_policy, is_container=, presence=False, yang_name="defined-policy", rest_name="defined-policy", parent=self, path_helper=self._path_helper, extmethods=self._...
Setter method for defined_policy, mapped from YANG variable /rbridge_id/secpolicy/defined_policy (container) If this variable is read-only (config: false) in the source YANG file, then _set_defined_policy is considered as a private method. Backends looking to populate this variable should do so via call...
379,827
def load_datafile(name, search_path, codecs=get_codecs(), **kwargs): return munge.load_datafile(name, search_path, codecs, **kwargs)
find datafile and load them from codec TODO only does the first one kwargs: default = if passed will return that on failure instead of throwing
379,828
def stats(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) alerts_severities_count = queryset.values().annotate(count=Count()) severity_names = dict(models.Alert.SeverityChoices.CHOICES) alerts_severities_count = { sever...
To get count of alerts per severities - run **GET** request against */api/alerts/stats/*. This endpoint supports all filters that are available for alerts list (*/api/alerts/*). Response example: .. code-block:: javascript { "debug": 2, "error": 1, ...
379,829
def _get_snmpv3(self, oid): snmp_target = (self.hostname, self.snmp_port) cmd_gen = cmdgen.CommandGenerator() (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd( cmdgen.UsmUserData( self.user, self.auth_key, ...
Try to send an SNMP GET operation using SNMPv3 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value from the OID you are trying to retrieve.
379,830
def to_frame(self, data, state): data_len = data.find(b) if data_len < 0: raise exc.NoFrames() frame_len = data_len + 1 if (self.carriage_return and data_len and data[data_len - 1] == ord(b)): da...
Extract a single frame from the data buffer. The consumed data should be removed from the buffer. If no complete frame can be read, must raise a ``NoFrames`` exception. :param data: A ``bytearray`` instance containing the data so far read. :param state: An instanc...
379,831
def arch(self): if self.method in (, , ): return self.params[2] if self.method in (, ): return self.params[1] if self.method == : return self.params[3] if self.method == : return self.params[0][]
Return an architecture for this task. :returns: an arch string (eg "noarch", or "ppc64le"), or None this task has no architecture associated with it.
379,832
def filter_params(self, value): if value is None: return {} val_min = value.get(, None) val_max = value.get(, None) params = {} if val_min == val_max: return { self.target: val_min } key = self.target + "__" if val_min is not No...
return filtering params
379,833
def grant_usage_install_privileges(cls, cur, schema_name, roles): cur.execute( .format(schema_name, roles))
Sets search path
379,834
def parent(self, parent): if parent is None: self._parent = None else: from rafcon.core.states.state import State assert isinstance(parent, State) old_parent = self.parent self._parent = ref(parent) valid, message = self....
Setter for the parent state of the state element :param rafcon.core.states.state.State parent: Parent state or None
379,835
def create_columns(self): reader = self._get_csv_reader() headings = six.next(reader) try: examples = six.next(reader) except StopIteration: examples = [] found_fields = set() for i, value in enumerate(headings): if i >= 20: ...
For each column in file create a TransactionCsvImportColumn
379,836
def cmdline(argv=sys.argv[1:]): parser = ArgumentParser( description=) parser.add_argument(, help=) parser.add_argument(, help=) options = parser.parse_args(argv) factory = StopWordFactory() language = options.language stop_words = factory.get_stop_words(language, fail_safe=Tru...
Script for rebasing a text file
379,837
def extract_datetime_hour(cls, datetime_str): if not datetime_str: raise DateTimeFormatterException() try: return cls._extract_timestamp(datetime_str, cls.DATETIME_HOUR_FORMAT) except (TypeError, ValueError): raise DateTimeFormatterException(.format(...
Tries to extract a `datetime` object from the given string, including only hours. Raises `DateTimeFormatterException` if the extraction fails.
379,838
def fromML(vec): if isinstance(vec, newlinalg.DenseVector): return DenseVector(vec.array) elif isinstance(vec, newlinalg.SparseVector): return SparseVector(vec.size, vec.indices, vec.values) else: raise TypeError("Unsupported vector type %s" % type(ve...
Convert a vector from the new mllib-local representation. This does NOT copy the data; it copies references. :param vec: a :py:class:`pyspark.ml.linalg.Vector` :return: a :py:class:`pyspark.mllib.linalg.Vector` .. versionadded:: 2.0.0
379,839
def get_resource_by_agent(self, agent_id): collection = JSONClientValidated(, collection=, runtime=self._runtime) result = collection.find_one( dict({: {: [str(agent_id)]}}, **self._vi...
Gets the ``Resource`` associated with the given agent. arg: agent_id (osid.id.Id): ``Id`` of the ``Agent`` return: (osid.resource.Resource) - associated resource raise: NotFound - ``agent_id`` is not found raise: NullArgument - ``agent_id`` is ``null`` raise: OperationFail...
379,840
def clear_max_string_length(self): if (self.get_max_string_length_metadata().is_read_only() or self.get_max_string_length_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map[] = \ self.get_max_string_length_metadata().get_default_...
stub
379,841
def update(context, id, export_control, active): component_info = component.get(context, id=id) etag = component_info.json()[][] result = component.update(context, id=id, etag=etag, export_control=export_control, state=utils.active_string(a...
update(context, id, export_control, active) Update a component >>> dcictl component-update [OPTIONS] :param string id: ID of the component [required] :param boolean export-control: Set the component visible for users :param boolean active: Set the component in the active state
379,842
def all_state_variables_read(self): if self._all_state_variables_read is None: self._all_state_variables_read = self._explore_functions( lambda x: x.state_variables_read) return self._all_state_variables_read
recursive version of variables_read
379,843
def sendConnect(self, data): if self.backend == : import zmq self.context = zmq.Context() self.socket = self.context.socket(zmq.DEALER) if sys.version_info < (3,): self.socket.setsockopt_string(zmq.IDENTITY, unicode()) ...
Send a CONNECT command to the broker :param data: List of other broker main socket URL
379,844
def update_peer(self, current_name, new_name, new_url, username, password, peer_type="REPLICATION"): if self._get_resource_root().version < 11: peer_type = None peer = ApiCmPeer(self._get_resource_root(), name=new_name, url=new_url, username=username, passw...
Update a replication peer. @param current_name: The name of the peer to updated. @param new_name: The new name for the peer. @param new_url: The new url for the peer. @param username: The admin username to use to setup the remote side of the peer connection. @param password: The password of the adm...
379,845
def bake_content(request): ident_hash = request.matchdict[] try: id, version = split_ident_hash(ident_hash) except IdentHashError: raise httpexceptions.HTTPNotFound() if not version: raise httpexceptions.HTTPBadRequest() with db_connect() as db_conn: with db_co...
Invoke the baking process - trigger post-publication
379,846
def add_tcp_callback(port, callback, threaded_callback=False): _rpio.add_tcp_callback(port, callback, threaded_callback)
Adds a unix socket server callback, which will be invoked when values arrive from a connected socket client. The callback must accept two parameters, eg. ``def callback(socket, msg)``.
379,847
def put(self, locator = None, component = None): if component == None: raise Exception("Component cannot be null") self._lock.acquire() try: self._references.append(Reference(locator, component)) finally: self._lock.release()
Puts a new reference into this reference map. :param locator: a component reference to be added. :param component: a locator to find the reference by.
379,848
def shift_and_scale(matrix, shift, scale): zeroed = matrix - matrix.min() scaled = (scale - shift) * (zeroed / zeroed.max()) return scaled + shift
Shift and scale matrix so its minimum value is placed at `shift` and its maximum value is scaled to `scale`
379,849
def strip_rate(self, idx): val, = struct.unpack_from(, self._rtap, idx) rate_unit = float(1) / 2 return idx + 1, rate_unit * val
strip(1 byte) radiotap.datarate note that, unit of this field is originally 0.5 Mbps :idx: int :return: int idx :return: double rate in terms of Mbps
379,850
def nullspace(A, atol=1e-13, rtol=0): A = np.atleast_2d(A) u, s, vh = np.linalg.svd(A) tol = max(atol, rtol * s[0]) nnz = (s >= tol).sum() ns = vh[nnz:].conj().T return ns
Compute an approximate basis for the nullspace of A. The algorithm used by this function is based on the singular value decomposition of `A`. Parameters ---------- A : numpy.ndarray A should be at most 2-D. A 1-D array with length k will be treated as a 2-D with shape (1, k) at...
379,851
def get_wulff_shape(self, material_id): from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from pymatgen.analysis.wulff import WulffShape, hkl_tuple_to_str structure = self.get_structure_by_material_id(material_id) surfaces = self.get_surface_data(material_id)["surfaces"...
Constructs a Wulff shape for a material. Args: material_id (str): Materials Project material_id, e.g. 'mp-123'. Returns: pymatgen.analysis.wulff.WulffShape
379,852
def mimetype_icon(path, fallback=None): mime = mimetypes.guess_type(path)[0] if mime: icon = mime.replace(, ) if QtGui.QIcon.hasThemeIcon(icon): icon = QtGui.QIcon.fromTheme(icon) if not icon.isNull(): ...
Tries to create an icon from theme using the file mimetype. E.g.:: return self.mimetype_icon( path, fallback=':/icons/text-x-python.png') :param path: file path for which the icon must be created :param fallback: fallback icon path (qrc or file system) :ret...
379,853
def unique_filename(**kwargs): if not in kwargs: path = temp_dir() kwargs[] = path else: path = temp_dir(kwargs[]) kwargs[] = path if not os.path.exists(kwargs[]): os.umask(umask) handle, filename = mkstemp(**kwargs) os.close...
Create new filename guaranteed not to exist previously Use mkstemp to create the file, then remove it and return the name If dir is specified, the tempfile will be created in the path specified otherwise the file will be created in a directory following this scheme: :file:'/tmp/inasafe/<dd-mm-yyyy>/<...
379,854
def naiveWordAlignment(tg, utteranceTierName, wordTierName, isleDict, phoneHelperTierName=None, removeOverlappingSegments=False): utterance utteranceTier = tg.tierDict[utteranceTierName] wordTier = None if wordTierName in tg.tierNameList: wordTi...
Performs naive alignment for utterances in a textgrid Naive alignment gives each segment equal duration. Word duration is determined by the duration of an utterance and the number of phones in the word. By 'utterance' I mean a string of words separated by a space bounded in time eg (0.5, ...
379,855
def configure_logging(logger_name, filename=None): if filename is None: if logger_name is None: probing_paths = [path.join(, ), path.join(, )] else: probing_paths = [ path.join(, logger_name + ), path.join(, logger_name + ), ...
Configure logging and return the named logger and the location of the logging configuration file loaded. This function expects a Splunk app directory structure:: <app-root> bin ... default ... local ... This function ...
379,856
def reporter(self, analysistype=): logging.info(.format(analysistype)) genusgenes = dict() targetpath = str() for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != : targetpath = sample[analysistype].targetpat...
Creates a report of the genesippr results :param analysistype: The variable to use when accessing attributes in the metadata object
379,857
def parse_pv(header): order_fit = parse_order_fit(header) def parse_with_base(i): key_base = "PV%d_" % i pvi_x = [header[key_base + "0"]] def parse_range(lower, upper): for j in range(lower, upper + 1): pvi_x.append(header[key_base + str(j)]) ...
Parses the PV array from an astropy FITS header. Args: header: astropy.io.fits.header.Header The header containing the PV values. Returns: cd: 2d array (list(list(float)) [[PV1_0, PV1_1, ... PV1_N], [PV2_0, PV2_1, ... PV2_N]] Note that N depends on the order of the fit. Fo...
379,858
def download(url): session = requests.Session() session.mount(, FileAdapter()) try: res = session.get(url) except requests.exceptions.ConnectionError as e: raise e res.raise_for_status() return res
Uses requests to download an URL, maybe from a file
379,859
def get_nets_radb(self, response, is_http=False): nets = [] if is_http: regex = r else: regex = r for match in re.finditer( regex, response, re.MULTILINE ): try: ...
The function for parsing network blocks from ASN origin data. Args: response (:obj:`str`): The response from the RADB whois/http server. is_http (:obj:`bool`): If the query is RADB HTTP instead of whois, set to True. Defaults to False. Returns: ...
379,860
def _ReadTab(Year): dtype_in = [(,),(,),(,),(,), (,),(,),(,), (,),(,),(,), (,),(,),(,),(,),(,), (,),(,),(,),(,),(,), (,),(,),(,)] fname = Globals.DataPath+.format(Year) data = pf.ReadASCIIData(fname,Header=False,dtype=dtype_in) dtype_out = [(,),(,),(,),(,),(,),(,), (,),(,),(,),(,),(,...
Reads OMNI data tab with Tsyganenko parameters. Input: Year: Integer year to read
379,861
def set_firewall_settings(profile, inbound=None, outbound=None, store=): if profile.lower() not in (, , ): raise ValueError(.format(profile)) if inbound and inbound.lower() not in (, ...
Set the firewall inbound/outbound settings for the specified profile and store Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private inbound (str): The inbound setting. If ``None`` is...
379,862
def init_app(self, app): super(InvenioIIIFAPI, self).init_app(app) api = Api(app=app) self.iiif_ext.init_restful(api, prefix=app.config[])
Flask application initialization.
379,863
def trace_memory_start(self): self.trace_memory_clean_caches() objgraph.show_growth(limit=30) gc.collect() self._memory_start = self.worker.get_memory()["total"]
Starts measuring memory consumption
379,864
def on_fork(): reset_logging_framework() fixup_prngs() mitogen.core.Latch._on_fork() mitogen.core.Side._on_fork() mitogen.core.ExternalContext.service_stub_lock = threading.Lock() mitogen__service = sys.modules.get() if mitogen__service: mitogen__service._pool_lock = threadin...
Should be called by any program integrating Mitogen each time the process is forked, in the context of the new child.
379,865
def _JzStaeckelIntegrandSquared(v,E,Lz,I3V,delta,u0,cosh2u0,sinh2u0, potu0pi2,pot): sin2v= nu.sin(v)**2. dV= cosh2u0*potu0pi2\ -(sinh2u0+sin2v)*potentialStaeckel(u0,v,pot,delta) return E*sin2v+I3V+dV-Lz**2./2./delta**2./sin2v
The J_z integrand: p_v(v)/2/delta^2
379,866
def swipe_right(self, steps=10, *args, **selectors): self.device(**selectors).swipe.right(steps=steps)
Swipe the UI object with *selectors* from center to right See `Swipe Left` for more details.
379,867
def add_table(self, table, row=None, col=0, row_spaces=1): name = table.name assert name is not None, "Tables must have a name" assert name not in self.__tables, "Table %s already exists in this worksheet" % name if row is None: row = self.__next_row self.__n...
Adds a table to the worksheet at (row, col). Return the (row, col) where the table has been put. :param xltable.Table table: Table to add to the worksheet. :param int row: Row to start the table at (defaults to the next free row). :param int col: Column to start the table at. :p...
379,868
def query(self): logger.debug("Grafana query... %s", cherrypy.request.method) if cherrypy.request.method == : cherrypy.response.headers[] = cherrypy.response.headers[] = cherrypy.response.headers[] = cherrypy.request.handler = None ...
Request object passed to datasource.query function: { 'timezone': 'browser', 'panelId': 38, 'range': { 'from': '2018-08-29T02:38:09.633Z', 'to': '2018-08-29T03:38:09.633Z', 'raw': {'from': 'now-1h', 'to': 'now'} }, ...
379,869
def start(self, host, nornir): self.host = host self.nornir = nornir try: logger.debug("Host %r: running task %r", self.host.name, self.name) r = self.task(self, **self.params) if not isinstance(r, Result): r = Result(host=host, resul...
Run the task for the given host. Arguments: host (:obj:`nornir.core.inventory.Host`): Host we are operating with. Populated right before calling the ``task`` nornir(:obj:`nornir.core.Nornir`): Populated right before calling the ``task`` Returns: ...
379,870
def _format_arg_list(args, variadic=False): def sugar(s): s = s.replace("{", "{{").replace("}", "}}") if len(s) > 50: return s[:20] + " ... " + s[-20:] else: return s def arg_to_str(arg): if isinstance(arg, str): return ...
Format a list of arguments for pretty printing. :param a: list of arguments. :type a: list :param v: tell if the function accepts variadic arguments :type v: bool
379,871
def info(self): url = "{}/v7/finance/quote?symbols={}".format( self._base_url, self.ticker) r = _requests.get(url=url).json()["quoteResponse"]["result"] if len(r) > 0: return r[0] return {}
retreive metadata and currenct price data
379,872
def fonts(self): for width in (w for w in FontWidth if w in self): for slant in (s for s in FontSlant if s in self[width]): for weight in (w for w in FontWeight if w in self[width][slant]): yield self[width][slant][weight]
Generator yielding all fonts of this typeface Yields: Font: the next font in this typeface
379,873
def parts_to_url(parts=None, scheme=None, netloc=None, path=None, query=None, fragment=None): if isinstance(parts, _urllib_parse.SplitResult): scheme, netloc, path, query, fragment = parts elif parts and isinstance(parts, dict): scheme = parts.get(, ) netloc = parts.get(, ) ...
Build url urlunsplit style, but optionally handle path as a list and/or query as a dict
379,874
def _processDocstring(self, node, tail=, **kwargs): typeName = type(node).__name__ curLineNum = startLineNum = 0 if typeName != : startLineNum = curLineNum = node.lineno - 1 line = while curLineNum < len(self.lines): line = self...
Handles a docstring for functions, classes, and modules. Basically just figures out the bounds of the docstring and sends it off to the parser to do the actual work.
379,875
def backup_key(self, name, mount_point=DEFAULT_MOUNT_POINT): api_path = .format( mount_point=mount_point, name=name, ) response = self._adapter.get( url=api_path, ) return response.json()
Return a plaintext backup of a named key. The backup contains all the configuration data and keys of all the versions along with the HMAC key. The response from this endpoint can be used with the /restore endpoint to restore the key. Supported methods: GET: /{mount_point}/backup/{n...
379,876
def _set_overlay_policy_map(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("pmap_name",overlay_policy_map.overlay_policy_map, yang_name="overlay-policy-map", rest_name="overlay-policy-map", parent=self, is_container=, user_ordered=False,...
Setter method for overlay_policy_map, mapped from YANG variable /overlay_policy_map (list) If this variable is read-only (config: false) in the source YANG file, then _set_overlay_policy_map is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._s...
379,877
def remove_listener(self, callback): listeners = filter(lambda x: x[] == callback, self.listeners) for l in listeners: self.listeners.remove(l)
Remove a listener.
379,878
def _operation_status_message(self): msg = None action = None if not google_v2_operations.is_done(self._op): last_event = google_v2_operations.get_last_event(self._op) if last_event: msg = last_event[] action_id = last_event.get(, {}).get() if action_id: ac...
Returns the most relevant status string and failed action. This string is meant for display only. Returns: A printable status string and name of failed action (if any).
379,879
def get_scoped_package_version_metadata_from_recycle_bin(self, feed_id, package_scope, unscoped_package_name, package_version): route_values = {} if feed_id is not None: route_values[] = self._serialize.url(, feed_id, ) if package_scope is not None: route_values[...
GetScopedPackageVersionMetadataFromRecycleBin. [Preview API] Get information about a scoped package version in the recycle bin. :param str feed_id: Name or ID of the feed. :param str package_scope: Scope of the package (the 'scope' part of @scope/name) :param str unscoped_package_name: N...
379,880
def removeUserGroups(self, users=None): admin = None userCommunity = None portal = None groupAdmin = None user = None userCommData = None group = None try: admin = arcrest.manageorg.Administration(securityHandler=self._securityHandle...
Removes users' groups. Args: users (str): A comma delimited list of user names. Defaults to ``None``. Warning: When ``users`` is not provided (``None``), all users in the organization will have their groups deleted!
379,881
def initialize(self, timeouts): if self.bind is True: self.socket.bind(self.address) else: self.socket.connect(self.address) self._set_timeouts(timeouts)
Bind or connect the nanomsg socket to some address
379,882
def fromjson(source, *args, **kwargs): source = read_source_from_arg(source) return JsonView(source, *args, **kwargs)
Extract data from a JSON file. The file must contain a JSON array as the top level object, and each member of the array will be treated as a row of data. E.g.:: >>> import petl as etl >>> data = ''' ... [{"foo": "a", "bar": 1}, ... {"foo": "b", "bar": 2}, ... {"foo": "c"...
379,883
def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False): if axis is None: axis = self.axis or 0 labels = self.obj._get_axis(axis) if isinstance(obj, slice): return self._convert_slice_indexer(obj, axis) ...
Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[['foo', 'bar', 'baz']] -> [i, j, k] (indices of foo, bar, baz) Going by Zen of Python? 'In the face of ambiguity, re...
379,884
def load_dynamic_config(config_file=DEFAULT_DYNAMIC_CONFIG_FILE): dynamic_configurations = {} sys.path.insert(0, path.dirname(path.abspath(config_file))) try: config_module = __import__() dynamic_configurations = config_module.CONFIG except ImportError: LOG.e...
Load and parse dynamic config
379,885
def pull_commits(self, pr_number): payload = { : PER_PAGE, } commit_url = urijoin("pulls", str(pr_number), "commits") return self.fetch_items(commit_url, payload)
Get pull request commits
379,886
def get_free_diskbytes(dir_): r if WIN32: import ctypes free_bytes = ctypes.c_ulonglong(0) outvar = ctypes.pointer(free_bytes) dir_ptr = ctypes.c_wchar_p(dir_) ctypes.windll.kernel32.GetDiskFreeSpaceExW(dir_ptr, None, None, outvar) bytes_ = free_bytes.value ...
r""" Args: dir_ (str): Returns: int: bytes_ folder/drive free space (in bytes) References:: http://stackoverflow.com/questions/51658/cross-platform-space-remaining-on-volume-using-python http://linux.die.net/man/2/statvfs CommandLine: python -m utool.util_cplat...
379,887
def paginate_queryset(self, queryset, page_size): paginator = self.get_paginator( queryset, page_size, orphans = self.get_paginate_orphans(), allow_empty_first_page = self.get_allow_empty() ) page_kwarg = self.page_kwarg...
Returns tuple containing paginator instance, page instance, object list, and whether there are other pages. :param queryset: the queryset instance to paginate. :param page_size: the number of instances per page. :rtype: tuple.
379,888
def get_daemon_stats(self, details=False): res = super(BaseSatellite, self).get_daemon_stats(details=details) counters = res[] counters[] = len(self.external_commands) counters[] = len(self.arbiters) counters[] = len(self.schedulers) return res
Increase the stats provided by the Daemon base class :return: stats dictionary :rtype: dict
379,889
def extend_instance(instance, *bases, **kwargs): last = kwargs.get(, False) bases = tuple(bases) for base in bases: assert inspect.isclass(base), "bases must be classes" assert not inspect.isclass(instance) base_cls = instance.__class__ base_cls_name = instance.__class__.__name__ ...
Apply subclass (mixin) to a class object or its instance By default, the mixin is placed at the start of bases to ensure its called first as per MRO. If you wish to have it injected last, which is useful for monkeypatching, then you can specify 'last=True'. See here: http://stackoverflow.com/a/1001...
379,890
def copy_figure(self): if self.figviewer and self.figviewer.figcanvas.fig: self.figviewer.figcanvas.copy_figure()
Copy figure from figviewer to clipboard.
379,891
def publishing(self, service): to_update = False status = False self.log_update(service, to_update, status, count_new_data) if to_update and status: self.update_trigger(service)
the purpose of this tasks is to get the data from the cache then publish them :param service: service object where we will publish :type service: object
379,892
def galactic_to_equatorial(gl, gb): gal = SkyCoord(gl*u.degree, gl*u.degree, frame=) transformed = gal.transform_to() return transformed.ra.degree, transformed.dec.degree
This converts from galactic coords to equatorial coordinates. Parameters ---------- gl : float or array-like Galactic longitude values(s) in decimal degrees. gb : float or array-like Galactic latitude value(s) in decimal degrees. Returns ------- tuple of (float, float) o...
379,893
def get_resources(self): collection = JSONClientValidated(, collection=, runtime=self._runtime) result = collection.find(self._view_filter()).sort(, DESCENDING) return objects.Re...
Gets all ``Resources``. In plenary mode, the returned list contains all known resources or an error results. Otherwise, the returned list may contain only those resources that are accessible through this session. return: (osid.resource.ResourceList) - a list of ``Resources`` ra...
379,894
def get_analyzable_segments(workflow, sci_segs, cat_files, out_dir, tags=None): if tags is None: tags = [] logging.info() make_analysis_dir(out_dir) sci_ok_seg_name = "SCIENCE_OK" sci_ok_seg_dict = segments.segmentlistdict() sci_ok_segs = {} cat_sets = parse_cat_ini_opt(w...
Get the analyzable segments after applying ini specified vetoes and any other restrictions on the science segs, e.g. a minimum segment length, or demanding that only coincident segments are analysed. Parameters ----------- workflow : Workflow object Instance of the workflow object sci_s...
379,895
def _start_workflow_stages(pb: ProcessingBlock, pb_id: str, workflow_stage_dict: dict, workflow_stage: WorkflowStage, docker: DockerSwarmClient): stage_data = workflow_stage_dict[workflow_stage.id] stage_data[] = False ...
Start a workflow stage by starting a number of docker services. This function first assesses if the specified workflow stage can be started based on its dependencies. If this is found to be the case, the workflow stage is stared by first resolving and template arguments in the workflow stage configurat...
379,896
def open_pickle(path: str): try: with open(path, ) as opened_pickle: try: return pickle.load(opened_pickle) except Exception as pickle_error: logger.error(pickle_error) raise except FileNotFoundError as fnf_error: logge...
Open a pickle and return loaded pickle object. :type path: str :param : path: File path to pickle file to be opened. :rtype : object
379,897
def get_members(self, role=github.GithubObject.NotSet): assert role is github.GithubObject.NotSet or isinstance(role, (str, unicode)), role url_parameters = dict() if role is not github.GithubObject.NotSet: assert role in [, , ] url_parameters["role"] = role ...
:calls: `GET /teams/:id/members <https://developer.github.com/v3/teams/members/#list-team-members>`_ :param role: string :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
379,898
def decrypt(s, base64 = False): return _cipher().decrypt(base64 and b64decode(s) or s)
对称解密函数
379,899
def _query(self): formated_property_names = ",".join(self.property_names) wql = "Select {property_names} from {class_name}{filters}".format( property_names=formated_property_names, class_name=self.class_name, filters=self.formatted_filters ) self.logger.debug(u"Que...
Query WMI using WMI Query Language (WQL) & parse the results. Returns: List of WMI objects or `TimeoutException`.