_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q258600
DeploySatchel.manifest_filename
validation
def manifest_filename(self): """ Returns the path to the manifest file. """ r
python
{ "resource": "" }
q258601
DeploySatchel.get_current_thumbprint
validation
def get_current_thumbprint(self, components=None): """ Returns a dictionary representing the current configuration state. Thumbprint is of the form: { component_name1: {key: value}, component_name2: {key: value}, ... } """ components = str_to_component_list(components) if self.verbose: print('deploy.get_current_thumbprint.components:', components) manifest_data = {} # {component:data} for component_name, func in sorted(manifest_recorder.items()):
python
{ "resource": "" }
q258602
DeploySatchel.get_previous_thumbprint
validation
def get_previous_thumbprint(self, components=None): """ Returns a dictionary representing the previous configuration state. Thumbprint is of the form: { component_name1: {key: value}, component_name2: {key: value}, ... } """ components = str_to_component_list(components) tp_fn = self.manifest_filename tp_text = None if self.file_exists(tp_fn): fd = six.BytesIO() get(tp_fn, fd) tp_text = fd.getvalue()
python
{ "resource": "" }
q258603
DeploySatchel.lock
validation
def lock(self): """ Marks the remote server as currently being deployed to. """ self.init() r = self.local_renderer if self.file_exists(r.env.lockfile_path): raise exceptions.AbortDeployment('Lock file %s exists. Perhaps another deployment is currently underway?' % r.env.lockfile_path) else:
python
{ "resource": "" }
q258604
DeploySatchel.unlock
validation
def unlock(self): """ Unmarks the remote server as currently being deployed to. """ self.init()
python
{ "resource": "" }
q258605
DeploySatchel.fake
validation
def fake(self, components=None):#, set_satchels=None): """ Update the thumbprint on the remote server but execute no satchel configurators. components = A comma-delimited list of satchel names to limit the fake deployment to. set_satchels = A semi-colon delimited list of key-value pairs to set in satchels before recording a fake deployment. """ self.init() # In cases where we only want to fake deployment of a specific satchel, then simply copy the last thumbprint and overwrite with a subset # of the current thumbprint filtered by our target components. if components: current_tp = self.get_previous_thumbprint() or {} current_tp.update(self.get_current_thumbprint(components=components)
python
{ "resource": "" }
q258606
DeploySatchel.get_component_funcs
validation
def get_component_funcs(self, components=None): """ Calculates the components functions that need to be executed for a deployment. """ current_tp = self.get_current_thumbprint(components=components) or {} previous_tp = self.get_previous_thumbprint(components=components) or {} if self.verbose: print('Current thumbprint:') pprint(current_tp, indent=4) print('Previous thumbprint:') pprint(previous_tp, indent=4) differences = list(iter_dict_differences(current_tp, previous_tp)) if self.verbose: print('Differences:')
python
{ "resource": "" }
q258607
DeploySatchel.preview
validation
def preview(self, components=None, ask=0): """ Inspects differences between the last deployment and the current code state. """ ask = int(ask) self.init() component_order, plan_funcs = self.get_component_funcs(components=components) print('\n%i changes found for host %s.\n' % (len(component_order), self.genv.host_string)) if component_order and plan_funcs: if self.verbose: print('These components have changed:\n') for component in sorted(component_order): print((' '*4)+component)
python
{ "resource": "" }
q258608
DeploySatchel.push
validation
def push(self, components=None, yes=0): """ Executes all satchel configurators to apply pending changes to the server. """ from burlap import notifier service = self.get_satchel('service') self.lock() try: yes = int(yes) if not yes: # If we want to confirm the deployment with the user, and we're at the first server, # then run the preview. if self.genv.host_string == self.genv.hosts[0]: execute(partial(self.preview, components=components, ask=1)) notifier.notify_pre_deployment()
python
{ "resource": "" }
q258609
DjangoSatchel.get_settings
validation
def get_settings(self, site=None, role=None): """ Retrieves the Django settings dictionary. """ r = self.local_renderer _stdout = sys.stdout _stderr = sys.stderr if not self.verbose: sys.stdout = StringIO() sys.stderr = StringIO() try: sys.path.insert(0, r.env.src_dir) # Temporarily override SITE. tmp_site = self.genv.SITE if site and site.endswith('_secure'): site = site[:-7] site = site or self.genv.SITE or self.genv.default_site self.set_site(site) # Temporarily override ROLE. tmp_role = self.genv.ROLE if role: self.set_role(role) try: # We need to explicitly delete sub-modules from sys.modules. Otherwise, reload() skips # them and they'll continue to contain obsolete settings. if r.env.delete_module_with_prefixes: for name in sorted(sys.modules): for prefix in r.env.delete_module_with_prefixes: if name.startswith(prefix): if self.verbose: print('Deleting module %s prior to re-import.' % name) del sys.modules[name] break for name in list(sys.modules): for s in r.env.delete_module_containing: if s in name: del sys.modules[name] break if r.env.settings_module in sys.modules: del sys.modules[r.env.settings_module] #TODO:fix r.env.settings_module not loading from settings? # print('r.genv.django_settings_module:', r.genv.django_settings_module, file=_stdout) # print('r.genv.dj_settings_module:', r.genv.dj_settings_module, file=_stdout) # print('r.env.settings_module:', r.env.settings_module, file=_stdout)
python
{ "resource": "" }
q258610
DjangoSatchel.createsuperuser
validation
def createsuperuser(self, username='admin', email=None, password=None, site=None): """ Runs the Django createsuperuser management command. """ r = self.local_renderer site = site or self.genv.SITE self.set_site_specifics(site) options = ['--username=%s' % username] if email: options.append('--email=%s' % email) if password: options.append('--password=%s' % password) r.env.options_str = ' '.join(options) if
python
{ "resource": "" }
q258611
DjangoSatchel.loaddata
validation
def loaddata(self, path, site=None): """ Runs the Dango loaddata management command. By default, runs on only the current site. Pass site=all to run on all sites. """ site = site or self.genv.SITE r = self.local_renderer r.env._loaddata_path = path for _site, site_data in self.iter_sites(site=site, no_secure=True): try: self.set_db(site=_site) r.env.SITE = _site
python
{ "resource": "" }
q258612
DjangoSatchel.manage
validation
def manage(self, cmd, *args, **kwargs): """ A generic wrapper around Django's manage command. """ r = self.local_renderer environs = kwargs.pop('environs', '').strip() if environs: environs = ' '.join('export %s=%s;' % tuple(_.split('=')) for _ in environs.split(',')) environs = ' ' + environs + ' ' r.env.cmd = cmd r.env.SITE = r.genv.SITE or r.genv.default_site r.env.args = ' '.join(map(str, args)) r.env.kwargs = ' '.join( ('--%s' % _k if _v in (True, 'True')
python
{ "resource": "" }
q258613
DjangoSatchel.load_django_settings
validation
def load_django_settings(self): """ Loads Django settings for the current site and sets them so Django internals can be run. """ r = self.local_renderer # Save environment variables so we can restore them later. _env = {} save_vars = ['ALLOW_CELERY', 'DJANGO_SETTINGS_MODULE'] for var_name in save_vars: _env[var_name] = os.environ.get(var_name) try: # Allow us to import local app modules. if r.env.local_project_dir: sys.path.insert(0, r.env.local_project_dir) #TODO:remove this once bug in django-celery has been fixed os.environ['ALLOW_CELERY'] = '0' # print('settings_module:', r.format(r.env.settings_module)) os.environ['DJANGO_SETTINGS_MODULE'] = r.format(r.env.settings_module) # os.environ['CELERY_LOADER'] = 'django' # os.environ['SITE'] = r.genv.SITE or r.genv.default_site # os.environ['ROLE'] = r.genv.ROLE or r.genv.default_role # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet # Disabling, in Django >= 1.10, throws exception: # RuntimeError: Model class django.contrib.contenttypes.models.ContentType # doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. # try: # from django.core.wsgi import get_wsgi_application # application = get_wsgi_application() # except (ImportError, RuntimeError): # raise # print('Unable to get wsgi application.') # traceback.print_exc() # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet try: import django django.setup() except AttributeError: # This doesn't exist in Django < 1.7, so ignore it.
python
{ "resource": "" }
q258614
DjangoSatchel.shell
validation
def shell(self): """ Opens a Django focussed Python shell. Essentially the equivalent of running `manage.py shell`. """ r = self.local_renderer if '@' in self.genv.host_string: r.env.shell_host_string = self.genv.host_string else: r.env.shell_host_string = '{user}@{host_string}' r.env.shell_default_dir =
python
{ "resource": "" }
q258615
DjangoSatchel.syncdb
validation
def syncdb(self, site=None, all=0, database=None, ignore_errors=1): # pylint: disable=redefined-builtin """ Runs the standard Django syncdb command for one or more sites. """ r = self.local_renderer ignore_errors = int(ignore_errors) post_south = self.version_tuple >= (1, 7, 0) use_run_syncdb = self.version_tuple >= (1, 9, 0) # DEPRECATED: removed in Django>=1.7 r.env.db_syncdb_all_flag = '--all' if int(all) else '' r.env.db_syncdb_database = '' if database: r.env.db_syncdb_database = ' --database=%s' % database if self.is_local: r.env.project_dir = r.env.local_project_dir site = site or self.genv.SITE for _site, site_data in r.iter_unique_databases(site=site): r.env.SITE = _site with self.settings(warn_only=ignore_errors): if post_south: if use_run_syncdb: r.run_or_local( 'export SITE={SITE};
python
{ "resource": "" }
q258616
DjangoSatchel.manage_async
validation
def manage_async(self, command='', name='process', site=ALL, exclude_sites='', end_message='', recipients=''): """ Starts a Django management command in a screen. Parameters: command :- all arguments passed to `./manage` as a single string site :- the site to run the command for (default is all) Designed to be ran like: fab <role> dj.manage_async:"some_management_command --force" """ exclude_sites = exclude_sites.split(':') r = self.local_renderer for _site, site_data in self.iter_sites(site=site, no_secure=True): if _site in exclude_sites: continue r.env.SITE = _site r.env.command = command r.env.end_email_command = '' r.env.recipients = recipients or '' r.env.end_email_command = '' if end_message: end_message = end_message + '
python
{ "resource": "" }
q258617
DjangoSatchel.get_media_timestamp
validation
def get_media_timestamp(self, last_timestamp=None): """ Retrieves the most recent timestamp of the media in the static root. If last_timestamp is given, retrieves the first timestamp more recent than this value. """ r = self.local_renderer _latest_timestamp = -1e9999999999999999 for path in self.iter_static_paths(): path = r.env.static_root + '/' + path self.vprint('checking timestamp of path:', path) if not os.path.isfile(path): continue
python
{ "resource": "" }
q258618
DatabaseSatchel.set_root_login
validation
def set_root_login(self, r): """ Looks up the root login for the given database on the given host and sets it to environment variables. Populates these standard variables: db_root_password db_root_username """ # Check the legacy password location. try: r.env.db_root_username = r.env.root_username except AttributeError: pass try: r.env.db_root_password = r.env.root_password except AttributeError: pass
python
{ "resource": "" }
q258619
DatabaseSatchel.database_renderer
validation
def database_renderer(self, name=None, site=None, role=None): """ Renders local settings for a specific database. """ name = name or self.env.default_db_name site = site or self.genv.SITE role = role or self.genv.ROLE key = (name, site, role) self.vprint('checking key:', key) if key not in self._database_renderers: self.vprint('No cached db renderer, generating...') if self.verbose: print('db.name:', name) print('db.databases:', self.env.databases) print('db.databases[%s]:' % name, self.env.databases.get(name)) d = type(self.genv)(self.lenv) d.update(self.get_database_defaults()) d.update(self.env.databases.get(name, {})) d['db_name'] = name if self.verbose: print('db.d:') pprint(d, indent=4) print('db.connection_handler:', d.connection_handler) if d.connection_handler == CONNECTION_HANDLER_DJANGO: self.vprint('Using django handler...') dj = self.get_satchel('dj') if self.verbose: print('Loading Django DB settings for site {} and role {}.'.format(site, role), file=sys.stderr) dj.set_db(name=name, site=site, role=role) _d = dj.local_renderer.collect_genv(include_local=True, include_global=False) # Copy "dj_db_*" into "db_*". for k, v in _d.items(): if k.startswith('dj_db_'): _d[k[3:]] = v del _d[k] if self.verbose: print('Loaded:')
python
{ "resource": "" }
q258620
DatabaseSatchel.get_free_space
validation
def get_free_space(self): """ Return free space in bytes. """ cmd = "df -k | grep -vE '^Filesystem|tmpfs|cdrom|none|udev|cgroup' | awk '{ print($1 \" \" $4 }'" lines = [_
python
{ "resource": "" }
q258621
DatabaseSatchel.load_db_set
validation
def load_db_set(self, name, r=None): """ Loads database parameters from a specific
python
{ "resource": "" }
q258622
DatabaseSatchel.loadable
validation
def loadable(self, src, dst): """ Determines if there's enough space to load the target database. """ from fabric import state from fabric.task_utils import crawl src_task = crawl(src, state.commands) assert src_task, 'Unknown source role: %s' % src dst_task = crawl(dst, state.commands) assert dst_task, 'Unknown destination role: %s' % src # Get source database size. src_task() env.host_string = env.hosts[0] src_size_bytes = self.get_size() # Get target database size, if any. dst_task() env.host_string = env.hosts[0]
python
{ "resource": "" }
q258623
RaspberryPiSatchel.assume_localhost
validation
def assume_localhost(self): """ Sets connection parameters to localhost, if not set already. """ if not self.genv.host_string:
python
{ "resource": "" }
q258624
RaspberryPiSatchel.init_raspbian_disk
validation
def init_raspbian_disk(self, yes=0): """ Downloads the latest Raspbian image and writes it to a microSD card. Based on the instructions from: https://www.raspberrypi.org/documentation/installation/installing-images/linux.md """ self.assume_localhost() yes = int(yes) device_question = 'SD card present at %s? ' % self.env.sd_device if not yes and not raw_input(device_question).lower().startswith('y'): return r = self.local_renderer r.local_if_missing( fn='{raspbian_image_zip}', cmd='wget {raspbian_download_url} -O raspbian_lite_latest.zip') r.lenv.img_fn = \ r.local("unzip -l {raspbian_image_zip} | sed -n 4p | awk '{{print $4}}'", capture=True) or '$IMG_FN' r.local('echo {img_fn}') r.local('[
python
{ "resource": "" }
q258625
RaspberryPiSatchel.init_ubuntu_disk
validation
def init_ubuntu_disk(self, yes=0): """ Downloads the latest Ubuntu image and writes it to a microSD card. Based on the instructions from: https://wiki.ubuntu.com/ARM/RaspberryPi For recommended SD card brands, see: http://elinux.org/RPi_SD_cards Note, if you get an error like: Kernel panic-not syncing: VFS: unable to mount root fs that means the SD card is corrupted. Try re-imaging the card or use a different card. """ self.assume_localhost() yes = int(yes) if not self.dryrun: device_question = 'SD card present at %s? ' % self.env.sd_device
python
{ "resource": "" }
q258626
RaspberryPiSatchel.init_raspbian_vm
validation
def init_raspbian_vm(self): """ Creates an image for running Raspbian in a QEMU virtual machine. Based on the guide at: https://github.com/dhruvvyas90/qemu-rpi-kernel/wiki/Emulating-Jessie-image-with-4.1.x-kernel """ r = self.local_renderer r.comment('Installing system packages.') r.sudo('add-apt-repository ppa:linaro-maintainers/tools') r.sudo('apt-get update') r.sudo('apt-get install libsdl-dev qemu-system') r.comment('Download image.') r.local('wget https://downloads.raspberrypi.org/raspbian_lite_latest') r.local('unzip raspbian_lite_latest.zip') #TODO:fix name? #TODO:resize image? r.comment('Find start of the Linux ext4 partition.') r.local( "parted -s 2016-03-18-raspbian-jessie-lite.img unit B print | "
python
{ "resource": "" }
q258627
RaspberryPiSatchel.create_raspbian_vagrant_box
validation
def create_raspbian_vagrant_box(self): """ Creates a box for easily spinning up a virtual machine with Vagrant. http://unix.stackexchange.com/a/222907/16477 https://github.com/pradels/vagrant-libvirt """ r = self.local_renderer r.sudo('adduser --disabled-password --gecos "" vagrant') #vagrant user should be able to run sudo commands without a password prompt r.sudo('echo "vagrant ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/vagrant') r.sudo('chmod 0440 /etc/sudoers.d/vagrant') r.sudo('apt-get update') r.sudo('apt-get install -y openssh-server') #put ssh key from vagrant user r.sudo('mkdir -p /home/vagrant/.ssh') r.sudo('chmod 0700 /home/vagrant/.ssh') r.sudo('wget --no-check-certificate https://raw.github.com/mitchellh/vagrant/master/keys/vagrant.pub -O /home/vagrant/.ssh/authorized_keys') r.sudo('chmod 0600 /home/vagrant/.ssh/authorized_keys') r.sudo('chown -R vagrant /home/vagrant/.ssh') #open sudo vi /etc/ssh/sshd_config and change #PubKeyAuthentication yes #PermitEmptyPasswords no r.sudo("sed -i '/AuthorizedKeysFile/s/^#//g' /etc/ssh/sshd_config") #PasswordAuthentication no r.sudo("sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/sshd_config") r.sudo("sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config") #restart ssh service using #sudo service ssh restart #install additional development packages for the tools to properly compile and install r.sudo('apt-get upgrade') r.sudo('apt-get install -y gcc build-essential') #TODO:fix? throws dpkg: error: fgets gave an empty string from `/var/lib/dpkg/triggers/File' #r.sudo('apt-get install -y linux-headers-rpi') #do any change that you want and shutdown the
python
{ "resource": "" }
q258628
RaspberryPiSatchel.configure_hdmi
validation
def configure_hdmi(self): """ Configures HDMI to support hot-plugging, so it'll work even if it wasn't plugged in when the Pi was originally powered up. Note, this does cause slightly higher power consumption, so if you don't need HDMI, don't bother with this. http://raspberrypi.stackexchange.com/a/2171/29103 """ r = self.local_renderer # use HDMI mode even if no HDMI monitor is detected r.enable_attr( filename='/boot/config.txt', key='hdmi_force_hotplug', value=1,
python
{ "resource": "" }
q258629
RaspberryPiSatchel.configure_camera
validation
def configure_camera(self): """ Enables access to the camera. http://raspberrypi.stackexchange.com/questions/14229/how-can-i-enable-the-camera-without-using-raspi-config https://mike632t.wordpress.com/2014/06/26/raspberry-pi-camera-setup/ Afterwards, test with: /opt/vc/bin/raspistill --nopreview --output image.jpg Check for compatibility with: vcgencmd get_camera which should show: supported=1 detected=1 """ #TODO:check per OS? Works on Raspbian Jessie r = self.local_renderer if self.env.camera_enabled: r.pc('Enabling camera.') #TODO:fix, doesn't work on Ubuntu, which uses commented-out values # Set start_x=1 #r.sudo('if grep "start_x=0" /boot/config.txt; then sed -i "s/start_x=0/start_x=1/g" /boot/config.txt; fi') #r.sudo('if grep "start_x" /boot/config.txt; then true; else echo "start_x=1" >> /boot/config.txt; fi') r.enable_attr( filename='/boot/config.txt', key='start_x', value=1, use_sudo=True,
python
{ "resource": "" }
q258630
RaspberryPiSatchel.fix_lsmod_for_pi3
validation
def fix_lsmod_for_pi3(self): """ Some images purporting to support both the Pi2 and Pi3 use the wrong kernel modules. """ r =
python
{ "resource": "" }
q258631
ServiceManagementSatchel.pre_deploy
validation
def pre_deploy(self): """ Runs methods services have requested be run before each deployment. """ for service in self.genv.services: service = service.strip().upper() funcs = common.service_pre_deployers.get(service) if funcs:
python
{ "resource": "" }
q258632
ServiceManagementSatchel.deploy
validation
def deploy(self): """ Applies routine, typically application-level changes to the service. """ for service in self.genv.services: service = service.strip().upper() funcs = common.service_deployers.get(service) if funcs:
python
{ "resource": "" }
q258633
ServiceManagementSatchel.post_deploy
validation
def post_deploy(self): """ Runs methods services have requested be run before after deployment. """ for service in self.genv.services: service = service.strip().upper() self.vprint('post_deploy:', service) funcs = common.service_post_deployers.get(service) if funcs: self.vprint('Running post-deployments for service %s...' % (service,)) for func in funcs:
python
{ "resource": "" }
q258634
ServiceManagementSatchel.configure
validation
def configure(self): """ Applies one-time settings changes to the host, usually to initialize the service. """ print('env.services:', self.genv.services) for service in list(self.genv.services): service = service.strip().upper()
python
{ "resource": "" }
q258635
ApacheSatchel.enable_mods
validation
def enable_mods(self): """ Enables all modules in the current module list. Does not disable any currently enabled modules not in the list. """ r = self.local_renderer for mod_name in
python
{ "resource": "" }
q258636
ApacheSatchel.optimize_wsgi_processes
validation
def optimize_wsgi_processes(self): """ Based on the number of sites per server and the number of resources on the server, calculates the optimal number of processes that should be allocated for each WSGI site. """ r = self.local_renderer
python
{ "resource": "" }
q258637
ApacheSatchel.create_local_renderer
validation
def create_local_renderer(self): """ Instantiates a new local renderer. Override this to do any additional initialization. """ r = super(ApacheSatchel, self).create_local_renderer() # Dynamically set values based on target operating
python
{ "resource": "" }
q258638
ApacheSatchel.install_auth_basic_user_file
validation
def install_auth_basic_user_file(self, site=None): """ Installs users for basic httpd auth. """ r = self.local_renderer hostname = self.current_hostname target_sites = self.genv.available_sites_by_host.get(hostname, None) for _site, site_data in self.iter_sites(site=site, setter=self.set_site_specifics): if self.verbose: print('~'*80, file=sys.stderr) print('Site:', _site, file=sys.stderr) print('env.apache_auth_basic:', r.env.auth_basic, file=sys.stderr) # Only load site configurations that are allowed for this host. if target_sites is not None: assert isinstance(target_sites, (tuple, list)) if _site not in target_sites: continue if not r.env.auth_basic: continue assert r.env.auth_basic_users, 'No apache auth users specified.'
python
{ "resource": "" }
q258639
ApacheSatchel.sync_media
validation
def sync_media(self, sync_set=None, clean=0, iter_local_paths=0): """ Uploads select media to an Apache accessible directory. """ # Ensure a site is selected. self.genv.SITE = self.genv.SITE or self.genv.default_site r = self.local_renderer clean = int(clean) self.vprint('Getting site data for %s...' % self.genv.SITE) self.set_site_specifics(self.genv.SITE) sync_sets = r.env.sync_sets if sync_set: sync_sets = [sync_set] ret_paths = [] for _sync_set in sync_sets: for paths in r.env.sync_sets[_sync_set]: r.env.sync_local_path = os.path.abspath(paths['local_path'] % self.genv) if paths['local_path'].endswith('/') and not r.env.sync_local_path.endswith('/'): r.env.sync_local_path += '/' if iter_local_paths: ret_paths.append(r.env.sync_local_path) continue r.env.sync_remote_path = paths['remote_path'] % self.genv if clean:
python
{ "resource": "" }
q258640
ApacheSatchel.configure_modevasive
validation
def configure_modevasive(self): """ Installs the mod-evasive Apache module for combating DDOS attacks. https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache """ r = self.local_renderer if r.env.modevasive_enabled: self.install_packages() # Write conf for each Ubuntu version since they don't conflict. fn = r.render_to_file('apache/apache_modevasive.template.conf') # Ubuntu 12.04 r.put( local_path=fn, remote_path='/etc/apache2/mods-available/mod-evasive.conf', use_sudo=True) # Ubuntu 14.04 r.put( local_path=fn, remote_path='/etc/apache2/mods-available/evasive.conf',
python
{ "resource": "" }
q258641
ApacheSatchel.configure_modsecurity
validation
def configure_modsecurity(self): """ Installs the mod-security Apache module. https://www.modsecurity.org """ r = self.local_renderer if r.env.modsecurity_enabled and not self.last_manifest.modsecurity_enabled: self.install_packages() # Write modsecurity.conf. fn = self.render_to_file('apache/apache_modsecurity.template.conf') r.put(local_path=fn, remote_path='/etc/modsecurity/modsecurity.conf', use_sudo=True) # Write OWASP rules. r.env.modsecurity_download_filename = '/tmp/owasp-modsecurity-crs.tar.gz' r.sudo('cd /tmp; wget --output-document={apache_modsecurity_download_filename} {apache_modsecurity_download_url}') r.env.modsecurity_download_top = r.sudo(
python
{ "resource": "" }
q258642
ApacheSatchel.configure_modrpaf
validation
def configure_modrpaf(self): """ Installs the mod-rpaf Apache module. https://github.com/gnif/mod_rpaf """ r = self.local_renderer
python
{ "resource": "" }
q258643
ApacheSatchel.maint_up
validation
def maint_up(self): """ Forwards all traffic to a page saying the server is down for maintenance. """ r = self.local_renderer fn = self.render_to_file(r.env.maintenance_template, extra={'current_hostname': self.current_hostname})
python
{ "resource": "" }
q258644
SupervisorSatchel.restart
validation
def restart(self): """ Supervisor can take a very long time to start and stop, so wait for it. """ n = 60 sleep_n = int(self.env.max_restart_wait_minutes/10.*60) for _ in xrange(n): self.stop() if self.dryrun or not self.is_running(): break print('Waiting for supervisor to stop (%i of %i)...' % (_, n)) time.sleep(sleep_n) self.start() for _ in
python
{ "resource": "" }
q258645
SupervisorSatchel.deploy_services
validation
def deploy_services(self, site=None): """ Collects the configurations for all registered services and writes the appropriate supervisord.conf file. """ verbose = self.verbose r = self.local_renderer if not r.env.manage_configs: return # # target_sites = self.genv.available_sites_by_host.get(hostname, None) self.render_paths() supervisor_services = [] if r.env.purge_all_confs: r.sudo('rm -Rf /etc/supervisor/conf.d/*') #TODO:check available_sites_by_host and remove dead? self.write_configs(site=site) for _site, site_data in self.iter_sites(site=site, renderer=self.render_paths): if verbose: print('deploy_services.site:', _site) # Only load site configurations that are allowed for this host. # if target_sites is not None: # assert isinstance(target_sites, (tuple, list)) # if site not in target_sites: # continue for cb in self.genv._supervisor_create_service_callbacks: if self.verbose: print('cb:', cb) ret = cb(site=_site) if self.verbose: print('ret:', ret) if isinstance(ret, six.string_types): supervisor_services.append(ret) elif isinstance(ret, tuple): assert len(ret) == 2 conf_name, conf_content = ret
python
{ "resource": "" }
q258646
GitSatchel.clone
validation
def clone(self, remote_url, path=None, use_sudo=False, user=None): """ Clone a remote Git repository into a new directory. :param remote_url: URL of the remote repository to clone. :type remote_url: str :param path: Path of the working copy directory. Must not exist yet. :type path: str :param use_sudo: If ``True`` execute ``git`` with :func:`fabric.operations.sudo`, else with :func:`fabric.operations.run`. :type use_sudo: bool :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo`
python
{ "resource": "" }
q258647
GitSatchel.add_remote
validation
def add_remote(self, path, name, remote_url, use_sudo=False, user=None, fetch=True): """ Add a remote Git repository into a directory. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to fetch from. :type path: str :param use_sudo: If ``True`` execute ``git`` with :func:`fabric.operations.sudo`, else with :func:`fabric.operations.run`. :type use_sudo: bool :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo` with the given user. If ``use_sudo is False`` this parameter has no effect. :type user: str :param name: name for the remote repository :type name: str :param remote_url: URL of the remote repository :type remote_url: str :param fetch: If ``True`` execute ``git remote add -f``
python
{ "resource": "" }
q258648
GitSatchel.fetch
validation
def fetch(self, path, use_sudo=False, user=None, remote=None): """ Fetch changes from the default remote repository. This will fetch new changesets, but will not update the contents of the working tree unless yo do a merge or rebase. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to fetch from. :type path: str :param use_sudo: If ``True`` execute ``git`` with :func:`fabric.operations.sudo`, else with :func:`fabric.operations.run`. :type use_sudo: bool :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo` with the given user. If ``use_sudo is False`` this parameter has no effect. :type user: str :type remote: Fetch this remote or default remote if is None
python
{ "resource": "" }
q258649
GitSatchel.pull
validation
def pull(self, path, use_sudo=False, user=None, force=False): """ Fetch changes from the default remote repository and merge them. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to pull from. :type path: str :param use_sudo: If ``True`` execute ``git`` with :func:`fabric.operations.sudo`, else with :func:`fabric.operations.run`. :type use_sudo: bool :param user: If ``use_sudo is True``, run :func:`fabric.operations.sudo` with the given user. If ``use_sudo is False`` this parameter has no effect. :type user: str :param force: If ``True``, append the ``--force`` option to the command. :type force: bool """ if path is None:
python
{ "resource": "" }
q258650
GitTrackerSatchel.get_logs_between_commits
validation
def get_logs_between_commits(self, a, b): """ Retrieves all commit messages for all commits between the given commit numbers on the
python
{ "resource": "" }
q258651
GitTrackerSatchel.get_current_commit
validation
def get_current_commit(self): """ Retrieves the git commit number of the current head branch. """ with hide('running', 'stdout', 'stderr', 'warnings'):
python
{ "resource": "" }
q258652
VagrantSatchel.ssh_config
validation
def ssh_config(self, name=''): """ Get the SSH parameters for connecting to a vagrant VM. """ r = self.local_renderer with self.settings(hide('running')): output = r.local('vagrant ssh-config %s' % name, capture=True) config = {}
python
{ "resource": "" }
q258653
VagrantSatchel.version
validation
def version(self): """ Get the Vagrant version. """ r = self.local_renderer with self.settings(hide('running', 'warnings'), warn_only=True): res = r.local('vagrant --version', capture=True) if res.failed: return None
python
{ "resource": "" }
q258654
VagrantSatchel.vagrant
validation
def vagrant(self, name=''): """ Run the following tasks on a vagrant box. First, you need to import this task in your ``fabfile.py``:: from fabric.api import * from burlap.vagrant import vagrant @task def some_task(): run('echo hello') Then you can easily run tasks on your current Vagrant box::
python
{ "resource": "" }
q258655
VagrantSatchel.vagrant_settings
validation
def vagrant_settings(self, name='', *args, **kwargs): """ Context manager that sets a vagrant VM as the remote host. Use this context manager inside a task to run commands on your current Vagrant box::
python
{ "resource": "" }
q258656
VagrantSatchel.base_boxes
validation
def base_boxes(self): """ Get the list of vagrant base boxes """
python
{ "resource": "" }
q258657
VagrantSatchel.install_from_upstream
validation
def install_from_upstream(self): """ Installs Vagrant from the most recent package available from their homepage. """ from burlap.system import get_arch, distrib_family r = self.local_renderer content = urlopen(r.env.download_url).read() print(len(content)) matches = DOWNLOAD_LINK_PATTERN.findall(content) print(matches) arch = get_arch() # e.g. 'x86_64' family = distrib_family() if family == DEBIAN: ext = '.deb' matches = [match for match in matches if match.endswith(ext) and arch in match] print('matches:', matches)
python
{ "resource": "" }
q258658
distrib_id
validation
def distrib_id(): """ Get the OS distribution ID. Example:: from burlap.system import distrib_id if distrib_id() != 'Debian': abort(u"Distribution is not supported") """ with settings(hide('running', 'stdout')): kernel = (run('uname -s') or '').strip().lower() if kernel == LINUX: # lsb_release works on Ubuntu and Debian >= 6.0 # but is not always included in other distros if is_file('/usr/bin/lsb_release'): id_ = run('lsb_release --id --short').strip().lower() if id in ['arch', 'archlinux']: # old IDs used before lsb-release 1.4-14 id_ = ARCH return id_ else: if is_file('/etc/debian_version'): return DEBIAN elif is_file('/etc/fedora-release'): return FEDORA
python
{ "resource": "" }
q258659
distrib_release
validation
def distrib_release(): """ Get the release number of the distribution. Example:: from burlap.system import distrib_id, distrib_release if distrib_id() == 'CentOS' and distrib_release() == '6.1': print(u"CentOS 6.2 has been released. Please upgrade.") """ with settings(hide('running', 'stdout')):
python
{ "resource": "" }
q258660
distrib_family
validation
def distrib_family(): """ Get the distribution family. Returns one of ``debian``, ``redhat``, ``arch``, ``gentoo``, ``sun``, ``other``. """ distrib = (distrib_id() or '').lower() if distrib in ['debian', 'ubuntu', 'linuxmint', 'elementary os']: return DEBIAN elif distrib in ['redhat', 'rhel', 'centos', 'sles', 'fedora']: return REDHAT
python
{ "resource": "" }
q258661
supported_locales
validation
def supported_locales(): """ Gets the list of supported locales. Each locale is returned as a ``(locale, charset)`` tuple. """ family = distrib_family() if family == 'debian':
python
{ "resource": "" }
q258662
CelerySatchel.force_stop
validation
def force_stop(self): """ Forcibly terminates all Celery processes. """ r = self.local_renderer with self.settings(warn_only=True):
python
{ "resource": "" }
q258663
CelerySatchel.set_permissions
validation
def set_permissions(self): """ Sets ownership and permissions for Celery-related files. """ r = self.local_renderer for path in r.env.paths_owned:
python
{ "resource": "" }
q258664
CelerySatchel.create_supervisor_services
validation
def create_supervisor_services(self, site): """ This is called for each site to render a Celery config file. """ self.vprint('create_supervisor_services:', site) self.set_site_specifics(site=site) r = self.local_renderer if self.verbose: print('r.env:') pprint(r.env, indent=4) self.vprint('r.env.has_worker:', r.env.has_worker) if not r.env.has_worker: self.vprint('skipping: no celery worker') return if self.name.lower() not in self.genv.services: self.vprint('skipping: celery not enabled') return
python
{ "resource": "" }
q258665
BuildBotSatchel.check_ok
validation
def check_ok(self): """ Ensures all tests have passed for this branch. This should be called before deployment, to prevent accidental deployment of code that hasn't passed automated testing. """ import requests if not self.env.check_ok: return # Find current git branch. branch_name = self._local('git rev-parse --abbrev-ref
python
{ "resource": "" }
q258666
HostSatchel.is_present
validation
def is_present(self, host=None): """ Returns true if the given host exists on the network. Returns false otherwise. """ r = self.local_renderer r.env.host = host or self.genv.host_string ret = r._local("getent hosts {host} | awk '{{ print $1 }}'", capture=True) or '' if self.verbose: print('ret:', ret) ret = ret.strip() if self.verbose: print('Host %s %s present.' % (r.env.host, 'IS' if bool(ret) else 'IS NOT')) ip = ret ret = bool(ret) if not ret: return
python
{ "resource": "" }
q258667
HostSatchel.purge_keys
validation
def purge_keys(self): """ Deletes all SSH keys on the localhost associated with the current remote host. """ r = self.local_renderer r.env.default_ip = self.hostname_to_ip(self.env.default_hostname) r.env.home_dir = '/home/%s' % getpass.getuser() r.local('ssh-keygen -f "{home_dir}/.ssh/known_hosts" -R {host_string}') if self.env.default_hostname:
python
{ "resource": "" }
q258668
HostSatchel.find_working_password
validation
def find_working_password(self, usernames=None, host_strings=None): """ Returns the first working combination of username and password for the current host. """ r = self.local_renderer if host_strings is None: host_strings = [] if not host_strings: host_strings.append(self.genv.host_string) if usernames is None: usernames = [] if not usernames: usernames.append(self.genv.user) for host_string in host_strings: for username in usernames: passwords = [] passwords.append(self.genv.user_default_passwords[username]) passwords.append(self.genv.user_passwords[username]) passwords.append(self.env.default_password) for password in passwords: with settings(warn_only=True): r.env.host_string = host_string r.env.password = password r.env.user = username
python
{ "resource": "" }
q258669
HostSatchel.needs_initrole
validation
def needs_initrole(self, stop_on_error=False): """ Returns true if the host does not exist at the expected location and may need to have its initial configuration set. Returns false if the host exists at the expected location. """ ret = False target_host_present = self.is_present() if not target_host_present: default_host_present = self.is_present(self.env.default_hostname) if default_host_present: if self.verbose: print('Target host missing and default host present so host init required.') ret = True else: if self.verbose: print('Target host missing but default host also missing, '
python
{ "resource": "" }
q258670
HostSatchel.initrole
validation
def initrole(self, check=True): """ Called to set default password login for systems that do not yet have passwordless login setup. """ if self.env.original_user is None: self.env.original_user = self.genv.user if self.env.original_key_filename is None: self.env.original_key_filename = self.genv.key_filename host_string = None user = None password = None if self.env.login_check: host_string, user, password = self.find_working_password( usernames=[self.genv.user, self.env.default_user], host_strings=[self.genv.host_string, self.env.default_hostname], ) if self.verbose: print('host.initrole.host_string:', host_string) print('host.initrole.user:', user) print('host.initrole.password:', password) # needs = True # if check: # needs = self.needs_initrole(stop_on_error=True) needs = False if host_string is not None: self.genv.host_string = host_string if user is not None: self.genv.user = user if password is not None: self.genv.password = password if not needs: return assert self.env.default_hostname, 'No default hostname set.' assert self.env.default_user, 'No default user set.' self.genv.host_string = self.env.default_hostname if self.env.default_hosts: self.genv.hosts = self.env.default_hosts else: self.genv.hosts = [self.env.default_hostname] self.genv.user = self.env.default_user self.genv.password = self.env.default_password self.genv.key_filename = self.env.default_key_filename # If the host has been reformatted, the SSH keys will mismatch, throwing an error, so clear them. self.purge_keys() # Do a test login with the default password to determine which password we should use. # r.env.password = self.env.default_password # with settings(warn_only=True): # ret = r._local("sshpass -p '{password}' ssh -o StrictHostKeyChecking=no {user}@{host_string} echo hello", capture=True) # print('ret.return_code:', ret.return_code) # # print('ret000:[%s]' % ret) # #code 1 = good password, but prompts needed # #code 5 = bad password # #code 6 = good password, but host public key is unknown # if ret.return_code in (1, 6) or
python
{ "resource": "" }
q258671
HostnameSatchel.get_public_ip
validation
def get_public_ip(self): """ Gets the public IP for a host. """ r = self.local_renderer
python
{ "resource": "" }
q258672
HostnameSatchel.configure
validation
def configure(self, reboot=1): """ Assigns a name to the server accessible from user space. Note, we add the name to /etc/hosts since not all programs use /etc/hostname to reliably identify the server hostname. """ r = self.local_renderer for ip, hostname in self.iter_hostnames(): self.vprint('ip/hostname:', ip, hostname) r.genv.host_string = ip r.env.hostname = hostname with settings(warn_only=True):
python
{ "resource": "" }
q258673
partitions
validation
def partitions(device=""): """ Get a partition list for all disk or for selected device only Example:: from burlap.disk import partitions spart = {'Linux': 0x83, 'Swap': 0x82} parts = partitions() # parts = {'/dev/sda1': 131, '/dev/sda2': 130, '/dev/sda3': 131} r = parts['/dev/sda1'] == spart['Linux'] r = r and parts['/dev/sda2'] == spart['Swap'] if r: print("You can format these partitions") """ partitions_list = {} with settings(hide('running', 'stdout')): res = run_as_root('sfdisk -d
python
{ "resource": "" }
q258674
getdevice_by_uuid
validation
def getdevice_by_uuid(uuid): """ Get a HDD device by uuid Example:: from burlap.disk import getdevice_by_uuid device = getdevice_by_uuid("356fafdc-21d5-408e-a3e9-2b3f32cb2a8c")
python
{ "resource": "" }
q258675
ismounted
validation
def ismounted(device): """ Check if partition is mounted Example:: from burlap.disk import ismounted if ismounted('/dev/sda1'): print ("disk sda1 is mounted") """ # Check filesystem with settings(hide('running', 'stdout')):
python
{ "resource": "" }
q258676
query
validation
def query(query, use_sudo=True, **kwargs): """ Run a MySQL query. """ func = use_sudo and run_as_root or run user = kwargs.get('mysql_user') or env.get('mysql_user') password = kwargs.get('mysql_password') or env.get('mysql_password')
python
{ "resource": "" }
q258677
create_user
validation
def create_user(name, password, host='localhost', **kwargs): """ Create a MySQL user. Example:: import burlap # Create DB user if it does not exist if not burlap.mysql.user_exists('dbuser'):
python
{ "resource": "" }
q258678
database_exists
validation
def database_exists(name, **kwargs): """ Check if a MySQL database exists. """ with settings(hide('running', 'stdout', 'stderr',
python
{ "resource": "" }
q258679
create_database
validation
def create_database(name, owner=None, owner_host='localhost', charset='utf8', collate='utf8_general_ci', **kwargs): """ Create a MySQL database. Example:: import burlap # Create DB if it does not exist if not burlap.mysql.database_exists('myapp'): burlap.mysql.create_database('myapp', owner='dbuser') """ with settings(hide('running')): query("CREATE DATABASE %(name)s CHARACTER SET %(charset)s COLLATE %(collate)s;" % { 'name': name, 'charset': charset, 'collate': collate
python
{ "resource": "" }
q258680
MySQLSatchel.conf_path
validation
def conf_path(self): """ Retrieves the path to the MySQL configuration file. """ from burlap.system import distrib_id, distrib_release hostname = self.current_hostname if hostname not in self._conf_cache: self.env.conf_specifics[hostname] = self.env.conf_default d_id = distrib_id()
python
{ "resource": "" }
q258681
MySQLSatchel.prep_root_password
validation
def prep_root_password(self, password=None, **kwargs): """ Enters the root password prompt entries into the debconf cache so we can set them without user interaction. We keep this process separate from set_root_password() because we also need to do this before installing the base MySQL package, because that will also prompt the user for a root login. """
python
{ "resource": "" }
q258682
MySQLSatchel.drop_views
validation
def drop_views(self, name=None, site=None): """ Drops all views. """ r = self.database_renderer result = r.sudo("mysql --batch -v -h {db_host} " #"-u {db_root_username} -p'{db_root_password}' " "-u {db_user} -p'{db_password}' " "--execute=\"SELECT GROUP_CONCAT(CONCAT(TABLE_SCHEMA,'.',table_name) SEPARATOR ', ') AS views " "FROM INFORMATION_SCHEMA.views WHERE TABLE_SCHEMA = '{db_name}' ORDER BY table_name DESC;\"") result = re.findall( r'^views[\s\t\r\n]+(.*)', result,
python
{ "resource": "" }
q258683
tic_single_object_crossmatch
validation
def tic_single_object_crossmatch(ra, dec, radius): '''This does a cross-match against the TIC catalog on MAST. Speed tests: about 10 crossmatches per second. (-> 3 hours for 10^5 objects to crossmatch). Parameters ---------- ra,dec : np.array The coordinates to cross match against, all in decimal degrees. radius : float The cross-match radius to use, in decimal degrees. Returns ------- dict Returns the match results JSON from MAST loaded into a dict. '''
python
{ "resource": "" }
q258684
normalized_flux_to_mag
validation
def normalized_flux_to_mag(lcdict, columns=('sap.sap_flux', 'sap.sap_flux_err', 'sap.sap_bkg', 'sap.sap_bkg_err', 'pdc.pdcsap_flux', 'pdc.pdcsap_flux_err')): '''This converts the normalized fluxes in the TESS lcdicts to TESS mags. Uses the object's TESS mag stored in lcdict['objectinfo']['tessmag']:: mag - object_tess_mag = -2.5 log (flux/median_flux) Parameters ---------- lcdict : lcdict An `lcdict` produced by `read_tess_fitslc` or `consolidate_tess_fitslc`. This must have normalized fluxes in its measurement columns (use the `normalize` kwarg for these functions). columns : sequence of str The column keys of the normalized flux and background measurements in
python
{ "resource": "" }
q258685
get_time_flux_errs_from_Ames_lightcurve
validation
def get_time_flux_errs_from_Ames_lightcurve(infile, lctype, cadence_min=2): '''Reads TESS Ames-format FITS light curve files. MIT TOI alerts include Ames lightcurve files. This function gets the finite, nonzero times, fluxes, and errors with QUALITY == 0. NOTE: the PDCSAP lightcurve typically still need "pre-whitening" after this step. .. deprecated:: 0.3.20 This function will be removed in astrobase v0.4.2. Use the `read_tess_fitslc` and `consolidate_tess_fitslc` functions instead. Parameters ---------- infile : str The path to `*.fits.gz` TOI alert file, from Ames pipeline. lctype : {'PDCSAP','SAP'} The type of light curve to extract from the FITS LC file. cadence_min : int The expected frame cadence in units of minutes. Raises ValueError if you use the wrong cadence. Returns ------- tuple The tuple returned is of the form: (times, normalized (to median) fluxes, flux errors) ''' warnings.warn( "Use the astrotess.read_tess_fitslc and " "astrotess.consolidate_tess_fitslc functions instead of this function. " "This function will be removed in astrobase v0.4.2.", FutureWarning ) if lctype not in ('PDCSAP','SAP'): raise ValueError('unknown light curve type requested: %s' % lctype) hdulist = pyfits.open(infile) main_hdr = hdulist[0].header lc_hdr = hdulist[1].header lc = hdulist[1].data if (('Ames' not in main_hdr['ORIGIN']) or ('LIGHTCURVE' not in lc_hdr['EXTNAME'])): raise ValueError( 'could not understand input LC format. '
python
{ "resource": "" }
q258686
_pkl_periodogram
validation
def _pkl_periodogram(lspinfo, plotdpi=100, override_pfmethod=None): '''This returns the periodogram plot PNG as base64, plus info as a dict. Parameters ---------- lspinfo : dict This is an lspinfo dict containing results from a period-finding function. If it's from an astrobase period-finding function in periodbase, this will already be in the correct format. To use external period-finder results with this function, the `lspinfo` dict must be of the following form, with at least the keys listed below:: {'periods': np.array of all periods searched by the period-finder, 'lspvals': np.array of periodogram power value for each period, 'bestperiod': a float value that is the period with the highest peak in the periodogram, i.e. the most-likely actual period, 'method': a three-letter code naming the period-finder used; must be one of the keys in the `astrobase.periodbase.METHODLABELS` dict, 'nbestperiods': a list of the periods corresponding to periodogram peaks (`nbestlspvals` below) to annotate on the periodogram plot so they can be called out visually, 'nbestlspvals': a list of the power values associated with periodogram peaks to annotate on the periodogram plot so they can be called out visually; should be the same length as `nbestperiods` above} `nbestperiods` and `nbestlspvals` must have at least 5 elements each, e.g. describing the five 'best' (highest power) peaks in the periodogram. plotdpi : int The resolution in DPI of the output periodogram plot to make. override_pfmethod : str or None This is used to set a custom label for this periodogram method. Normally, this is taken from the 'method' key in the input `lspinfo` dict, but if you want to override the output method name, provide this as a string here. This can be useful if you have multiple results you want to incorporate into a checkplotdict from a single period-finder (e.g.
python
{ "resource": "" }
q258687
_pkl_magseries_plot
validation
def _pkl_magseries_plot(stimes, smags, serrs, plotdpi=100, magsarefluxes=False): '''This returns the magseries plot PNG as base64, plus arrays as dict. Parameters ---------- stimes,smags,serrs : np.array The mag/flux time-series arrays along with associated errors. These should all have been run through nan-stripping and sigma-clipping beforehand. plotdpi : int The resolution of the plot to make in DPI. magsarefluxes : bool If True, indicates the input time-series is fluxes and not mags so the plot y-axis direction and range can be set appropriately. Returns ------- dict A dict of the following form is returned:: {'magseries': {'plot': base64 encoded str representation of the magnitude/flux time-series plot, 'times': the `stimes` array, 'mags': the `smags` array, 'errs': the 'serrs' array}} The dict is returned in this format so it can be directly incorporated in a checkplotdict, using Python's dict `update()` method. ''' scaledplottime = stimes - npmin(stimes) # open the figure instance magseriesfig = plt.figure(figsize=(7.5,4.8),dpi=plotdpi) plt.plot(scaledplottime, smags, marker='o', ms=2.0, ls='None',mew=0, color='green', rasterized=True) # flip y axis for mags if not magsarefluxes: plot_ylim = plt.ylim() plt.ylim((plot_ylim[1], plot_ylim[0])) # set the x axis limit plt.xlim((npmin(scaledplottime)-2.0, npmax(scaledplottime)+2.0)) # make a grid plt.grid(color='#a9a9a9', alpha=0.9, zorder=0, linewidth=1.0, linestyle=':') # make the x and y axis labels plot_xlabel = 'JD - %.3f' % npmin(stimes) if magsarefluxes: plot_ylabel =
python
{ "resource": "" }
q258688
find_lc_timegroups
validation
def find_lc_timegroups(lctimes, mingap=4.0): '''Finds gaps in the provided time-series and indexes them into groups. This finds the gaps in the provided `lctimes` array, so we can figure out which times are for consecutive observations and which represent gaps between seasons or observing eras. Parameters ---------- lctimes : array-like This contains the times to analyze for gaps; assumed to be some form of Julian date. mingap : float This defines how much the difference between consecutive measurements is allowed to be to consider them as parts of different timegroups. By default it is set to 4.0 days. Returns ------- tuple A tuple of the form: `(ngroups, [slice(start_ind_1, end_ind_1), ...])`
python
{ "resource": "" }
q258689
normalize_magseries
validation
def normalize_magseries(times, mags, mingap=4.0, normto='globalmedian', magsarefluxes=False, debugmode=False): '''This normalizes the magnitude time-series to a specified value. This is used to normalize time series measurements that may have large time gaps and vertical offsets in mag/flux measurement between these 'timegroups', either due to instrument changes or different filters. NOTE: this works in-place! The mags array will be replaced with normalized mags when this function finishes. Parameters ---------- times,mags : array-like The times (assumed to be some form of JD) and mags (or flux) measurements to be normalized. mingap : float This defines how much the difference between consecutive measurements is allowed to be to consider them as parts of different timegroups. By default it is set to 4.0 days. normto : {'globalmedian', 'zero'} or a float Specifies the normalization type:: 'globalmedian' -> norms each mag to the global median of the LC column 'zero' -> norms each mag to zero a float -> norms each mag to this specified float value. magsarefluxes : bool Indicates if the input `mags` array is actually an array of flux measurements instead of magnitude measurements. If this is set to True, then: - if `normto` is 'zero', then the median flux is divided from each observation's flux value to yield normalized fluxes with 1.0 as the global median. - if `normto` is 'globalmedian', then the global median flux value across the entire time series is multiplied with each measurement. - if `norm` is set to a `float`, then this number is multiplied with the flux value for each measurement. debugmode : bool If this is True, will print out verbose info on each timegroup found. Returns ------- times,normalized_mags : np.arrays Normalized magnitude values after normalization. If normalization fails for some reason, `times` and `normalized_mags` will both be None. ''' ngroups, timegroups = find_lc_timegroups(times, mingap=mingap) # find all the non-nan indices finite_ind = np.isfinite(mags) if any(finite_ind): # find the global median global_mag_median = np.median(mags[finite_ind])
python
{ "resource": "" }
q258690
get_snr_of_dip
validation
def get_snr_of_dip(times, mags, modeltimes, modelmags, atol_normalization=1e-8, indsforrms=None, magsarefluxes=False, verbose=True, transitdepth=None, npoints_in_transit=None): '''Calculate the total SNR of a transit assuming gaussian uncertainties. `modelmags` gets interpolated onto the cadence of `mags`. The noise is calculated as the 1-sigma std deviation of the residual (see below). Following Carter et al. 2009:: Q = sqrt( Γ T ) * δ / σ for Q the total SNR of the transit in the r->0 limit, where:: r = Rp/Rstar, T = transit duration, δ = transit depth, σ = RMS of the lightcurve in transit. Γ = sampling rate Thus Γ * T is roughly the number of points obtained during transit. (This doesn't correctly account for the SNR during ingress/egress, but this is a second-order correction). Note this is the same total SNR as described by e.g., Kovacs et al. 2002, their Equation 11. NOTE: this only works with fluxes at the moment. Parameters ---------- times,mags : np.array The input flux time-series to process. modeltimes,modelmags : np.array A transiting planet model, either from BLS, a trapezoid model, or a Mandel-Agol model. atol_normalization : float The absolute tolerance to which the median of the passed model fluxes must be equal to 1. indsforrms : np.array A array of bools of `len(mags)` used to select points for the RMS measurement. If not passed, the RMS of the entire passed timeseries is used as an approximation. Genearlly, it's best to use out of transit points, so the RMS measurement is not model-dependent. magsarefluxes : bool Currently forced to be True because this function only works with fluxes. verbose : bool If True, indicates progress and warns about problems. transitdepth : float or None If the transit depth is known, pass it in here. Otherwise, it is calculated assuming OOT flux is 1. npoints_in_transits : int or None If the number of points in transit is known, pass it in here. Otherwise, the function will guess at this value. Returns ------- (snr, transit_depth, noise) : tuple The returned tuple contains the calculated SNR, transit depth, and noise of the residual lightcurve calculated using the relation described above. ''' if magsarefluxes: if not np.isclose(np.nanmedian(modelmags), 1, atol=atol_normalization): raise AssertionError('snr calculation assumes modelmags are '
python
{ "resource": "" }
q258691
estimate_achievable_tmid_precision
validation
def estimate_achievable_tmid_precision(snr, t_ingress_min=10, t_duration_hr=2.14): '''Using Carter et al. 2009's estimate, calculate the theoretical optimal precision on mid-transit time measurement possible given a transit of a particular SNR. The relation used is:: sigma_tc = Q^{-1} * T * sqrt(θ/2) Q = SNR of the transit. T = transit duration, which is 2.14 hours from discovery paper. θ = τ/T = ratio of ingress to total duration ~= (few minutes [guess]) / 2.14 hours Parameters ---------- snr : float The measured signal-to-noise of the transit, e,g. from :py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod` or from running the `.compute_stats()` method on an Astropy BoxLeastSquares object. t_ingress_min : float The ingress duration in minutes. This is t_I to t_II in Winn (2010) nomenclature. t_duration_hr : float The transit duration in hours. This is t_I to t_IV in Winn (2010) nomenclature. Returns ------- float Returns the precision achievable for transit-center time as calculated from
python
{ "resource": "" }
q258692
given_lc_get_transit_tmids_tstarts_tends
validation
def given_lc_get_transit_tmids_tstarts_tends( time, flux, err_flux, blsfit_savpath=None, trapfit_savpath=None, magsarefluxes=True, nworkers=1, sigclip=None, extra_maskfrac=0.03 ): '''Gets the transit start, middle, and end times for transits in a given time-series of observations. Parameters ---------- time,flux,err_flux : np.array The input flux time-series measurements and their associated measurement errors blsfit_savpath : str or None If provided as a str, indicates the path of the fit plot to make for a simple BLS model fit to the transit using the obtained period and epoch. trapfit_savpath : str or None If provided as a str, indicates the path of the fit plot to make for a trapezoidal transit model fit to the transit using the obtained period and epoch. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. magsarefluxes : bool This is by default True for this function, since it works on fluxes only at the moment. nworkers : int The number of parallel BLS period-finder workers to use. extra_maskfrac : float This is the separation (N) from in-transit points you desire, in units of the transit duration. `extra_maskfrac = 0` if you just want points inside transit, otherwise:: t_starts = t_Is - N*tdur, t_ends = t_IVs + N*tdur Thus setting N=0.03 masks slightly more than the guessed transit duration. Returns ------- (tmids_obsd, t_starts, t_ends) : tuple The returned items are:: tmids_obsd (np.ndarray): best guess of transit midtimes in lightcurve. Has length number of transits in lightcurve. t_starts (np.ndarray): t_Is - extra_maskfrac*tdur, for t_Is transit first contact point. t_ends (np.ndarray): t_Is + extra_maskfrac*tdur,
python
{ "resource": "" }
q258693
given_lc_get_out_of_transit_points
validation
def given_lc_get_out_of_transit_points( time, flux, err_flux, blsfit_savpath=None, trapfit_savpath=None, in_out_transit_savpath=None, sigclip=None, magsarefluxes=True, nworkers=1, extra_maskfrac=0.03 ): '''This gets the out-of-transit light curve points. Relevant during iterative masking of transits for multiple planet system search. Parameters ---------- time,flux,err_flux : np.array The input flux time-series measurements and their associated measurement errors blsfit_savpath : str or None If provided as a str, indicates the path of the fit plot to make for a simple BLS model fit to the transit using the obtained period and epoch. trapfit_savpath : str or None If provided as a str, indicates the path of the fit plot to make for a trapezoidal transit model fit to the transit using the obtained period and epoch. in_out_transit_savpath : str or None If provided as a str, indicates the path of the plot file that will be made for a plot showing the in-transit points and out-of-transit points tagged separately. sigclip : float or int or sequence of two floats/ints or None If a single float or int, a symmetric sigma-clip will be performed using the number provided as the sigma-multiplier to cut out from the input time-series. If a list of two ints/floats is provided, the function will perform an 'asymmetric' sigma-clip. The first element in this list is the sigma value to use for fainter flux/mag values; the second element in this list is the sigma value to use for brighter flux/mag values. For example, `sigclip=[10., 3.]`, will sigclip out greater than 10-sigma dimmings and greater than 3-sigma brightenings. Here the meaning of "dimming" and "brightening" is set by *physics* (not the magnitude system), which is why the `magsarefluxes` kwarg must be correctly set. If `sigclip` is None, no sigma-clipping will be performed, and the time-series (with non-finite elems removed) will be passed through to the output. magsarefluxes : bool This is by default True for this function, since it works on fluxes only at the moment. nworkers : int The number of parallel BLS period-finder workers to use. extra_maskfrac : float This is the separation (N) from in-transit points you desire, in units of the transit duration. `extra_maskfrac = 0` if you just want
python
{ "resource": "" }
q258694
_pycompress_sqlitecurve
validation
def _pycompress_sqlitecurve(sqlitecurve, force=False): '''This just compresses the sqlitecurve. Should be independent of OS. ''' outfile = '%s.gz' % sqlitecurve try: if os.path.exists(outfile) and not force: os.remove(sqlitecurve) return outfile else: with open(sqlitecurve,'rb') as infd: with gzip.open(outfile,'wb') as outfd:
python
{ "resource": "" }
q258695
_pyuncompress_sqlitecurve
validation
def _pyuncompress_sqlitecurve(sqlitecurve, force=False): '''This just uncompresses the sqlitecurve. Should be independent of OS. ''' outfile = sqlitecurve.replace('.gz','') try: if os.path.exists(outfile) and not force: return outfile else: with gzip.open(sqlitecurve,'rb') as infd: with open(outfile,'wb') as outfd:
python
{ "resource": "" }
q258696
_gzip_sqlitecurve
validation
def _gzip_sqlitecurve(sqlitecurve, force=False): '''This just compresses the sqlitecurve in gzip format. FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably). ''' # -k to keep the input file just in case something explodes if force: cmd = 'gzip -k -f %s' % sqlitecurve else: cmd = 'gzip -k %s' % sqlitecurve try: outfile = '%s.gz' % sqlitecurve if os.path.exists(outfile) and not force: # get rid of the .sqlite file only os.remove(sqlitecurve)
python
{ "resource": "" }
q258697
_gunzip_sqlitecurve
validation
def _gunzip_sqlitecurve(sqlitecurve): '''This just uncompresses the sqlitecurve in gzip format. FIXME: this doesn't work with gzip < 1.6 or non-GNU gzip (probably). ''' # -k to keep the input .gz just in case something explodes cmd = 'gunzip -k %s' % sqlitecurve try:
python
{ "resource": "" }
q258698
_validate_sqlitecurve_filters
validation
def _validate_sqlitecurve_filters(filterstring, lccolumns): '''This validates the sqlitecurve filter string. This MUST be valid SQL but not contain any commands. ''' # first, lowercase, then _squeeze to single spaces stringelems = _squeeze(filterstring).lower() # replace shady characters stringelems = filterstring.replace('(','') stringelems = stringelems.replace(')','') stringelems = stringelems.replace(',','') stringelems = stringelems.replace("'",'"') stringelems = stringelems.replace('\n',' ') stringelems = stringelems.replace('\t',' ') stringelems = _squeeze(stringelems) # split into words stringelems = stringelems.split(' ') stringelems = [x.strip() for x in stringelems] # get rid of all numbers stringwords = [] for x in stringelems: try: float(x) except ValueError as e: stringwords.append(x) # get rid of everything within quotes stringwords2 = [] for x in stringwords: if not(x.startswith('"') and x.endswith('"')): stringwords2.append(x) stringwords2 = [x for x in stringwords2 if len(x) > 0]
python
{ "resource": "" }
q258699
_smartcast
validation
def _smartcast(castee, caster, subval=None): ''' This just tries to apply the caster function to castee. Returns None on failure. ''' try: return caster(castee) except Exception as e: if caster is float
python
{ "resource": "" }