Search is not available for this dataset
text
stringlengths
75
104k
def _map_exception(e): """Maps an exception from urlib3 to httplib2.""" if isinstance(e, urllib3.exceptions.MaxRetryError): if not e.reason: return e e = e.reason message = e.args[0] if e.args else '' if isinstance(e, urllib3.exceptions.ResponseError): if 'too many re...
def run_workers(no_subprocess, watch_paths=None, is_background=False): """ subprocess handler """ import atexit, os, subprocess, signal if watch_paths: from watchdog.observers import Observer # from watchdog.observers.fsevents import FSEventsObserver as Observer # from watchd...
def exit(self, signal=None, frame=None): """ Properly close the AMQP connections """ self.input_channel.close() self.client_queue.close() self.connection.close() log.info("Worker exiting") sys.exit(0)
def connect(self): """ make amqp connection and create channels and queue binding """ self.connection = pika.BlockingConnection(BLOCKING_MQ_PARAMS) self.client_queue = ClientQueue() self.input_channel = self.connection.channel() self.input_channel.exchange_declar...
def clear_queue(self): """ clear outs all messages from INPUT_QUEUE_NAME """ def remove_message(ch, method, properties, body): print("Removed message: %s" % body) self.input_channel.basic_consume(remove_message, queue=self.INPUT_QUEUE_NAME, no_ack=True) try: ...
def run(self): """ actual consuming of incoming works starts here """ self.input_channel.basic_consume(self.handle_message, queue=self.INPUT_QUEUE_NAME, no_ack=True ...
def handle_message(self, ch, method, properties, body): """ this is a pika.basic_consumer callback handles client inputs, runs appropriate workflows and views Args: ch: amqp channel method: amqp method properties: body: message body ...
def get_progress(start, finish): """ Args: start (DateTime): start date finish (DateTime): finish date Returns: """ now = datetime.now() dif_time_start = start - now dif_time_finish = finish - now if dif_time_start.days < 0 and dif_time_finish.days < 0: return P...
def sync_wf_cache(current): """ BG Job for storing wf state to DB """ wf_cache = WFCache(current) wf_state = wf_cache.get() # unicode serialized json to dict, all values are unicode if 'role_id' in wf_state: # role_id inserted by engine, so it's a sign that we get it from cache not db ...
def get_or_create_by_content(cls, name, content): """ if xml content updated, create a new entry for given wf name Args: name: name of wf content: xml content Returns (DiagramXML(), bool): A tuple with two members. (DiagramXML instance and True if it's ne...
def get_description(self): """ Tries to get WF description from 'collabration' or 'process' or 'pariticipant' Returns str: WF description """ paths = ['bpmn:collaboration/bpmn:participant/bpmn:documentation', 'bpmn:collaboration/bpmn:documentation', ...
def get_name(self): """ Tries to get WF name from 'process' or 'collobration' or 'pariticipant' Returns: str. WF name. """ paths = ['bpmn:process', 'bpmn:collaboration/bpmn:participant/', 'bpmn:collaboration', ] ...
def set_xml(self, diagram, force=False): """ updates xml link if there aren't any running instances of this wf Args: diagram: XMLDiagram object """ no_of_running = WFInstance.objects.filter(wf=self, finished=False, started=True).count() if no_of_running and no...
def create_wf_instances(self, roles=None): """ Creates wf instances. Args: roles (list): role list Returns: (list): wf instances """ # if roles specified then create an instance for each role # else create only one instance if ro...
def create_tasks(self): """ will create a WFInstance per object and per TaskInvitation for each role and WFInstance """ roles = self.get_roles() if self.task_type in ["A", "D"]: instances = self.create_wf_instances(roles=roles) self.create_task_in...
def get_object_query_dict(self): """returns objects keys according to self.object_query_code which can be json encoded queryset filter dict or key=value set in the following format: ```"key=val, key2 = val2 , key3= value with spaces"``` Returns: (dict): Queryset filtering ...
def get_object_keys(self, wfi_role=None): """returns object keys according to task definition which can be explicitly selected one object (self.object_key) or result of a queryset filter. Returns: list of object keys """ if self.object_key: return...
def get_model_objects(model, wfi_role=None, **kwargs): """ Fetches model objects by filtering with kwargs If wfi_role is specified, then we expect kwargs contains a filter value starting with role, e.g. {'user': 'role.program.user'} We replace this `role` key with role...
def get_roles(self): """ Returns: Role instances according to task definition. """ if self.role.exist: # return explicitly selected role return [self.role] else: roles = [] if self.role_query_code: # use...
def post_save(self): """can be removed when a proper task manager admin interface implemented""" if self.run: self.run = False self.create_tasks() self.save()
def delete_other_invitations(self): """ When one person use an invitation, we should delete other invitations """ # TODO: Signal logged-in users to remove the task from their task list self.objects.filter(instance=self.instance).exclude(key=self.key).delete()
def save(self, wf_state): """ write wf state to DB through MQ >> Worker >> _zops_sync_wf_cache Args: wf_state dict: wf state """ self.wf_state = wf_state self.wf_state['role_id'] = self.current.role_id self.set(self.wf_state) if self.wf_state[...
def send_to_default_exchange(self, sess_id, message=None): """ Send messages through RabbitMQ's default exchange, which will be delivered through routing_key (sess_id). This method only used for un-authenticated users, i.e. login process. Args: sess_id string: Sessi...
def send_to_prv_exchange(self, user_id, message=None): """ Send messages through logged in users private exchange. Args: user_id string: User key message dict: Message object """ exchange = 'prv_%s' % user_id.lower() msg = json.dumps(message, cls...
def compose(self, other): """ compose 2 graphs to CGR :param other: Molecule or CGR Container :return: CGRContainer """ if not isinstance(other, Compose): raise TypeError('CGRContainer or MoleculeContainer [sub]class expected') cgr = self._get_subcla...
def decompose(self): """ decompose CGR to pair of Molecules, which represents reactants and products state of reaction :return: tuple of two molecules """ mc = self._get_subclass('MoleculeContainer') reactants = mc() products = mc() for n, atom in self.a...
def cycle_data(self, verbose=False, result_cycle=None, result_size=None, result_edges=None,changelog=True): """Get data from JIRA for cycle/flow times and story points size change. Build a numerically indexed data frame with the following 'fixed' columns: `key`, 'url', 'issue_type', `summary`, ...
def size_history(self,size_data): """Return the a DataFrame, indexed by day, with columns containing story size for each issue. In addition, columns are soted by Jira Issue key. First by Project and then by id number. """ def my_merge(df1, df2): # http://stackoverfl...
def cfd(self, cycle_data,size_history= None, pointscolumn= None, stacked = True ): """Return the data to build a cumulative flow diagram: a DataFrame, indexed by day, with columns containing cumulative counts for each of the items in the configured cycle. In addition, a column called `c...
def histogram(self, cycle_data, bins=10): """Return histogram data for the cycle times in `cycle_data`. Returns a dictionary with keys `bin_values` and `bin_edges` of numpy arrays """ values, edges = np.histogram(cycle_data['cycle_time'].astype('timedelta64[D]').dropna(), bins=bins) ...
def throughput_data(self, cycle_data, frequency='1D',pointscolumn= None): """Return a data frame with columns `completed_timestamp` of the given frequency, either `count`, where count is the number of items 'sum', where sum is the sum of value specified by pointscolumn. Expected to be 'S...
def scatterplot(self, cycle_data): """Return scatterplot data for the cycle times in `cycle_data`. Returns a data frame containing only those items in `cycle_data` where values are set for `completed_timestamp` and `cycle_time`, and with those two columns as the first two, both normalise...
def _is_ready(self, topic_name): ''' Is NSQ running and have space to receive messages? ''' url = 'http://%s/stats?format=json&topic=%s' % (self.nsqd_http_address, topic_name) #Cheacking for ephmeral channels if '#' in topic_name: topic_name, tag =topic_name.s...
def _matcher(self, other): """ QueryContainer < MoleculeContainer QueryContainer < QueryContainer[more general] QueryContainer < QueryCGRContainer[more general] """ if isinstance(other, MoleculeContainer): return GraphMatcher(other, self, lambda x, y: y == x, ...
def _matcher(self, other): """ QueryCGRContainer < CGRContainer QueryContainer < QueryCGRContainer[more general] """ if isinstance(other, CGRContainer): return GraphMatcher(other, self, lambda x, y: y == x, lambda x, y: y == x) elif isinstance(other, QueryCGRC...
def calculate2d(self, force=False, scale=1): """ recalculate 2d coordinates. currently rings can be calculated badly. :param scale: rescale calculated positions. :param force: ignore existing coordinates of atoms """ dist = {} # length forces for n, m_bon...
def possible_moves(self, position): """ Finds all possible knight moves :type: position Board :rtype: list """ for direction in [0, 1, 2, 3]: angles = self._rotate_direction_ninety_degrees(direction) for angle in angles: try: ...
def centers_list(self): """ get a list of lists of atoms of reaction centers """ center = set() adj = defaultdict(set) for n, atom in self.atoms(): if atom._reactant != atom._product: center.add(n) for n, m, bond in self.bonds(): i...
def center_atoms(self): """ get list of atoms of reaction center (atoms with dynamic: bonds, charges, radicals). """ nodes = set() for n, atom in self.atoms(): if atom._reactant != atom._product: nodes.add(n) for n, m, bond in self.bonds(): ...
def center_bonds(self): """ get list of bonds of reaction center (bonds with dynamic orders). """ return [(n, m) for n, m, bond in self.bonds() if bond._reactant != bond._product]
def reset_query_marks(self): """ set or reset hyb and neighbors marks to atoms. """ for i, atom in self.atoms(): neighbors = 0 hybridization = 1 p_neighbors = 0 p_hybridization = 1 # hyb 1- sp3; 2- sp2; 3- sp1; 4- aromatic ...
def substructure(self, atoms, meta=False, as_view=True): """ create substructure containing atoms from nbunch list :param atoms: list of atoms numbers of substructure :param meta: if True metadata will be copied to substructure :param as_view: If True, the returned graph-view pr...
def _matcher(self, other): """ CGRContainer < CGRContainer """ if isinstance(other, CGRContainer): return GraphMatcher(other, self, lambda x, y: x == y, lambda x, y: x == y) raise TypeError('only cgr-cgr possible')
def __plain_bfs(adj, source): """modified NX fast BFS node generator""" seen = set() nextlevel = {source} while nextlevel: thislevel = nextlevel nextlevel = set() for v in thislevel: if v not in seen: yield v ...
def token(self): """ Returns authorization token provided by Cocaine. The real meaning of the token is determined by its type. For example OAUTH2 token will have "bearer" type. :return: A tuple of token type and body. """ if self._token is None: toke...
def _send(self): """ Send a message lazy formatted with args. External log attributes can be passed via named attribute `extra`, like in logging from the standart library. Note: * Attrs must be dict, otherwise the whole message would be skipped. * The key field i...
def moves_in_direction(self, direction, position): """ Finds moves in a given direction :type: direction: lambda :type: position: Board :rtype: list """ current_square = self.location while True: try: current_square = directio...
def possible_moves(self, position): """ Returns all possible rook moves. :type: position: Board :rtype: list """ for move in itertools.chain(*[self.moves_in_direction(fn, position) for fn in self.cross_fn]): yield move
def overlap_status(a, b): """Check overlap between two arrays. Parameters ---------- a, b : array-like Arrays to check. Assumed to be in the same unit. Returns ------- result : {'full', 'partial', 'none'} * 'full' - ``a`` is within or same as ``b`` * 'partial' - ``a...
def validate_totalflux(totalflux): """Check integrated flux for invalid values. Parameters ---------- totalflux : float Integrated flux. Raises ------ synphot.exceptions.SynphotError Input is zero, negative, or not a number. """ if totalflux <= 0.0: raise e...
def validate_wavelengths(wavelengths): """Check wavelengths for ``synphot`` compatibility. Wavelengths must satisfy these conditions: * valid unit type, if given * no zeroes * monotonic ascending or descending * no duplicate values Parameters ---------- wavelengths...
def generate_wavelengths(minwave=500, maxwave=26000, num=10000, delta=None, log=True, wave_unit=u.AA): """Generate wavelength array to be used for spectrum sampling. .. math:: minwave \\le \\lambda < maxwave Parameters ---------- minwave, maxwave : float L...
def merge_wavelengths(waveset1, waveset2, threshold=1e-12): """Return the union of the two sets of wavelengths using :func:`numpy.union1d`. The merged wavelengths may sometimes contain numbers which are nearly equal but differ at levels as small as 1e-14. Having values this close together can cause...
def download_data(cdbs_root, verbose=True, dry_run=False): """Download CDBS data files to given root directory. Download is skipped if a data file already exists. Parameters ---------- cdbs_root : str Root directory for CDBS data files. verbose : bool Print extra information to...
async def main(loop): """Demonstrate functionality of PyVLX.""" pyvlx = PyVLX('pyvlx.yaml', loop=loop) # Alternative: # pyvlx = PyVLX(host="192.168.2.127", password="velux123", loop=loop) # Runing scenes: await pyvlx.load_scenes() await pyvlx.scenes["All Windows Closed"].run() # Changi...
def get_payload(self): """Return Payload.""" if self.password is None: raise PyVLXException("password is none") if len(self.password) > self.MAX_SIZE: raise PyVLXException("password is too long") return string_to_bytes(self.password, self.MAX_SIZE)
def add(self, node): """Add Node, replace existing node if node with node_id is present.""" if not isinstance(node, Node): raise TypeError() for i, j in enumerate(self.__nodes): if j.node_id == node.node_id: self.__nodes[i] = node return ...
async def load(self, node_id=None): """Load nodes from KLF 200, if no node_id is specified all nodes are loaded.""" if node_id is not None: await self._load_node(node_id=node_id) else: await self._load_all_nodes()
async def _load_node(self, node_id): """Load single node via API.""" get_node_information = GetNodeInformation(pyvlx=self.pyvlx, node_id=node_id) await get_node_information.do_api_call() if not get_node_information.success: raise PyVLXException("Unable to retrieve node inform...
async def _load_all_nodes(self): """Load all nodes via API.""" get_all_nodes_information = GetAllNodesInformation(pyvlx=self.pyvlx) await get_all_nodes_information.do_api_call() if not get_all_nodes_information.success: raise PyVLXException("Unable to retrieve node informatio...
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetAllNodesInformationConfirmation): self.number_of_nodes = frame.number_of_nodes # We are still waiting for FrameGetAllNodesInformationNoti...
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetNodeInformationConfirmation) and frame.node_id == self.node_id: # We are still waiting for GetNodeInformationNotification return False ...
def start(self): """Create loop task.""" self.run_task = self.pyvlx.loop.create_task( self.loop())
async def stop(self): """Stop heartbeat.""" self.stopped = True self.loop_event.set() # Waiting for shutdown of loop() await self.stopped_event.wait()
async def loop(self): """Pulse every timeout seconds until stopped.""" while not self.stopped: self.timeout_handle = self.pyvlx.connection.loop.call_later( self.timeout_in_seconds, self.loop_timeout) await self.loop_event.wait() if not self.stopped: ...
async def pulse(self): """Send get state request to API to keep the connection alive.""" get_state = GetState(pyvlx=self.pyvlx) await get_state.do_api_call() if not get_state.success: raise PyVLXException("Unable to send get state.")
def get_payload(self): """Return Payload.""" payload = bytes([self.gateway_state.value, self.gateway_sub_state.value]) payload += bytes(4) # State date, reserved for future use return payload
def from_payload(self, payload): """Init frame from binary data.""" self.gateway_state = GatewayState(payload[0]) self.gateway_sub_state = GatewaySubState(payload[1])
def string_to_bytes(string, size): """Convert string to bytes add padding.""" if len(string) > size: raise PyVLXException("string_to_bytes::string_to_large") encoded = bytes(string, encoding='utf-8') return encoded + bytes(size-len(encoded))
def bytes_to_string(raw): """Convert bytes to string.""" ret = bytes() for byte in raw: if byte == 0x00: return ret.decode("utf-8") ret += bytes([byte]) return ret.decode("utf-8")
def get_payload(self): """Return Payload.""" payload = bytes([self.node_id]) payload += bytes([self.state]) payload += bytes(self.current_position.raw) payload += bytes(self.target.raw) payload += bytes(self.current_position_fp1.raw) payload += bytes(self.current_...
def from_payload(self, payload): """Init frame from binary data.""" self.node_id = payload[0] self.state = payload[1] self.current_position = Parameter(payload[2:4]) self.target = Parameter(payload[4:6]) self.current_position_fp1 = Parameter(payload[6:8]) self.cur...
async def house_status_monitor_enable(pyvlx): """Enable house status monitor.""" status_monitor_enable = HouseStatusMonitorEnable(pyvlx=pyvlx) await status_monitor_enable.do_api_call() if not status_monitor_enable.success: raise PyVLXException("Unable enable house status monitor.")
async def house_status_monitor_disable(pyvlx): """Disable house status monitor.""" status_monitor_disable = HouseStatusMonitorDisable(pyvlx=pyvlx) await status_monitor_disable.do_api_call() if not status_monitor_disable.success: raise PyVLXException("Unable disable house status monitor.")
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameHouseStatusMonitorEnableConfirmation): return False self.success = True return True
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if not isinstance(frame, FrameHouseStatusMonitorDisableConfirmation): return False self.success = True return True
def BitmathType(bmstring): """An 'argument type' for integrations with the argparse module. For more information, see https://docs.python.org/2/library/argparse.html#type Of particular interest to us is this bit: ``type=`` can take any callable that takes a single string argument and returns the converted v...
def update(self, pbar): """Updates the widget with the current NIST/SI speed. Basically, this calculates the average rate of update and figures out how to make a "pretty" prefix unit""" if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: scaled = bitmath.Byte() else: ...
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameCommandSendConfirmation) and frame.session_id == self.session_id: if frame.status == CommandSendConfirmationStatus.ACCEPTED: self.succes...
def request_frame(self): """Construct initiating frame.""" self.session_id = get_new_session_id() return FrameCommandSendRequest(node_ids=[self.node_id], parameter=self.parameter, session_id=self.session_id)
def read_config(self, path): """Read configuration file.""" PYVLXLOG.info('Reading config file: %s', path) try: with open(path, 'r') as filehandle: doc = yaml.safe_load(filehandle) self.test_configuration(doc, path) self.host = doc['con...
def setup_apiv2(): """ Setup apiv2 when using PyQt4 and Python2. """ # setup PyQt api to version 2 if sys.version_info[0] == 2: logging.getLogger(__name__).debug( 'setting up SIP API to version 2') import sip try: sip.setapi("QString", 2) s...
def autodetect(): """ Auto-detects and use the first available QT_API by importing them in the following order: 1) PyQt5 2) PyQt4 3) PySide """ logging.getLogger(__name__).debug('auto-detecting QT_API') try: logging.getLogger(__name__).debug('trying PyQt5') import Py...
def from_config(cls, pyvlx, item): """Read roller shutter from config.""" name = item['name'] ident = item['id'] subtype = item['subtype'] typeid = item['typeId'] return cls(pyvlx, ident, name, subtype, typeid)
async def handle_frame(self, frame): """Handle incoming API frame, return True if this was the expected frame.""" if isinstance(frame, FrameGetSceneListConfirmation): self.count_scenes = frame.count_scenes if self.count_scenes == 0: self.success = True ...
def get_payload(self): """Return Payload.""" ret = bytes([len(self.scenes)]) for number, name in self.scenes: ret += bytes([number]) ret += string_to_bytes(name, 64) ret += bytes([self.remaining_scenes]) return ret
def from_payload(self, payload): """Init frame from binary data.""" number_of_objects = payload[0] self.remaining_scenes = payload[-1] predicted_len = number_of_objects * 65 + 2 if len(payload) != predicted_len: raise PyVLXException('scene_list_notification_wrong_leng...
def read_remote_spec(filename, encoding='binary', cache=True, show_progress=True, **kwargs): """Read FITS or ASCII spectrum from a remote location. Parameters ---------- filename : str Spectrum filename. encoding, cache, show_progress See :func:`~astropy.utils....
def read_spec(filename, fname='', **kwargs): """Read FITS or ASCII spectrum. Parameters ---------- filename : str or file pointer Spectrum file name or pointer. fname : str Filename. This is *only* used if ``filename`` is a pointer. kwargs : dict Keywords acceptable by...
def read_ascii_spec(filename, wave_unit=u.AA, flux_unit=units.FLAM, **kwargs): """Read ASCII spectrum. ASCII table must have following columns: #. Wavelength data #. Flux data It can have more than 2 columns but the rest is ignored. Comments are discarded. Parameters --------...
def read_fits_spec(filename, ext=1, wave_col='WAVELENGTH', flux_col='FLUX', wave_unit=u.AA, flux_unit=units.FLAM): """Read FITS spectrum. Wavelength and flux units are extracted from ``TUNIT1`` and ``TUNIT2`` keywords, respectively, from data table (not primary) header. If these keyw...
def write_fits_spec(filename, wavelengths, fluxes, pri_header={}, ext_header={}, overwrite=False, trim_zero=True, pad_zero_ends=True, precision=None, epsilon=0.00032, wave_col='WAVELENGTH', flux_col='FLUX', wave_unit=u.AA, flux_unit=units.F...
def spectral_density_vega(wav, vegaflux): """Flux equivalencies between PHOTLAM and VEGAMAG. Parameters ---------- wav : `~astropy.units.quantity.Quantity` Quantity associated with values being converted (e.g., wavelength or frequency). vegaflux : `~astropy.units.quantity.Quantity`...
def spectral_density_count(wav, area): """Flux equivalencies between PHOTLAM and count/OBMAG. Parameters ---------- wav : `~astropy.units.quantity.Quantity` Quantity associated with values being converted (e.g., wavelength or frequency). area : `~astropy.units.quantity.Quantity` ...
def convert_flux(wavelengths, fluxes, out_flux_unit, **kwargs): """Perform conversion for :ref:`supported flux units <synphot-flux-units>`. Parameters ---------- wavelengths : array-like or `~astropy.units.quantity.Quantity` Wavelength values. If not a Quantity, assumed to be in Angstro...
def _convert_flux(wavelengths, fluxes, out_flux_unit, area=None, vegaspec=None): """Flux conversion for PHOTLAM <-> X.""" flux_unit_names = (fluxes.unit.to_string(), out_flux_unit.to_string()) if PHOTLAM.to_string() not in flux_unit_names: raise exceptions.SynphotError( ...
def validate_unit(input_unit): """Validate unit. To be compatible with existing SYNPHOT data files: * 'angstroms' and 'inversemicrons' are accepted although unrecognized by astropy units * 'transmission', 'extinction', and 'emissivity' are converted to astropy dimensionless...
def validate_wave_unit(wave_unit): """Like :func:`validate_unit` but specific to wavelength.""" output_unit = validate_unit(wave_unit) unit_type = output_unit.physical_type if unit_type not in ('length', 'wavenumber', 'frequency'): raise exceptions.SynphotError( 'wavelength physical...
def validate_quantity(input_value, output_unit, equivalencies=[]): """Validate quantity (value and unit). .. note:: For flux conversion, use :func:`convert_flux` instead. Parameters ---------- input_value : number, array-like, or `~astropy.units.quantity.Quantity` Quantity to vali...
def add(self, device): """Add device.""" if not isinstance(device, Device): raise TypeError() self.__devices.append(device)