text
stringlengths
81
112k
Connect to server and start serving registered functions. :type socket_or_address: tuple or socket object :arg socket_or_address: A ``(host, port)`` pair to be passed to `socket.create_connection`, or a socket object. def connect(self,...
Quick CLI to serve Python functions in a module. Example usage:: python -m epc.server --allow-dotted-names os Note that only the functions which gets and returns simple built-in types (str, int, float, list, tuple, dict) works. def main(args=None): """ Quick CLI to serve Python functions...
Print port this EPC server runs on. As Emacs client reads port number from STDOUT, you need to call this just before calling :meth:`serve_forever`. :type stream: text stream :arg stream: A stream object to write port on. Default is :data:`sys.stdout`. def print_...
Call method connected to this handler. :type name: str :arg name: Method name to call. :type args: list :arg args: Arguments for remote method to call. :type callback: callable :arg callback: A function to be called with returned value of ...
Request info of callable remote methods. Arguments for :meth:`call` except for `name` can be applied to this function too. def methods(self, *args, **kwds): """ Request info of callable remote methods. Arguments for :meth:`call` except for `name` can be applied to this...
Blocking version of :meth:`call`. :type name: str :arg name: Remote function name to call. :type args: list :arg args: Arguments passed to the remote function. :type timeout: int or None :arg timeout: Timeout in second. None means no timeout. If ...
Return arguments and keyword arguments as formatted string >>> func_call_as_str('f', 1, 2, a=1) 'f(1, 2, a=1)' def func_call_as_str(name, *args, **kwds): """ Return arguments and keyword arguments as formatted string >>> func_call_as_str('f', 1, 2, a=1) 'f(1, 2, a=1)' """ return '{0}...
Instantiate :class:`threading.Thread` with an appropriate name. def newthread(template="EPCThread-{0}", **kwds): """ Instantiate :class:`threading.Thread` with an appropriate name. """ if not isinstance(template, str): template = '{0}.{1}-{{0}}'.format(template.__module__, ...
A decorator to wrap execution of function with a context manager. def callwith(context_manager): """ A decorator to wrap execution of function with a context manager. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwds): with context_manager: ...
Compute image center coordinates :return: Tuple of image center in lat, lon def _scene_centroid(self): """ Compute image center coordinates :return: Tuple of image center in lat, lon """ ul_lat = self.corner_ul_lat_product ll_lat = self.corner_ll_lat_product ul_l...
Earth-sun distance in AU :param dtime time, e.g. datetime.datetime(2007, 5, 1) :type datetime object :return float(distance from sun to earth in astronomical units) def earth_sun_d(dtime): """ Earth-sun distance in AU :param dtime time, e.g. datetime.datetime(2...
:param band: An optical band, i.e. 1-5, 7 :return: At satellite reflectance, [-] def reflectance(self, band): """ :param band: An optical band, i.e. 1-5, 7 :return: At satellite reflectance, [-] """ if band == 6: raise ValueError('LT5 reflectance must be oth...
Finds broad-band surface reflectance (albedo) Smith (2010), “The heat budget of the earth’s surface deduced from space” LT5 toa reflectance bands 1, 3, 4, 5, 7 # normalized i.e. 0.356 + 0.130 + 0.373 + 0.085 + 0.07 = 1.014 Should have option for Liang, 2000; ...
Mask saturated pixels, 1 (True) is saturated. :param band: Image band with dn values, type: array :param value: Maximum (saturated) value, i.e. 255 for 8-bit data, type: int :return: boolean array def saturation_mask(self, band, value=255): """ Mask saturated pixels, 1 (True) is saturat...
Normalized difference vegetation index. :return: NDVI def ndvi(self): """ Normalized difference vegetation index. :return: NDVI """ red, nir = self.reflectance(3), self.reflectance(4) ndvi = self._divide_zero((nir - red), (nir + red), nan) return ndvi
Leaf area index (LAI), or the surface area of leaves to surface area ground. Trezza and Allen, 2014 :param ndvi: normalized difference vegetation index [-] :return: LAI [-] def lai(self): """ Leaf area index (LAI), or the surface area of leaves to surface area ground. Tr...
Mean values from Allen (2007) :return: def land_surface_temp(self): """ Mean values from Allen (2007) :return: """ rp = 0.91 tau = 0.866 rsky = 1.32 epsilon = self.emissivity(approach='tasumi') radiance = self.radiance(6) rc = ((r...
Calculate brightness temperature of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php T = K2 / log((K1 / L) + 1) and L = ML * Q + AL where: T = At-satellite brightness temperature (degrees kelvin) L = TOA spectral radiance (Watts / (m2 * srad * mm)...
Calculate top of atmosphere reflectance of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php R_raw = MR * Q + AR R = R_raw / cos(Z) = R_raw / sin(E) Z = 90 - E (in degrees) where: R_raw = TOA planetary reflectance,...
Calculate top of atmosphere radiance of Landsat 8 as outlined here: http://landsat.usgs.gov/Landsat8_Using_Product.php L = ML * Q + AL where: L = TOA spectral radiance (Watts / (m2 * srad * mm)) ML = Band-specific multiplicative rescaling factor from the metada...
Normalized difference snow index. :return: NDSI def ndsi(self): """ Normalized difference snow index. :return: NDSI """ green, swir1 = self.reflectance(3), self.reflectance(6) ndsi = self._divide_zero((green - swir1), (green + swir1), nan) return ndsi
Index of "Whiteness" based on visible bands. Parameters ---------- Output ------ ndarray: whiteness index def whiteness_index(self): """Index of "Whiteness" based on visible bands. Parameters ---------- Output ------ ...
Determine potential cloud pixels (PCPs) Combine basic spectral testsr to get a premliminary cloud mask First pass, section 3.1.1 in Zhu and Woodcock 2012 Equation 6 (Zhu and Woodcock, 2012) Parameters ---------- ndvi: ndarray ndsi: ndarray blue: ndarray ...
Use water to mask tirs and find 82.5 pctile Equation 7 and 8 (Zhu and Woodcock, 2012) Parameters ---------- is_water: ndarray, boolean water mask, water is True, land is False swir2: ndarray tirs1: ndarray Output ------ float: ...
Temperature probability for water Equation 9 (Zhu and Woodcock, 2012) Parameters ---------- water_temp: float 82.5th percentile temperature over water swir2: ndarray tirs1: ndarray Output ------ ndarray: probability of cloud...
The brightest water may have Band 5 reflectance as high as LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF.11 Equation 10 (Zhu and Woodcock, 2012) Parameters ---------- nir: ndarray clip: boolean Output ------ ndarray: brightness p...
Derive high/low percentiles of land temperature Equations 12 an 13 (Zhu and Woodcock, 2012) Parameters ---------- pcps: ndarray potential cloud pixels, boolean water: ndarray water mask, boolean tirs1: ndarray Output ------ ...
Temperature-based probability of cloud over land Equation 14 (Zhu and Woodcock, 2012) Parameters ---------- tirs1: ndarray tlow: float Low (17.5 percentile) temperature of land thigh: float High (82.5 percentile) temperature of land Output ...
Use the probability of the spectral variability to identify clouds over land. Equation 15 (Zhu and Woodcock, 2012) Parameters ---------- ndvi: ndarray ndsi: ndarray whiteness: ndarray Output ------ ndarray : probability of cloud...
Dynamic threshold for determining cloud cutoff Equation 17 (Zhu and Woodcock, 2012) Parameters ---------- land_cloud_prob: ndarray probability of cloud over land pcps: ndarray potential cloud pixels water: ndarray water mask Out...
Final step of determining potential cloud layer Equation 18 (Zhu and Woodcock, 2012) Saturation (green or red) test is not in the algorithm Parameters ---------- pcps: ndarray potential cloud pixels water: ndarray water mask ...
Spectral test to determine potential snow Uses the 9.85C (283K) threshold defined in Zhu, Woodcock 2015 Parameters ---------- ndsi: ndarray green: ndarray nir: ndarray tirs1: ndarray Output ------ ndarray: boolean, True is poten...
Calculate the potential cloud layer from source data *This is the high level function which ties together all the equations for generating potential clouds* Parameters ---------- blue: ndarray green: ndarray red: ndarray nir: ndarray swir1: ndarray...
Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate the GDAL-style uint8 mask def gdal_nodata_mask(pcl, pcsl, tirs_arr): """ Given a boolean potential cloud layer, a potential cloud shadow layer and a thermal band Calculate ...
Parses the metadata from a Landsat image bundle. Arguments: metadataloc: a filename or a directory. Returns metadata dictionary def parsemeta(metadataloc): """Parses the metadata from a Landsat image bundle. Arguments: metadataloc: a filename or a directory. ...
Returns state/status after reading the next line. The status codes are:: LE07_clip_L1TP_039027_20150529_20160902_01_T1_B1.TIF - BEGIN parsing; 1 - ENTER METADATA GROUP, 2 - READ METADATA LINE, 3 - END METDADATA GROUP, 4 - END PARSING Permitted Transitions:: LE07_clip_L1TP_039027_20150529...
Executes processing steps when reading a line def _transstat(status, grouppath, dictpath, line): """Executes processing steps when reading a line""" if status == 0: raise MTLParseError( "Status should not be '%s' after reading line:\n%s" % (STATUSCODE[status], line)) elif st...
Takes value as str, returns str, int, float, date, datetime, or time def _postprocess(valuestr): """ Takes value as str, returns str, int, float, date, datetime, or time """ # USGS has started quoting time sometimes. Grr, strip quotes in this case intpattern = re.compile(r'^\-?\d+$') floatpatt...
Read in image geometry, resample subsequent images to same grid. The purpose of this function is to snap many Landsat images to one geometry. Use Landsat578 to download and unzip them, then run them through this to get identical geometries for analysis. Files :param use_band_map: :param delete_extr...
Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it. ``envconfig`` is the testenv configuration which contains per-testenv configuration, notably the ``.envname`` and ``.basepython`` setting. def tox_get_python_executable...
Add the option, --tox-pyenv-no-fallback. If this option is set, do not allow fallback to tox's built-in strategy for looking up python executables if the call to `pyenv which` by this plugin fails. This will allow the error to raise instead of falling back to tox's default behavior. def _setup_no_fall...
Send one or more emails from Salesforce. Parameters: emails - a dictionary or list of dictionaries, each representing a single email as described by https://www.salesforce.com/us /developer/docs/api/Content/sforce_api_calls_sendemail.htm massTyp...
URL encode string def quote(myitem, elt=True): '''URL encode string''' if elt and '<' in myitem and len(myitem) > 24 and myitem.find(']]>') == -1: return '<![CDATA[%s]]>' % (myitem) else: myitem = myitem.replace('&', '&amp;').\ replace('<', '&lt;').replace(']]>', ']]&gt;') i...
_doPrep is makes changes in-place. Do some prep work converting python types into formats that Salesforce will accept. This includes converting lists of strings to "apple;orange;pear". Dicts will be converted to embedded objects None or empty list values will be Null-ed def _doPrep(field_dict): ...
Prepare a SObject def _prepareSObjects(sObjects): '''Prepare a SObject''' sObjectsCopy = copy.deepcopy(sObjects) if isinstance(sObjectsCopy, dict): # If root element is a dict, then this is a single object not an array _doPrep(sObjectsCopy) else: # else this is an array, and eac...
Send one or more emails from Salesforce. Parameters: emails - a dictionary or list of dictionaries, each representing a single email as described by https://www.salesforce.com /us/developer/docs/api/Content/sforce_api_calls_sendemail .h...
Given a list of types, construct a dictionary such that each key is a type, and each value is the corresponding sObject for that type. def queryTypesDescriptions(self, types): """ Given a list of types, construct a dictionary such that each key is a type, and each value is the c...
Create a session protection token for this client. This method generates a session protection token for the cilent, which consists in a hash of the user agent and the IP address. This method can be overriden by subclasses to implement different token generation algorithms. def create_t...
Clear the session. This method is invoked when the session is found to be invalid. Subclasses can override this method to implement a custom session reset. def clear_session(self, response): """Clear the session. This method is invoked when the session is found to be invalid. ...
Generate heroku-like random names to use in your python applications :param delimiter: Delimiter :param token_length: TokenLength :param token_hex: TokenHex :param token_chars: TokenChars :type delimiter: str :type token_length: int :type token_hex: bool ...
Returns the parser according to the system platform def get_parser_class(): """ Returns the parser according to the system platform """ global distro if distro == 'Linux': Parser = parser.LinuxParser if not os.path.exists(Parser.get_command()[0]): Parser = parser.UnixIPP...
Return just the default interface device dictionary. :param ifconfig: For mocking actual command output :param route_output: For mocking actual command output def default_interface(ifconfig=None, route_output=None): """ Return just the default interface device dictionary. :param ifconfig: For moc...
Parse ifconfig output into self._interfaces. Optional Arguments: ifconfig The data (stdout) from the ifconfig command. Default is to call exec_cmd(self.get_command()). def parse(self, ifconfig=None): # noqa: max-complexity=12 """ Parse ifconfig ou...
Used to provide the ability to alter the interfaces dictionary before it is returned from self.parse(). Required Arguments: interfaces The interfaces dictionary. Returns: interfaces dict def alter(self, interfaces): """ Used to provide the ability ...
:param route_output: For mocking actual output def _default_interface(self, route_output=None): """ :param route_output: For mocking actual output """ if not route_output: out, __, __ = exec_cmd('/sbin/ip route') lines = out.splitlines() else: ...
Return the needle positions or None. :param int line_number: the number of the line :rtype: list :return: the needle positions for a specific line specified by :paramref:`line_number` or :obj:`None` if no were given def get(self, line_number): """Return the needle positions o...
Get the bytes representing needle positions or None. :param int line_number: the line number to take the bytes from :rtype: bytes :return: the bytes that represent the message or :obj:`None` if no data is there for the line. Depending on the :attr:`machine`, the length and re...
Return the cnfLine content without id for the line. :param int line_number: the number of the line :rtype: bytes :return: a cnfLine message without id as defined in :ref:`cnfLine` def get_line_configuration_message(self, line_number): """Return the cnfLine content without id for the li...
Read the message type from a file. def read_message_type(file): """Read the message type from a file.""" message_byte = file.read(1) if message_byte == b'': return ConnectionClosed message_number = message_byte[0] return _message_types.get(message_number, UnknownMessage)
Read the b"\\r\\n" at the end of the message. def read_end_of_message(self): """Read the b"\\r\\n" at the end of the message.""" read = self._file.read last = read(1) current = read(1) while last != b'' and current != b'' and not \ (last == b'\r' and current == b...
Read the success byte. def _init(self): """Read the success byte.""" self._api_version = self._file.read(1)[0] self._firmware_version = FirmwareVersion(*self._file.read(2))
Read the line number. def _init(self): """Read the line number.""" self._line_number = next_line( self._communication.last_requested_line_number, self._file.read(1)[0])
Read the success byte. def _init(self): """Read the success byte.""" self._ready = self._file.read(1) self._hall_left = self._file.read(2) self._hall_right = self._file.read(2) self._carriage_type = self._file.read(1)[0] self._carriage_position = self._file.read(1)[0]
Read the b"\\r\\n" at the end of the message. def _init(self): """Read the b"\\r\\n" at the end of the message.""" read_values = [] read = self._file.read last = read(1) current = read(1) while last != b'' and current != b'' and not \ (last == b'\r' and c...
Send this message to the controller. def send(self): """Send this message to the controller.""" self._file.write(self.as_bytes()) self._file.write(b'\r\n')
Initialize the StartRequest with start and stop needle. :raises TypeError: if the arguments are not integers :raises ValueError: if the values do not match the :ref:`specification <m4-01>` def init(self, left_end_needle, right_end_needle): """Initialize the StartRequest with start an...
Return the start and stop needle. def content_bytes(self): """Return the start and stop needle.""" get_message = \ self._communication.needle_positions.get_line_configuration_message return get_message(self._line_number)
Sum up an iterable starting with a start value. In contrast to :func:`sum`, this also works on other types like :class:`lists <list>` and :class:`sets <set>`. def sum_all(iterable, start): """Sum up an iterable starting with a start value. In contrast to :func:`sum`, this also works on other types li...
Compute the next line based on the last line and a 8bit next line. The behaviour of the function is specified in :ref:`reqline`. :param int last_line: the last line that was processed :param int next_line_8bit: the lower 8 bits of the next line :return: the next line closest to :paramref:`last_line` ...
Return the underscore name of a camel case name. :param str camel_case_name: a name in camel case such as ``"ACamelCaseName"`` :return: the name using underscores, e.g. ``"a_camel_case_name"`` :rtype: str def camel_case_to_under_score(camel_case_name): """Return the underscore name of a camel ca...
Notify the observers about the received message. def _message_received(self, message): """Notify the observers about the received message.""" with self.lock: self._state.receive_message(message) for callable in chain(self._on_message_received, self._on_message): ...
Receive a message from the file. def receive_message(self): """Receive a message from the file.""" with self.lock: assert self.can_receive_messages() message_type = self._read_message_type(self._file) message = message_type(self._file, self) self._message...
Whether tihs communication is ready to receive messages.] :rtype: bool .. code:: python assert not communication.can_receive_messages() communication.start() assert communication.can_receive_messages() communication.stop() assert not communi...
Stop the communication with the shield. def stop(self): """Stop the communication with the shield.""" with self.lock: self._message_received(ConnectionClosed(self._file, self))
Send a host message. :param type host_message_class: a subclass of :class:`AYABImterface.communication.host_messages.Message` :param args: additional arguments that shall be passed to the :paramref:`host_message_class` as arguments def send(self, host_message_class, *args): ...
Set the state. def state(self, new_state): """Set the state.""" with self.lock: self._state.exit() self._state = new_state self._state.enter()
Start a parallel thread for receiving messages. If :meth:`start` was no called before, start will be called in the thread. The thread calls :meth:`receive_message` until the :attr:`state` :meth:`~AYABInterface.communication.states.State.is_connection_closed`. :param float secon...
Run the receiving in parallel. def _parallel_receive_loop(self, seconds_to_wait): """Run the receiving in parallel.""" sleep(seconds_to_wait) with self._lock: self._number_of_threads_receiving_messages += 1 try: with self._lock: if self.state.is_w...
Transition into the next state. :param type state_class: a subclass of :class:`State`. It is intialized with the communication object and :paramref:`args` :param args: additional arguments def _next(self, state_class, *args): """Transition into the next state. :param type st...
A InformationConfirmation is received. If :meth:`the api version is supported <AYABInterface.communication.Communication.api_version_is_supported>`, the communication object transitions into a :class:`InitializingMachine`, if unsupported, into a :class:`UnsupportedApiVersion` d...
Receive a StartConfirmation message. :param message: a :class:`StartConfirmation <AYABInterface.communication.hardware_messages.StartConfirmation>` message If the message indicates success, the communication object transitions into :class:`KnittingStarted` or else, into :cl...
Send a StartRequest. def enter(self): """Send a StartRequest.""" self._communication.send(StartRequest, self._communication.left_end_needle, self._communication.right_end_needle)
Send a LineConfirmation to the controller. When this state is entered, a :class:`AYABInterface.communication.host_messages.LineConfirmation` is sent to the controller. Also, the :attr:`last line requested <AYABInterface.communication.Communication.last_requested_line_number>` ...
Convert rows to needle positions. :return: :rtype: list def colors_to_needle_positions(rows): """Convert rows to needle positions. :return: :rtype: list """ needles = [] for row in rows: colors = set(row) if len(colors) == 1: needles.append([NeedlePositions...
Check for validity. :raises ValueError: - if not all lines are as long as the :attr:`number of needles <AYABInterface.machines.Machine.number_of_needles>` - if the contents of the rows are not :attr:`needle positions <AYABInterface.machines.Machine.needle_positions>...
Return the row at the given index or the default value. def get_row(self, index, default=None): """Return the row at the given index or the default value.""" if not isinstance(index, int) or index < 0 or index >= len(self._rows): return default return self._rows[index]
Mark the row at index as completed. .. seealso:: :meth:`completed_row_indices` This method notifies the obsevrers from :meth:`on_row_completed`. def row_completed(self, index): """Mark the row at index as completed. .. seealso:: :meth:`completed_row_indices` This method noti...
Setup communication through a file. :rtype: AYABInterface.communication.Communication def communicate_through(self, file): """Setup communication through a file. :rtype: AYABInterface.communication.Communication """ if self._communication is not None: raise ValueEr...
A list of actions to perform. :return: a list of :class:`AYABInterface.actions.Action` def actions(self): """A list of actions to perform. :return: a list of :class:`AYABInterface.actions.Action` """ actions = [] do = actions.append # determine the number of c...
Convert the needle positions to the wire format. This conversion is used for :ref:`cnfline`. :param needle_positions: an iterable over :attr:`needle_positions` of length :attr:`number_of_needles` :rtype: bytes def needle_positions_to_bytes(self, needle_positions): """Convert...
The identifier of the machine. def name(self): """The identifier of the machine.""" name = self.__class__.__name__ for i, character in enumerate(name): if character.isdigit(): return name[:i] + "-" + name[i:] return name
What this object is equal to. def _id(self): """What this object is equal to.""" return (self.__class__, self.number_of_needles, self.needle_positions, self.left_end_needle)
Add a Chapter to your epub. Args: c (Chapter): A Chapter object representing your chapter. Raises: TypeError: Raised if a Chapter object isn't supplied to this method. def add_chapter(self, c): """ Add a Chapter to your epub. Args: ...
Create an epub file from this object. Args: output_directory (str): Directory to output the epub file to epub_name (Option[str]): The file name of your epub. This should not contain .epub at the end. If this argument is not provided, defaults to the title of the epub. d...
Saves an online image from image_url to image_directory with the name image_name. Returns the extension of the image saved, which is determined dynamically. Args: image_url (str): The url of the image. image_directory (str): The directory to save the image in. image_name (str): The file...
Replaces the src of an image to link to the local copy in the images folder of the ebook. Tightly coupled with bs4 package. Args: image_url (str): The url of the image. image_tag (bs4.element.Tag): The bs4 tag containing the image. ebook_folder (str): The directory where the ebook f...
Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to. def write(self, file_name): """ Writes the chapter object to an xhtml file. Args: file_name (str): The full name of the xhtml file to save to. ...
Creates a Chapter object from a url. Pulls the webpage from the given url, sanitizes it using the clean_function method, and saves it as the content of the created chapter. Basic webpage loaded before any javascript executed. Args: url (string): The url to pull the content o...
Creates a Chapter object from an html or xhtml file. Sanitizes the file's content using the clean_function method, and saves it as the content of the created chapter. Args: file_name (string): The file_name containing the html or xhtml content of the created Chapter ...
Creates a Chapter object from a string. Sanitizes the string using the clean_function method, and saves it as the content of the created chapter. Args: html_string (string): The html or xhtml content of the created Chapter url (Option[string]): A url to i...