INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Utility function for the RedisLogRecord.
def _getCallingContext(): """ Utility function for the RedisLogRecord. Returns the module, function, and lineno of the function that called the logger. We look way up in the stack. The stack at this point is: [0] logger.py _getCallingContext (hey, that's me!) [1] logger.py __init__ ...
JSON - encode a record for serializing through redis.
def format(self, record): """ JSON-encode a record for serializing through redis. Convert date to iso format, and stringify any exceptions. """ data = record._raw.copy() # serialize the datetime date as utc string data['time'] = data['time'].isoformat() ...
Publish record to redis logging channel
def emit(self, record): """ Publish record to redis logging channel """ try: self.redis_client.publish(self.channel, self.format(record)) except redis.RedisError: pass
Publish record to redis logging list
def emit(self, record): """ Publish record to redis logging list """ try: if self.max_messages: p = self.redis_client.pipeline() p.rpush(self.key, self.format(record)) p.ltrim(self.key, -self.max_messages, -1) p....
Decorated function is a no - op if TEMPLATE_DEBUG is False
def require_template_debug(f): """Decorated function is a no-op if TEMPLATE_DEBUG is False""" def _(*args, **kwargs): TEMPLATE_DEBUG = getattr(settings, 'TEMPLATE_DEBUG', False) return f(*args, **kwargs) if TEMPLATE_DEBUG else '' return _
Given a dictionary of variable attribute data from get_details display the data in the terminal.
def _display_details(var_data): """ Given a dictionary of variable attribute data from get_details display the data in the terminal. """ meta_keys = (key for key in list(var_data.keys()) if key.startswith('META_')) for key in meta_keys: display_key = key[5:].capitalize()...
Start a pdb set_trace inside of the template with the context available as context. Uses ipdb if available.
def set_trace(context): """ Start a pdb set_trace inside of the template with the context available as 'context'. Uses ipdb if available. """ try: import ipdb as pdb except ImportError: import pdb print("For best results, pip install ipdb.") print("Variables that are ...
Start a pydev settrace
def pydevd(context): """ Start a pydev settrace """ global pdevd_not_available if pdevd_not_available: return '' try: import pydevd except ImportError: pdevd_not_available = True return '' render = lambda s: template.Template(s).render(context) availab...
Given an iterable with nested iterables generate a flat iterable
def _flatten(iterable): """ Given an iterable with nested iterables, generate a flat iterable """ for i in iterable: if isinstance(i, Iterable) and not isinstance(i, string_types): for sub_i in _flatten(i): yield sub_i else: yield i
Given a variable inside the context obtain the attributes/ callables their values where possible and the module name and class name if possible
def get_details(var): """ Given a variable inside the context, obtain the attributes/callables, their values where possible, and the module name and class name if possible """ var_data = {} # Obtain module and class details if available and add them in module = getattr(var, '__module__', '')...
Given a variable and one of its attributes that are available inside of a template return its method if it is a callable its class name if it is a model manager otherwise return its value
def _get_detail_value(var, attr): """ Given a variable and one of its attributes that are available inside of a template, return its 'method' if it is a callable, its class name if it is a model manager, otherwise return its value """ value = getattr(var, attr) # Rename common Django class n...
Given a varaible return the list of attributes that are available inside of a template
def get_attributes(var): """ Given a varaible, return the list of attributes that are available inside of a template """ is_valid = partial(is_valid_in_template, var) return list(filter(is_valid, dir(var)))
Given a variable and one of its attributes determine if the attribute is accessible inside of a Django template and return True or False accordingly
def is_valid_in_template(var, attr): """ Given a variable and one of its attributes, determine if the attribute is accessible inside of a Django template and return True or False accordingly """ # Remove private variables or methods if attr.startswith('_'): return False # Remove any ...
Increment version number string version. Type can be one of: major minor or bug
def version_bump(self, version, type="bug"): """ Increment version number string 'version'. Type can be one of: major, minor, or bug """ parsed_version = LooseVersion(version).version total_components = max(3, len(parsed_version)) bits = [] ...
Will parse git log messages in the short format
def parse_log_messages(self, text): """Will parse git log messages in the 'short' format""" regex = r"commit ([0-9a-f]+)\nAuthor: (.*?)\n\n(.*?)(?:\n\n|$)" messages = re.findall(regex, text, re.DOTALL) parsed = [] for commit, author, message in messages: pars...
Determine paths automatically and a little intelligently
def determine_paths(self, package_name=None, create_package_dir=False, dry_run=False): """Determine paths automatically and a little intelligently""" # Give preference to the environment variable here as it will not # derefrence sym links self.project_dir = Path(os.getenv('PWD'...
Checks the format of the sakefile dictionary to ensure it conforms to specification
def check_integrity(sakefile, settings): """ Checks the format of the sakefile dictionary to ensure it conforms to specification Args: A dictionary that is the parsed Sakefile (from sake.py) The setting dictionary (for print functions) Returns: True if the Sakefile is confor...
Checks the integrity of a specific target. Gets called multiple times from check_integrity ()
def check_target_integrity(key, values, meta=False, all=False, parent=None): """ Checks the integrity of a specific target. Gets called multiple times from check_integrity() Args: The target name The dictionary values of that target A boolean representing whether it is a meta-ta...
This function gives us the option to emit errors or warnings after sake upgrades
def check_shastore_version(from_store, settings): """ This function gives us the option to emit errors or warnings after sake upgrades """ sprint = settings["sprint"] error = settings["error"] sprint("checking .shastore version for potential incompatibilities", level="verbose") ...
Returns sha1 hash of the file supplied as an argument
def get_sha(a_file, settings=None): """ Returns sha1 hash of the file supplied as an argument """ if settings: error = settings["error"] else: error = ERROR_FN try: BLOCKSIZE = 65536 hasher = hashlib.sha1() with io.open(a_file, "rb") as fh: buf...
Writes a sha1 dictionary stored in memory to the. shastore file
def write_shas_to_shastore(sha_dict): """ Writes a sha1 dictionary stored in memory to the .shastore file """ if sys.version_info[0] < 3: fn_open = open else: fn_open = io.open with fn_open(".shastore", "w") as fh: fh.write("---\n") fh.write('sake version: {}\...
Takes sha1 hash of all dependencies and outputs of all targets
def take_shas_of_all_files(G, settings): """ Takes sha1 hash of all dependencies and outputs of all targets Args: The graph we are going to build The settings dictionary Returns: A dictionary where the keys are the filenames and the value is the sha1 hash """ gl...
Determines if a target needs to run. This can happen in two ways: ( a ) If a dependency of the target has changed ( b ) If an output of the target is missing
def needs_to_run(G, target, in_mem_shas, from_store, settings): """ Determines if a target needs to run. This can happen in two ways: (a) If a dependency of the target has changed (b) If an output of the target is missing Args: The graph we are going to build The name of the target ...
Runs the commands supplied as an argument It will exit the program if the commands return a non - zero code
def run_commands(commands, settings): """ Runs the commands supplied as an argument It will exit the program if the commands return a non-zero code Args: the commands to run The settings dictionary """ sprint = settings["sprint"] quiet = settings["quiet"] error = set...
Wrapper function that sends to commands in a target s formula to run_commands ()
def run_the_target(G, target, settings): """ Wrapper function that sends to commands in a target's 'formula' to run_commands() Args: The graph we are going to build The target to run The settings dictionary """ sprint = settings["sprint"] sprint("Running target {}".f...
Helper function that returns the node data of the node with the name supplied
def get_the_node_dict(G, name): """ Helper function that returns the node data of the node with the name supplied """ for node in G.nodes(data=True): if node[0] == name: return node[1]
Returns a list of nodes that are the parents from all of the nodes given as an argument. This is for use in the parallel topo sort
def get_direct_ancestors(G, list_of_nodes): """ Returns a list of nodes that are the parents from all of the nodes given as an argument. This is for use in the parallel topo sort """ parents = [] for item in list_of_nodes: anc = G.predecessors(item) for one in anc: ...
A sink is a node with no children. This means that this is the end of the line and it should be run last in topo sort. This returns a list of all sinks in a graph
def get_sinks(G): """ A sink is a node with no children. This means that this is the end of the line, and it should be run last in topo sort. This returns a list of all sinks in a graph """ sinks = [] for node in G: if not len(list(G.successors(node))): sinks.append(n...
For the parallel topo sort to work the targets have to be executed in layers such that there is no dependency relationship between any nodes in a layer. What is returned is a list of lists representing all the layers or levels
def get_levels(G): """ For the parallel topo sort to work, the targets have to be executed in layers such that there is no dependency relationship between any nodes in a layer. What is returned is a list of lists representing all the layers, or levels """ levels = [] ends = get_sinks...
There are repeats in the output from get_levels (). We want only the earliest occurrence ( after it s reversed )
def remove_redundancies(levels): """ There are repeats in the output from get_levels(). We want only the earliest occurrence (after it's reversed) """ seen = [] final = [] for line in levels: new_line = [] for item in line: if item not in seen: see...
The parallel equivalent of run_this_target () It receives a list of targets to execute in parallel. Unlike run_this_target () it has to update the shas ( in memory and in the store ) within the function. This is because one of the targets may fail but many can succeed and those outputs need to be updated
def parallel_run_these(G, list_of_targets, in_mem_shas, from_store, settings, dont_update_shas_of): """ The parallel equivalent of "run_this_target()" It receives a list of targets to execute in parallel. Unlike "run_this_target()" it has to update the shas (in memory and in t...
If we don t merge the shas from the sha store and if we build a subgraph the. shastore will only contain the shas of the files from the subgraph and the rest of the graph will have to be rebuilt
def merge_from_store_and_in_mems(from_store, in_mem_shas, dont_update_shas_of): """ If we don't merge the shas from the sha store and if we build a subgraph, the .shastore will only contain the shas of the files from the subgraph and the rest of the graph will have to be rebuilt """ if not f...
This is the master function that performs the building.
def build_this_graph(G, settings, dont_update_shas_of=None): """ This is the master function that performs the building. Args: A graph (often a subgraph) The settings dictionary An optional list of files to not update the shas of (needed when building specific targets) ...
This returns the appropriate print functions in a tuple The print function are: - sprint - for standard printing - warn - for warnings - error - for errors This will all be the same if color is False.
def get_print_functions(settings): """ This returns the appropriate print functions in a tuple The print function are: - sprint - for standard printing - warn - for warnings - error - for errors This will all be the same if color is False. The returned print functions wi...
Returns the filename of the appropriate sakefile
def find_standard_sakefile(settings): """Returns the filename of the appropriate sakefile""" error = settings["error"] if settings["customsake"]: custom = settings["customsake"] if not os.path.isfile(custom): error("Specified sakefile '{}' doesn't exist", custom) sys....
This function is used to normalize the path ( of an output or dependency ) and also provide the path in relative form. It is relative to the current working directory
def clean_path(a_path, force_os=None, force_start=None): """ This function is used to normalize the path (of an output or dependency) and also provide the path in relative form. It is relative to the current working directory """ if not force_start: force_start = os.curdir if force_o...
Returns the prettily formatted help strings ( for printing )
def get_help(sakefile): """ Returns the prettily formatted help strings (for printing) Args: A dictionary that is the parsed Sakefile (from sake.py) NOTE: the list sorting in this function is required for this function to be deterministic """ full_string = "You can 'sak...
This parses a list of define argument in the form of - DNAME = VALUE or - DNAME ( which is treated as - DNAME = 1 ).
def parse_defines(args): """ This parses a list of define argument in the form of -DNAME=VALUE or -DNAME ( which is treated as -DNAME=1). """ macros = {} for arg in args: try: var, val = arg.split('=', 1) except ValueError: var = arg val = '1' ...
this gets called before the sakefile is parsed. it looks for macros defined anywhere in the sakefile ( the start of the line is #! ) and then replaces all occurences of $variable with the value defined in the macro. it then returns the contents of the file with the macros expanded.
def expand_macros(raw_text, macros): """ this gets called before the sakefile is parsed. it looks for macros defined anywhere in the sakefile (the start of the line is '#!') and then replaces all occurences of '$variable' with the value defined in the macro. it then returns the contents of the f...
Function to help construct_graph () identify dependencies
def check_for_dep_in_outputs(dep, verbose, G): """ Function to help construct_graph() identify dependencies Args: A dependency A flag indication verbosity A (populated) NetworkX DiGraph Returns: A list of targets that build given dependency """ if verbose: ...
If you specify a target that shares a dependency with another target both targets need to be updated. This is because running one will resolve the sha mismatch and sake will think that the other one doesn t have to run. This is called a tie. This function will find such ties.
def get_ties(G): """ If you specify a target that shares a dependency with another target, both targets need to be updated. This is because running one will resolve the sha mismatch and sake will think that the other one doesn't have to run. This is called a "tie". This function will find such ties....
This function gets called when a target is specified to ensure that all tied targets also get included in the subgraph to be built
def get_tied_targets(original_targets, the_ties): """ This function gets called when a target is specified to ensure that all 'tied' targets also get included in the subgraph to be built """ my_ties = [] for original_target in original_targets: for item in the_ties: if or...
Takes the sakefile dictionary and builds a NetworkX graph
def construct_graph(sakefile, settings): """ Takes the sakefile dictionary and builds a NetworkX graph Args: A dictionary that is the parsed Sakefile (from sake.py) The settings dictionary Returns: A NetworkX graph """ verbose = settings["verbose"] sprint = settings...
This function takes a node dictionary and returns a list of the node s output files. Some of the entries in the output attribute may be globs and without this function sake won t know how to handle that. This will unglob all globs and return the true list of * all * outputs.
def get_all_outputs(node_dict): """ This function takes a node dictionary and returns a list of the node's output files. Some of the entries in the 'output' attribute may be globs, and without this function, sake won't know how to handle that. This will unglob all globs and return the true list ...
...............................
def get_all_dependencies(node_dict): """ ............................... """ deplist = [] for item in node_dict['dependencies']: glist = glob.glob(item) if glist: for oneglob in glist: deplist.append(oneglob) else: deplist.append(item) ...
Removes all the output files from all targets. Takes the graph as the only argument
def clean_all(G, settings): """ Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed """ quiet = settings["quie...
Writes the graph G in dot file format for graphviz visualization.
def write_dot_file(G, filename): """ Writes the graph G in dot file format for graphviz visualization. Args: a Networkx graph A filename to name the dot files """ with io.open(filename, "w") as fh: fh.write("strict digraph DependencyDiagram {\n") edge_list = G.edges(...
Uses networkX to draw a graphviz dot file either ( a ) calls the graphviz command dot to turn it into a SVG and remove the dotfile ( default ) or ( b ) if no_graphviz is True just output the graphviz dot file
def visualize(G, settings, filename="dependencies", no_graphviz=False): """ Uses networkX to draw a graphviz dot file either (a) calls the graphviz command "dot" to turn it into a SVG and remove the dotfile (default), or (b) if no_graphviz is True, just output the graphviz dot file Args: ...
Auxiliary function for iterating over a data table.
def itertable(table): """Auxiliary function for iterating over a data table.""" for item in table: res = { k.lower(): nfd(v) if isinstance(v, text_type) else v for k, v in item.items()} for extra in res.pop('extra', []): k, _, v = extra.partition(':') res[k.st...
Prepare transcriptiondata from the transcription sources.
def _make_package(args): # pragma: no cover """Prepare transcriptiondata from the transcription sources.""" from lingpy.sequence.sound_classes import token2class from lingpy.data import Model columns = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE'] bipa = TranscriptionSystem('bipa') ...
Check the consistency of a given transcription system conversino
def is_valid_sound(sound, ts): """Check the consistency of a given transcription system conversino""" if isinstance(sound, (Marker, UnknownSound)): return False s1 = ts[sound.name] s2 = ts[sound.s] return s1.name == s2.name and s1.s == s2.s
Function tries to identify a sound in the data.
def resolve_sound(self, sound): """Function tries to identify a sound in the data. Notes ----- The function tries to resolve sounds to take a sound with less complex features in order to yield the next approximate sound class, if the transcription data are sound classes....
Extended normalization: normalize by list of norm - characers split by character/.
def _norm(self, string): """Extended normalization: normalize by list of norm-characers, split by character "/".""" nstring = norm(string) if "/" in string: s, t = string.split('/') nstring = t return self.normalize(nstring)
Normalize the string according to normalization list
def normalize(self, string): """Normalize the string according to normalization list""" return ''.join([self._normalize.get(x, x) for x in nfd(string)])
Parse a sound from its name
def _from_name(self, string): """Parse a sound from its name""" components = string.split(' ') if frozenset(components) in self.features: return self.features[frozenset(components)] rest, sound_class = components[:-1], components[-1] if sound_class in ['diphthong', 'c...
Parse a string and return its features.
def _parse(self, string): """Parse a string and return its features. :param string: A one-symbol string in NFD Notes ----- Strategy is rather simple: we determine the base part of a string and then search left and right of this part for the additional features as ...
Function tries to identify a sound in the data.
def resolve_sound(self, sound): """Function tries to identify a sound in the data. Notes ----- The function tries to resolve sounds to take a sound with less complex features in order to yield the next approximate sound class, if the transcription data are sound classes....
Runs the ipfn method from a matrix m aggregates/ marginals and the dimension ( s ) preserved. For example: from ipfn import ipfn import numpy as np m = np. array ( [[ 8. 4. 6. 7. ] [ 3. 6. 5. 2. ] [ 9. 11. 3. 1. ]] ) xip = np. array ( [ 20. 18. 22. ] ) xpj = np. array ( [ 18. 16. 12. 14. ] ) aggregates = [ xip xpj ] di...
def ipfn_np(self, m, aggregates, dimensions, weight_col='total'): """ Runs the ipfn method from a matrix m, aggregates/marginals and the dimension(s) preserved. For example: from ipfn import ipfn import numpy as np m = np.array([[8., 4., 6., 7.], [3., 6., 5., 2.], [9., 11...
Runs the ipfn method from a dataframe df aggregates/ marginals and the dimension ( s ) preserved. For example: from ipfn import ipfn import pandas as pd age = [ 30 30 30 30 40 40 40 40 50 50 50 50 ] distance = [ 10 20 30 40 10 20 30 40 10 20 30 40 ] m = [ 8. 4. 6. 7. 3. 6. 5. 2. 9. 11. 3. 1. ] df = pd. DataFrame () df ...
def ipfn_df(self, df, aggregates, dimensions, weight_col='total'): """ Runs the ipfn method from a dataframe df, aggregates/marginals and the dimension(s) preserved. For example: from ipfn import ipfn import pandas as pd age = [30, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, ...
Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes.
def iteration(self): """ Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes. """ i = 0 conv = np.inf old_conv = -np.inf conv_list = [] m = self.original # If the original data input is in pandas Data...
Render link as HTML output tag <a >.
def render(self, obj): """ Render link as HTML output tag <a>. """ self.obj = obj attrs = ' '.join([ '%s="%s"' % (attr_name, attr.resolve(obj)) if isinstance(attr, Accessor) else '%s="%s"' % (attr_name, attr) for attr_name, attr in self.att...
Return an object described by the accessor by traversing the attributes of context.
def resolve(self, context, quiet=True): """ Return an object described by the accessor by traversing the attributes of context. """ try: obj = context for level in self.levels: if isinstance(obj, dict): obj = ...
[ [ header1 ] [ header3 header4 ] ]
def header_rows(self): """ [ [header1], [header3, header4] ] """ # TO BE FIX: refactor header_rows = [] headers = [col.header for col in self.columns] for header in headers: if len(header_rows) <= header.row_order: header_rows.append([]...
Get context data for datatable server - side response. See http:// www. datatables. net/ usage/ server - side
def get_context_data(self, **kwargs): """ Get context data for datatable server-side response. See http://www.datatables.net/usage/server-side """ sEcho = self.query_data["sEcho"] context = super(BaseListView, self).get_context_data(**kwargs) queryset = context["...
Calculate how many days the month spans.
def get_days_span(self, month_index): """ Calculate how many days the month spans. """ is_first_month = month_index == 0 is_last_month = month_index == self.__len__() - 1 y = int(self.start_date.year + (self.start_date.month + month_index) / 13) m = int((self.sta...
Returns an IEEE 754 float from an array of 4 bytes
def _calculate_float(self, byte_array): """Returns an IEEE 754 float from an array of 4 bytes :param byte_array: Expects an array of 4 bytes :type byte_array: array :rtype: float """ if len(byte_array) != 4: return None return struct.unpack('f', st...
calculate the sampling period in seconds
def _calculate_period(self, vals): ''' calculate the sampling period in seconds ''' if len(vals) < 4: return None if self.firmware['major'] < 16: return ((vals[3] << 24) | (vals[2] << 16) | (vals[1] << 8) | vals[0]) / 12e6 else: return self._calculate...
Wait for the OPC to prepare itself for data transmission. On some devides this can take a few seconds: rtype: self: Example: >> alpha = opc. OPCN2 ( spi debug = True ). wait ( check = 200 ) >> alpha = opc. OPCN2 ( spi debug = True wait = True check = 200 )
def wait(self, **kwargs): """Wait for the OPC to prepare itself for data transmission. On some devides this can take a few seconds :rtype: self :Example: >> alpha = opc.OPCN2(spi, debug=True).wait(check=200) >> alpha = opc.OPCN2(spi, debug=True, wait=True, check=200) """ ...
Calculate the adc value that corresponds to a specific bin boundary diameter in microns.
def calculate_bin_boundary(self, bb): """Calculate the adc value that corresponds to a specific bin boundary diameter in microns. :param bb: Bin Boundary in microns :type bb: float :rtype: int """ return min(enumerate(OPC_LOOKUP), key = lambda x: abs(x[1] ...
Reads the information string for the OPC
def read_info_string(self): """Reads the information string for the OPC :rtype: string :Example: >>> alpha.read_info_string() 'OPC-N2 FirmwareVer=OPC-018.2....................BD' """ infostring = [] # Send the command byte and sleep for 9 ms se...
Checks the connection between the Raspberry Pi and the OPC
def ping(self): """Checks the connection between the Raspberry Pi and the OPC :rtype: Boolean """ b = self.cnxn.xfer([0xCF])[0] # send the command byte sleep(0.1) return True if b == 0xF3 else False
Turn ON the OPC ( fan and laser )
def on(self): """Turn ON the OPC (fan and laser) :rtype: boolean :Example: >>> alpha.on() True """ b1 = self.cnxn.xfer([0x03])[0] # send the command byte sleep(9e-3) # sleep for 9 ms b2, b3 = self.cnxn.xfer([...
Turn OFF the OPC ( fan and laser )
def off(self): """Turn OFF the OPC (fan and laser) :rtype: boolean :Example: >>> alpha.off() True """ b1 = self.cnxn.xfer([0x03])[0] # send the command byte sleep(9e-3) # sleep for 9 ms b2 = self.cnxn.xfer([0...
Read the configuration variables and returns them as a dictionary
def config(self): """Read the configuration variables and returns them as a dictionary :rtype: dictionary :Example: >>> alpha.config() { 'BPD 13': 1.6499, 'BPD 12': 1.6499, 'BPD 11': 1.6499, 'BPD 10': 1.6499, 'BPD 15'...
Read the second set of configuration variables and return as a dictionary.
def config2(self): """Read the second set of configuration variables and return as a dictionary. **NOTE: This method is supported by firmware v18+.** :rtype: dictionary :Example: >>> a.config2() { 'AMFanOnIdle': 0, 'AMIdleIntervalCount': 0, ...
Read and reset the histogram. As of v1. 3. 0 histogram values are reported in particle number concentration ( #/ cc ) by default.
def histogram(self, number_concentration=True): """Read and reset the histogram. As of v1.3.0, histogram values are reported in particle number concentration (#/cc) by default. :param number_concentration: If true, histogram bins are reported in number concentration vs. raw values. :ty...
Save the configuration variables in non - volatile memory. This method should be used in conjuction with * write_config_variables *.
def save_config_variables(self): """Save the configuration variables in non-volatile memory. This method should be used in conjuction with *write_config_variables*. :rtype: boolean :Example: >>> alpha.save_config_variables() True """ command = 0x43 ...
Set only the Fan power.
def set_fan_power(self, power): """Set only the Fan power. :param power: Fan power value as an integer between 0-255. :type power: int :rtype: boolean :Example: >>> alpha.set_fan_power(255) True """ # Check to make sure the value is a single b...
Toggle the power state of the laser.
def toggle_laser(self, state): """Toggle the power state of the laser. :param state: Boolean state of the laser :type state: boolean :rtype: boolean :Example: >>> alpha.toggle_laser(True) True """ # Send the command byte and wait 10 ms ...
Read the status of the digital pot. Firmware v18 + only. The return value is a dictionary containing the following as unsigned 8 - bit integers: FanON LaserON FanDACVal LaserDACVal.
def read_pot_status(self): """Read the status of the digital pot. Firmware v18+ only. The return value is a dictionary containing the following as unsigned 8-bit integers: FanON, LaserON, FanDACVal, LaserDACVal. :rtype: dict :Example: >>> alpha.read_pot_status() ...
Read the Serial Number string. This method is only available on OPC - N2 firmware versions 18 +.
def sn(self): """Read the Serial Number string. This method is only available on OPC-N2 firmware versions 18+. :rtype: string :Example: >>> alpha.sn() 'OPC-N2 123456789' """ string = [] # Send the command byte and sleep for 9 ms self.cn...
Read the firmware version of the OPC - N2. Firmware v18 + only.
def read_firmware(self): """Read the firmware version of the OPC-N2. Firmware v18+ only. :rtype: dict :Example: >>> alpha.read_firmware() { 'major': 18, 'minor': 2, 'version': 18.2 } """ # Send the command byte and sl...
Read the PM data and reset the histogram
def pm(self): """Read the PM data and reset the histogram **NOTE: This method is supported by firmware v18+.** :rtype: dictionary :Example: >>> alpha.pm() { 'PM1': 0.12, 'PM2.5': 0.24, 'PM10': 1.42 } """ res...
Turn ON the OPC ( fan and laser )
def on(self): """Turn ON the OPC (fan and laser) :returns: boolean success state """ b1 = self.cnxn.xfer([0x0C])[0] # send the command byte sleep(9e-3) # sleep for 9 ms return True if b1 == 0xF3 else False
Turn OFF the OPC ( fan and laser )
def off(self): """Turn OFF the OPC (fan and laser) :returns: boolean success state """ b1 = self.cnxn.xfer([0x03])[0] # send the command byte sleep(9e-3) # sleep for 9 ms return True if b1 == 0xF3 else False
Read the gain - scaling - coefficient and sample flow rate.
def read_gsc_sfr(self): """Read the gain-scaling-coefficient and sample flow rate. :returns: dictionary containing GSC and SFR """ config = [] data = {} # Send the command byte and sleep for 10 ms self.cnxn.xfer([0x33]) sleep(10e-3) # Read t...
Return the bin boundaries.
def read_bin_boundaries(self): """Return the bin boundaries. :returns: dictionary with 17 bin boundaries. """ config = [] data = {} # Send the command byte and sleep for 10 ms self.cnxn.xfer([0x33]) sleep(10e-3) # Read the config variables b...
Read the bin particle density
def read_bin_particle_density(self): """Read the bin particle density :returns: float """ config = [] # Send the command byte and sleep for 10 ms self.cnxn.xfer([0x33]) sleep(10e-3) # Read the config variables by sending 256 empty bytes for i in...
Read and reset the histogram. The expected return is a dictionary containing the counts per bin MToF for bins 1 3 5 and 7 temperature pressure the sampling period the checksum PM1 PM2. 5 and PM10.
def read_histogram(self): """Read and reset the histogram. The expected return is a dictionary containing the counts per bin, MToF for bins 1, 3, 5, and 7, temperature, pressure, the sampling period, the checksum, PM1, PM2.5, and PM10. **NOTE:** The sampling period for the OPCN1 seems t...
Starts HDLC controller s threads.
def start(self): """ Starts HDLC controller's threads. """ self.receiver = self.Receiver( self.read, self.write, self.send_lock, self.senders, self.frames_received, callback=self.receive_callback, fcs_na...
Stops HDLC controller s threads.
def stop(self): """ Stops HDLC controller's threads. """ if self.receiver != None: self.receiver.join() for s in self.senders.values(): s.join()
Sends a new data frame.
def send(self, data): """ Sends a new data frame. This method will block until a new room is available for a new sender. This limit is determined by the size of the window. """ while len(self.senders) >= self.window: pass self.senders[self.new_seq_n...
* Note: checks Range. start () only * Key: self = [] other = {} * [ { ---- ] ---- } = > - 1 * { --- [ --- } ] = > 1 * [ --- ] { --- } = > - 1 * [ --- ] same as { --- } = > 0 * [ -- { - } -- ] = > - 1
def cmp(self, other): """*Note: checks Range.start() only* Key: self = [], other = {} * [ {----]----} => -1 * {---[---} ] => 1 * [---] {---} => -1 * [---] same as {---} => 0 * [--{-}--] => -1 """ if isinstance(other, Range):...
Cuts this object from_start to the number requestd returns new instance
def cut(self, by, from_start=True): """ Cuts this object from_start to the number requestd returns new instance """ s, e = copy(self.start), copy(self.end) if from_start: e = s + by else: s = e - by return Range(s, e)
Returns a new instance of self times is not supported yet.
def next(self, times=1): """Returns a new instance of self times is not supported yet. """ return Range(copy(self.end), self.end + self.elapse, tz=self.start.tz)
Returns a new instance of self times is not supported yet.
def prev(self, times=1): """Returns a new instance of self times is not supported yet. """ return Range(self.start - self.elapse, copy(self.start), tz=self.start.tz)
Note returns a new Date obj
def replace(self, **k): """Note returns a new Date obj""" if self.date != 'infinity': return Date(self.date.replace(**k)) else: return Date('infinity')
Adjusts the time from kwargs to timedelta ** Will change this object **
def adjust(self, to): ''' Adjusts the time from kwargs to timedelta **Will change this object** return new copy of self ''' if self.date == 'infinity': return new = copy(self) if type(to) in (str, unicode): to = to.lower() ...
Find all the timestrings within a block of text.
def findall(text): """Find all the timestrings within a block of text. >>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.") [ ('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>), ('august 15th at 7:20 am', <ti...
Returns two - tuple of ( user token ) if authentication succeeds or None otherwise.
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ try: oauth_request = oauth_provider.utils.get_oauth_request(request) except oauth.Error as err: raise exceptions.Authenticati...