text:
/* eslint-env jest */
/**
 * @fileoverview Performs validity check on anchor hrefs. Warns when anchors are used as buttons.
 * @author Almero Steyn
 */

// -----------------------------------------------------------------------------
// Requirements
// -----------------------------------------------------------------------------

import { RuleTester } from 'eslint';
import parserOptionsMapper from '../../__util__/parserOptionsMapper';
import rule from '../../../src/rules/anchor-is-valid';

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

const ruleTester = new RuleTester();

const preferButtonErrorMessage = 'Anchor used as a button. ' +
  'Anchors are primarily expected to navigate. ' +
  'Use the button element instead.';

const noHrefErrorMessage = 'The href attribute is required on an anchor. ' +
  'Provide a valid, navigable address as the href value.';

const invalidHrefErrorMessage = 'The href attribute requires a valid address. ' +
  'Provide a valid, navigable address as the href value.';

const preferButtonexpectedError = {
  message: preferButtonErrorMessage,
  type: 'JSXOpeningElement',
};
const noHrefexpectedError = {
  message: noHrefErrorMessage,
  type: 'JSXOpeningElement',
};
const invalidHrefexpectedError = {
  message: invalidHrefErrorMessage,
  type: 'JSXOpeningElement',
};

const components = [{
  components: ['Anchor', 'Link'],
}];
const specialLink = [{
  specialLink: ['hrefLeft', 'hrefRight'],
}];
const noHrefAspect = [{
  aspects: ['noHref'],
}];
const invalidHrefAspect = [{
  aspects: ['invalidHref'],
}];
const preferButtonAspect = [{
  aspects: ['preferButton'],
}];
const noHrefInvalidHrefAspect = [{
  aspects: ['noHref', 'invalidHref'],
}];
const noHrefPreferButtonAspect = [{
  aspects: ['noHref', 'preferButton'],
}];
const preferButtonInvalidHrefAspect = [{
  aspects: ['preferButton', 'invalidHref'],
}];

const componentsAndSpecialLink = [{
  components: ['Anchor'],
  specialLink: ['hrefLeft'],
}];

const componentsAndSpecialLinkAndInvalidHrefAspect = [{
  components: ['Anchor'],
  specialLink: ['hrefLeft'],
  aspects: ['invalidHref'],
}];

const componentsAndSpecialLinkAndNoHrefAspect = [{
  components: ['Anchor'],
  specialLink: ['hrefLeft'],
  aspects: ['noHref'],
}];

