code stringlengths 1 18.2k |
|---|
def index_all(self): """ Index all records under :attr:`record_path`. """ self.logger.debug('Start indexing all records under: %s', self.record_path) with self.db.connection(): for json_path in sorted(self.find_record_files()): self.index_record(json_path) |
def fig_lfp_corr(params, savefolders, transient=200, channels=[0,3,7,11,13], Df=None, mlab=True, NFFT=256, noverlap=128, window=plt.mlab.window_hanning, letterslist=['AB', 'CD'], data_type = 'LFP'): '''This figure compares power spectra for correlated and uncorrelated signals ''' ana_params.set_PLOS_2column_fig_style(r... |
ax.text(0.80,0.82,'ch. %i' %(channels[0]+1),horizontalalignment='left', verticalalignment='center', fontsize=6, transform=ax.transAxes) ax.yaxis.set_minor_locator(plt.NullLocator()) ax.set_ylabel('(mV$^2$/Hz)', labelpad=0.) ax.set_xticks([]) ax.set_xticklabels([]) ax.tick_params(axis='y',which='minor',bottom='off') ax.... |
% 2)*2]) phlp.remove_axis_junk(ax) ax.loglog(freqs,LFP_PSD_corr[channels[4]], color='k', label='corr') ax.loglog(freqs,LFP_PSD_uncorr[channels[4]], color='gray' if analysis_params.bw else analysis_params.colorP, lw=1, label='uncorr') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_xlabe... |
def sli_run(parameters=object(), fname='microcircuit.sli', verbosity='M_ERROR'): ''' Takes parameter-class and name of main sli-script as input, initiating the simulation. kwargs: :: parameters : object, parameter class instance fname : str, path to sli codes to be executed verbosity : 'str', nest verbosity flag ''' # ... |
def buffer_to_value(self, obj, buffer, offset, default_endianness=DEFAULT_ENDIANNESS): """ Converts the bytes in ``buffer`` at ``offset`` to a native Python value. Returns that value and the number of bytes consumed to create it. :param obj: The parent :class:`.PebblePacket` of this field :type obj: .PebblePacket :para... |
length except struct.error as e: raise PacketDecodeError("{}: {}".format(self.type, e)) |
def value_to_bytes(self, obj, value, default_endianness=DEFAULT_ENDIANNESS): """ Converts the given value to an appropriately encoded string of bytes that represents it. :param obj: The parent :class:`.PebblePacket` of this field :type obj: .PebblePacket :param value: The python value to serialise. :param default_endia... |
def profile(func): """ Decorator to profile functions with cProfile Args: func: python function Returns: profile report References: https://osf.io/upav8/ """ def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_st... |
def rpc(self, cmd, **kwargs): """Generic helper function to call an RPC method.""" func = getattr(self.client, cmd) try: if self.credentials is None: return func(kwargs) else: return func(self.credentials, kwargs) except socket.error as e: raise BackendConnectionError(e) except (xmlrpclib.ProtocolError, BadStatusLine) ... |
def message_user(self, username, domain, subject, message): """Currently use send_message_chat and discard subject, because headline messages are not stored by mod_offline.""" kwargs = { 'body': message, 'from': domain, 'to': '%s@%s' % (username, domain), } if self.api_version <= (14, 7): # TODO: it's unclear when send... |
def fig_network_input_structure(fig, params, bottom=0.1, top=0.9, transient=200, T=[800, 1000], Df= 0., mlab= True, NFFT=256, srate=1000, window=plt.mlab.window_hanning, noverlap=256*3/4, letters='abcde', flim=(4, 400), show_titles=True, show_xlabels=True, show_CSD=False): ''' This figure is the top part for plotting a... |
############################################################################ # B part, firing rate spectra ############################################################################ # Get the firing rate from Potjan Diesmann et al network activity #collect the spikes x is the times, y is the id of the cell. T_all=[tr... |
histogram hist = np.histogram(x[X], bins=bins)[0].astype(float) hist -= hist.mean() if mlab: Pxx, freqs=plt.mlab.psd(hist, NFFT=NFFT, Fs=srate, noverlap=noverlap, window=window) else: [freqs, Pxx] = hlp.powerspec([hist], tbin= 1., Df=Df, pointProcess=False) mask = np.where(freqs >= 0.) freqs = freqs[mask] Pxx = Pxx.fla... |
fig.add_subplot(gs1[:, 2]) phlp.annotate_subplot(ax2, ncols=5, nrows=1, letter=letters[2], linear_offset=0.065) phlp.remove_axis_junk(ax2) plot_signal_sum(ax2, params, fname=os.path.join(params.savefolder, 'LFPsum.h5'), unit='mV', T=T, ylim=[-1600, 40], rasterized=False) # CSD background colorplot if show_CSD: im = plo... |
= fig.add_subplot(gs1[i, 3]) phlp.remove_axis_junk(ax) if i == 0: ax.set_ylabel('(mV$^2$/Hz)', labelpad=0) ax.loglog(freqs[1:],PSD[ch][1:], color='k') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') if i < 4: ax.set_xticklabels([]) ax.text(0.75, 0.85,'ch. %i' %(channels[i]+1), horizontalalignm... |
def _get_rsa_public_key(cert): """ PyOpenSSL does not provide a public method to export the public key from a certificate as a properly formatted ASN.1 RSAPublicKey structure. There are 'hacks' which use dump_privatekey(crypto.FILETYPE_ASN1, <public_key>), but this dumps the public key within a PrivateKeyInfo structure... |
def _credssp_processor(self, context): """ Implements a state machine :return: """ http_response = (yield) credssp_context = self._get_credssp_header(http_response) if credssp_context is None: raise Exception('The remote host did not respond with a \'www-authenticate\' header containing ' '\'CredSSP\' as an available a... |
Request context_generator = context.initialize_security_context() negotiate_token = context_generator.send(None) log.debug("NTLM Type 1: %s", AsHex(negotiate_token)) ts_request = TSRequest() ts_request['negoTokens'] = negotiate_token self.tls_connection.send(ts_request.getData()) http_response = yield self._set_credssp... |
of the CredSSP protocol is designed to thwart 'man-in-the-middle' attacks # Build and encrypt the response to the server ts_request = TSRequest() type3= context_generator.send(challenge_token) log.debug("NTLM Type 3: %s", AsHex(type3)) ts_request['negoTokens'] = type3 public_key_encrypted, signature = context.wrap_mess... |
= self.password_authenticator.get_domain() tsp['username'] = self.password_authenticator.get_username() tsp['password'] = self.password_authenticator.get_password() tsc = TSCredentials() tsc['type'] = 1 tsc['credentials'] = tsp.getData() ts_request = TSRequest() encrypted, signature = context.wrap_message(tsc.getData()... |
def install(self, force_install=False): """ Installs an app. Blocks until the installation is complete, or raises :exc:`AppInstallError` if it fails. While this method runs, "progress" events will be emitted regularly with the following signature: :: (sent_this_interval, sent_total, total_size) :param force_install: In... |
def _parse_chemical_equation(value): """ Parse the chemical equation mini-language. See the docstring of `ChemicalEquation` for more. Parameters ---------- value : `str` A string in chemical equation mini-language. Returns ------- mapping A mapping in the format specified by the mini-language (see notes on `ChemicalEqu... |
parsed['reactants'] parsed['arrow'] = '->' return parsed |
def _get_chemical_equation_piece(species_list, coefficients): """ Produce a string from chemical species and their coefficients. Parameters ---------- species_list : iterable of `str` Iterable of chemical species. coefficients : iterable of `float` Nonzero stoichiometric coefficients. The length of `species_list` and `... |
'.join(bag)) |
def _check_data(data): """ Check a data object for inconsistencies. Parameters ---------- data : `pandas.DataFrame` A `data` object, i.e., a table whose rows store information about chemical species, indexed by chemical species. Warns ----- UserWarning Warned if a ground state species has one or more imaginary vibratio... |
in data.index: vibfreqs = data.loc[species, "vibfreqs"] nimagvibfreqs = _np.sum(_np.array(vibfreqs) < 0) if species[-1] == '#' and nimagvibfreqs != 1: _warnings.warn("'{}' should have 1 imaginary vibfreqs but {} " "found".format(species, nimagvibfreqs)) elif species[-1] != '#' and nimagvibfreqs != 0: _warnings.warn("'{... |
def _split_chemical_equations(value): """ Split a string with sequential chemical equations into separate strings. Each string in the returned iterable represents a single chemical equation of the input. See the docstrings of `ChemicalEquation` and `ChemicalSystem` for more. Parameters ---------- value : `str` A string... |
I'] """ pieces = _split_arrows(value) return [(pieces[i] + pieces[i + 1] + pieces[i + 2]).strip() for i in range(0, len(pieces) - 2, 2)] |
def to_series(self, only=None, intensive_columns=["temperature", "pressure"], check_data=True): """ Produce a data record for `ChemicalEquation`. All possible linear differences for all numeric attributes are computed and stored in the returned `pandas.Series` object (see examples below). This allows for easy applicati... |
of attribute differences, whose name is the canonical string representation of the `ChemicalEquation` or, if `only` is given, a string representing either reactants or products (see examples below). Raises ------ ValueError Raised if `self.data` wasn't defined (e.g. is `None`), if `only` is something other than ``"reac... |
products can be computed: >>> equilibrium.to_series("reactants") charge 0.000000 enthalpy -228.533374 entropy 0.031135 freeenergy -228.564509 mult 1.000000 natom 8.000000 nbasis 68.000000 nmo 68.000000 pressure 1.000000 temperature 298.150000 Name: AcOH(g), dtype: float64 """ if self.data is None: # TODO: should an emp... |
all([s in self.data.index for s in species]): series = (self.data.loc[species, extensive_columns] .mul(self.coefficient, axis="index").sum("index")) for column in intensive_columns: vals = self.data[column].unique() if len(vals) > 1: raise ValueError("different values for {}: " "{}".format(column, vals)) series[column]... |
def to_dataframe(self, *args, **kwargs): """ Produce a data table with records for all chemical equations. All possible differences for numeric attributes are computed and stored as columns in the returned `pandas.DataFrame` object (see examples below), whose rows represent chemical equations. In terms of behavior, thi... |
+NORMALIZE_WHITESPACE enthalpy entropy freeenergy chemical_equation AcOH(g) <=> AcOH(aq) -0.010958 -0.000198 -0.010759 """ dataframe = _pd.DataFrame([equation.to_series(*args, **kwargs) for equation in self.equations]) dataframe.index.name = "chemical_equation" return dataframe |
def to_digraph(self, *args, **kwargs): """ Compute a directed graph for the chemical system. Returns ------- digraph : `networkx.DiGraph` Graph nodes are reactants and/or products of chemical equations, while edges represent the equations themselves. Double ended edges are used to represent equilibria. Attributes are c... |
for value in _split_arrows(str(equation))] try: attr = equation.to_series("reactants", *args, **kwargs).to_dict() except ValueError: attr = dict() digraph.add_node(reactants, **attr) try: attr = equation.to_series("products", *args, **kwargs).to_dict() except ValueError: attr = dict() digraph.add_node(products, **attr)... |
def fig_exc_inh_contrib(fig, axes, params, savefolders, T=[800, 1000], transient=200, panel_labels = 'FGHIJ', show_xlabels=True): ''' plot time series LFPs and CSDs with signal variances as function of depth for the cases with all synapses intact, or knocking out excitatory input or inhibitory input to the postsynaptic... |
'gray', 'k'] # lws = [0.75, 0.75, 1.5] lws = [1.25, 1.25, 1.25] else: colors = [analysis_params.colorE, analysis_params.colorI, 'k'] # colors = 'rbk' # lws = [0.75, 0.75, 1.5] lws = [1.25, 1.25, 1.25] #scalebar labels units = ['$\mu$A mm$^{-3}$', 'mV'] #depth of each contact site depth = params.electrodeParams['z'] # #... |
im = plot_signal_sum_colorplot(dum_ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name), cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21), rasterized=False) if abs(im.get_array()).max() > vlim_CSD: vlim_CSD = abs(im.get_array()).max() plt.close(dum_fig) ... |
= [] for j, savefolder in enumerate(savefolders): f = h5py.File(os.path.join(os.path.split(params.savefolder)[0], savefolder, 'CSDsum.h5')) var = f['data'].value[:, transient:].var(axis=1) ax.semilogx(var, depth, color=colors[j], label=labels[j], lw=lws[j], clip_on=False) datas.append(f['data'].value[:, transient:]) f.... |
ax.set_yticklabels([]) |
def read_cclib(value, name=None): """ Create an `Atoms` object from data attributes parsed by cclib. `cclib <https://cclib.github.io/>`_ is an open source library, written in Python, for parsing and interpreting the results (logfiles) of computational chemistry packages. Parameters ---------- value : `str`, `cclib.pars... |
6, 6, 7, 1, 1, 1, 1, 1], dtype=int32) >>> molecule.charge 0 """ if isinstance(value, _logfileparser.Logfile): # TODO: test this case. jobfilename = value.filename ccdata = value.parse() elif isinstance(value, _data.ccData): # TODO: test this case. jobfilename = None ccdata = value else: # TODO: test this case. ccobj = ... |
def read_pybel(value, name=None): """ Create an `Atoms` object from content parsed by Pybel. `Pybel <https://openbabel.org/docs/dev/UseTheLibrary/Python_Pybel.html>`_ is a Python module that simplifies access to the OpenBabel API, a chemical toolbox designed to speak the many languages of chemical data. It’s an open, c... |
available as attributes in the returned object. Notes ----- The following attributes are converted from Pybel to cclib: `atomcoords`, `atommasses`, `atomnos`, `natom`, `charge` and `mult`. One must keep in mind that `charge` and `mult` are not always reliable, since these are often calculated from atomic formal charges... |
_os.path.splitext(jobfilename) # TODO: This only reads first structure. mol = next(_pb.readfile(jobfilename_ext[1:], jobfilename)) charge, mult = mol.charge, mol.spin ccdata = _makecclib(mol.OBMol) if name is None: name = jobfilename attributes = ccdata.getattributes() attributes.update({ 'name': name, 'jobfilename': j... |
def create_data(*args): """ Produce a single data object from an arbitrary number of different objects. This function returns a single `pandas.DataFrame` object from a collection of `Atoms` and `pandas.DataFrame` objects. The returned object, already indexed by `Atoms.name`, can be promptly used by e.g. `ChemicalSystem... |
`None` values) is created for the purpose of indexing. Notes ----- The returned `pandas.DataFrame` will be indexed by `Atoms.name` (see examples below), which might be the same as `Atoms.jobfilename` if no name was given to the constructor of `Atoms` (e.g. mapping). Examples -------- >>> from pyrrole.atoms import Atoms... |
def split(self, pattern=None): r""" Break molecule up into constituent fragments. By default (i.e., if `pattern` is `None`), each disconnected fragment is returned as a separate new `Atoms` object. This uses OpenBabel (through `OBMol.Separate`) and might not preserve atom order, depending on your version of the library... |
O 1.21457 0.03172 -0.27623 H 1.72977 -0.08038 0.53387 H 1.44927 0.91672 -0.58573 <BLANKLINE> Precise fragment grouping can be achieved by explicitly indicating which atoms belong to which fragments: >>> for frag in water_dimer.split([range(3), (5, 4), [3]]): ... print("{}\n".format(frag)) O -1.62893 -0.04138 0.37137 H ... |
def to_pybel(self): """ Produce a Pybel Molecule object. It is based on the capabilities of OpenBabel through Pybel. The present object must have at least `atomcoords`, `atomnos`, `charge` and `mult` defined. Returns ------- `pybel.Molecule` Examples -------- >>> from pyrrole.atoms import Atoms >>> dioxygen = Atoms({'a... |
def to_string(self, format="smi", dialect=None, with_header=False, fragment_id=None, constraints=None): r""" Produce a string representation of the molecule. This function wraps and extends the functionality of OpenBabel (which is accessible through `to_pybel`). Many chemical formats can thus be output (see the `pybel.... |
might not work with all dialects and/or formats. fragment_id : `str`, optional Indentify molecular fragments (see examples below). This might not work with all dialects and/or formats. constraints : iterable object of `int` Set cartesian constraints for selected atoms (see examples below). This might not work with all ... |
8], ... 'charge': 0, ... 'mult': 3, ... 'name': 'dioxygen'}) By default, a SMILES string is returned: >>> dioxygen.to_string() 'O=O\tdioxygen' Cartesian coordinates can be produced with ``format="xyz"``, which is equivalent to printing an `Atoms` instance: >>> print(dioxygen.to_string("xyz")) O 0.00000 0.00000 0.00000 ... |
H 1.0 -2.0666300000 -0.7349800000 -0.1366300000 O 8.0 1.2145700000 0.0317200000 -0.2762300000 H 1.0 1.4492700000 0.9167200000 -0.5857300000 H 1.0 1.7297700000 -0.0803800000 0.5338700000 >>> print(water_dimer.to_string("mop")) O -1.62893 1 -0.04138 1 0.37137 1 H -0.69803 1 -0.09168 1 0.09337 1 H -2.06663 1 -0.73498 1 -0... |
print(water_dimer.to_string("xyz", dialect="ADF", ... fragment_id="dimer")) O -1.62893 -0.04138 0.37137 f=dimer H -0.69803 -0.09168 0.09337 f=dimer H -2.06663 -0.73498 -0.13663 f=dimer O 1.21457 0.03172 -0.27623 f=dimer H 1.44927 0.91672 -0.58573 f=dimer H 1.72977 -0.08038 0.53387 f=dimer >>> print(water_dimer.to_strin... |
for line in body.split("\n")]) else: raise KeyError("fragment_id currently not supported " "with dialect '{}'".format(dialect)) else: raise KeyError("dialect '{}' currently not " "supported".format(dialect)) if with_header: s = "\n".join([natom, comment, body]) else: s = body elif format == "gamin": lines = s.split("\n... |
def run(macro, output_files=[], force_close=True): """ Runs Fiji with the suplied macro. Output of Fiji can be viewed by setting environment variable `DEBUG=fijibin`. Parameters ---------- macro : string or list of strings IJM-macro(s) to run. If list of strings, it will be joined with a space, so all statements should... |
errors. This is the default behaviour. One should also note that Fiji doesn't terminate right away if ``System.exit()`` is left out, and it may take several minutes for Fiji to close. Returns ------- int Files from output_files which exists after running macro. """ if type(macro) == list: macro = ' '.join(macro) if len... |
os.environ.copy() debugging = False if 'DEBUG' in env: if env['DEBUG'] == 'fijibin' or env['DEBUG'] == '*': debugging = True del env['DEBUG'] fptr, temp_filename = mkstemp(suffix='.ijm') m = os.fdopen(fptr, 'w') m.write(macro) m.flush() # make sure macro is written before running Fiji m.close() cmd = [fijibin.BIN, '--h... |
def stitch(folder, filenames, x_size, y_size, output_filename, x_start=0, y_start=0, overlap=10): """ Creates a Fiji Grid/Collection stitching macro. Parameters are the same as in the plugin and are described in further detail here: http://fiji.sc/Image_Stitching#Grid.2FCollection_Stitching. **Default stitch parameters... |
Should be `.png`. x_start : int Which x position grid start with. y_start : int Which y position grid start with. overlap : number Tile overlap in percent. Fiji will find the optimal overlap, but a precise overlap assumption will decrase computation time. Returns ------- string IJM-macro. """ macro = [] macro.append('r... |
def _exists(filenames): """Check if every filename exists. If not, print an error message and remove the item from the list. Parameters ---------- filenames : list List of filenames to check for existence. Returns ------- list Filtered list of filenames that exists. """ exists = [] for filename in filenames: if os.path... |
def send_stop_audio(self): ''' Stop an audio streaming session ''' assert self._session_id != VoiceService.SESSION_ID_INVALID self._pebble.send_packet(AudioStream(session_id=self._session_id, data=StopTransfer())) |
def send_session_setup_result(self, result, app_uuid=None): ''' Send the result of setting up a dictation session requested by the watch :param result: result of setting up the session :type result: .SetupResult :param app_uuid: UUID of app that initiated the session :type app_uuid: uuid.UUID ''' assert self._session_i... |
def send_dictation_result(self, result, sentences=None, app_uuid=None): ''' Send the result of a dictation session :param result: Result of the session :type result: DictationResult :param sentences: list of sentences, each of which is a list of words and punctuation :param app_uuid: UUID of app that initiated the sess... |
if app_uuid is not None else ")") self._pebble.send_packet(VoiceControlResult(flags=flags, data=DictationResult( session_id=self._session_id, result=result, attributes=AttributeList(dictionary=attributes)))) self._session_id = VoiceService.SESSION_ID_INVALID |
def load_ipython_extension(ip): """ register magics function, can be called from a notebook """ #ip = get_ipython() ip.register_magics(CustomMagics) # enable C# (CSHARP) highlight patch = ("IPython.config.cell_magic_highlight['clrmagic'] = " "{'reg':[/^%%CS/]};") js = display.Javascript(data=patch, lib=["https://github... |
def module(self): """The module specified by the ``library`` attribute.""" if self._module is None: if self.library is None: raise ValueError( "Backend '%s' doesn't specify a library attribute" % self.__class__) try: if '.' in self.library: mod_path, cls_name = self.library.rsplit('.', 1) mod = import_module(mod_path) ... |
def datetime_to_timestamp(self, dt): """Helper function to convert a datetime object to a timestamp. If datetime instance ``dt`` is naive, it is assumed that it is in UTC. In Python 3, this just calls ``datetime.timestamp()``, in Python 2, it substracts any timezone offset and returns the difference since 1970-01-01 00... |
1)).total_seconds()) |
def get_random_password(self, length=32, chars=None): """Helper function that gets a random password. :param length: The length of the random password. :type length: int :param chars: A string with characters to choose from. Defaults to all ASCII letters and digits. :type chars: str """ if chars is None: chars = string... |
def api_version(self): """Cached version of :py:func:`~xmpp_backends.base.XmppBackendBase.get_api_version`.""" now = datetime.utcnow() if self.version_cache_timestamp and self.version_cache_timestamp + self.version_cache_timeout > now: return self.version_cache_value # we have a cached value self.version_cache_value = ... |
def create_reservation(self, username, domain, email=None): """Reserve a new account. This method is called when a user account should be reserved, meaning that the account can no longer be registered by anybody else but the user cannot yet log in either. This is useful if e.g. an email confirmation is still pending. T... |
def confirm_reservation(self, username, domain, password, email=None): """Confirm a reservation for a username. The default implementation just calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` and optionally :py:func:`~xmpp_backends.base.XmppBackendBase.set_email`. """ self.set_password(username=userna... |
def block_user(self, username, domain): """Block the specified user. The default implementation calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` with a random password. :param username: The username of the user. :type username: str :param domain: The domain of the user. :type domain: str """ self.set_p... |
def parse_connection_string(self, connection): """Parse string as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls. >>> EjabberdBackendBase().parse_connection_string('c2s_tls') (0, True, False) >>> EjabberdBackendBase().parse_connection_string('c2s_compressed_tls') (0, True, True) >>> Ejabbe... |
def parse_ip_address(self, ip_address): """Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls. Example:: >>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT IPv4Address('192.168.0.1') >>> EjabberdBackendBase().parse_ip_address('::FFFF:192.168.0.... |
def pump_reader(self): """ Synchronously reads one message from the watch, blocking until a message is available. All events caused by the message read will be processed before this method returns. .. note:: You usually don't need to invoke this method manually; instead, see :meth:`run_sync` and :meth:`run_async`. """ ... |
def run_sync(self): """ Runs the message loop until the Pebble disconnects. This method will block until the watch disconnects or a fatal error occurs. For alternatives that don't block forever, see :meth:`pump_reader` and :meth:`run_async`. """ while self.connected: try: self.pump_reader() except PacketDecodeError as ... |
def run_async(self): """ Spawns a new thread that runs the message loop until the Pebble disconnects. ``run_async`` will call :meth:`fetch_watch_info` on your behalf, and block until it receives a response. """ thread = threading.Thread(target=self.run_sync) thread.daemon = True thread.name = "PebbleConnection" thread.... |
def _handle_watch_message(self, message): """ Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes """ if self.log_protocol_level is not None: logger.log(self.log_protocol_level, "<- %s", ... |
ensure forward motion (but we are quite probably # screwed). expected_length, = struct.unpack('!H', message[:2]) if expected_length == 0: self.pending_bytes = b'' else: self.pending_bytes = message[expected_length + 4:] raise self.event_handler.broadcast_event("raw_inbound", message[:length]) if self.log_packet_level i... |
def _broadcast_transport_message(self, origin, message): """ Broadcasts an event originating from a transport that does not represent a message from the Pebble. :param origin: The type of transport responsible for the message. :type origin: .MessageTarget :param message: The message from the transport """ self.event_ha... |
def register_transport_endpoint(self, origin, message_type, handler): """ Register a handler for a message received from a transport that does not indicate a message from the connected Pebble. :param origin: The type of :class:`.MessageTarget` that triggers the message :param message_type: The class of the message that... |
def register_endpoint(self, endpoint, handler): """ Register a handler for a message received from the Pebble. :param endpoint: The type of :class:`.PebblePacket` that is being listened for. :type endpoint: .PacketType :param handler: A callback to be called when a message is received. :type handler: callable :return: ... |
def read_from_endpoint(self, endpoint, timeout=15): """ Blocking read from an endpoint. Will block until a message is received, or it times out. Also see :meth:`get_endpoint_queue` if you are considering calling this in a loop. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to lead... |
def read_transport_message(self, origin, message_type, timeout=15): """ Blocking read of a transport message that does not indicate a message from the Pebble. Will block until a message is received, or it times out. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to lead to deadlock... |
def send_packet(self, packet): """ Sends a message to the Pebble. :param packet: The message to send. :type packet: .PebblePacket """ if self.log_packet_level: logger.log(self.log_packet_level, "-> %s", packet) serialised = packet.serialise_packet() self.event_handler.broadcast_event("raw_outbound", serialised) self.se... |
def send_and_read(self, packet, endpoint, timeout=15): """ Sends a packet, then returns the next response received from that endpoint. This method sets up a listener before it actually sends the message, avoiding a potential race. .. warning:: Avoid calling this method from an endpoint callback; doing so is likely to l... |
def send_raw(self, message): """ Sends a raw binary message to the Pebble. No processing will be applied, but any transport framing should be omitted. :param message: The message to send to the pebble. :type message: bytes """ if self.log_protocol_level: logger.log(self.log_protocol_level, "-> %s", hexlify(message).dec... |
def fetch_watch_info(self): """ This method should be called before accessing :attr:`watch_info`, :attr:`firmware_version` or :attr:`watch_platform`. Blocks until it has fetched the required information. """ self._watch_info = self.send_and_read(WatchVersion(data=WatchVersionRequest()), WatchVersion).data |
def firmware_version(self): """ Provides information on the connected Pebble, including its firmware version, language, capabilities, etc. .. note: This is a blocking call if :meth:`fetch_watch_info` has not yet been called, which could lead to deadlock if called in an endpoint callback. :rtype: .WatchVersionResponse "... |
def _blockread(self, fname): """ Generator yields bsize lines from gdf file. Hidden method. Parameters ---------- fname : str Name of gdf-file. Yields ------ list file contents """ with open(fname, 'rb') as f: while True: a = [] for i in range(self.bsize): line = f.readline() if not line: break a.append(line.split()) i... |
def create(self, re='brunel-py-ex-*.gdf', index=True): """ Create db from list of gdf file glob Parameters ---------- re : str File glob to load. index : bool Create index on neurons for speed. Returns ------- None See also -------- sqlite3.connect.cursor, sqlite3.connect """ self.cursor.execute('CREATE TABLE IF NOT EX... |
def create_from_list(self, re=[], index=True): """ Create db from list of arrays. Parameters ---------- re : list Index of element is cell index, and element `i` an array of spike times in ms. index : bool Create index on neurons for speed. Returns ------- None See also -------- sqlite3.connect.cursor, sqlite3.connect ... |
def select(self, neurons): """ Select spike trains. Parameters ---------- neurons : numpy.ndarray or list Array of list of neurons. Returns ------- list List of numpy.ndarray objects containing spike times. See also -------- sqlite3.connect.cursor """ s = [] for neuron in neurons: self.cursor.execute('SELECT time FROM ... |
def interval(self, T=[0, 1000]): """ Get all spikes in a time interval T. Parameters ---------- T : list Time interval. Returns ------- s : list Nested list with spike times. See also -------- sqlite3.connect.cursor """ self.cursor.execute('SELECT * FROM spikes WHERE time BETWEEN %f AND %f' % tuple(T)) sel = self.curso... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.