code
stringlengths
1
18.2k
def list_user_participants(self, id, registration_status=None): """ List user participants. List users that are (or may be) participating in this appointment group. Refer to the Users API for the response fields. Returns no results for appointment groups with the "Group" participant_type. """ path = {} data = {} params...
def get_next_appointment(self, appointment_group_ids=None): """ Get next appointment. Return the next appointment available to sign up for. The appointment is returned in a one-element array. If no future appointments are available, an empty array is returned. """ path = {} data = {} params = {} # OPTIONAL - appointmen...
def to_funset(self, discrete): """ Converts the dataset to a set of `gringo.Fun`_ instances Parameters ---------- discrete : callable A discretization function Returns ------- set Representation of the dataset as a set of `gringo.Fun`_ instances .. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun """ fs = s...
def open_file(default_dir='~', extensions=None, title='Choose a file', multiple_files=False, directory=False): '''Start the native file dialog for opening file(s). Starts the system native file dialog in order to open a file (or multiple files). The toolkit used for each platform: +-------------------------------------...
etc. (virtually every Linux desktop has this). It depends on `PyGTK <https://pygtk.org>`_ for other desktops (not usually installed, so has a GTK+ 3 fallback). Args: default_dir (str) : The directory to start the dialog in. Default: User home directory. extensions (dict) : The extensions to filter by. Format: .. code-b...
'windows': pass # TODO: Implement Win32 file dialog elif system.get_name() == 'mac': pass # TODO: Implement Cocoa file dialog else: def gtk3_dialog(): # GTK+ 3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class FileChooserWindow(Gtk.Window): def __init__(self): self.path = '' Gtk.Window.__in...
FileChooserWindow(Qt.QWidget): def __init__(self): super().__init__() extensions_string = '' if extensions: for entry in extensions: # entry → Filter name (i.e. 'Image Files' etc) # value → Filter expression (i.e. '*.png, *.jpg' # etc) extensions_string += '%s (%s);;' % (entry, ' '.join(extensions[entry])) else: extens...
== gtk.RESPONSE_CANCEL: return None dialog.destroy() if system.get_name() in ['gnome', 'unity', 'cinnamon', 'pantheon']: return gtk3_dialog() elif system.get_name() in ['kde', 'lxqt']: try: return qt5_dialog() except ImportError: return gtk3_dialog() else: try: return gtk2_dialog() except ImportError: return gtk3_dialo...
def set_dump_directory(base=None, sub_dir=None): """Create directory for dumping SQL commands.""" # Set current timestamp timestamp = datetime.fromtimestamp(time()).strftime('%Y-%m-%d %H-%M-%S') # Clean sub_dir if sub_dir and '.' in sub_dir: sub_dir = sub_dir.rsplit('.', 1)[0] # Create a directory to save fail SQL scri...
def dump_commands(commands, directory=None, sub_dir=None): """ Dump SQL commands to .sql files. :param commands: List of SQL commands :param directory: Directory to dump commands to :param sub_dir: Sub directory :return: Directory failed commands were dumped to """ print('\t' + str(len(commands)), 'failed commands') # ...
: {0}'.format(timer.end), '\n\t\tMethod : (multiprocessing)\n\t\tDirectory : {0}'.format(dump_dir)) else: for tup in command_filepath: write_text_tup(tup) print('\tDumped ', len(command_filepath), 'commands\n\t\tTime : {0}'.format(timer.end), '\n\t\tMethod : (sequential)\n\t\tDirectory : {0}'.format(dump_dir)) # Return...
def write_text(_command, txt_file): """Dump SQL command to a text file.""" command = _command.strip() with open(txt_file, 'w') as txt: txt.writelines(command)
def get_commands_from_dir(directory, zip_backup=True, remove_dir=True): """Traverse a directory and read contained SQL files.""" # Get SQL commands file paths failed_scripts = sorted([os.path.join(directory, fn) for fn in os.listdir(directory) if fn.endswith('.sql')]) # Read each failed SQL file and append contents to ...
def blueprint(self): """ blueprint support, returns a partial dictionary """ blueprint = dict() blueprint['type'] = "%s.%s" % (self.__module__, self.__class__.__name__) # Fields fields = dict() # inspects the attributes of a parameter set and tries to validate the input for attribute_name, type_instance in self.getmemb...
def validate(self, request): """ validate method for %ParameterSet Since the introduction of ResponseFieldListParser, the parameter _response_field_list will be ignored, this is a prestans reserved parameter, and cannot be used by apps. :param request: The request object to be validated :type request: webob.request.Req...
not isinstance(type_instance.element_template, Float) and \ not isinstance(type_instance.element_template, Integer): raise TypeError("%s elements should be of \ type prestans.types.String/Integer/Float" % attribute_name) try: #: Get input from parameters #: Empty list returned if key is missing for getall if issubclass...
def _check_methods(cls, subclass): # pylint: disable=too-many-branches """ Args: cls(:py:class:`Plugin`): Parent class subclass(:py:class:`Plugin`): Subclass to evaluate Returns: Result: Named tuple Validate abstract methods are defined in subclass For error codes see _inspect_class """ for meth, methobj in cls.__abstr...
(%s)' % meth, 210) elif isinstance(methobj, staticmethod): if submethobj is UNDEFINED or not isinstance(submethobj, staticmethod): result = Result(False, 'Does not contain required static method (%s)' % meth, 211) elif PY26: # pragma: no cover if getfullargspec(methobj.__get__(True)) != \ getfullargspec(submethobj.__ge...
% meth, 213) elif getfullargspec(methobj) != getfullargspec(submethobj): result = Result(False, bad_arg_spec % meth, 220) # If it's not a type we're specifically checking, just check for existence elif submethobj is UNDEFINED: result = Result(False, 'Does not contain required attribute (%s)' % meth, 214) if result: ret...
def _inspect_class(cls, subclass): """ Args: cls(:py:class:`Plugin`): Parent class subclass(:py:class:`Plugin`): Subclass to evaluate Returns: Result: Named tuple Inspect subclass for inclusion Values for errorcode: * 0: No error Error codes between 0 and 100 are not intended for import * 50 Skipload flag is True Error...
subclass._skipload_: return Result(False, 'Skipload flag is True', 50) return _check_methods(cls, subclass)
def version(cls): # noqa: N805 # pylint: disable=no-self-argument """ :py:class:Returns `str` -- Returns :attr:`_version_` if set, otherwise falls back to module `__version__` or None """ return cls._version_ or getattr(sys.modules.get(cls.__module__, None), '__version__', None)
def preload_pages(): """Register all pages before the first application request.""" try: _add_url_rule([page.url for page in Page.query.all()]) except Exception: # pragma: no cover current_app.logger.warn('Pages were not loaded.') raise
def render_page(path): """Internal interface to the page view. :param path: Page path. :returns: The rendered template. """ try: page = Page.get_by_url(request.path) except NoResultFound: abort(404) return render_template( [page.template_name, current_app.config['PAGES_DEFAULT_TEMPLATE']], page=page)
def handle_not_found(exception, **extra): """Custom blueprint exception handler.""" assert isinstance(exception, NotFound) page = Page.query.filter(db.or_(Page.url == request.path, Page.url == request.path + "/")).first() if page: _add_url_rule(page.url) return render_template( [ page.template_name, current_app.config[...
def _add_url_rule(url_or_urls): """Register URL rule to application URL map.""" old = current_app._got_first_request # This is bit of cheating to overcome @flask.app.setupmethod decorator. current_app._got_first_request = False if isinstance(url_or_urls, six.string_types): url_or_urls = [url_or_urls] map(lambda url: cu...
def list_members_of_collaboration(self, id, include=None): """ List members of a collaboration. List the collaborators of a given collaboration """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - include """- "collaborator_lti_id": Optional information to include with each m...
def list_discussion_topics_courses(self, course_id, exclude_context_module_locked_topics=None, include=None, only_announcements=None, order_by=None, scope=None, search_term=None): """ List discussion topics. Returns the paginated list of discussion topics for this course or group. """ path = {} data = {} params = {} # ...
if topics are filtered. Can pass multiple states as comma separated string.""" if scope is not None: self._validate_enum(scope, ["locked", "unlocked", "pinned", "unpinned"]) params["scope"] = scope # OPTIONAL - only_announcements """Return announcements instead of discussion topics. Defaults to false""" if only_announc...
def create_new_discussion_topic_courses(self, course_id, allow_rating=None, assignment=None, attachment=None, delayed_post_at=None, discussion_type=None, group_category_id=None, is_announcement=None, lock_at=None, message=None, only_graders_can_rate=None, pinned=None, podcast_enabled=None, podcast_has_student_posts=Non...
"threaded"]) data["discussion_type"] = discussion_type # OPTIONAL - published """Whether this topic is published (true) or draft state (false). Only teachers and TAs have the ability to create draft state topics.""" if published is not None: data["published"] = published # OPTIONAL - delayed_post_at """If a timestamp i...
- podcast_has_student_posts """If true, the podcast will include posts from students as well. Implies podcast_enabled.""" if podcast_has_student_posts is not None: data["podcast_has_student_posts"] = podcast_has_student_posts # OPTIONAL - require_initial_post """If true then a user may not respond to other replies unti...
assignment # OPTIONAL - is_announcement """If true, this topic is an announcement. It will appear in the announcement's section rather than the discussions section. This requires announcment-posting permissions.""" if is_announcement is not None: data["is_announcement"] = is_announcement # OPTIONAL - pinned """If true,...
OPTIONAL - allow_rating """If true, users will be allowed to rate entries.""" if allow_rating is not None: data["allow_rating"] = allow_rating # OPTIONAL - only_graders_can_rate """If true, only graders will be allowed to rate entries.""" if only_graders_can_rate is not None: data["only_graders_can_rate"] = only_grader...
def delete_topic_groups(self, group_id, topic_id): """ Delete a topic. Deletes the discussion topic. This will also delete the assignment, if it's an assignment discussion. """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - PATH - topic_id """ID""" path["t...
def reorder_pinned_topics_courses(self, order, course_id): """ Reorder pinned topics. Puts the pinned discussion topics in the specified order. All pinned topics should be included. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - order """The ids of ...
def reorder_pinned_topics_groups(self, order, group_id): """ Reorder pinned topics. Puts the pinned discussion topics in the specified order. All pinned topics should be included. """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - order """The ids of the p...
def post_entry_courses(self, topic_id, course_id, attachment=None, message=None): """ Post an entry. Create a new entry in a discussion topic. Returns a json representation of the created entry (see documentation for 'entries' method) on success. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""...
def post_reply_groups(self, group_id, topic_id, entry_id, attachment=None, message=None): """ Post a reply. Add a reply to an entry in a discussion topic. Returns a json representation of the created reply (see documentation for 'replies' method) on success. May require (depending on the topic) that the user has posted...
# OPTIONAL - attachment """a multipart/form-data form-field-style attachment. Attachments larger than 1 kilobyte are subject to quota restrictions.""" if attachment is not None: data["attachment"] = attachment self.logger.debug("POST /api/v1/groups/{group_id}/discussion_topics/{topic_id}/entries/{entry_id}/replies with...
def rate_entry_courses(self, topic_id, entry_id, course_id, rating=None): """ Rate entry. Rate a discussion entry. On success, the response will be 204 No Content with an empty body. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - topic_id """...
def cli(**settings): """Notify about new reviews in AppStore and Google Play in slack. Launch command using supervisor or using screen/tmux/etc. Reviews are fetched for multiple apps and languages in --beat=300 interval. """ setup_logging(settings) settings = setup_languages(settings) channels = setup_channel_map(setti...
1000 * settings['beat'], loop) google_play.start() echo_channel_map(channels) if settings['ios']: app.poll_store('ios', notify=notify) if settings['android']: app.poll_store('android', notify=notify) if settings['stats']: port = int(settings['stats']) logger.debug('Serving metrics server on port %s' % port) start_http_...
def create_fa(self): """Create a FASTA file with extracted sequences. """ if self._seqs is None: os.symlink(self._fa0_fn, self._fa_fn) else: in_seqs = pyfaidx.Fasta(self._fa0_fn) with open(self._fa_fn, "w+") as g: for seq_desc in self._seqs: x = in_seqs[seq_desc] name, seq = x.name, str(x) g.write(">" + name + "\n") n ...
def recode_sam_reads( sam_fn, fastq_rnf_fo, fai_fo, genome_id, number_of_read_tuples=10**9, simulator_name=None, allow_unmapped=False, ): """Transform a SAM file to RNF-compatible FASTQ. Args: sam_fn (str): SAM/BAM file - file name. fastq_rnf_fo (str): Output FASTQ file - file object. fai_fo (str): FAI index of the ref...
"A", "C": "G", "G": "C", "N": "N", } read_tuple_id = 0 last_read_tuple_name = None with pysam.AlignmentFile( sam_fn, check_header=False, ) as samfile: for alignment in samfile: if alignment.query_name != last_read_tuple_name and last_read_tuple_name is not None: read_tuple_id += 1 last_read_tuple_name = alignment.query...
left - 1 for (steps, operation) in cigar_reg_shift.findall(alignment.cigarstring): right += int(steps) segment = rnftools.rnfformat.Segment( genome_id=genome_id, chr_id=chr_id, direction=direction, left=left, right=right, ) fq_creator.add_read( read_tuple_id=read_tuple_id, bases=bases, qualities=qualities, segments=[se...
def instantiate(config): """ instantiate all registered vodka applications Args: config (dict or MungeConfig): configuration object """ for handle, cfg in list(config["apps"].items()): if not cfg.get("enabled", True): continue app = get_application(handle) instances[app.handle] = app(cfg)
def compile_resource(resource): """ Return compiled regex for resource matching """ return re.compile("^" + trim_resource(re.sub(r":(\w+)", r"(?P<\1>[\w-]+?)", resource)) + r"(\?(?P<querystring>.*))?$")
def create_handler_func(self, method): """ create_handler_func """ def _handler(callback, schema=None): """ _handler """ # reentrant default is False [POST, DELETE, PUT] reentrant = False if method == "get": reentrant = True self.handlers.append({ "method": method, "callback": callback, "schema": schema, "reentrant": r...
def dispatch(self, message): """ dispatch """ handlers = [] for handler in self.handlers: if handler["method"] != message.method: continue handlers.append(handler) return handlers
def route(self, resource): """ route """ route = self.routes.get(resource, Route(resource)) self.routes.update({resource: route}) return route
def create_route_func(self, method): """ create_route_func """ def _route(resource, handler, schema=None): """ _route """ route = self.routes.get(resource, Route(resource)) route.__getattribute__(method)(handler, schema) self.routes.update({resource: route}) return self return _route
def dispatch(self, message): """ dispatch """ results = [] # match routes for resource, route in self.routes.items(): __message = message.match(route) if __message is None: continue route_result = route.dispatch(__message) if len(route_result) == 0: continue results.append({ "handlers": route_result, "message": __messa...
def handle(data_type, data, data_id=None, caller=None): """ execute all data handlers on the specified data according to data type Args: data_type (str): data type handle data (dict or list): data Kwargs: data_id (str): can be used to differentiate between different data sets of the same data type. If not specified wil...
inst: vodka.log.error("Data handler '%s' failed with error" % handler) vodka.log.error(traceback.format_exc()) return data
def validate_query(self, query): """Confirm query exists given common filters.""" if query is None: return query query = self.update_reading_list(query) return query
def get_validated_augment_query(self, augment_query=None): """ Common rules for reading list augmentation hierarchy. 1. Sponsored Content. 2. Video Content. """ augment_query = self.validate_query(augment_query) # Given an invalid query, reach for a Sponsored query. if not augment_query: augment_query = self.validate_q...
def augment_reading_list(self, primary_query, augment_query=None, reverse_negate=False): """Apply injected logic for slicing reading lists with additional content.""" primary_query = self.validate_query(primary_query) augment_query = self.get_validated_augment_query(augment_query=augment_query) try: # We use this for c...
def update_reading_list(self, reading_list): """Generic behaviors for reading lists before being rendered.""" # remove the current piece of content from the query. reading_list = reading_list.filter( ~es_filter.Ids(values=[self.id]) ) # remove excluded document types from the query. reading_list_config = getattr(settin...
def get_reading_list_context(self, **kwargs): """Returns the context dictionary for a given reading list.""" reading_list = None context = { "name": "", "content": reading_list, "targeting": {}, "videos": [] } if self.reading_list_identifier == "popular": reading_list = popular_content() context.update({"name": self.re...
"content": reading_list }) return context
def read_file(cls, path): """Reads file at path and returns dict with separated frontmatter. See read() for more info on dict return value. """ with open(path, encoding="utf-8") as file: file_contents = file.read() return cls.read(file_contents)
def read(cls, string): """Returns dict with separated frontmatter from string. Returned dict keys: attributes -- extracted YAML attributes in dict form. body -- string contents below the YAML separators frontmatter -- string representation of YAML """ fmatter = "" body = "" result = cls._regex.search(string) if result:...
def run_suite(case, config, summary): """ Run the full suite of performance tests """ config["name"] = case timing_data = dict() model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case) plot_dir = os.path.join(livvkit.output_dir, "perfor...
"_weak_scaling.png") ), weak_scaling_efficiency_plot(weak_data, "Weak scaling efficiency for " + case.capitalize(), "Parallel efficiency (% of linear)", "", os.path.join(plot_dir, case + "_weak_scaling_efficiency.png") ), generate_scaling_plot(strong_data, "Strong scaling for " + case.capitalize(), "Runtime (s)", "", o...
def _analyze_case(model_dir, bench_dir, config): """ Generates statistics from the timing summaries """ model_timings = set(glob.glob(os.path.join(model_dir, "*" + config["timing_ext"]))) if bench_dir is not None: bench_timings = set(glob.glob(os.path.join(bench_dir, "*" + config["timing_ext"]))) else: bench_timings = ...
def _print_result(case, summary): """ Show some statistics from the run """ for case, case_data in summary.items(): for dof, data in case_data.items(): print(" " + case + " " + dof) print(" -------------------") for header, val in data.items(): print(" " + header + " : " + str(val)) print("")
def _summarize_result(result, config): """ Trim out some data to return for the index page """ timing_var = config['scaling_var'] summary = LIVVDict() for size, res in result.items(): proc_counts = [] bench_times = [] model_times = [] for proc, data in res.items(): proc_counts.append(int(proc[1:])) try: bench_times.app...
def generate_timing_stats(file_list, var_list): """ Parse all of the timing files, and generate some statistics about the run. Args: file_list: A list of timing files to parse var_list: A list of variables to look for in the timing file Returns: A dict containing values that have the form: [mean, min, max, mean, standa...
def weak_scaling(timing_stats, scaling_var, data_points): """ Generate data for plotting weak scaling. The data points keep a constant amount of work per processor for each data point. Args: timing_stats: the result of the generate_timing_stats function scaling_var: the variable to select from the timing_stats dictiona...
[] for point in data_points: size = point[0] proc = point[1] try: model_data = timing_stats[size][proc]['model'][scaling_var] bench_data = timing_stats[size][proc]['bench'][scaling_var] except KeyError: continue proc_counts.append(proc) model_means.append(model_data['mean']) model_mins.append(model_data['min']) model_m...
def generate_scaling_plot(timing_data, title, ylabel, description, plot_file): """ Generate a scaling plot. Args: timing_data: data returned from a `*_scaling` method title: the title of the plot ylabel: the y-axis label of the plot description: a description of the plot plot_file: the file to write out to Returns: an ...
the") plt.text(0.0, 0.36, "performance option enabled.") if livvkit.publish: plt.savefig(os.path.splitext(plot_file)[0]+'.eps', dpi=600) plt.savefig(plot_file) plt.close() return elements.image(title, description, os.path.basename(plot_file))
def generate_timing_breakdown_plot(timing_stats, scaling_var, title, description, plot_file): """ Description Args: timing_stats: a dictionary of the form {proc_count : {model||bench : { var : { stat : val }}}} scaling_var: the variable that accounts for the total runtime title: the title of the plot description: the d...
case == 'bench': bar_num = 2 else: bar_num = 1 offset = 0 if var_data != {}: for var in sorted(six.iterkeys(var_data), reverse=True): if var != scaling_var: plt.bar(bar_num, var_data[var]['mean'], 0.8, bottom=offset, color=colors[var], label=(var if bar_num == 1 else '_none')) offset += var_data[var]['mean'] plt.bar(ba...
def add_source(self, ra, dec, flag='', radius=10*q.arcsec): """ Add a source to the catalog manually and find data in existing catalogs Parameters ---------- ra: astropy.units.quantity.Quantity The RA of the source dec: astropy.units.quantity.Quantity The Dec of the source flag: str A flag for the source radius: float ...
def delete_source(self, id): """ Delete a source from the catalog Parameters ---------- id: int The id of the source in the catalog """ # Set the index self.catalog.set_index('id') # Exclude the unwanted source self.catalog = self.catalog[self.catalog.id!=id] # Remove the records from the catalogs for cat_name in self....
def ingest_data(self, data, cat_name, id_col, ra_col='_RAJ2000', dec_col='_DEJ2000', cat_loc='', append=False, count=-1): """ Ingest a data file and regroup sources Parameters ---------- data: str, pandas.DataFrame, astropy.table.Table The path to the exported VizieR data or the data table cat_name: str The name of the...
cat_loc or data data = pd.read_csv(data, sep='\t', comment='#', engine='python')[:count] elif isinstance(data, pd.core.frame.DataFrame): cat_loc = cat_loc or type(data) elif isinstance(data, (at.QTable, at.Table)): cat_loc = cat_loc or type(data) data = pd.DataFrame(list(data), columns=data.colnames) else: print("Sorry...
the raw data as an attribute if append: setattr(self, cat_name, getattr(self, cat_name).append(data, ignore_index=True)) else: setattr(self, cat_name, data) # Update the history self.history += "\n{}: Catalog {} ingested.".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),cat_name) self.catalogs.update({cat_...
def inventory(self, source_id): """ Look at the inventory for a given source Parameters ---------- source_id: int The id of the source to inspect """ if self.n_sources==0: print('Please run group_sources() to create the catalog first.') else: if source_id>self.n_sources or source_id<1 or not isinstance(source_id, int):...
def _catalog_check(self, cat_name, append=False): """ Check to see if the name of the ingested catalog is valid Parameters ---------- cat_name: str The name of the catalog in the Catalog object append: bool Append the catalog rather than replace Returns ------- bool True if good catalog name else False """ good = True ...
def SDSS_spectra_query(self, cat_name, ra, dec, radius, group=True, **kwargs): """ Use astroquery to search SDSS for sources within a search cone Parameters ---------- cat_name: str A name for the imported catalog (e.g. '2MASS') ra: astropy.units.quantity.Quantity The RA of the center of the cone search dec: astropy.un...
data self.ingest_data(data, cat_name, 'id', ra_col=ra_col, dec_col=dec_col) # Regroup if len(self.catalogs)>1 and group: self.group_sources(self.xmatch_radius)
def Vizier_query(self, viz_cat, cat_name, ra, dec, radius, ra_col='RAJ2000', dec_col='DEJ2000', columns=["**"], append=False, group=True, **kwargs): """ Use astroquery to search a catalog for sources within a search cone Parameters ---------- viz_cat: str The catalog string from Vizier (e.g. 'II/246' for 2MASS PSC) cat...
self._catalog_check(cat_name, append=append): # Cone search Vizier print("Searching {} for sources within {} of ({}, {}). Please be patient...".format(viz_cat, radius, ra, dec)) crds = coord.SkyCoord(ra=ra, dec=dec, frame='icrs') V = Vizier(columns=columns, **kwargs) V.ROW_LIMIT = -1 try: data = V.query_region(crds, ra...
def Vizier_xmatch(self, viz_cat, cat_name, ra_col='_RAJ2000', dec_col='_DEJ2000', radius='', group=True): """ Use astroquery to pull in and cross match a catalog with sources in self.catalog Parameters ---------- viz_cat: str The catalog string from Vizier (e.g. 'II/246' for 2MASS PSC) cat_name: str A name for the impo...
self.group_sources(self.xmatch_radius)
def group_sources(self, radius='', plot=False): """ Calculate the centers of the point clusters given the radius and minimum number of points Parameters ---------- coords: array-like The list of (x,y) coordinates of all clicks radius: int The distance threshold in degrees for cluster membership [default of 0.36 arcseco...
= DBSCAN(eps=self.xmatch_radius, min_samples=1, n_jobs=-1).fit(coords) # Group the sources core_samples_mask = np.zeros_like(db.labels_, dtype=bool) core_samples_mask[db.core_sample_indices_] = True source_ids = db.labels_+1 unique_source_ids = list(set(source_ids)) self.n_sources = len(unique_source_ids) # Get the ave...
cat_source_ids setattr(self, cat_name, cat) del cat, cat_source_ids del cats # Plot it if plot: plt.figure() plt.title('{} clusters for {} sources'.format(self.n_sources,len(coords))) colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, self.n_sources)] for k, col in zip(unique_source_ids, colors): class_membe...
def drop_catalog(self, cat_name): """ Remove an imported catalog from the Dataset object Parameters ---------- cat_name: str The name given to the catalog """ # Delete the name and data self.catalogs.pop(cat_name) delattr(self, cat_name) # Update history print("Deleted {} catalog.".format(cat_name)) self.history += "\n...
def load(self, path): """ Load the catalog from file Parameters ---------- path: str The path to the file """ # Get the object DB = joblib.load(path) # Load the attributes self.catalog = DB.catalog self.n_sources = DB.n_sources self.name = DB.name self.history = DB.history del DB
def correct_offsets(self, cat_name, truth='ACS'): """ Function to determine systematic, linear offsets between catalogs FUTURE -- do this with TweakReg, which also accounts for rotation/scaling See thread at https://github.com/spacetelescope/drizzlepac/issues/77 Parameters ---------- cat_name: str Name of catalog to co...
SkyCoord(o2o_old.loc[o2o_old['cat_name'] == truth, 'ra_corr'],\ o2o_old.loc[o2o_old['cat_name'] == truth, 'dec_corr'], unit='degree') print(len(c_o2o_old), 'one-to-one matches found!') if len(c_o2o_old)>0: delta_ra = [] delta_dec = [] for i in range(len(c_o2o_old)): # offsets FROM ACS TO new catalog ri, di = c_o2o_old[...
have moved self.group_sources(self.xmatch_radius) else: print('Cannot correct offsets in {} sources.'.format(cat_name))
def jinja_env(self): """Create a sandboxed Jinja environment.""" if self._jinja_env is None: self._jinja_env = SandboxedEnvironment( extensions=[ 'jinja2.ext.autoescape', 'jinja2.ext.with_', ], autoescape=True, ) self._jinja_env.globals['url_for'] = url_for # Load whitelisted configuration variables. for var in self.ap...
def render_template(self, source, **kwargs_context): r"""Render a template string using sandboxed environment. :param source: A string containing the page source. :param \*\*kwargs_context: The context associated with the page. :returns: The rendered template. """ return self.jinja_env.from_string(source).render(kwargs...
def wrap_errorhandler(app): """Wrap error handler. :param app: The Flask application. """ try: existing_handler = app.error_handler_spec[None][404][NotFound] except (KeyError, TypeError): existing_handler = None if existing_handler: app.error_handler_spec[None][404][NotFound] = \ lambda error: handle_not_found(error, w...