ruleTester.run('anchor-is-valid', rule, {
  valid: [
    // DEFAULT ELEMENT 'a' TESTS
    { code: '' },
    { code: '' },
    { code: '' },
    { code: '' },
    { code: '' },
    { code: '
' },
    { code: '<a href={`#foo`}/>' },
    { code: '' },
    { code: '' },
    { code: '<UX.Layout>test</UX.Layout>' },
    { code: '' },

    // CUSTOM ELEMENT TEST FOR ARRAY OPTION
    { code: '<Anchor {...props} />', options: components },
    { code: '<Anchor href="foo" />', options: components },
    { code: '<Anchor href={foo} />', options: components },
    { code: '<Anchor href="/foo" />', options: components },
    { code: '<Anchor href="https://foo.bar.com" />', options: components },
    { code: '
', options: components },
    { code: '<Anchor href={`#foo`}/>', options: components },
    { code: '<Anchor href={"foo"}/>', options: components },
    { code: '<Anchor href="#foo" />', options: components },
    { code: '<Link {...props} />', options: components },
    { code: '<Link href="foo" />', options: components },
    { code: '<Link href={foo} />', options: components },
    { code: '<Link href="/foo" />', options: components },
    { code: '<Link href="https://foo.bar.com" />', options: components },
    { code: '
', options: components },
    { code: '<Link href={`#foo`}/>', options: components },
    { code: '<Link href={"foo"}/>', options: components },
    { code: '<Link href="#foo" />', options: components },

    // CUSTOM PROP TESTS
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '
', options: specialLink },
    { code: '<a hrefLeft={`#foo`}/>', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '<UX.Layout>test</UX.Layout>', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '
', options: specialLink },
    { code: '<a hrefRight={`#foo`}/>', options: specialLink },
    { code: '', options: specialLink },
    { code: '', options: specialLink },
    { code: '<UX.Layout>test</UX.Layout>', options: specialLink },
    { code: '', options: specialLink },

    // CUSTOM BOTH COMPONENTS AND SPECIALLINK TESTS
    { code: '<Anchor {...props} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="foo" />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={foo} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="/foo" />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="https://foo.bar.com" />', options: componentsAndSpecialLink },
    { code: '
', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={`#foo`}/>', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={"foo"}/>', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="#foo" />', options: componentsAndSpecialLink },
    { code: '<UX.Layout>test</UX.Layout>', options: componentsAndSpecialLink },

    // WITH ONCLICK
    // DEFAULT ELEMENT 'a' TESTS
    { code: ' void 0} />' },
    { code: ' void 0} />' },
    { code: ' void 0} />' },
    { code: ' void 0} />' },
    { code: ' void 0} />' },
    { code: '
 void 0} />' },
    { code: '<a href={`#foo`} onClick={() => void 0} />' },
    { code: ' void 0} />' },
    { code: ' void 0} />' },
    { code: ' void 0} />' },

    // CUSTOM ELEMENT TEST FOR ARRAY OPTION
    { code: '<Anchor {...props} onClick={() => void 0} />', options: components },
    { code: '<Anchor href="foo" onClick={() => void 0} />', options: components },
    { code: '<Anchor href={foo} onClick={() => void 0} />', options: components },
    { code: '<Anchor href="/foo" onClick={() => void 0} />', options: components },
    { code: '<Anchor href="https://foo.bar.com" onClick={() => void 0} />', options: components },
    { code: '<Anchor href={`#foo`} onClick={() => void 0} />', options: components },
    { code: '<Anchor href={"foo"} onClick={() => void 0} />', options: components },
    { code: '<Anchor href="#foo" onClick={() => void 0} />', options: components },
    { code: '<Link {...props} onClick={() => void 0} />', options: components },
    { code: '<Link href="foo" onClick={() => void 0} />', options: components },
    { code: '<Link href={foo} onClick={() => void 0} />', options: components },
    { code: '<Link href="/foo" onClick={() => void 0} />', options: components },
    { code: '<Link href="https://foo.bar.com" onClick={() => void 0} />', options: components },
    { code: '
 void 0} />', options: components },
    { code: '<Link href={`#foo`} onClick={() => void 0} />', options: components },
    { code: '<Link href={"foo"} onClick={() => void 0} />', options: components },
    { code: '<Link href="#foo" onClick={() => void 0} />', options: components },

    // CUSTOM PROP TESTS
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: '
 void 0} />', options: specialLink },
    { code: '<a hrefLeft={`#foo`} onClick={() => void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: '
 void 0} />', options: specialLink },
    { code: '<a hrefRight={`#foo`} onClick={() => void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },
    { code: ' void 0} />', options: specialLink },

    // CUSTOM BOTH COMPONENTS AND SPECIALLINK TESTS
    { code: '<Anchor {...props} onClick={() => void 0} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="foo" onClick={() => void 0} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={foo} onClick={() => void 0} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="/foo" onClick={() => void 0} />', options: componentsAndSpecialLink },
    {
      code: '<Anchor hrefLeft href="https://foo.bar.com" onClick={() => void 0} />',
      options: componentsAndSpecialLink,
    },
    { code: '<Anchor hrefLeft={`#foo`} onClick={() => void 0} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={"foo"} onClick={() => void 0} />', options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="#foo" onClick={() => void 0} />', options: componentsAndSpecialLink },

    // WITH ASPECTS TESTS
    // NO HREF
    { code: '', options: invalidHrefAspect },
    { code: '', options: invalidHrefAspect },
    { code: '', options: invalidHrefAspect },
    { code: '', options: preferButtonAspect },
    { code: '', options: preferButtonAspect },
    { code: '', options: preferButtonAspect },
    { code: '', options: preferButtonInvalidHrefAspect },
    { code: '', options: preferButtonInvalidHrefAspect },
    { code: '', options: preferButtonInvalidHrefAspect },

    // INVALID HREF
    { code: ';', options: preferButtonAspect },
    { code: '', options: preferButtonAspect },
    { code: '', options: preferButtonAspect },
    { code: '', options: preferButtonAspect },
    { code: '', options: preferButtonAspect },
    { code: ';', options: noHrefAspect },
    { code: '', options: noHrefAspect },
    { code: '', options: noHrefAspect },
    { code: '', options: noHrefAspect },
    { code: '', options: noHrefAspect },
    { code: ';', options: noHrefPreferButtonAspect },
    { code: '', options: noHrefPreferButtonAspect },
    { code: '', options: noHrefPreferButtonAspect },
    { code: '', options: noHrefPreferButtonAspect },
    { code: '', options: noHrefPreferButtonAspect },

    // SHOULD BE BUTTON
    { code: ' void 0} />', options: invalidHrefAspect },
    { code: ' void 0} />', options: noHrefAspect },
    { code: ' void 0} />', options: noHrefAspect },
    {
      code: ' void 0} />',
      options: noHrefAspect,
    },

    // CUSTOM COMPONENTS AND SPECIALLINK AND ASPECT
    { code: '<Anchor hrefLeft={undefined} />', options: componentsAndSpecialLinkAndInvalidHrefAspect },
    { code: '<Anchor hrefLeft={null} />', options: componentsAndSpecialLinkAndInvalidHrefAspect },
    { code: '<Anchor hrefLeft={undefined} />', options: componentsAndSpecialLinkAndInvalidHrefAspect },
    { code: '<Anchor hrefLeft={null} />', options: componentsAndSpecialLinkAndInvalidHrefAspect },
    { code: '<Anchor hrefLeft={undefined} />', options: componentsAndSpecialLinkAndInvalidHrefAspect },
    { code: '<Anchor hrefLeft={null} />', options: componentsAndSpecialLinkAndInvalidHrefAspect },

  ].map(parserOptionsMapper),
  invalid: [
    // DEFAULT ELEMENT 'a' TESTS
    // NO HREF
    { code: '', errors: [noHrefexpectedError] },
    { code: '', errors: [noHrefexpectedError] },
    { code: '', errors: [noHrefexpectedError] },
    // INVALID HREF
    { code: ';', errors: [invalidHrefexpectedError] },
    { code: '', errors: [invalidHrefErrorMessage] },
    { code: '', errors: [invalidHrefErrorMessage] },
    { code: '', errors: [invalidHrefexpectedError] },
    { code: '', errors: [invalidHrefexpectedError] },
    // SHOULD BE BUTTON
    { code: ' void 0} />', errors: [preferButtonexpectedError] },
    { code: ' void 0} />', errors: [preferButtonexpectedError] },
    { code: ' void 0} />', errors: [preferButtonexpectedError] },
    {
      code: ' void 0} />',
      errors: [preferButtonexpectedError],
    },

    // CUSTOM ELEMENT TEST FOR ARRAY OPTION
    // NO HREF
    { code: '<Link />', errors: [noHrefexpectedError], options: components },
    { code: '<Link href={undefined} />', errors: [noHrefexpectedError], options: components },
    { code: '<Link href={null} />', errors: [noHrefexpectedError], options: components },
    // INVALID HREF
    { code: '<Link href="" />', errors: [invalidHrefexpectedError], options: components },
    { code: '<Link href="#" />', errors: [invalidHrefErrorMessage], options: components },
    { code: '<Link href={"#"} />', errors: [invalidHrefErrorMessage], options: components },
    { code: '<Link href="javascript:void(0)" />', errors: [invalidHrefexpectedError], options: components },
    { code: '<Link href={"javascript:void(0)"} />', errors: [invalidHrefexpectedError], options: components },
    { code: '<Anchor href="" />', errors: [invalidHrefexpectedError], options: components },
    { code: '<Anchor href="#" />', errors: [invalidHrefErrorMessage], options: components },
    { code: '<Anchor href={"#"} />', errors: [invalidHrefErrorMessage], options: components },
    { code: '<Anchor href="javascript:void(0)" />', errors: [invalidHrefexpectedError], options: components },
    { code: '<Anchor href={"javascript:void(0)"} />', errors: [invalidHrefexpectedError], options: components },
    // SHOULD BE BUTTON
    { code: '<Link onClick={() => void 0} />', errors: [preferButtonexpectedError], options: components },
    { code: '<Link href="#" onClick={() => void 0} />', errors: [preferButtonexpectedError], options: components },
    {
      code: '<Link href="javascript:void(0)" onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: components,
    },
    {
      code: '<Link href={"javascript:void(0)"} onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: components,
    },
    { code: '<Anchor onClick={() => void 0} />', errors: [preferButtonexpectedError], options: components },
    { code: '<Anchor href="#" onClick={() => void 0} />', errors: [preferButtonexpectedError], options: components },
    {
      code: '<Anchor href="javascript:void(0)" onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: components,
    },
    {
      code: '<Anchor href={"javascript:void(0)"} onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: components,
    },

    // CUSTOM PROP TESTS
    // NO HREF
    { code: '', errors: [noHrefexpectedError], options: specialLink },
    { code: '', errors: [noHrefexpectedError], options: specialLink },
    // INVALID HREF
    { code: ';', errors: [invalidHrefexpectedError], options: specialLink },
    { code: '', errors: [invalidHrefErrorMessage], options: specialLink },
    { code: '', errors: [invalidHrefErrorMessage], options: specialLink },
    { code: '', errors: [invalidHrefexpectedError], options: specialLink },
    { code: '', errors: [invalidHrefexpectedError], options: specialLink },
    // SHOULD BE BUTTON
    { code: ' void 0} />', errors: [preferButtonexpectedError], options: specialLink },
    {
      code: ' void 0} />',
      errors: [preferButtonexpectedError],
      options: specialLink,
    },
    {
      code: ' void 0} />',
      errors: [preferButtonexpectedError],
      options: specialLink,
    },

    // CUSTOM BOTH COMPONENTS AND SPECIALLINK TESTS
    // NO HREF
    { code: '<Anchor Anchor={undefined} />', errors: [noHrefexpectedError], options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={null} />', errors: [noHrefexpectedError], options: componentsAndSpecialLink },
    // INVALID HREF
    { code: '<Anchor hrefLeft="" />;', errors: [invalidHrefexpectedError], options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft="#" />', errors: [invalidHrefErrorMessage], options: componentsAndSpecialLink },
    { code: '<Anchor hrefLeft={"#"} />', errors: [invalidHrefErrorMessage], options: componentsAndSpecialLink },
    {
      code: '<Anchor hrefLeft="javascript:void(0)" />',
      errors: [invalidHrefexpectedError],
      options: componentsAndSpecialLink,
    },
    {
      code: '<Anchor hrefLeft={"javascript:void(0)"} />',
      errors: [invalidHrefexpectedError],
      options: componentsAndSpecialLink,
    },
    // SHOULD BE BUTTON
    {
      code: '<Anchor hrefLeft="#" onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: componentsAndSpecialLink,
    },
    {
      code: '<Anchor hrefLeft="javascript:void(0)" onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: componentsAndSpecialLink,
    },
    {
      code: '<Anchor hrefLeft={"javascript:void(0)"} onClick={() => void 0} />',
      errors: [preferButtonexpectedError],
      options: componentsAndSpecialLink,
    },

    // WITH ASPECTS TESTS
    // NO HREF
    { code: '', options: noHrefAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefPreferButtonAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefInvalidHrefAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefPreferButtonAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefInvalidHrefAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefPreferButtonAspect, errors: [noHrefErrorMessage] },
    { code: '', options: noHrefInvalidHrefAspect, errors: [noHrefErrorMessage] },

    // INVALID HREF
    { code: ';', options: invalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: noHrefInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: preferButtonInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: invalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: noHrefInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: preferButtonInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: invalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: noHrefInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: preferButtonInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: invalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: noHrefInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    {
      code: ';',
      options: preferButtonInvalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },
    { code: ';', options: invalidHrefAspect, errors: [invalidHrefErrorMessage] },
    { code: ';', options: noHrefInvalidHrefAspect, errors: [invalidHrefErrorMessage] },
    {
      code: ';',
      options: preferButtonInvalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },

    // SHOULD BE BUTTON
    { code: ' void 0} />', options: preferButtonAspect, errors: [preferButtonErrorMessage] },
    {
      code: ' void 0} />',
      options: preferButtonInvalidHrefAspect,
      errors: [preferButtonErrorMessage],
    },
    { code: ' void 0} />', options: noHrefPreferButtonAspect, errors: [preferButtonErrorMessage] },
    { code: ' void 0} />', options: noHrefAspect, errors: [noHrefErrorMessage] },
    { code: ' void 0} />', options: noHrefInvalidHrefAspect, errors: [noHrefErrorMessage] },
    { code: ' void 0} />', options: preferButtonAspect, errors: [preferButtonErrorMessage] },
    {
      code: ' void 0} />',
      options: noHrefPreferButtonAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: preferButtonInvalidHrefAspect,
      errors: [preferButtonErrorMessage],
    },
    { code: ' void 0} />', options: invalidHrefAspect, errors: [invalidHrefErrorMessage] },
    {
      code: ' void 0} />',
      options: noHrefInvalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },
    {
      code: ' void 0} />',
      options: preferButtonAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: noHrefPreferButtonAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: preferButtonInvalidHrefAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: invalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },
    {
      code: ' void 0} />',
      options: noHrefInvalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },
    {
      code: ' void 0} />',
      options: preferButtonAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: noHrefPreferButtonAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: preferButtonInvalidHrefAspect,
      errors: [preferButtonErrorMessage],
    },
    {
      code: ' void 0} />',
      options: invalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },
    {
      code: ' void 0} />',
      options: noHrefInvalidHrefAspect,
      errors: [invalidHrefErrorMessage],
    },

    // CUSTOM COMPONENTS AND SPECIALLINK AND ASPECT
    {
      code: '<Anchor hrefLeft={undefined} />',
      options: componentsAndSpecialLinkAndNoHrefAspect,
      errors: [noHrefErrorMessage],
    },
    {
      code: '<Anchor hrefLeft={null} />',
      options: componentsAndSpecialLinkAndNoHrefAspect,
      errors: [noHrefErrorMessage],
    },
    {
      code: '<Anchor hrefLeft={undefined} />',
      options: componentsAndSpecialLinkAndNoHrefAspect,
      errors: [noHrefErrorMessage],
    },
    {
      code: '<Anchor hrefLeft={null} />',
      options: componentsAndSpecialLinkAndNoHrefAspect,
      errors: [noHrefErrorMessage],
    },
    {
      code: '<Anchor hrefLeft={undefined} />',
      options: componentsAndSpecialLinkAndNoHrefAspect,
      errors: [noHrefErrorMessage],
    },
    {
      code: '<Anchor hrefLeft={null} />',
      options: componentsAndSpecialLinkAndNoHrefAspect,
      errors: [noHrefErrorMessage],
    },
  ].map(parserOptionsMapper),
});


text:
package com.huhaoyu.rx_wind;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * To work on unit tests, switch the Test Artifact in the Build Variants view.
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<title>WebMail Hilfe</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<LINK href="javascript/stylehelp.css" rel=stylesheet type=text/css>

Tipps und Tricks  [ Language/help/file.html">Hilfe Index ]

WebMail Tipps und Tricks

Erhöhen Sie die Performance des WebMail Systems, indem Sie Ihren Browser veranlassen, HTML und Bilder zu cachen. Im Internet Explorer ist diese Option zu finden unter: Internetoptionen -> Temporary Internet Files -> Einstellungen -> Neuere Version gespeicherter Seiten suchen: Automatisch.

 Indem Sie auf eine Nachtricht Rechtsklicken, öffnet sich ein Kontextmenü. Dieses offeriert Ihnen einen komfortablen Weg, auf Nachrichten zu antworten, sie weiterzuleiten oder eine Nachricht zu öffnen.

Über den "Empfänger hinzufügen" Knopf können Sie E-Mail Adressen aus Ihrem Adressbuch in das Empfängerfeld einfügen. Wenn Sie auf den Knopf klicken öffnet sich hierzu das Adressbuch.

Wollen Sie Adressen aus anderen LDAP-Servern verwenden? Kein Problem - im Nach Personen suchen Fenster können Sie den LDAP-Server, sowie die Suchkriterien angeben.

Wussten Sie, daß Sie Nachrichten auf einfache Art und Weise per Drag n Drop von einem Ordner in einen anderen verschieben können?


text:
import tornado.web
import tornado.util
import my.db
import my.session

class Handler(tornado.web.RequestHandler, my.db.Mixin, my.session.Mixin):

    def initialize(self):
        self.db = my.db.Postgres(self.application.config.database)
        self.session = None
        self.session_prepare()

    def set_default_headers(self):
        # For security
        self.clear_header('Server')

    def get_current_user(self):
        log_token = self.get_secure_cookie('log_token', None)
        if log_token:
            return self.session['user']['name']
        else:
            return None

    def get_cookie_utf8(self, name):
        value = self.get_secure_cookie(name)
        if value:
            return value.decode('utf-8')

    def write_error(self, status_code, **kwargs):
        if self.settings['debug']:
            super().write_error(status_code, **kwargs)
        else:
            self.render('error', code=status_code)
    def bulk_arguments(self, fields):
        return { field: self.get_body_argument(field, '') for field in fields }

    def get_template_namespace(self):
        namespace = super().get_template_namespace()
        namespace.update({
            'helper': tornado.util.import_object('tmpl.helper')
        })
        return namespace


text:
<?php

// No direct access
defined('_HZEXEC_') or die();

$course = \Components\Courses\Models\Course::getInstance($this->model->get('course_id'));
$roles = $course->offering(0)->roles(array('alias' => '!student'));
$offerings = $course->offerings();

$this->js('managers.js');
?>
<?php if ($this->getError()) { ?>

<?php echo Lang::txt('ERROR'); ?>

<?php echo implode('
', $this->getErrors()); ?>

<?php } ?>

	<form action="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=' . $this->controller); ?>" method="post">

							<input type="text" name="usernames" value="" />
							<?php echo Lang::txt('COM_COURSES_ENTER_USERS'); ?>

						<select name="role">
						<?php foreach ($roles as $role) { ?>
							<option value="<?php echo $role->id; ?>"><?php echo $this->escape(stripslashes($role->title)); ?></option>
						<?php } ?>
						<?php
						foreach ($offerings as $offering)
						{
							$oroles = $offering->roles(array('offering_id' => $offering->get('id')));
							if (!$oroles || !count($oroles))
							{
								continue;
							}
						?>
							<optgroup label="<?php echo Lang::txt('Offering:') . ' ' . $this->escape($offering->get('title')); ?>">
							<?php foreach ($oroles as $role) { ?>
								<option value="<?php echo $role->id; ?>"><?php echo $this->escape(stripslashes($role->title)); ?></option>
							<?php } ?>
							</optgroup>
						<?php } ?>
						</select>

						<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
						<input type="hidden" name="controller" value="<?php echo $this->controller; ?>">
						<input type="hidden" name="tmpl" value="component" />
						<input type="hidden" name="section" value="<?php echo $this->model->section()->get('id'); ?>" />
						<input type="hidden" name="offering" value="<?php echo $this->model->get('id'); ?>" />
						<input type="hidden" name="task" value="add" />

						<input type="submit" value="<?php echo Lang::txt('COM_COURSES_ADD_USER'); ?>" />

		<?php echo Html::input('token'); ?>
	</form>
	<form action="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=' . $this->controller); ?>" method="post" id="adminForm">

						<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
						<input type="hidden" name="controller" value="<?php echo $this->controller; ?>">
						<input type="hidden" name="tmpl" value="component" />
						<input type="hidden" name="section" value="<?php echo $this->model->section()->get('id'); ?>" />
						<input type="hidden" name="offering" value="<?php echo $this->model->get('id'); ?>" />
						<input type="hidden" name="task" id="task" value="remove" />

						<input type="submit" name="action" value="<?php echo Lang::txt('COM_COURSES_REMOVE_USER'); ?>" />

<?php
		$managers = $this->model->members(array(
			'student'     => 0,
			'course_id'   => $this->model->get('course_id'),
			'offering_id' => $this->model->get('id'),
			'section_id'  => $this->model->section()->get('id')
		), true);

		$i = 0;
			foreach ($managers as $manager)
			{
				$u = User::getInstance($manager->get('user_id'));
				if (!is_object($u))
				{
					continue;
				}
?>

						<input type="hidden" name="entries[<?php echo $i; ?>][id]" value="<?php echo $manager->get('id'); ?>" />
						<input type="hidden" name="entries[<?php echo $i; ?>][course_id]" value="<?php echo $this->model->get('course_id'); ?>" />
						<input type="hidden" name="entries[<?php echo $i; ?>][offering_id]" value="<?php echo $this->model->get('id'); ?>" />
						<input type="hidden" name="entries[<?php echo $i; ?>][section_id]" value="<?php echo $this->model->section()->get('id'); ?>" />
						<input type="hidden" name="entries[<?php echo $i; ?>][user_id]" value="<?php echo $u->get('id'); ?>" />
						<input type="checkbox" name="entries[<?php echo $i; ?>][select]" value="<?php echo $manager->get('id'); ?>" />

						<a href="<?php echo Route::url('index.php?option=' . $this->option  . '&controller=members&task=edit&id=' . $u->get('id')); ?>" target="_parent">
							<?php echo $this->escape($u->get('name')) . ' (' . $this->escape($u->get('username')) . ')'; ?>

						<a href="mailto:<?php echo $this->escape($u->get('email')); ?>"><?php echo $this->escape($u->get('email')); ?>

						<select name="entries[<?php echo $i; ?>][role_id]" class="entry-role">
						<?php foreach ($roles as $role) { ?>
							<option value="<?php echo $role->id; ?>"<?php if ($manager->get('role_id') == $role->id) { echo ' selected="selected"'; } ?>><?php echo $this->escape(stripslashes($role->title)); ?></option>
						<?php } ?>
						<?php
						foreach ($offerings as $offering)
						{
							$oroles = $offering->roles(array('offering_id' => $offering->get('id')));
							if (!$oroles || !count($oroles))
							{
								continue;
							}
						?>
							<optgroup label="<?php echo Lang::txt('COM_COURSES_OFFERING') . ': ' . $this->escape($offering->get('title')); ?>">
							<?php foreach ($oroles as $role) { ?>
								<option value="<?php echo $role->id; ?>"<?php if ($manager->get('role_id') == $role->id) { echo ' selected="selected"'; } ?>><?php echo $this->escape(stripslashes($role->title)); ?></option>
							<?php } ?>
							</optgroup>
						<?php } ?>
						</select>

<?php
				$i++;
			}

?>

		<?php echo Html::input('token'); ?>
	</form>


text:
class SessionsController < ApplicationController
  skip_before_action :check_login, only: [:new, :create]

  def new
    if !current_user.nil?
        redirect_to home_path
    end
  end

  def create
    user = User.find_by_email(params[:email])
    puts "user: #{user.to_yaml}"
    if user && User.authenticate(params[:email], params[:password])
      session[:user_id] = user.id
      redirect_to home_path, notice: "Logged in!"
    else
      flash.now.alert = "Email or password is invalid"
      render "new"
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to home_path, notice: "Logged out!"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09_Extract_Middle_Elements
{
    class ExtractMiddleElements
    {
        /*Write a method to extract the middle 1, 2 or 3 elements from array of n integers and print them.
            n = 1 -> 1 element
            even n -> 2 elements
            odd n -> 3 elements
        Create a program that reads an array of integers (space separated values) and prints the middle elements in the format shown in the examples.*/

        static void Main(string[] args)
        {
            int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int n = numbers.Length;
            int[] result;

            if (n == 1)
            {
                result = new int[1];
                result[0] = numbers[0];
            }

            else if (n % 2 == 0)
            {
                result = new int[2];
                result[0] = numbers[n / 2 - 1];
                result[1] = numbers[n / 2];
            }

            else
            {
                result = new int[3];
                result[0] = numbers[n / 2 - 1];
                result[1] = numbers[n / 2];
                result[2] = numbers[n / 2 + 1];
            }
            Console.WriteLine(string.Join(", ", result));
        }
    }
}


text:
package org.apache.ibatis.builder;

import static com.googlecode.catchexception.apis.BDDCatchException.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.BDDAssertions.then;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.InputStream;
import java.io.StringReader;
import java.math.RoundingMode;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;

import org.apache.ibatis.builder.mapper.CustomMapper;
import org.apache.ibatis.builder.typehandler.CustomIntegerTypeHandler;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.domain.blog.Author;
import org.apache.ibatis.domain.blog.Blog;
import org.apache.ibatis.domain.blog.mappers.BlogMapper;
import org.apache.ibatis.domain.blog.mappers.NestedBlogMapper;
import org.apache.ibatis.domain.jpetstore.Cart;
import org.apache.ibatis.executor.loader.cglib.CglibProxyFactory;
import org.apache.ibatis.executor.loader.javassist.JavassistProxyFactory;
import org.apache.ibatis.io.JBoss6VFS;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.ResultSetType;
import org.apache.ibatis.scripting.defaults.RawLanguageDriver;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.EnumOrdinalTypeHandler;
import org.apache.ibatis.type.EnumTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.junit.jupiter.api.Test;

class XmlConfigBuilderTest {

  @Test
  void shouldSuccessfullyLoadMinimalXMLConfigFile() throws Exception {
    String resource = "org/apache/ibatis/builder/MinimalMapperConfig.xml";
    try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
      XMLConfigBuilder builder = new XMLConfigBuilder(inputStream);
      Configuration config = builder.parse();
      assertNotNull(config);
      assertThat(config.getAutoMappingBehavior()).isEqualTo(AutoMappingBehavior.PARTIAL);
      assertThat(config.getAutoMappingUnknownColumnBehavior()).isEqualTo(AutoMappingUnknownColumnBehavior.NONE);
      assertThat(config.isCacheEnabled()).isTrue();
      assertThat(config.getProxyFactory()).isInstanceOf(JavassistProxyFactory.class);
      assertThat(config.isLazyLoadingEnabled()).isFalse();
      assertThat(config.isAggressiveLazyLoading()).isFalse();
      assertThat(config.isMultipleResultSetsEnabled()).isTrue();
      assertThat(config.isUseColumnLabel()).isTrue();
      assertThat(config.isUseGeneratedKeys()).isFalse();
      assertThat(config.getDefaultExecutorType()).isEqualTo(ExecutorType.SIMPLE);
      assertNull(config.getDefaultStatementTimeout());
      assertNull(config.getDefaultFetchSize());
      assertNull(config.getDefaultResultSetType());
      assertThat(config.isMapUnderscoreToCamelCase()).isFalse();
      assertThat(config.isSafeRowBoundsEnabled()).isFalse();
      assertThat(config.getLocalCacheScope()).isEqualTo(LocalCacheScope.SESSION);
      assertThat(config.getJdbcTypeForNull()).isEqualTo(JdbcType.OTHER);
      assertThat(config.getLazyLoadTriggerMethods()).isEqualTo(new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString")));
      assertThat(config.isSafeResultHandlerEnabled()).isTrue();
      assertThat(config.getDefaultScriptingLanuageInstance()).isInstanceOf(XMLLanguageDriver.class);
      assertThat(config.isCallSettersOnNulls()).isFalse();
      assertNull(config.getLogPrefix());
      assertNull(config.getLogImpl());
      assertNull(config.getConfigurationFactory());
      assertThat(config.getTypeHandlerRegistry().getTypeHandler(RoundingMode.class)).isInstanceOf(EnumTypeHandler.class);
      assertThat(config.isShrinkWhitespacesInSql()).isFalse();
      assertThat(config.getDefaultSqlProviderType()).isNull();
    }
  }

  enum MyEnum {
    ONE, TWO
  }

  public static class EnumOrderTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> {

    private E[] constants;

    public EnumOrderTypeHandler(Class<E> javaType) {
      constants = javaType.getEnumConstants();
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
      ps.setInt(i, parameter.ordinal() + 1); // 0 means NULL so add +1
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
      int index = rs.getInt(columnName) - 1;
      return index < 0 ? null : constants[index];
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
      int index = rs.getInt(rs.getInt(columnIndex)) - 1;
      return index < 0 ? null : constants[index];
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
      int index = cs.getInt(columnIndex) - 1;
      return index < 0 ? null : constants[index];
    }
  }

  @Test
  void registerJavaTypeInitializingTypeHandler() {
    final String MAPPER_CONFIG = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
        + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n"
        + "<configuration>\n"
        + "  <typeHandlers>\n"
        + "    <typeHandler javaType=\"org.apache.ibatis.builder.XmlConfigBuilderTest$MyEnum\"\n"
        + "      handler=\"org.apache.ibatis.builder.XmlConfigBuilderTest$EnumOrderTypeHandler\"/>\n"
        + "  </typeHandlers>\n"
        + "</configuration>\n";

    XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG));
    builder.parse();

    TypeHandlerRegistry typeHandlerRegistry = builder.getConfiguration().getTypeHandlerRegistry();
    TypeHandler<MyEnum> typeHandler = typeHandlerRegistry.getTypeHandler(MyEnum.class);

    assertTrue(typeHandler instanceof EnumOrderTypeHandler);
    assertArrayEquals(MyEnum.values(), ((EnumOrderTypeHandler<MyEnum>) typeHandler).constants);
  }

  @Test
  void shouldSuccessfullyLoadXMLConfigFile() throws Exception {
    String resource = "org/apache/ibatis/builder/CustomizedSettingsMapperConfig.xml";
    try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
      Properties props = new Properties();
      props.put("prop2", "cccc");
      XMLConfigBuilder builder = new XMLConfigBuilder(inputStream, null, props);
      Configuration config = builder.parse();

      assertThat(config.getAutoMappingBehavior()).isEqualTo(AutoMappingBehavior.NONE);
      assertThat(config.getAutoMappingUnknownColumnBehavior()).isEqualTo(AutoMappingUnknownColumnBehavior.WARNING);
      assertThat(config.isCacheEnabled()).isFalse();
      assertThat(config.getProxyFactory()).isInstanceOf(CglibProxyFactory.class);
      assertThat(config.isLazyLoadingEnabled()).isTrue();
      assertThat(config.isAggressiveLazyLoading()).isTrue();
      assertThat(config.isMultipleResultSetsEnabled()).isFalse();
      assertThat(config.isUseColumnLabel()).isFalse();
      assertThat(config.isUseGeneratedKeys()).isTrue();
      assertThat(config.getDefaultExecutorType()).isEqualTo(ExecutorType.BATCH);
      assertThat(config.getDefaultStatementTimeout()).isEqualTo(10);
      assertThat(config.getDefaultFetchSize()).isEqualTo(100);
      assertThat(config.getDefaultResultSetType()).isEqualTo(ResultSetType.SCROLL_INSENSITIVE);
      assertThat(config.isMapUnderscoreToCamelCase()).isTrue();
      assertThat(config.isSafeRowBoundsEnabled()).isTrue();
      assertThat(config.getLocalCacheScope()).isEqualTo(LocalCacheScope.STATEMENT);
      assertThat(config.getJdbcTypeForNull()).isEqualTo(JdbcType.NULL);
      assertThat(config.getLazyLoadTriggerMethods()).isEqualTo(new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString", "xxx")));
      assertThat(config.isSafeResultHandlerEnabled()).isFalse();
      assertThat(config.getDefaultScriptingLanuageInstance()).isInstanceOf(RawLanguageDriver.class);
      assertThat(config.isCallSettersOnNulls()).isTrue();
      assertThat(config.getLogPrefix()).isEqualTo("mybatis_");
      assertThat(config.getLogImpl().getName()).isEqualTo(Slf4jImpl.class.getName());
      assertThat(config.getVfsImpl().getName()).isEqualTo(JBoss6VFS.class.getName());
      assertThat(config.getConfigurationFactory().getName()).isEqualTo(String.class.getName());
      assertThat(config.isShrinkWhitespacesInSql()).isTrue();
      assertThat(config.getDefaultSqlProviderType().getName()).isEqualTo(MySqlProvider.class.getName());

      assertThat(config.getTypeAliasRegistry().getTypeAliases().get("blogauthor")).isEqualTo(Author.class);
      assertThat(config.getTypeAliasRegistry().getTypeAliases().get("blog")).isEqualTo(Blog.class);
      assertThat(config.getTypeAliasRegistry().getTypeAliases().get("cart")).isEqualTo(Cart.class);

      assertThat(config.getTypeHandlerRegistry().getTypeHandler(Integer.class)).isInstanceOf(CustomIntegerTypeHandler.class);
      assertThat(config.getTypeHandlerRegistry().getTypeHandler(Long.class)).isInstanceOf(CustomLongTypeHandler.class);
      assertThat(config.getTypeHandlerRegistry().getTypeHandler(String.class)).isInstanceOf(CustomStringTypeHandler.class);
      assertThat(config.getTypeHandlerRegistry().getTypeHandler(String.class, JdbcType.VARCHAR)).isInstanceOf(CustomStringTypeHandler.class);
      assertThat(config.getTypeHandlerRegistry().getTypeHandler(RoundingMode.class)).isInstanceOf(EnumOrdinalTypeHandler.class);

      ExampleObjectFactory objectFactory = (ExampleObjectFactory) config.getObjectFactory();
      assertThat(objectFactory.getProperties().size()).isEqualTo(1);
      assertThat(objectFactory.getProperties().getProperty("objectFactoryProperty")).isEqualTo("100");

      assertThat(config.getObjectWrapperFactory()).isInstanceOf(CustomObjectWrapperFactory.class);

      assertThat(config.getReflectorFactory()).isInstanceOf(CustomReflectorFactory.class);

      ExamplePlugin plugin = (ExamplePlugin) config.getInterceptors().get(0);
      assertThat(plugin.getProperties().size()).isEqualTo(1);
      assertThat(plugin.getProperties().getProperty("pluginProperty")).isEqualTo("100");

      Environment environment = config.getEnvironment();
      assertThat(environment.getId()).isEqualTo("development");
      assertThat(environment.getDataSource()).isInstanceOf(UnpooledDataSource.class);
      assertThat(environment.getTransactionFactory()).isInstanceOf(JdbcTransactionFactory.class);

      assertThat(config.getDatabaseId()).isEqualTo("derby");

      assertThat(config.getMapperRegistry().getMappers().size()).isEqualTo(4);
      assertThat(config.getMapperRegistry().hasMapper(CachedAuthorMapper.class)).isTrue();
      assertThat(config.getMapperRegistry().hasMapper(CustomMapper.class)).isTrue();
      assertThat(config.getMapperRegistry().hasMapper(BlogMapper.class)).isTrue();
      assertThat(config.getMapperRegistry().hasMapper(NestedBlogMapper.class)).isTrue();
    }
  }

  @Test
  void shouldSuccessfullyLoadXMLConfigFileWithPropertiesUrl() throws Exception {
    String resource = "org/apache/ibatis/builder/PropertiesUrlMapperConfig.xml";
    try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
      XMLConfigBuilder builder = new XMLConfigBuilder(inputStream);
      Configuration config = builder.parse();
      assertThat(config.getVariables().get("driver").toString()).isEqualTo("org.apache.derby.jdbc.EmbeddedDriver");
      assertThat(config.getVariables().get("prop1").toString()).isEqualTo("bbbb");
    }
  }

  @Test
  void parseIsTwice() throws Exception {
    String resource = "org/apache/ibatis/builder/MinimalMapperConfig.xml";
    try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
      XMLConfigBuilder builder = new XMLConfigBuilder(inputStream);
      builder.parse();

      when(builder::parse);
      then(caughtException()).isInstanceOf(BuilderException.class)
              .hasMessage("Each XMLConfigBuilder can only be used once.");
    }
  }

  @Test
  void unknownSettings() {
    final String MAPPER_CONFIG = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
            + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n"
            + "<configuration>\n"
            + "  <settings>\n"
            + "    <setting name=\"foo\" value=\"bar\"/>\n"
            + "  </settings>\n"
            + "</configuration>\n";

    XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG));
    when(builder::parse);
    then(caughtException()).isInstanceOf(BuilderException.class)
      .hasMessageContaining("The setting foo is not known.  Make sure you spelled it correctly (case sensitive).");
  }

  @Test
  void unknownJavaTypeOnTypeHandler() {
    final String MAPPER_CONFIG = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
            + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n"
            + "<configuration>\n"
            + "  <typeAliases>\n"
            + "    <typeAlias type=\"a.b.c.Foo\"/>\n"
            + "  </typeAliases>\n"
            + "</configuration>\n";

    XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG));
    when(builder::parse);
    then(caughtException()).isInstanceOf(BuilderException.class)
      .hasMessageContaining("Error registering typeAlias for 'null'. Cause: ");
  }

  @Test
  void propertiesSpecifyResourceAndUrlAtSameTime() {
    final String MAPPER_CONFIG = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
            + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n"
            + "<configuration>\n"
            + "  <properties resource=\"a/b/c/foo.properties\" url=\"file:./a/b/c/jdbc.properties\"/>\n"
            + "</configuration>\n";

    XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG));
    when(builder::parse);
    then(caughtException()).isInstanceOf(BuilderException.class)
      .hasMessageContaining("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
  }

  static class MySqlProvider {
    @SuppressWarnings("unused")
    public static String provideSql() {
      return "SELECT 1";
    }
  }

}


text:
import six
from ...errors.httpforbiddenexception import HttpForbiddenException
import saklient

str = six.text_type
# module saklient.cloud.errors.disabledinsandboxexception

class DisabledInSandboxException(HttpForbiddenException):
    ## 要求された操作は許可されていません。このゾーンではこの操作は禁止されています。他のゾーンでお試しください。

    ## @param {int} status
    # @param {str} code=None
    # @param {str} message=""
    def __init__(self, status, code=None, message=""):
        super(DisabledInSandboxException, self).__init__(status, code, "要求された操作は許可されていません。このゾーンではこの操作は禁止されています。他のゾーンでお試しください。" if message is None or message == "" else message)


text:
indicator = {
    shortcode: 'N11',
    shortcodeSlug: 'n11',
    name: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
    points: -150,
    soleProprietorship: true
};


text:
#ifndef CXXLAPACK_INTERFACE_GESVJ_H
#define CXXLAPACK_INTERFACE_GESVJ_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename IndexType>
    IndexType
    gesvj(char          jobA,
          char          jobU,
          char          jobV,
          IndexType     m,
          IndexType     n,
          float         *A,
          IndexType     ldA,
          float         *sva,
          IndexType     mv,
          float         *V,
          IndexType     ldV,
          float         *work,
          IndexType     lWork);

template <typename IndexType>
    IndexType
    gesvj(char          jobA,
          char          jobU,
          char          jobV,
          IndexType     m,
          IndexType     n,
          double        *A,
          IndexType     ldA,
          double        *sva,
          IndexType     mv,
          double        *V,
          IndexType     ldV,
          double        *work,
          IndexType     lWork);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_GESVJ_H


text:
bash /home/ubuntu/stopLoadBalancer

cd


text:
package com.parse.starter;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;

public class SignUpActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Log.d("demo", "user set");

        findViewById(R.id.buttonSignUpNow).setOnClickListener(new View.OnClickListener() {
                                                                  @Override
                                                                  public void onClick(View v) {
                                                                      EditText email = (EditText) findViewById(R.id.editTextUserEmail);
                                                                      if (email.getText().length() < 1 || email == null) {
                                                                          Toast.makeText(SignUpActivity.this, "Please Provide an Email Address", Toast.LENGTH_SHORT).show();
                                                                      } else {

                                                                          ParseUser user = new ParseUser();
                                                                          user.setUsername((((EditText) findViewById(R.id.editTextUserEmail)).getText().toString()));
                                                                          user.setPassword(((EditText) findViewById(R.id.editTextUserPasswordLogIn)).getText().toString());
                                                                          user.setEmail(((EditText) findViewById(R.id.editTextUserEmail)).getText().toString());
                                                                          user.put("UserFullName", ((EditText) findViewById(R.id.editTextUserNameLogin)).getText().toString());

                                                                          user.signUpInBackground(new SignUpCallback() {
                                                                              public void done(ParseException e) {
                                                                                if (e == null) {
                                                                                // Hooray! Let them use the app now.
                                                                                Log.d("demo", "signed up OK!");
                                                                                Toast.makeText(SignUpActivity.this, "Sign Up Successful! \n", Toast.LENGTH_SHORT).show();
                                                                                } else {
                                                                                // Sign up didn't succeed. Look at the ParseException
                                                                                // to figure out what went wrong
                                                                                Log.d("demo", "issue!, exception says:" + e);
                                                                                Toast.makeText(SignUpActivity.this, "Sign Up not successful, " + e.getMessage(), Toast.LENGTH_SHORT).show();
                                                                                }
                                                                              }
                                                                          });

                                                                      }//end else
                                                                  }//end onclick
                                                              }

        );

        findViewById(R.id.buttonCancelSignUp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent intent = new Intent(SignUpActivity.this, LogInActivity.class);
                startActivity(intent);
            }
        });

    }

}


