Use xdg-email to compose in an X environment.

    Needs xdg-utils and a running X session. Works with GNOME, KDE,
    MATE, XFCE, ...
515794
def xdg_compose(to, subject, body=None, cc=None, bcc=None):
    
    command = ["xdg-email", "--utf8", "--subject", subject]

    if body:
        command += ["--body", body]
    if cc:
        if type(cc) is list:
            cc = ", ".join(cc)
        command += ["--cc", cc]
    if bcc:
        if type(bcc) is list:
            bcc = ", ".join(bcc)
        command += ["--bcc", bcc]
    if type(to) is list:
        to = ", ".join(to)
    command.append(to)
    return subprocess.call(command)
1234215
function WGStoCHx(lat, lng) {

  // Converts degrees dec to sex
  lat = DECtoSEX(lat);
  lng = DECtoSEX(lng);

  // Converts degrees to seconds (sex)
  lat = DEGtoSEC(lat);
  lng = DEGtoSEC(lng);

  // Axiliary values (% Bern)
  const lat_aux = (lat - 169028.66) / 10000;
  const lng_aux = (lng - 26782.5) / 10000;

  // Process X
  const x = 200147.07 +
      308807.95 * lat_aux +
      3745.25 * Math.pow(lng_aux, 2) +
      76.63 * Math.pow(lat_aux, 2) -
      194.56 * Math.pow(lng_aux, 2) * lat_aux +
      119.79 * Math.pow(lat_aux, 3);

  return x;

}
344529
def get_xdg_env(env_name, fallback):
    
    env = os.environ.get(env_name)
    return env if env else fallback
775305
def xdg_config_dir():
    '''
    
    '''
    xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
    xdg_config_directory = os.path.join(xdg_config, 'salt')
    return xdg_config_directory
249030
private XLinguServiceManager GetLinguSvcMgr(XComponentContext xContext) {
    try {
      XMultiComponentFactory xMCF = UnoRuntime.queryInterface(XMultiComponentFactory.class,
          xContext.getServiceManager());
      if (xMCF == null) {
        printText("XMultiComponentFactory == null");
        return null;
      }
      // retrieve Office's remote component context as a property
      XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, xMCF);
      if (props == null) {
        printText("XPropertySet == null");
        return null;
      }
      // initObject);
      Object defaultContext = props.getPropertyValue("DefaultContext");
      // get the remote interface XComponentContext
      XComponentContext xComponentContext = UnoRuntime.queryInterface(XComponentContext.class, defaultContext);
      if (xComponentContext == null) {
        printText("XComponentContext == null");
        return null;
      }
      Object o = xMCF.createInstanceWithContext("com.sun.star.linguistic2.LinguServiceManager", xComponentContext);     
      // create service component using the specified component context
      XLinguServiceManager mxLinguSvcMgr = UnoRuntime.queryInterface(XLinguServiceManager.class, o);
      if (mxLinguSvcMgr == null) {
        printText("XLinguServiceManager2 == null");
        return null;
      }
      return mxLinguSvcMgr;
    } catch (Throwable t) {
      // If anything goes wrong, give the user a stack trace
      printMessage(t);
    }
    return null;
  }
