code stringlengths 1 18.2k |
|---|
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: Session id message dict: Message object. """ msg = json.dum... |
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=ZEngineJSONEncoder) log.debug("Sending following users \"%s\" exchange:\n... |
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_subclass('CGRContainer') common = self._node.keys() & other if not common: i... |
- common h = cgr() atoms = h._node bonds = [] common_adj = {n: {} for n in common} common_bonds = [] r_atoms = {} r_skin = defaultdict(list) if isinstance(self, cgr): for n in unique_reactant: h.add_atom(self._node[n], n) for m, bond in self._adj[n].items(): if m not in atoms: if m in common: # bond to common atoms is ... |
is None: # skip None>None continue r_skin[n].append(m) bond = DynBond.__new__(DynBond) bond.__init_copy__(r_bond, None) bonds.append((n, m, bond)) for n in common: r_atoms[n] = self._node[n]._reactant for m, bond in self._adj[n].items(): if m not in r_atoms and m in common: tmp = [bond._reactant, None] common_adj[n][m]... |
h.add_atom(atom, n) for m, r_bond in self._adj[n].items(): # unique atom neighbors if m not in atoms: # bond not analyzed yet bond = DynBond.__new__(DynBond) if m in common: # bond to common atoms r_skin[n].append(m) bond.__init_copy__(r_bond, None) else: # bond static bond.__init_copy__(r_bond, r_bond) bonds.append((n... |
in common: # analyze only common atoms bonds tmp = [bond, None] # reactant state only common_adj[n][m] = common_adj[m][n] = tmp common_bonds.append((n, m, tmp)) p_atoms = {} p_skin = defaultdict(list) if isinstance(other, cgr): for n in unique_product: h.add_atom(other._node[n], n) for m, bond in other._adj[n].items():... |
if p_bond is None: # skip None>None continue p_skin[n].append(m) bond = DynBond.__new__(DynBond) bond.__init_copy__(None, p_bond) bonds.append((n, m, bond)) for n in common: p_atoms[n] = other._node[n]._product n_bonds = common_adj[n] for m, bond in other._adj[n].items(): if m in n_bonds: n_bonds[m][1] = bond._product ... |
bond = DynBond.__new__(DynBond) bond.__init_copy__(None, p_bond) bonds.append((n, m, bond)) else: for n in unique_product: atom = DynAtom.__new__(DynAtom) atom.__init_copy__(other._node[n], other._node[n]) h.add_atom(atom, n) for m, p_bond in other._adj[n].items(): if m not in atoms: bond = DynBond.__new__(DynBond) if ... |
n_bonds: # set product state of changed bond n_bonds[m][1] = p_bond elif m not in p_atoms and m in common: # new bond of reaction bond = DynBond.__new__(DynBond) bond.__init_copy__(None, p_bond) bonds.append((n, m, bond)) for n, r_atom in r_atoms.items(): # prepare common DynAtom's p_atom = p_atoms[n] if r_atom.element... |
for n, m, (r_bond, p_bond) in common_bonds: if r_bond is p_bond is None: # skip None>None continue bond = DynBond.__new__(DynBond) bond.__init_copy__(r_bond, p_bond) h.add_bond(n, m, bond) for n, m, bond in bonds: h.add_bond(n, m, bond) return h |
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.atoms(): reactants.add_atom(atom._reactant, n) products.add_atom(at... |
reactants, products |
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`, `status`, and `resolution... |
as keys and a list of known values for each field as values) and a field in `fields` contains a list of values, only the first value in the list of known values will be used. If 'query_attribute' is set in `settings`, a column with this name will be added, and populated with the `value` key, if any, from each criteria ... |
in settings. In addition, `cycle_time` will be set to the time delta between the first `accepted`-type column and the first `complete` column, or None. The remaining columns are the names of the items in the configured cycle, in order. Each cell contains the last date/time stamp when the relevant status was set. If an ... |
the cycle are erased. """ cycle_names = [s['name'] for s in self.settings['cycle']] accepted_steps = set(s['name'] for s in self.settings['cycle'] if s['type'] == StatusTypes.accepted) completed_steps = set(s['name'] for s in self.settings['cycle'] if s['type'] == StatusTypes.complete) series = { 'key': {'data': [], 'd... |
[], 'dtype': str}, 'cycle_time': {'data': [], 'dtype': 'timedelta64[ns]'}, 'completed_timestamp': {'data': [], 'dtype': 'datetime64[ns]'}, 'created_timestamp': {'data': [], 'dtype': 'datetime64[ns]'} } if sys.platform.startswith('win'): buffer = open("cycledata.tmp", "w+",1) # Opens a file for writing only in binary fo... |
= open("issuelinks.csv", "w+", 1) #df_edges = pd.DataFrame() #df_edges = pd.DataFrame(columns=['Source', 'OutwardLink', 'Target', 'Inwardlink','LinkType']) #df_edges.to_csv(issuelinks, columns=['Source', 'OutwardLink', 'Target', 'Inwardlink','LinkType'], header=True, index=None, sep='\t',encoding='utf-8') df_size_histo... |
self.settings['queries']: for issue in self.find_issues(criteria, order='updatedDate DESC', verbose=verbose, changelog=changelog): # Deal with the differences in strings between Python 2 & 3 if (sys.version_info > (3, 0)): # Python 3 code in this block item = { 'key': issue.key, 'url': "%s/browse/%s" % (self.jira._opti... |
else: # Python 2 code in this block item = { 'key': issue.key, 'url': "%s/browse/%s" % (self.jira._options['server'], issue.key,), 'issue_type': issue.fields.issuetype.name, 'summary': issue.fields.summary.encode('utf-8'), 'status': issue.fields.status.name, 'resolution': issue.fields.resolution.name if issue.fields.re... |
for this issue edges = [] # Source, Target, Inward Link, Outward Link, Type issuelinks = issue.fields.issuelinks # It is seems that having an Epic Parent does not record an Epic Link, just the name "Epic Name" # Creating Epic relationship requires more work. Also each Jira instance will have different customfields for ... |
else None # Epic Link #if issueEpic is not None: # data = {'Source':issueEpic, 'Target':issue.key, 'InwardLink':'Belongs to Epic', 'OutwardLink':'Issue in Epic', 'LinkType':'EpicIssue'} # edges.append(data) for link in issuelinks: inwardissue = None outwardissue = None try: inwardissue = link.inwardIssue.key except: ou... |
edges.append(data) if len(edges)>0: try: df_edges except NameError: #print('Not found') df_edges = pd.DataFrame(edges) else: df_links = pd.DataFrame(edges) df_edges=df_edges.append(df_links) # = pd.DataFrame(edges) # Got all the relationships for this issue rows = [] try: for snapshot in self.iter_size_changes(issue): ... |
Round Down datetimes to full dates df['fromDate'] = df['fromDate'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day)) df['toDate'] = df['toDate'].apply(lambda dt: datetime.datetime(dt.year, dt.month, dt.day)) # If we only have one row of size changes and current issue has a size then it must have been creat... |
row we have with the current issue size. # Get Story Points size changes history #If condition is met update the size cell if getattr(item, 'StoryPoints', None) is not None and (df.shape[0]==1): #if (item['StoryPoints'] is not None ) and (len(df)==1): df.loc[df.index[0], 'size'] = item['StoryPoints'] # Append to csv fi... |
in item lifecycle was scipted put the created data in it. if item[cycle_names[0]] is None: item[cycle_names[0]] = dateutil.parser.parse(item['created_timestamp']) #item['created_timestamp'] # Figure out why the first Column does not have created date #print(dateutil.parser.parse(item['created_timestamp'])) # Record dat... |
# Keep the first time we entered a step if item[snapshot_cycle_step_name] is None: item[snapshot_cycle_step_name] = snapshot.date # Wipe any subsequent dates, in case this was a move backwards found_cycle_name = False for cycle_name in cycle_names: if not found_cycle_name and cycle_name == snapshot_cycle_step_name: fou... |
step", cycle_name) item[cycle_name] = None # Wipe timestamps if items have moved backwards; calculate cycle time previous_timestamp = None accepted_timestamp = None completed_timestamp = None for cycle_name in cycle_names: if item[cycle_name] is not None: previous_timestamp = item[cycle_name] if accepted_timestamp is N... |
in completed_steps: completed_timestamp = previous_timestamp if accepted_timestamp is not None and completed_timestamp is not None: item['cycle_time'] = completed_timestamp - accepted_timestamp item['completed_timestamp'] = completed_timestamp for k, v in item.items(): series[k]['data'].append(v) data = {} for k, v in ... |
result_size = pd.DataFrame() buffer.seek(0) result_size = result_size.from_csv(buffer, sep='\t') buffer.close() try: df_edges except NameError: # print('Not found') df_edges = pd.DataFrame() try: df_edges = df_edges[['Source', 'OutwardLink', 'Target', 'InwardLink','LinkType','LinkID']] # Specify dataframe sort order #d... |
= ['fromDate', 'toDate', 'size']) result_size['toDate'] = pd.to_datetime(result_size['toDate'], format=('%Y-%m-%d')) result_size['fromDate'] = pd.to_datetime(result_size['fromDate'], format=('%Y-%m-%d')) return result_cycle, result_size, result_edges |
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://stackoverflow.com/questions/34411495/pandas-merge-several-datafra... |
col2)) for col1, col2 in pairs: res[col1[:-2]] = res[col1].combine_first(res[col2]) res = res.drop([col1, col2], axis=1) return res dfs_key = [] # Group the dataframe by regiment, and for each regiment, for name, group in size_data.groupby('key'): dfs = [] for row in group.itertuples(): # print(row.Index, row.fromDate,... |
'size']) pd.to_datetime(df2['date'], format=('%Y-%m-%d')) df2.set_index(['date'], inplace=True) dfs.append(df2) # df_final = reduce(lambda left,right: pd.merge(left,right), dfs) df_key = (reduce(my_merge, dfs)) df_key.columns = [name if x == 'size' else x for x in df_key.columns] dfs_key.append(df_key) df_all = (reduce... |
sure we have all dates start, end = df_all.index.min(), df_all.index.max() df_all = df_all.reindex(pd.date_range(start, end, freq='D'), method='ffill') return df_all |
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 `cycle_time` contains the approxima... |
If stacked = True then return dataframe suitable for plotting as stacked area chart else return for platting as non-staked or line chart. """ # Define helper function def cumulativeColumnStates(df,stacked): """ Calculate the column sums, were the incoming matrix columns represents items in workflow states States progre... |
counting items in prior states. :param df: :return: pandas dataframe row with sum of column items """ # Helper functions to return the right most cells in 2D array def last_number(lst): if all(map(lambda x: x == 0, lst)): return 0 elif lst[-1] != 0: return len(lst) - 1 else: return last_number(lst[:-1]) def fill_others... |
= df.fillna(value=0) # ,inplace = True Get rid of non numeric items. Make a ?deep? copy if stacked: df_result = df_zeroed.apply(lambda x: fill_others(x.values.tolist()), axis=1) else: df_result = df_zeroed sum_row = df_result[df.columns].sum() # Sum Columns return pd.DataFrame(data=sum_row).T # Transpose into row dataf... |
workflow states States progress from left to right. We what to zero out items, other than right most value. :param df: :return: pandas dataframe row with sum of column items """ def last_number(lst): if all(map(lambda x: x == 0, lst)): return 0 elif lst[-1] != 0: return len(lst) - 1 else: return last_number(lst[:-1]) d... |
new_lst df_zeroed = df.fillna(value=0) # ,inplace = True Get rid of non numeric items. Make a ?deep? copy df_result = df_zeroed.apply(lambda x: fill_others(x.values.tolist()), axis=1) return df_result # Define helper function def hide_greater_than_date(cell, adate): """ Helper function to compare date values in cells "... |
We have a date value in cell and it is less than or equal to input date # Helper function def appendDFToCSV(df, csvFilePath, sep="\t",date_format='%Y-%m-%d', encoding='utf-8'): import os if not os.path.isfile(csvFilePath): df.to_csv(csvFilePath, mode='a', index=False, sep=sep, date_format=date_format, encoding=encoding... |
sep=sep).columns)) + " columns.") elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all(): raise Exception("Columns and column order of dataframe and csv file do not match!!") else: df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False, date_format=date_format, encoding=encoding)... |
in our results dataFrame slice_columns = list(self.settings['none_sized_statuses']) # Make a COPY of the list so that we dont modify the reference. if pointscolumn: for size_state in self.settings['sized_statuses']: # states_to_size: sizedStateName = size_state + 'Sized' slice_columns.append(sizedStateName) # Check tha... |
# Build a dataframe of just the "date" columns df = cycle_data[cycle_names].copy() # Strip out times from all dates df = pd.DataFrame( np.array(df.values, dtype='<M8[ns]').astype('<M8[D]').astype('<M8[ns]'), columns=df.columns, index=df.index ) # No history provided this thus we return dataframe with just column header... |
state_changes_on_dates_set = state_changes_on_dates_set.union(set(df[state])) # How many unique days did a issue stage state # Remove non timestamp vlaues and sort the list state_changes_on_dates = filter(lambda x: type(x.date()) == datetime.date, sorted(list(state_changes_on_dates_set))) # Replace missing NaT values (... |
results dataframe df_results = pd.DataFrame() # For each date on which we had a issue state change we want to count and sum the totals for each of the given states # 'Open','Analysis','Backlog','In Process','Done','Withdrawn' timenowstr = datetime.datetime.now().strftime('-run-%Y-%m-%d_%H-%M-%S') for date_index,statech... |
filterdate.year,filterdate.month,filterdate.day filterdate = datetime.date(statechangedate.year, statechangedate.month, statechangedate.day) # statechangedate.datetime() # Apply function to each cell and only make it visible if issue was in state on or after the filter date df_filtered = df.applymap(lambda x: 0 if hide... |
pd.Series.to_frame(storypoints_series_on) df_size_on_day.columns = [pointscolumn] # Make sure get size data in the same sequence as ids. left = pd.Series.to_frame(ids) right = df_size_on_day result = left.join(right, on=['key']) # http://pandas.pydata.org/pandas-docs/stable/merging.html\ df_countable = pd.concat([resul... |
file_name ) else: df_countable = df_filtered # Because we size issues with Story Points we need to add some additional columns # for each state based on size not just count if pointscolumn: for size_state in self.settings['sized_statuses']: #states_to_size: sizedStateName = size_state + 'Sized' df_countable[sizedStateN... |
filterdate.isoformat()+timenowstr+".csv" #df_countable.to_csv(file_name, sep='\t', encoding='utf-8', quoting=csv.QUOTE_ALL) df_slice = df_countable.loc[:,slice_columns].copy() df_sub_sum = cumulativeColumnStates(df_slice,stacked) final_table = df_sub_sum.rename(index={0: filterdate}) # append to results df_results = df... |
we have all dates start, end = df.index.min(), df.index.max() try: # If we have no change history we will not have any data in the df and will get a ValueError on reindex df = df.reindex(pd.date_range(start, end, freq='D'), method='ffill') except ValueError: pass return df |
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) index = [] for i, v in enumerate(edg... |
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 'StoryPoints' completed at that ti... |
.rename(columns={pointscolumn: 'sum'}) \ .groupby('completed_timestamp').sum() \ .resample(frequency).sum() \ .fillna(0) else: return cycle_data[['completed_timestamp', 'key']] \ .rename(columns={'key': 'count'}) \ .groupby('completed_timestamp').count() \ .resample(frequency).sum() \ .fillna(0) |
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 normalised to whole days, and with `compl... |
( cycle_data[columns] .dropna(subset=['cycle_time', 'completed_timestamp']) .rename(columns={'completed_timestamp': 'completed_date'}) ) data['cycle_time'] = data['cycle_time'].astype('timedelta64[D]') data['completed_date'] = data['completed_date'].map(pd.Timestamp.date) return data |
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.split("#", 1) try: data = self.session.get(url).json() ''' da... |
\ u'percentiles': None}}]} ''' topics = data.get('topics', []) topics = [t for t in topics if t['topic_name'] == topic_name] if not topics: raise Exception('topic_missing_at_nsq') topic = topics[0] depth = topic['depth'] depth += sum(c.get('depth', 0) for c in topic['channels']) self.log.debug('nsq_depth_check', topic=... |
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, lambda x, y: y == x) elif isinstance(other, (QueryContainer,... |
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, QueryCGRContainer): return GraphMatcher(other, self, lambda x, y: x =... |
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_bond in self._adj.items(): dist[n] = {} for m in m_bond: dist[n][m] ... |
bonds has angle = 120, other 180 (m1, b1), (m2, b2) = m_bond.items() dist[m1][m2] = dist[m2][m1] = 1.43 if b1.order + b2.order in (2, 3) else 1.7 # +.05 elif len(m_bond) == 3: m1, m2, m3 = m_bond dist[m1][m2] = dist[m1][m3] = dist[m2][m3] = dist[m3][m2] = dist[m2][m1] = dist[m3][m1] = 1.43 elif len(m_bond) == 4: # 1 # ... |
3 m1, m2, m3, m4 = m_bond dist[m1][m2] = dist[m1][m4] = dist[m2][m1] = dist[m2][m3] = 1.17 dist[m3][m2] = dist[m3][m4] = dist[m4][m1] = dist[m4][m3] = 1.17 dist[m1][m3] = dist[m3][m1] = dist[m2][m4] = dist[m4][m2] = 1.7 # +.05 # cycle forces for r in self.sssr: if len(r) == 6: # 6 # # 1 5 # # 2 4 # # 3 m1, m2, m3, m4, |
m5, m6 = r dist[m1][m4] = dist[m4][m1] = dist[m2][m5] = dist[m5][m2] = dist[m3][m6] = dist[m6][m3] = 1.7 # +.05 if force: pos = None else: pos = {n: (atom.x or uniform(0, .01), atom.y or uniform(0, .01)) for n, atom in self.atoms()} for n, xy in kamada_kawai_layout(self, dist=dict(dist), pos=pos, scale=scale).items(): ... |
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: end_loc = self.location.shift(angle).shift(direction).shift(direction) if position.is_square_e... |
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(): if bond._reactant != bond._product: adj[n].add(m) adj[m].add(n) center.add(n) center.add(m... |
return out |
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(): if bond._reactant != bond._product: nodes.add(n) nodes.add(m) return list(nodes... |
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 for j, bond in self._adj[i].items(): isnth = self._node[j].element != 'H' order = bond.order if o... |
(3, 4): if order == 4: hybridization = 4 elif order == 3: hybridization = 3 elif order == 2: if hybridization == 2: hybridization = 3 else: hybridization = 2 order = bond.p_order if order: if isnth: p_neighbors += 1 if p_hybridization not in (3, 4): if order == 4: p_hybridization = 4 elif order == 3: p_hybridization = ... |
2: if p_hybridization == 2: p_hybridization = 3 else: p_hybridization = 2 atom._reactant._neighbors = neighbors atom._reactant._hybridization = hybridization atom._product._neighbors = p_neighbors atom._product._hybridization = p_hybridization atom.__dict__.clear() # flush cache self.flush_cache() |
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 provides a read-only view of the original s... |
s |
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 seen.add(v) nextlevel.update(adj[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: token_type = os.getenv(TOKEN_TYPE_KEY, '') token_body = os.getenv(TOKEN_BO... |
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 in an attr is converted to string. * The value is sent as ... |
float, long, bool), otherwise we convert the value to string. """ buff = BytesIO() while True: msgs = list() try: msg = yield self.queue.get() # we need to connect first, as we issue verbosity request just after connection # and channels should strictly go in ascending order if not self._connected: yield self.connect()... |
= self.queue.get_nowait() except queues.QueueEmpty: pass try: yield self.pipe.write(buff.getvalue()) except Exception: pass # clean the buffer or we will end up without memory buff.truncate(0) except Exception: for message in msgs: self._log_to_fallback(message) |
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 = direction(current_square) except IndexError: return if self.contains_opposite_color_piece(current_squa... |
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`` partially overlaps with ``b`` * 'none' - ``a`` does... |
= a.min(), a.max() b1, b2 = b.min(), b.max() # Do the comparison if a1 >= b1 and a2 <= b2: result = 'full' elif a2 < b1 or b2 < a1: result = 'none' else: result = 'partial' return result |
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 exceptions.SynphotError('Integrated flux is <= 0') elif np.isnan... |
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 : array-like or `~astropy.units.quantity.Quantity` Wav... |
occurs in wavelength array. """ if isinstance(wavelengths, u.Quantity): units.validate_wave_unit(wavelengths.unit) wave = wavelengths.value else: wave = wavelengths if np.isscalar(wave): wave = [wave] wave = np.asarray(wave) # Check for zeroes if np.any(wave <= 0): raise exceptions.ZeroWavelength( 'Negative or zero wav... |
descending is allowed else: raise exceptions.UnsortedWavelength( 'Wavelength array is not monotonic', rows=np.where(sorted_wave != wave)[0]) # Check for duplicate values if wave.size > 1: dw = sorted_wave[1:] - sorted_wave[:-1] if np.any(dw == 0): raise exceptions.DuplicateWavelength( 'Wavelength array contains duplica... |
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 Lower and upper limits of the wavelengths. These must be values i... |
`None` Delta between wavelength values. When ``log=True``, this is the spacing in log space. log : bool If `True`, the wavelength values are evenly spaced in log scale. Otherwise, spacing is linear. wave_unit : str or `~astropy.units.core.Unit` Wavelength unit. Default is Angstrom. Returns ------- waveset : `~astropy.u... |
delta is not None: num = None waveset_str = 'Min: {0}, Max: {1}, Num: {2}, Delta: {3}, Log: {4}'.format( minwave, maxwave, num, delta, log) # Log space if log: logmin = np.log10(minwave) logmax = np.log10(maxwave) if delta is None: waveset = np.logspace(logmin, logmax, num, endpoint=False) else: waveset = 10 ** np.aran... |
maxwave, num, endpoint=False) else: waveset = np.arange(minwave, maxwave, delta) return waveset.astype(np.float64) * wave_unit, waveset_str |
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 problems down the li... |
``threshold``. If a small difference is present, the lower of the too-close pair is removed. Parameters ---------- waveset1, waveset2 : array-like or `None` Wavelength values, assumed to be in the same unit already. Also see :func:`~synphot.models.get_waveset`. threshold : float, optional Merged wavelength values are c... |
array-like or `None` Merged wavelengths. `None` if undefined. """ if waveset1 is None and waveset2 is None: out_wavelengths = None elif waveset1 is not None and waveset2 is None: out_wavelengths = waveset1 elif waveset1 is None and waveset2 is not None: out_wavelengths = waveset2 else: out_wavelengths = np.union1d(wave... |
duplicates if len(i_good[0]) < delta.size: out_wavelengths = np.append( out_wavelengths[i_good], out_wavelengths[-1]) return out_wavelengths |
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 screen. dry_run : bool Go through the log... |
without network calls. Use this option for debugging or testing. Raises ------ OSError Problem with directory. Returns ------- file_list : list of str A list of downloaded files. """ from .config import conf # Avoid potential circular import if not os.path.exists(cdbs_root): os.makedirs(cdbs_root, exist_ok=True) if ver... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.