text:
001
017
018    package org.apache.commons.math3.optimization.general;
019
020    /**
021     * Available choices of update formulas for the &beta; parameter
022     * in {@link NonLinearConjugateGradientOptimizer}.
023     * <p>
024     * The &beta; parameter is used to compute the successive conjugate
025     * search directions. For non-linear conjugate gradients, there are
026     * two formulas to compute &beta;:
027     * <ul>
028     *   <li>Fletcher-Reeves formula</li>
029     *   <li>Polak-Ribi&egrave;re formula</li>
030     * </ul>
031     * On the one hand, the Fletcher-Reeves formula is guaranteed to converge
032     * if the start point is close enough of the optimum whether the
033     * Polak-Ribi&egrave;re formula may not converge in rare cases. On the
034     * other hand, the Polak-Ribi&egrave;re formula is often faster when it
035     * does converge. Polak-Ribi&egrave;re is often used.
036     * <p>
037     * @see NonLinearConjugateGradientOptimizer
038     * @version $Id: ConjugateGradientFormula.java 1422230 2012-12-15 12:11:13Z erans $
039     * @deprecated As of 3.1 (to be removed in 4.0).
040     * @since 2.0
041     */
042    @Deprecated
043    public enum ConjugateGradientFormula {
044
045        /** Fletcher-Reeves formula. */
046        FLETCHER_REEVES,
047
048        /** Polak-Ribi&egrave;re formula. */
049        POLAK_RIBIERE
050
051    }