104587
function init() {
	// Locate config if we dont have one {{{
	if (_.isUndefined(appConfig)) {
		appConfigLocations.forEach(function(key) {
			if (_.has(global, key)) {
				appConfig = _.get(global, key);
				return false;
			}
		});
		if (_.isUndefined(appConfig)) throw new Error('Cannot find email config in', appConfigLocations);
	}
	// }}}

	this.config = { // Reset basics
		from: appConfig.email.from,
		to: appConfig.email.to,
		subject: appConfig.email.subject || '',
		cc: appConfig.email.cc || [],
		bcc: appConfig.email.bcc || [],
	};

	// Work out mail transport {{{
	if (appConfig.email.enabled) {
		switch (appConfig.email.method) {
			case 'mailgun':
				if (
					/^https?:\/\//.test(appConfig.mailgun.domain) ||
					/mailgun/.test(appConfig.mailgun.domain)
				) throw new Error("Mailgun domain should not contain 'http(s)://' prefix or mailgun. Should resemble the domain name e.g. 'acme.com'");

				transporter = nodemailer.createTransport(nodemailerMailgun({
					auth: {
						api_key: appConfig.mailgun.apiKey,
						domain: appConfig.mailgun.domain,
					},
				}));
				break
			case 'sendmail':
				transporter = nodemailer.createTransport(nodemailerSendmail());
				break;
			default:
				next('Unknown mail transport method: ' + appConfig.email.method);
		}
	}
	// }}}

	return this;
}
968363
def main():
    
    log = logging.getLogger(mod_logger + '.main')
    parser = argparse.ArgumentParser(description='This module allows sending email messages.')
    parser.add_argument('-f', '--file', help='Full path to a plain text file', required=False)
    parser.add_argument('-s', '--sender', help='Email address of the sender', required=False)
    parser.add_argument('-r', '--recipient', help='Email address of the recipient', required=False)
    args = parser.parse_args()

    am = AssetMailer()
    err = None
    if args.file:
        try:
            am.send_text_file(text_file=args.file, sender=args.sender, recipient=args.recipient)
        except AssetMailerError:
            _, ex, trace = sys.exc_info()
            err = '{n}: There was a problem sending email with file {f} from sender {s} to recipient {r}:\n{e}'.format(
                n=ex.__class__.__name__, f=args.file, s=args.sender, r=args.recipient, e=str(ex))
            log.error(err)
    else:
        try:
            am.send_cons3rt_agent_logs()
        except AssetMailerError:
            _, ex, trace = sys.exc_info()
            err = '{n}: There was a problem sending cons3rt agent log files:\n{e}'.format(
                n=ex.__class__.__name__, e=str(ex))
            log.error(err)
    if err is None:
        log.info('Successfully send email')
791458
final MimeMessage populateMimeMessage(@Nonnull final Email email, @Nonnull Session session)
			throws MessagingException, UnsupportedEncodingException {
		checkArgumentNotEmpty(email, "email is missing");
		checkArgumentNotEmpty(session, "session is needed, it cannot be attached later");
		
		final MimeMessage message = new MimeMessage(session) {
			@Override
			protected void updateMessageID() throws MessagingException {
				if (valueNullOrEmpty(email.getId())) {
					super.updateMessageID();
				} else {
					setHeader("Message-ID", email.getId());
				}
			}
			
			@Override
			public String toString() {
				try {
					return "MimeMessage<id:" + super.getMessageID() + ", subject:" + super.getSubject() + ">";
				} catch (MessagingException e) {
					throw new AssertionError("should not reach here");
				}
			}
		};
		
		// set basic email properties
		MimeMessageHelper.setSubject(email, message);
		MimeMessageHelper.setFrom(email, message);
		MimeMessageHelper.setReplyTo(email, message);
		MimeMessageHelper.setRecipients(email, message);
		
		populateMimeMessageMultipartStructure(message, email);
		
		MimeMessageHelper.setHeaders(email, message);
		message.setSentDate(new Date());

		if (!valueNullOrEmpty(email.getDkimSigningDomain())) {
			return signMessageWithDKIM(message, email);
		}
		
		return message;
	}
649386
def send_email(recipients, subject, text_content=None, html_content=None, from_email=None, use_base_template=True, category=None, fail_silently=False, language=None, cc=None, bcc=None, attachments=None, headers=None, bypass_queue=False, bypass_hijacking=False, attach_files=None):
    
    from django.conf import settings
    if not bypass_queue and hasattr(settings, 'MAILING_USE_CELERY') and settings.MAILING_USE_CELERY:
        from celery.execute import send_task
        return send_task('mailing.queue_send_email',[recipients, subject, text_content, html_content, from_email, use_base_template, category, fail_silently, language if language else translation.get_language(), cc, bcc, attachments, headers, bypass_hijacking, attach_files])
    else:

        header_category_value = '%s%s' % (settings.MAILING_HEADER_CATEGORY_PREFIX if hasattr(settings, 'MAILING_HEADER_CATEGORY_PREFIX') else '', category)
        # Check for sendgrid support and add category header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_SENDGRID'):
            send_grid_support = settings.MAILING_USE_SENDGRID
        else:
            send_grid_support = False

        if not headers:
            headers = dict()        
        if send_grid_support and category:
            headers['X-SMTPAPI'] = '{"category": "%s"}' % header_category_value

        # Check for Mailgun support and add label header
        # --------------------------------
        if hasattr(settings, 'MAILING_USE_MAILGUN'):
            mailgun_support = settings.MAILING_USE_MAILGUN
        else:
            mailgun_support = False

        if not headers:
            headers = dict()        
        if mailgun_support and category:
            headers['X-Mailgun-Tag'] = header_category_value


        # Ensure recipients are in a list
        # --------------------------------
        if isinstance(recipients, basestring):
            recipients_list = [recipients]
        else:
            recipients_list = recipients

        # Check if we need to hijack the email
        # --------------------------------
        if hasattr(settings, 'MAILING_MAILTO_HIJACK') and not bypass_hijacking:
            headers['X-MAILER-ORIGINAL-MAILTO'] = ','.join(recipients_list)
            recipients_list = [settings.MAILING_MAILTO_HIJACK]

        if not subject:
            raise MailerMissingSubjectError('Subject not supplied')

        # Send ascii, html or multi-part email
        # --------------------------------
        if text_content or html_content:
            if use_base_template:
                prev_language = translation.get_language()
                language and translation.activate(language)
                text_content = render_to_string('mailing/base.txt', {'mailing_text_body': text_content, 'mailing_subject': subject, 'settings': settings}) if text_content else None
                html_content = render_to_string('mailing/base.html', {'mailing_html_body': html_content, 'mailing_subject': subject, 'settings': settings}) if html_content else None
                translation.activate(prev_language)
            msg = EmailMultiAlternatives(subject, text_content if text_content else html_content, from_email if from_email else settings.DEFAULT_FROM_EMAIL, recipients_list, cc=cc, bcc=bcc, attachments=attachments, headers = headers)
            if html_content and text_content:
                msg.attach_alternative(html_content, "text/html")
            elif html_content: # Only HTML
                msg.content_subtype = "html"

            # Attach files through attach_files helper
            # --------------------------------
            if attach_files:
                for att in attach_files:  # attachments are tuples of (filepath, mimetype, filename)
                    with open(att[0], 'rb') as f:
                        content = f.read()
                    msg.attach(att[2], content, att[1])

            # Send email
            # --------------------------------

            msg.send(fail_silently=fail_silently)
        else:
            raise MailerInvalidBodyError('No text or html body supplied.')
925632
def create_org(self):
        
        if not self.config_file:
            # FIXME: raise exception
            return
        if not self.scratch_org_type:
            self.config["scratch_org_type"] = "workspace"

        # If the scratch org definition itself contains an `adminEmail` entry,
        # we don't want to override it from our own configuration, which may
        # simply come from the user's Git config.

        with open(self.config_file, "r") as org_def:
            org_def_data = json.load(org_def)
            org_def_has_email = "adminEmail" in org_def_data

        options = {
            "config_file": self.config_file,
            "devhub": " --targetdevhubusername {}".format(self.devhub)
            if self.devhub
            else "",
            "namespaced": " -n" if not self.namespaced else "",
            "days": " --durationdays {}".format(self.days) if self.days else "",
            "alias": sarge.shell_format(' -a "{0!s}"', self.sfdx_alias)
            if self.sfdx_alias
            else "",
            "email": sarge.shell_format('adminEmail="{0!s}"', self.email_address)
            if self.email_address and not org_def_has_email
            else "",
            "extraargs": os.environ.get("SFDX_ORG_CREATE_ARGS", ""),
        }

        # This feels a little dirty, but the use cases for extra args would mostly
        # work best with env vars
        command = "sfdx force:org:create -f {config_file}{devhub}{namespaced}{days}{alias} {email} {extraargs}".format(
            **options
        )
        self.logger.info("Creating scratch org with command {}".format(command))
        p = sarge.Command(
            command,
            stdout=sarge.Capture(buffer_size=-1),
            stderr=sarge.Capture(buffer_size=-1),
            shell=True,
        )
        p.run()

        stderr = [line.strip() for line in io.TextIOWrapper(p.stderr)]
        stdout = [line.strip() for line in io.TextIOWrapper(p.stdout)]

        if p.returncode:
            message = "{}: \n{}\n{}".format(
                FAILED_TO_CREATE_SCRATCH_ORG, "\n".join(stdout), "\n".join(stderr)
            )
            raise ScratchOrgException(message)

        re_obj = re.compile("Successfully created scratch org: (.+), username: (.+)")
        for line in stdout:
            match = re_obj.search(line)
            if match:
                self.config["org_id"] = match.group(1)
                self.config["username"] = match.group(2)
            self.logger.info(line)
        for line in stderr:
            self.logger.error(line)

        self.config["date_created"] = datetime.datetime.now()

        if self.config.get("set_password"):
            self.generate_password()

        # Flag that this org has been created
        self.config["created"] = True