text:
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *

import os
import platform
import sys
from PyQt4.QtCore import (PYQT_VERSION_STR, QFile, QFileInfo, QSettings,
        QString, QT_VERSION_STR, QTimer, QVariant, Qt)
from PyQt4.QtCore import pyqtSignal as Signal
from PyQt4.QtGui import (QAction, QActionGroup, QApplication,
        QDockWidget, QFileDialog, QFrame, QIcon, QImage, QImageReader,
        QImageWriter, QInputDialog, QKeySequence, QLabel, QListWidget,
        QMainWindow, QMessageBox, QPainter, QPixmap, QPrintDialog,
        QPrinter, QSpinBox)
import helpform
import newimagedlg
import resizedlg
import qrc_resources

__version__ = "1.0.0"

class Window(QMainWindow):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.image = QImage()
        self.dirty = False
        self.filename = None
        self.mirroredvertically = False
        self.mirroredhorizontally = False
        self.printer = None
        self.create_widgets()
        self.create_actions()
        self.load_settings()
        self.setWindowTitle("Image Changer")
        self.updateFileMenu()
        QTimer.singleShot(0, self.loadInitialFile)

    def create_widgets(self):
        self.imageLabel = QLabel()
        self.imageLabel.setMinimumSize(200, 200)
        self.imageLabel.setAlignment(Qt.AlignCenter)
        self.imageLabel.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.setCentralWidget(self.imageLabel)

        logDockWidget = QDockWidget("Log", self)
        logDockWidget.setObjectName("LogDockWidget")
        logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea|
                                      Qt.RightDockWidgetArea)
        self.listWidget = QListWidget()
        logDockWidget.setWidget(self.listWidget)
        self.addDockWidget(Qt.RightDockWidgetArea, logDockWidget)

        self.sizeLabel = QLabel()
        self.sizeLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
        status = self.statusBar()
        status.setSizeGripEnabled(False)
        status.addPermanentWidget(self.sizeLabel)
        status.showMessage("Ready", 5000)

    def create_actions(self):
        fileNewAction = self.createAction("&New...", self.fileNew,
                QKeySequence.New, "filenew", "Create an image file")
        fileOpenAction = self.createAction("&Open...", self.fileOpen,
                QKeySequence.Open, "fileopen",
                "Open an existing image file")
        fileSaveAction = self.createAction("&Save", self.fileSave,
                QKeySequence.Save, "filesave", "Save the image")
        fileSaveAsAction = self.createAction("Save &As...",
                self.fileSaveAs, icon="filesaveas",
                tip="Save the image using a new name")
        filePrintAction = self.createAction("&Print", self.filePrint,
                QKeySequence.Print, "fileprint", "Print the image")
        fileQuitAction = self.createAction("&Quit", self.close,
                "Ctrl+Q", "filequit", "Close the application")
        editInvertAction = self.createAction("&Invert", None, "Ctrl+I",
                "editinvert", "Invert the image's colors", True)
        editInvertAction.toggled.connect(self.editInvert)
        editSwapRedAndBlueAction = self.createAction("Sw&ap Red and Blue",
                None, "Ctrl+A", "editswap",
                "Swap the image's red and blue color components", True)
        editSwapRedAndBlueAction.toggled.connect(self.editSwapRedAndBlue)
        editZoomAction = self.createAction("&Zoom...", self.editZoom,
                "Alt+Z", "editzoom", "Zoom the image")
        editResizeAction = self.createAction("&Resize...",
                self.editResize, "Ctrl+R", "editresize",
                "Resize the image")
        mirrorGroup = QActionGroup(self)
        editUnMirrorAction = self.createAction("&Unmirror", None, "Ctrl+U",
                "editunmirror", "Unmirror the image", True)
        editUnMirrorAction.toggled.connect(self.editUnMirror)
        mirrorGroup.addAction(editUnMirrorAction)
        editMirrorHorizontalAction = self.createAction(
                "Mirror &Horizontally", None, "Ctrl+H", "editmirrorhoriz",
                "Horizontally mirror the image", True)
        editMirrorHorizontalAction.toggled.connect(
                self.editMirrorHorizontal)
        mirrorGroup.addAction(editMirrorHorizontalAction)
        editMirrorVerticalAction = self.createAction( "Mirror &Vertically",
                None, "Ctrl+V", "editmirrorvert",
                "Vertically mirror the image", True)
        editMirrorVerticalAction.toggled.connect(self.editMirrorVertical)
        mirrorGroup.addAction(editMirrorVerticalAction)
        editUnMirrorAction.setChecked(True)
        helpAboutAction = self.createAction("&About Image Changer",
                self.helpAbout)
        helpHelpAction = self.createAction("&Help", self.helpHelp,
                QKeySequence.HelpContents)

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenuActions = (fileNewAction, fileOpenAction,
                fileSaveAction, fileSaveAsAction, None, filePrintAction,
                fileQuitAction)
        self.fileMenu.aboutToShow.connect(self.updateFileMenu)
        editMenu = self.menuBar().addMenu("&Edit")
        self.addActions(editMenu, (editInvertAction,
                editSwapRedAndBlueAction, editZoomAction,
                editResizeAction))
        mirrorMenu = editMenu.addMenu(QIcon(":/editmirror.png"),
                                      "&Mirror")
        self.addActions(mirrorMenu, (editUnMirrorAction,
                editMirrorHorizontalAction, editMirrorVerticalAction))
        helpMenu = self.menuBar().addMenu("&Help")
        self.addActions(helpMenu, (helpAboutAction, helpHelpAction))

        fileToolbar = self.addToolBar("File")
        fileToolbar.setObjectName("FileToolBar")
        self.addActions(fileToolbar, (fileNewAction, fileOpenAction,
                                      fileSaveAsAction))
        editToolbar = self.addToolBar("Edit")
        editToolbar.setObjectName("EditToolBar")
        self.addActions(editToolbar, (editInvertAction,
                editSwapRedAndBlueAction, editUnMirrorAction,
                editMirrorVerticalAction, editMirrorHorizontalAction))
        self.zoomSpinBox = QSpinBox()
        self.zoomSpinBox.setRange(1, 400)
        self.zoomSpinBox.setSuffix(" %")
        self.zoomSpinBox.setValue(100)
        self.zoomSpinBox.setToolTip("Zoom the image")
        self.zoomSpinBox.setStatusTip(self.zoomSpinBox.toolTip())
        self.zoomSpinBox.setFocusPolicy(Qt.NoFocus)
        self.zoomSpinBox.valueChanged.connect(self.showImage)
        editToolbar.addWidget(self.zoomSpinBox)

        self.addActions(self.imageLabel, (editInvertAction,
                editSwapRedAndBlueAction, editUnMirrorAction,
                editMirrorVerticalAction, editMirrorHorizontalAction))

        self.resetableActions = ((editInvertAction, False),
                                 (editSwapRedAndBlueAction, False),
                                 (editUnMirrorAction, True))

    def load_settings(self):
        settings = QSettings()
        self.recentFiles = settings.value("RecentFiles").toStringList()
        self.restoreGeometry(
                settings.value("MainWindow/Geometry").toByteArray())
        self.restoreState(settings.value("MainWindow/State").toByteArray())

    def createAction(self, text, slot=None, shortcut=None, icon=None,
                     tip=None, checkable=False):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/{0}.png".format(icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        if checkable:
            action.setCheckable(True)
        return action

    def addActions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def closeEvent(self, event):
        if self.okToContinue():
            settings = QSettings()
            filename = (QVariant(QString(self.filename))
                        if self.filename is not None else QVariant())
            settings.setValue("LastFile", filename)
            recentFiles = (QVariant(self.recentFiles)
                           if self.recentFiles else QVariant())
            settings.setValue("RecentFiles", recentFiles)
            settings.setValue("MainWindow/Geometry", QVariant(
                              self.saveGeometry()))
            settings.setValue("MainWindow/State", QVariant(
                              self.saveState()))
        else:
            event.ignore()

    def okToContinue(self):
        if self.dirty:
            reply = QMessageBox.question(self,
                    "Image Changer - Unsaved Changes",
                    "Save unsaved changes?",
                    QMessageBox.Yes|QMessageBox.No|QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                return self.fileSave()
        return True

    def loadInitialFile(self):
        settings = QSettings()
        fname = unicode(settings.value("LastFile").toString())
        if fname and QFile.exists(fname):
            self.loadFile(fname)

    def updateStatus(self, message):
        self.statusBar().showMessage(message, 5000)
        self.listWidget.addItem(message)
        if self.filename is not None:
            self.setWindowTitle("Image Changer - {0}[*]".format(
                                os.path.basename(self.filename)))
        elif not self.image.isNull():
            self.setWindowTitle("Image Changer - Unnamed[*]")
        else:
            self.setWindowTitle("Image Changer[*]")
        self.setWindowModified(self.dirty)

    def updateFileMenu(self):
        self.fileMenu.clear()
        self.addActions(self.fileMenu, self.fileMenuActions[:-1])
        current = (QString(self.filename)
                   if self.filename is not None else None)
        recentFiles = []
        for fname in self.recentFiles:
            if fname != current and QFile.exists(fname):
                recentFiles.append(fname)
        if recentFiles:
            self.fileMenu.addSeparator()
            for i, fname in enumerate(recentFiles):
                action = QAction(QIcon(":/icon.png"),
                        "&{0} {1}".format(i + 1, QFileInfo(
                        fname).fileName()), self)
                action.setData(QVariant(fname))
                action.triggered.connect(self.loadFile)
                self.fileMenu.addAction(action)
        self.fileMenu.addSeparator()
        self.fileMenu.addAction(self.fileMenuActions[-1])

    def fileNew(self):
        if not self.okToContinue():
            return
        dialog = newimagedlg.NewImageDlg(self)
        if dialog.exec_():
            self.addRecentFile(self.filename)
            self.image = QImage()
            for action, check in self.resetableActions:
                action.setChecked(check)
            self.image = dialog.image()
            self.filename = None
            self.dirty = True
            self.showImage()
            self.sizeLabel.setText("{0} x {1}".format(self.image.width(),
                                                      self.image.height()))
            self.updateStatus("Created new image")

    def fileOpen(self):
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        formats = (["*.{0}".format(unicode(format).lower())
                for format in QImageReader.supportedImageFormats()])
        fname = unicode(QFileDialog.getOpenFileName(self,
                "Image Changer - Choose Image", dir,
                "Image files ({0})".format(" ".join(formats))))
        if fname:
            self.loadFile(fname)

    def loadFile(self, fname=None):
        if fname is None:
            action = self.sender()
            if isinstance(action, QAction):
                fname = unicode(action.data().toString())
                if not self.okToContinue():
                    return
            else:
                return
        if fname:
            self.filename = None
            image = QImage(fname)
            if image.isNull():
                message = "Failed to read {0}".format(fname)
            else:
                self.addRecentFile(fname)
                self.image = QImage()
                for action, check in self.resetableActions:
                    action.setChecked(check)
                self.image = image
                self.filename = fname
                self.showImage()
                self.dirty = False
                self.sizeLabel.setText("{0} x {1}".format(
                                       image.width(), image.height()))
                message = "Loaded {0}".format(os.path.basename(fname))
            self.updateStatus(message)

    def addRecentFile(self, fname):
        if fname is None:
            return
        if not self.recentFiles.contains(fname):
            self.recentFiles.prepend(QString(fname))
            while self.recentFiles.count() > 9:
                self.recentFiles.takeLast()

    def fileSave(self):
        if self.image.isNull():
            return True
        if self.filename is None:
            return self.fileSaveAs()
        else:
            if self.image.save(self.filename, None):
                self.updateStatus("Saved as {0}".format(self.filename))
                self.dirty = False
                return True
            else:
                self.updateStatus("Failed to save {0}".format(
                                  self.filename))
                return False

    def fileSaveAs(self):
        if self.image.isNull():
            return True
        fname = self.filename if self.filename is not None else "."
        formats = (["*.{0}".format(unicode(format).lower())
                for format in QImageWriter.supportedImageFormats()])
        fname = unicode(QFileDialog.getSaveFileName(self,
                "Image Changer - Save Image", fname,
                "Image files ({0})".format(" ".join(formats))))
        if fname:
            if "." not in fname:
                fname += ".png"
            self.addRecentFile(fname)
            self.filename = fname
            return self.fileSave()
        return False

    def filePrint(self):
        if self.image.isNull():
            return
        if self.printer is None:
            self.printer = QPrinter(QPrinter.HighResolution)
            self.printer.setPageSize(QPrinter.Letter)
        form = QPrintDialog(self.printer, self)
        if form.exec_():
            painter = QPainter(self.printer)
            rect = painter.viewport()
            size = self.image.size()
            size.scale(rect.size(), Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(),
                                size.height())
            painter.drawImage(0, 0, self.image)

    def editInvert(self, on):
        if self.image.isNull():
            return
        self.image.invertPixels()
        self.showImage()
        self.dirty = True
        self.updateStatus("Inverted" if on else "Uninverted")

    def editSwapRedAndBlue(self, on):
        if self.image.isNull():
            return
        self.image = self.image.rgbSwapped()
        self.showImage()
        self.dirty = True
        self.updateStatus(("Swapped Red and Blue"
                           if on else "Unswapped Red and Blue"))

    def editUnMirror(self, on):
        if self.image.isNull():
            return
        if self.mirroredhorizontally:
            self.editMirrorHorizontal(False)
        if self.mirroredvertically:
            self.editMirrorVertical(False)

    def editMirrorHorizontal(self, on):
        if self.image.isNull():
            return
        self.image = self.image.mirrored(True, False)
        self.showImage()
        self.mirroredhorizontally = not self.mirroredhorizontally
        self.dirty = True
        self.updateStatus(("Mirrored Horizontally"
                           if on else "Unmirrored Horizontally"))

    def editMirrorVertical(self, on):
        if self.image.isNull():
            return
        self.image = self.image.mirrored(False, True)
        self.showImage()
        self.mirroredvertically = not self.mirroredvertically
        self.dirty = True
        self.updateStatus(("Mirrored Vertically"
                           if on else "Unmirrored Vertically"))

    def editZoom(self):
        if self.image.isNull():
            return
        percent, ok = QInputDialog.getInteger(self,
                "Image Changer - Zoom", "Percent:",
                self.zoomSpinBox.value(), 1, 400)
        if ok:
            self.zoomSpinBox.setValue(percent)

    def editResize(self):
        if self.image.isNull():
            return
        form = resizedlg.ResizeDlg(self.image.width(),
                                   self.image.height(), self)
        if form.exec_():
            width, height = form.result()
            if (width == self.image.width() and
                height == self.image.height()):
                self.statusBar().showMessage("Resized to the same size",
                                             5000)
            else:
                self.image = self.image.scaled(width, height)
                self.showImage()
                self.dirty = True
                size = "{0} x {1}".format(self.image.width(),
                                          self.image.height())
                self.sizeLabel.setText(size)
                self.updateStatus("Resized to {0}".format(size))

    def showImage(self, percent=None):
        if self.image.isNull():
            return
        if percent is None:
            percent = self.zoomSpinBox.value()
        factor = percent / 100.0
        width = self.image.width() * factor
        height = self.image.height() * factor
        image = self.image.scaled(width, height, Qt.KeepAspectRatio)
        self.imageLabel.setPixmap(QPixmap.fromImage(image))

    def helpAbout(self):
        QMessageBox.about(self, "About Image Changer",
                """Image Changer v {0}

Copyright © 2008 Qtrac Ltd.
                All rights reserved.

This application can be used to perform
                simple image manipulations.

Python {1} - Qt {2} - PyQt {3} on {4}""".format(
                __version__, platform.python_version(),
                QT_VERSION_STR, PYQT_VERSION_STR,
                platform.system()))

    def helpHelp(self):
        form = helpform.HelpForm("index.html", self)
        form.show()


text:
static NSString *ELNStringByAddingSlashes(NSString *string) {
    string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    return string;
}

@implementation NSURLRequest (ELNUtils)

- (NSString *)eln_CURL {
    NSMutableArray *args = [NSMutableArray new];
    NSMutableArray *flags = [[NSMutableArray alloc] initWithObjects:@"-sS", nil];

    // method
    NSString *method = [NSString stringWithFormat:@"-X \"%@\"", ELNStringByAddingSlashes(self.HTTPMethod ?: @"GET")];
    [args addObject:method];

    NSStringEncoding encoding = NSUTF8StringEncoding;

    // headers
    for (id key in self.allHTTPHeaderFields) {
        id value = self.allHTTPHeaderFields[key];
        NSString *header = [NSString stringWithFormat:@"-H \"%@: %@\"", ELNStringByAddingSlashes(key), ELNStringByAddingSlashes(value)];
        [args addObject:header];

        if ([key isEqualToString:@"Accept-Encoding"]) {
            [flags addObject:@"--compressed"];
        }

        if ([key isKindOfClass:[NSString class]] && [(NSString *)key isEqualToString:@"Content-Type"]) {
            NSArray *components = [value componentsSeparatedByString:@";"];
            for (NSString *component in components) {
                NSArray *keyValue = [component componentsSeparatedByString:@"="];
                if (keyValue.count == 2) {
                    NSString *k = [keyValue.firstObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                    NSString *v = [keyValue.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                    if ([k isEqualToString:@"charset"]) {
                        if ([v isEqualToString:@"windows-1251"]) {
                            encoding = NSWindowsCP1251StringEncoding;
                        }
                    }
                }
            }
        }
    }

    // body
    if (self.HTTPBody != nil) {
        NSString *body = [[NSString alloc] initWithData:self.HTTPBody encoding:encoding];
        if (body != nil) {
            NSString *data = [NSString stringWithFormat:@"--data \"%@\"", ELNStringByAddingSlashes(body)];
            [args addObject:data];
        }
    }

    return [NSString stringWithFormat:@"curl %@ \"%@\" %@", [args componentsJoinedByString:@" "], self.URL.absoluteString, [flags componentsJoinedByString:@" "]];
}

@end


text:
@extends('layouts.main')

@section('content')

Secret Key

                    Open up your 2FA mobile app and scan the following QR barcode:

                    If your 2FA mobile app does not support QR barcodes,
                    enter in the following number: {{ $secret }}

                    previous() }}">Return

@endsection


text:
FROM debian:testing

## This handle reaches Carl and Dirk
MAINTAINER "Carl Boettiger and Dirk Eddelbuettel" rocker-maintainers@eddelbuettel.com

## Set a default user. Available via runtime flag `--user docker`
## Add user to 'staff' group, granting them write privileges to /usr/local/lib/R/site.library
## User should also have & own a home directory (for rstudio or linked volumes to work properly).
RUN useradd docker \
	&& mkdir /home/docker \
	&& chown docker:docker /home/docker \
	&& addgroup docker staff

RUN apt-get update \
	&& apt-get install -y --no-install-recommends \
		ed \
		less \
		locales \
		vim-tiny \
		wget \
		ca-certificates \
		fonts-texgyre \
	&& rm -rf /var/lib/apt/lists/*

## Configure default locale, see https://github.com/rocker-org/rocker/issues/19
RUN echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen \
	&& locale-gen en_US.utf8 \
	&& /usr/sbin/update-locale LANG=en_US.UTF-8

ENV LC_ALL en_US.UTF-8
ENV LANG en_US.UTF-8

## Use Debian unstable via pinning -- new style via APT::Default-Release
RUN echo "deb http://http.debian.net/debian sid main" > /etc/apt/sources.list.d/debian-unstable.list \
	&& echo 'APT::Default-Release "testing";' > /etc/apt/apt.conf.d/default

ENV R_BASE_VERSION 3.3.2

## Now install R and littler, and create a link for littler in /usr/local/bin
## Also set a default CRAN repo, and make sure littler knows about it too
RUN apt-get update \
	&& apt-get install -t unstable -y --no-install-recommends \
		littler \
                r-cran-littler \
		r-base=${R_BASE_VERSION}* \
		r-base-dev=${R_BASE_VERSION}* \
		r-recommended=${R_BASE_VERSION}* \
        && echo 'options(repos = c(CRAN = "https://cran.rstudio.com/"), download.file.method = "libcurl")' >> /etc/R/Rprofile.site \
        && echo 'source("/etc/R/Rprofile.site")' >> /etc/littler.r \
	&& ln -s /usr/share/doc/littler/examples/install.r /usr/local/bin/install.r \
	&& ln -s /usr/share/doc/littler/examples/install2.r /usr/local/bin/install2.r \
	&& ln -s /usr/share/doc/littler/examples/installGithub.r /usr/local/bin/installGithub.r \
	&& ln -s /usr/share/doc/littler/examples/testInstalled.r /usr/local/bin/testInstalled.r \
	&& install.r docopt \
	&& rm -rf /tmp/downloaded_packages/ /tmp/*.rds \
	&& rm -rf /var/lib/apt/lists/*

CMD ["R"]


text:
 package afk.ge.tokyo.ems.nodes;

import afk.ge.ems.Node;
import afk.ge.tokyo.ems.components.State;
import afk.ge.tokyo.ems.components.Velocity;

/**
 *
 * @author daniel
 */
public class MovementNode extends Node
{
    public State state;
    public Velocity velocity;
}


text:
import os
import click

@click.group()
def cli():
    pass

@click.command()
def initdb():
    click.echo('Initialized the database')

@click.command()
def dropdb():
    click.echo('Dropped the database')

cli.add_command(initdb)
cli.add_command(dropdb)

cli()


text:
layout: article
published: true
title: Why use my services?
---

Why use my services?

Efficient, personal service with special attention to flexibility and feedback from clients is offered. The rates are very competitive.


text:
<template name="popup">
  {{#contentFor "headerButtonLeft"}}
    {{>ionNavBackButton path="index"}}
  {{/contentFor}}
  {{#contentFor "headerTitle"}}

Popup

  {{/contentFor}}

  {{#ionView}}
    {{#ionContent}}

        <button class="button button-block button-stable" data-action="showPopup" onclick="alert('TODO')">
          Show Popup
        </button>
        <button class="button button-block button-stable" data-action="showConfirm" onclick="alert('TODO')">
          Show Confirm
        </button>
        <button class="button button-block button-stable" data-action="showAlert" onclick="alert('TODO')">
          Show Alert
        </button>
        <button class="button button-block button-stable" data-action="showPrompt" onclick="alert('TODO')">
          Show Prompt
        </button>

    {{/ionContent}}
  {{/ionView}}
</template>


text:
package org.compass.core.load.simple;

import org.compass.core.Compass;
import org.compass.core.config.CompassConfiguration;

/**
 * @author kimchy
 */
public class Processor {

    public static void main(String[] args) throws Exception {
        CompassConfiguration conf = new CompassConfiguration();
        conf.configure("/org/compass/core/load/simple/compass.processor.cfg.xml");
        conf.addClass(A.class);
        Compass compass = conf.buildCompass();
        Thread.sleep(10000000);
    }
}


text:
<?php

use WebHemi\Acl;
use WebHemi\Application;
use WebHemi\Auth;
use WebHemi\Configuration;
use WebHemi\CSRF;
use WebHemi\Data;
use WebHemi\DependencyInjection;
use WebHemi\Environment;
use WebHemi\Http;
use WebHemi\I18n;
use WebHemi\Logger;
use WebHemi\Middleware;
use WebHemi\MiddlewarePipeline;
use WebHemi\Parser;
use WebHemi\Renderer;
use WebHemi\Router;
use WebHemi\Session;
use WebHemi\Validator;

return [
    'dependencies' => [
        'Global' => [
            // Core objects
            Configuration\ServiceInterface::class => [
                'class' => Configuration\ServiceAdapter\Base\ServiceAdapter::class,
            ],
            DependencyInjection\ServiceInterface::class => [
                'class' => DependencyInjection\ServiceAdapter\Base\ServiceAdapter::class,
            ],
            Environment\ServiceInterface::class => [
                'class' => Environment\ServiceAdapter\Base\ServiceAdapter::class,
            ],
            MiddlewarePipeline\ServiceInterface::class => [
                'class' => MiddlewarePipeline\ServiceAdapter\Base\ServiceAdapter::class,
            ],
            Session\ServiceInterface::class => [
                'class' => Session\ServiceAdapter\Base\ServiceAdapter::class,
            ],
            Application\ServiceInterface::class => [
                'class' => Application\ServiceAdapter\Base\ServiceAdapter::class,
                'arguments' => [
                    DependencyInjection\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            // Services
            Acl\ServiceInterface::class => [
                'class'     => Acl\ServiceAdapter\Base\ServiceAdapter::class,
                'arguments' => [
                    Environment\ServiceInterface::class,
                    Data\Storage\UserStorage::class,
                    Data\Storage\PolicyStorage::class,
                ],
                'shared'    => true,
            ],
            Auth\CredentialInterface::class => [
                'class'     => Auth\Credential\NameAndPasswordCredential::class,
                'shared'    => false,
            ],
            Auth\ResultInterface::class => [
                'class'     => Auth\Result\Result::class,
                'shared'    => false,
            ],
            Auth\ServiceInterface::class => [
                'class'     => Auth\ServiceAdapter\Base\ServiceAdapter::class,
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    Auth\ResultInterface::class,
                    Auth\StorageInterface::class,
                    Data\Storage\UserStorage::class,
                ],
                'shared'    => true,
            ],
            Auth\StorageInterface::class => [
                'class'     => Auth\Storage\Session::class,
                'arguments' => [
                    Session\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            CSRF\ServiceInterface::class => [
                'class'     => CSRF\ServiceAdapter\Base\ServiceAdapter::class,
                'arguments' => [
                    Session\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            Http\ServiceInterface::class => [
                'class'     => Http\ServiceAdapter\GuzzleHttp\ServiceAdapter::class,
                'arguments' => [
                    Environment\ServiceInterface::class,
                ],
                'shared'    => true,
            ],
            I18n\ServiceInterface::class => [
                'class'     => I18n\ServiceAdapter\Base\ServiceAdapter::class,
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    Environment\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            I18n\DriverInterface::class => [
                'class'     => I18n\DriverAdapter\Gettext\DriverAdapter::class,
                'arguments' => [
                    I18n\ServiceInterface::class
                ],
            ],
            Parser\ServiceInterface::class => [
                'class'     => Parser\ServiceAdapter\Parsedown\ServiceAdapter::class,
                'shared'    => true,
            ],
            Renderer\ServiceInterface::class => [
                'class'     => Renderer\ServiceAdapter\Twig\ServiceAdapter::class,
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    Environment\ServiceInterface::class,
                    I18n\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            Router\ServiceInterface::class => [
                'class'     => Router\ServiceAdapter\Base\ServiceAdapter::class,
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    Environment\ServiceInterface::class,
                    Router\Result\Result::class
                ],
                'shared'    => true,
            ],
            // Logger
            'AccessLog' => [
                'class'     => Logger\ServiceAdapter\Klogger\ServiceAdapter::class,
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    'logType' => 'access'
                ]
            ],
            'EventLog' => [
                'class'     => Logger\ServiceAdapter\Klogger\ServiceAdapter::class,
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    'logType' => 'event'
                ]
            ],
            // Middleware
            Middleware\Common\RoutingMiddleware::class => [
                'arguments' => [
                    Router\ServiceInterface::class,
                ]
            ],
            Middleware\Common\DispatcherMiddleware::class => [
                'arguments' => []
            ],
            Middleware\Common\FinalMiddleware::class => [
                'arguments' => [
                    Auth\ServiceInterface::class,
                    Environment\ServiceInterface::class,
                    'AccessLog'
                ]
            ],
            // DataStorage
            Data\Storage\ApplicationStorage::class => [
                'arguments' => [
                    Data\Query\QueryInterface::class,
                    Data\Entity\EntitySet::class,
                    Data\Entity\ApplicationEntity::class
                ],
                'shared'    => true,
            ],
            Data\Storage\DomainStorage::class => [
                'arguments' => [
                    Data\Query\QueryInterface::class,
                    Data\Entity\EntitySet::class,
                    Data\Entity\DomainEntity::class
                ],
                'shared'    => true,
            ],
            Data\Storage\UserStorage::class => [
                'arguments' => [
                    Data\Query\QueryInterface::class,
                    Data\Entity\EntitySet::class,
                    Data\Entity\UserEntity::class,
                    Data\Entity\UserGroupEntity::class,
                    Data\Entity\UserMetaEntity::class
                ],
                'shared'    => true,
            ],
            Data\Storage\PolicyStorage::class => [
                'arguments' => [
                    Data\Query\QueryInterface::class,
                    Data\Entity\EntitySet::class,
                    Data\Entity\PolicyEntity::class,
                ],
                'shared'    => true,
            ],
            Data\Storage\ResourceStorage::class => [
                'arguments' => [
                    Data\Query\QueryInterface::class,
                    Data\Entity\EntitySet::class,
                    Data\Entity\ResourceEntity::class,
                ],
                'shared'    => true,
            ],
            Data\Storage\FilesystemStorage::class => [
                'arguments' => [
                    Data\Query\QueryInterface::class,
                    Data\Entity\EntitySet::class,
                    Data\Entity\FilesystemCategoryEntity::class,
                    Data\Entity\FilesystemDirectoryEntity::class,
                    Data\Entity\FilesystemDirectoryDataEntity::class,
                    Data\Entity\FilesystemDocumentEntity::class,
                    Data\Entity\FilesystemEntity::class,
                    Data\Entity\FilesystemMetaEntity::class,
                    Data\Entity\FilesystemPublishedDocumentEntity::class,
                    Data\Entity\FilesystemTagEntity::class,
                ],
                'shared'    => true,
            ],
            // Renderer Filter
            Renderer\Filter\MarkDownFilter::class => [
                'arguments' => [
                    Parser\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            Renderer\Filter\TranslateFilter::class => [
                'arguments' => [
                    I18n\DriverInterface::class
                ],
                'shared'    => true,
            ],
            Renderer\Filter\Tags\Url::class => [
                'arguments' => [
                    Environment\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            Renderer\Filter\TagParserFilter::class => [
                'arguments' => [
                    Renderer\Filter\Tags\Url::class
                ],
                'shared'    => true,
            ],
            // Renderer Helper
            Renderer\Helper\DefinedHelper::class => [
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    Environment\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            Renderer\Helper\FileExistsHelper::class => [
                'arguments' => [
                    Environment\ServiceInterface::class
                ],
                'shared'    => true,
            ],
            Renderer\Helper\GetStatHelper::class => [
                'shared'    => true,
            ],
            Renderer\Helper\IsAllowedHelper::class => [
                'arguments' => [
                    Configuration\ServiceInterface::class,
                    Environment\ServiceInterface::class,
                    Acl\ServiceInterface::class,
                    Auth\ServiceInterface::class,
                    Data\Storage\ResourceStorage::class,
                    Data\Storage\ApplicationStorage::class
                ],
                'shared'    => true,
            ],
            Renderer\Helper\GetCurrentUserHelper::class => [
                'arguments' => [
                    Auth\ServiceInterface::class
                ],
                'shared'    => true
            ],
            // Validators
            Validator\ValidatorCollection::class => [
                'arguments' => [
                    Validator\NotEmptyValidator::class,
                    Validator\RangeValidator::class
                ]
            ]
        ],
    ],
];


text:
function createImageWithMetadata({
    width,
    height,
    preferredWidth,
    preferredHeight,
    resolutionX,
    resolutionY,
    resolutionUnit,
    orientation
}) {
    const canvas = document.createElement('canvas')
    canvas.width = width || 100
    canvas.height = height || 100
    const ctx = canvas.getContext('2d')
    ctx.fillColor = 'green'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    const original = canvas.toDataURL('image/jpeg')
    const root = {}
    const exif = {}
    if (orientation !== undefined)
        root[piexif.ExifIFD.Orientation] = orientation
    if (resolutionX !== undefined)
        root[piexif.ImageIFD.XResolution] = Array.isArray(resolutionX) ? resolutionX : [resolutionX, 1]
    if (resolutionY !== undefined)
        root[piexif.ImageIFD.YResolution] = Array.isArray(resolutionY) ? resolutionY : [resolutionY, 1]
    if (resolutionUnit !== undefined)
        root[piexif.ImageIFD.ResolutionUnit] = resolutionUnit
    if (preferredWidth !== undefined)
        exif[piexif.ExifIFD.PixelXDimension] = preferredWidth
    if (preferredHeight !== undefined)
        exif[piexif.ExifIFD.PixelYDimension] = preferredHeight
    const exifString = piexif.dump({'0th': root, 'Exif': exif})
    const newDataUrl = piexif.insert(exifString, original)
    const image = new Image()
    image.src = newDataUrl
    return new Promise(resolve => {
        image.onload = () => resolve(image);
    })
}


text:
<?php

namespace Superbalist\EventPubSub;

use Exception;
use Throwable;

class ValidationException extends Exception
{
    /**
     * @var ValidationResult
     */
    protected $validationResult;

    /**
     * @param ValidationResult $validationResult
     * @param string $message
     * @param int $code
     * @param Throwable|null $previous
     */
    public function __construct(
        ValidationResult $validationResult,
        $message = 'The event failed validation.',
        $code = 0,
        Throwable $previous = null
    ) {
        parent::__construct($message, $code, $previous);

        $this->validationResult = $validationResult;
    }

    /**
     * @return ValidationResult
     */
    public function getValidationResult()
    {
        return $this->validationResult;
    }
}


text:
/* Author: Ioan Sucan */

#ifndef MOVEIT_MOVE_GROUP_TWIST_CONTROL_CAPABILITY_
#define MOVEIT_MOVE_GROUP_TWIST_CONTROL_CAPABILITY_

#include <moveit/move_group/move_group_capability.h>
#include <moveit_msgs/GetCartesianPath.h>

namespace move_group
{

class MoveGroupTwistControl : public MoveGroupCapability
{
public:

  MoveGroupTwistControl();

  virtual void initialize();

private:

  bool computeService(moveit_msgs::GetCartesianPath::Request &req, moveit_msgs::GetCartesianPath::Response &res);

  ros::ServiceServer cartesian_path_service_;
  ros::Publisher display_path_;
  bool display_computed_paths_;
};

}

#endif


text:
package rpkt

import (
	"github.com/scionproto/scion/go/border/rcmn"
	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/common"
	"github.com/scionproto/scion/go/lib/l4"
	"github.com/scionproto/scion/go/lib/spath"
)

type hookIA func() (HookResult, *addr.ISD_AS, error)
type hookHost func() (HookResult, addr.HostAddr, error)
type hookInfoF func() (HookResult, *spath.InfoField, error)
type hookHopF func() (HookResult, *spath.HopField, error)
type hookBool func() (HookResult, bool, error)
type hookIntf func(up bool, dirFrom, dirTo rcmn.Dir) (HookResult, common.IFIDType, error)
type hookValidate func() (HookResult, error)
type hookL4 func() (HookResult, l4.L4Header, error)
type hookPayload func() (HookResult, common.Payload, error)
type hookProcess func() (HookResult, error)
type hookRoute func() (HookResult, error)

// Hooks is a group of hook slices. Each hook slice is responsible for fetching
// the information named by the slice from a packet. Extensions and other parts
// of the router register to handle certain functions by adding a callback to
// the relevant slice.
type hooks struct {
	DstIA    []hookIA
	SrcIA    []hookIA
	DstHost  []hookHost
	SrcHost  []hookHost
	Infof    []hookInfoF
	HopF     []hookHopF
	UpFlag   []hookBool
	IFCurr   []hookIntf
	IFNext   []hookIntf
	Validate []hookValidate
	L4       []hookL4
	Payload  []hookPayload
	Process  []hookProcess
	Route    []hookRoute
}

type HookResult int

const (
	// HookError means the current hook has failed.
	HookError HookResult = iota
	// HookContinue means the caller should continue to call other hooks.
	HookContinue
	// HookFinish means the current hook has provided the definitive answer,
	// and no further hooks should be called.
	HookFinish
)


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>
			@section('title')
			@show
		</title>

		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<link rel="stylesheet" href="{{ asset('/css/bootstrap.min.css') }}">

		<link rel="stylesheet" href="{{ asset('/css/bootstrap-theme.min.css') }}">

	          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

	          </button>
	          L4 with Sentry

				@if (Sentry::check() && Sentry::getUser()->hasAccess('admin'))

Users

Groups

				@endif

	            @if (Sentry::check())

{{ Session::get('email') }}

Logout

				@else

Login

Register

				@endif

			@include('layouts/notifications')

			@yield('content')