1182780
def _do(name, gnome_kwargs, preferences):
    '''
    
    '''
    ret = {'name': name,
           'result': True,
           'changes': {},
           'comment': ''}

    messages = []

    for pref in preferences:
        key = pref
        value = preferences[pref]

        if isinstance(value, bool):
            ftype = 'boolean'

            # need to convert boolean values to strings and make lowercase to
            # pass to gsettings
            value = six.text_type(value).lower()

        elif isinstance(value, int):
            ftype = 'int'
        elif isinstance(value, six.string_types):
            ftype = 'string'
        else:
            ftype = 'string'

        gnome_kwargs.update({'key': key, 'value': value})

        if _check_current_value(gnome_kwargs, value):
            messages.append('{0} is already set to {1}'.format(key, value))
        else:
            result = __salt__['gnome.set'](**gnome_kwargs)
            if result['retcode'] == 0:
                messages.append('Setting {0} to {1}'.format(key, value))
                ret['changes'][key] = '{0}:{1}'.format(key, value)
                ret['result'] = True
            else:
                messages.append(result['stdout'])
                ret['result'] = False

        ret['comment'] = ', '.join(messages)

    return ret
791784
def xdg_config_dirs():
    
    paths = []
    if 'XDG_CONFIG_HOME' in os.environ:
        paths.append(os.environ['XDG_CONFIG_HOME'])
    if 'XDG_CONFIG_DIRS' in os.environ:
        paths.extend(os.environ['XDG_CONFIG_DIRS'].split(':'))
    else:
        paths.append('/etc/xdg')
    paths.append('/etc')
    return paths
1005995
def system_supports_plotting():
    
    try:
        if os.environ['ALLOW_PLOTTING'].lower() == 'true':
            return True
    except KeyError:
        pass
    try:
        p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
        p.communicate()
        return p.returncode == 0
    except:
        return False
298509
def get_x():
    '''
    
    '''
    cmd = 'setxkbmap -query | grep layout'
    out = __salt__['cmd.run'](cmd, python_shell=True).split(':')
    return out[1].strip()
167196
function Email (template, options) {
	debug('email %s', template);

	options = options || {};

	if (!template) {
		throw new Error('You must provide an email template');
	}

	// init extension and engine
	// options.ext is supported for backwards compatibility with keystone.Email
	this.ext = path.extname(template) || options.ext;
	var engine = options.engine;
	if (!this.ext && !engine) {
		throw new Error('You must provide options.engine or include the extension in your template path');
	} else if (!this.ext && typeof engine === 'function') {
		throw new Error('You must include the extension in your template path when options.engine is a function');
	} else if (!this.ext) {
		this.ext = '.' + engine;
	} else if (!engine) {
		engine = this.ext.substr(1);
	}
	this.engine = getEngine(engine);
	if (typeof this.engine !== 'function') {
		throw new Error('Invalid engine (' + engine + ')');
	}
	// this corrects for if options.ext is passed in without the `.`
	if (this.ext[0] !== '.') {
		this.ext = '.' + this.ext;
	}

	// init template
	this.root = options.root || process.cwd();
	this.template = this.resolve(template);
	if (!isFile(this.template)) {
		throw new Error('Invalid template (' + template + '), could not find file "' + this.template + '"');
	}

	// init transport
	if (options.transport) {
		this.transport = getTransport(options.transport);
	}

	// stash options without consumed properties, this.send() uses it as defaults
	this.options = assign({}, options);
	delete this.options.engine;
	delete this.options.ext;
	delete this.options.root;
	delete this.options.transport;
}
858607
def xrdb(xrdb_files=None):
    """"""
    xrdb_files = xrdb_files or \
        [os.path.join(CACHE_DIR, "colors.Xresources")]

    if shutil.which("xrdb") and OS != "Darwin":
        for file in xrdb_files:
            subprocess.run(["xrdb", "-merge", "-quiet", file])
793340
def execute_xelatex( latex, dir )
            success = false
            @log    = ''

            if @packages_path
                ENV['TEXINPUTS'] = "#{@packages_path}:"
            end
            Open3.popen2e( ErbLatex.config.xelatex_path,
              "--no-shell-escape", "-shell-restricted",
              "-jobname=output",   "-output-directory=#{dir}",
            ) do |stdin, output, wait_thr|
                stdin.write latex
                stdin.close
                @log    = output.read.strip
                success = ( 0 == wait_thr.value )
            end
            success
        end