text:
package main

import (
	"fmt"
	"path"
	"path/filepath"
	"runtime"
	"strings"
)

type tempNamer struct {
	prefix string
}

var defTempNamer = tempNamer{".syncthing"}

func (t tempNamer) IsTemporary(name string) bool {
	if runtime.GOOS == "windows" {
		name = filepath.ToSlash(name)
	}
	return strings.HasPrefix(path.Base(name), t.prefix)
}

func (t tempNamer) TempName(name string) string {
	tdir := path.Dir(name)
	tname := fmt.Sprintf("%s.%s", t.prefix, path.Base(name))
	return path.Join(tdir, tname)
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="Keywords" content="Computational Biology, Bioinformatics, CB2,
	Emidio Capriotti, Malay Basu
	Computational, Molecular, Biology, CMB,
	University, Alabama, Birmingham">
    <meta name="Author" content="Aysegul Bulut">

    <title>CB2-101</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/full-width-pics.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                CMB

                        About the Course

                        Course Handouts

                       Previous Version

CB2-101

Introduction to Scientific Computing

"CB2-101: Introduction to Scientific Computing" offered under the
						umbrella of the CB2 initiative at UAB (http://www.uab.edu/cb2).

						The course is a hands-on, rigorous, and fast-paced introduction to computer
						skills, modeled after the NSF "immersive learning" proposal
						(http://www.nsf.gov/pubs/2008/nsf08204/index.jsp).

Course Handouts

Introduction to Linux
									    November 6-7, 2014

Computers and Programming Languages    November 10, 2014

Introduction to Python    November 11, 2014

Data structure in Python     November 12-13, 2014

Advanced functions and Modules    November 14, 2014

University of Alabama at Birmingham. 619 19th St. South, WP220. Birmingham (AL), 35249 (USA).

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stormancer.Core;
using Stormancer.Plugins;
using Stormancer.Server;
using Stormancer;
using Stormancer.Diagnostics;

namespace Server.Users
{
    class UsersManagementPlugin : Stormancer.Plugins.IHostPlugin
    {
        private readonly UserManagementConfig _config;

        public UsersManagementPlugin(UserManagementConfig config = null)
        {
            if (config == null)
            {
                config = new UserManagementConfig();
            }
            _config = config;

        }
        public void Build(HostPluginBuildContext ctx)
        {
            ctx.HostStarting += HostStarting;

        }
        private void HostStarting(IHost host)
        {
            host.AddSceneTemplate("authenticator", AuthenticatorSceneFactory);
            host.DependencyResolver.Register<UserManagementConfig>(_config);
            host.DependencyResolver.Register<IUserService, UserService>();
        }

        private void AuthenticatorSceneFactory(ISceneHost scene)
        {
            scene.AddProcedure("login", async p =>
            {
                scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Logging in an user.", null);

                var accessor = scene.DependencyResolver.Resolve<Management.ManagementClientAccessor>();
                var authenticationCtx = p.ReadObject<Dictionary<string, string>>();
                var result = new LoginResult();
                var userService = scene.DependencyResolver.Resolve<IUserService>();

                foreach (var provider in _config.AuthenticationProviders)
                {
                    var authResult = await provider.Authenticate(authenticationCtx, userService);
                    if (authResult == null)
                    {
                        continue;
                    }

                    if (authResult.Success)
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication successful.", authResult);

                        result.Success = true;
                        var client = await accessor.GetApplicationClient();
                        result.Token = await client.CreateConnectionToken(_config.OnRedirect(authResult), _config.UserDataSelector(authResult));
                        userService.SetUid(p.RemotePeer, authResult.AuthenticatedId);
                        break;
                    }
                    else
                    {
                        scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "Authentication failed.", authResult);

                        result.ErrorMsg = authResult.ReasonMsg;
                        break;
                    }
                }
                if (!result.Success)
                {
                    if (result.ErrorMsg == null)
                    {
                        result.ErrorMsg = "No authentication provider able to handle these credentials were found.";
                    }
                }

                if (result.Success)
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "User logged in.", null);
                }
                else
                {
                    scene.GetComponent<ILogger>().Log(LogLevel.Trace, "user.login", "User failed to log in.", null);
                }
                p.SendValue(result);
            });

            foreach (var provider in _config.AuthenticationProviders)
            {
                provider.AdjustScene(scene);
            }

        }
        private Dictionary<string, string> GetAuthenticateRouteMetadata()
        {
            var result = new Dictionary<string, string>();

            foreach (var provider in _config.AuthenticationProviders)
            {
                provider.AddMetadata(result);
            }

            return result;
        }
    }

    public class LoginResult
    {
        public bool Success { get; set; }

        public string Token { get; set; } = "";

        public string ErrorMsg { get; set; } = "";
    }

}


text:
To install:

    npm install

To run the already passing tests:

    npm test tests/already_passing_tests.js

To run a failing test:

    npm test tests/failing_test_1.js


text:
<?php

namespace Minsal\GinecologiaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * SrgOrganismoCervico
 *
 * @ORM\Table(name="srg_organismo_cervico", indexes={@ORM\Index(name="IDX_8765FB5FC2E87B78", columns={"id_examen_cervico_vaginal"})})
 * @ORM\Entity
 */
class SrgOrganismoCervico
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="srg_organismo_cervico_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="cambios_celu_herpes_simple", type="boolean", nullable=true)
     */
    private $cambiosCeluHerpesSimple;

    /**
     * @var boolean
     *
     * @ORM\Column(name="cambios_flora_vaginosis", type="boolean", nullable=true)
     */
    private $cambiosFloraVaginosis;

    /**
     * @var string
     *
     * @ORM\Column(name="detalle_otros_organismos", type="string", length=100, nullable=true)
     */
    private $detalleOtrosOrganismos;

    /**
     * @var \SrgExamenCervicoVaginal
     *
     * @ORM\OneToOne(targetEntity="SrgExamenCervicoVaginal", inversedBy="SrgOrganismoCervico")
     *   @ORM\JoinColumn(name="id_examen_cervico_vaginal", referencedColumnName="id")
     */
    private $idExamenCervicoVaginal;

    /**
     * @ORM\OneToMany(targetEntity="SrgOrganismoCervicoMicroorga", mappedBy="idOrganismoCervico", cascade={"all"}, orphanRemoval=true))
     **/
    private $SrgOrganismoCervicoMicroorga;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set cambiosCeluHerpesSimple
     *
     * @param boolean $cambiosCeluHerpesSimple
     * @return SrgOrganismoCervico
     */
    public function setCambiosCeluHerpesSimple($cambiosCeluHerpesSimple)
    {
        $this->cambiosCeluHerpesSimple = $cambiosCeluHerpesSimple;

        return $this;
    }

    /**
     * Get cambiosCeluHerpesSimple
     *
     * @return boolean
     */
    public function getCambiosCeluHerpesSimple()
    {
        return $this->cambiosCeluHerpesSimple;
    }

    /**
     * Set cambiosFloraVaginosis
     *
     * @param boolean $cambiosFloraVaginosis
     * @return SrgOrganismoCervico
     */
    public function setCambiosFloraVaginosis($cambiosFloraVaginosis)
    {
        $this->cambiosFloraVaginosis = $cambiosFloraVaginosis;

        return $this;
    }

    /**
     * Get cambiosFloraVaginosis
     *
     * @return boolean
     */
    public function getCambiosFloraVaginosis()
    {
        return $this->cambiosFloraVaginosis;
    }

    /**
     * Set detalleOtrosOrganismos
     *
     * @param string $detalleOtrosOrganismos
     * @return SrgOrganismoCervico
     */
    public function setDetalleOtrosOrganismos($detalleOtrosOrganismos)
    {
        $this->detalleOtrosOrganismos = $detalleOtrosOrganismos;

        return $this;
    }

    /**
     * Get detalleOtrosOrganismos
     *
     * @return string
     */
    public function getDetalleOtrosOrganismos()
    {
        return $this->detalleOtrosOrganismos;
    }

    /**
     * Set idExamenCervicoVaginal
     *
     * @param \Minsal\GinecologiaBundle\Entity\SrgExamenCervicoVaginal $idExamenCervicoVaginal
     * @return SrgOrganismoCervico
     */
    public function setIdExamenCervicoVaginal(\Minsal\GinecologiaBundle\Entity\SrgExamenCervicoVaginal $idExamenCervicoVaginal = null)
    {
        $this->idExamenCervicoVaginal = $idExamenCervicoVaginal;

        return $this;
    }

    /**
     * Get idExamenCervicoVaginal
     *
     * @return \Minsal\GinecologiaBundle\Entity\SrgExamenCervicoVaginal
     */
    public function getIdExamenCervicoVaginal()
    {
        return $this->idExamenCervicoVaginal;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->SrgOrganismoCervicoMicroorga = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add SrgOrganismoCervicoMicroorga
     *
     * @param \Minsal\GinecologiaBundle\Entity\SrgOrganismoCervicoMicroorga $srgOrganismoCervicoMicroorga
     * @return SrgOrganismoCervico
     */
    public function addSrgOrganismoCervicoMicroorga(\Minsal\GinecologiaBundle\Entity\SrgOrganismoCervicoMicroorga $srgOrganismoCervicoMicroorga)
    {
        $this->SrgOrganismoCervicoMicroorga[] = $srgOrganismoCervicoMicroorga;

        return $this;
    }

    /**
     * Remove SrgOrganismoCervicoMicroorga
     *
     * @param \Minsal\GinecologiaBundle\Entity\SrgOrganismoCervicoMicroorga $srgOrganismoCervicoMicroorga
     */
    public function removeSrgOrganismoCervicoMicroorga(\Minsal\GinecologiaBundle\Entity\SrgOrganismoCervicoMicroorga $srgOrganismoCervicoMicroorga)
    {
        $this->SrgOrganismoCervicoMicroorga->removeElement($srgOrganismoCervicoMicroorga);
    }

    /**
     * Get SrgOrganismoCervicoMicroorga
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSrgOrganismoCervicoMicroorga()
    {
        return $this->SrgOrganismoCervicoMicroorga;
    }

   public function __toString() {
        return $this->id? (string) $this->id: '';
    }

}


text:
#pragma once
#include <aws/qldb/QLDB_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace QLDB
{
namespace Model
{
  enum class ErrorCause
  {
    NOT_SET,
    KINESIS_STREAM_NOT_FOUND,
    IAM_PERMISSION_REVOKED
  };

namespace ErrorCauseMapper
{
AWS_QLDB_API ErrorCause GetErrorCauseForName(const Aws::String& name);

AWS_QLDB_API Aws::String GetNameForErrorCause(ErrorCause value);
} // namespace ErrorCauseMapper
} // namespace Model
} // namespace QLDB
} // namespace Aws


text:
require 'sequel'
require 'safe_yaml'

module Services
  def self.configure!
    load_config
  end

  def self.load_config
    SafeYAML::OPTIONS[:default_mode] = :safe
    @config = SafeYAML.load_file('./config/config.yaml')
  end

  def self.database
    @database ||= Sequel.connect(@config['database']['endpoint'])
  end
end


text:
namespace Jal.Converter.Interface
{
    public interface IConverter<in TSource, TDestination> : IConverter
    {
        TDestination Convert(TSource source);

        TDestination Convert(TSource source, TDestination destination);

        TDestination Convert(TSource source, dynamic context);

        TDestination Convert(TSource source, TDestination destination, dynamic context);
    }

    public interface IConverter
    {

    }
}


text:
<?php declare(strict_types=1);
namespace Mfn\PHP\Analyzer\Report;

use PhpParser\Error;

class FileParserErrorReport extends StringReport
{

    /** @var  \SplFileInfo */
    private $file;
    /** @var  Error */
    private $error;

    /**
     * @param \SplFileInfo $file
     * @param Error $error
     */
    public function __construct(\SplFileInfo $file, Error $error)
    {
        $this->file = $file;
        $this->error = $error;
        $this->message = sprintf(
            '%s in %s',
            $this->error->getMessage(),
            $this->file->getRealPath()
        );
    }
}


text:
set -xe

# Start Apache with the right permissions
/app/docker/apache/start_safe_perms -DFOREGROUND


text:
:- module(tk_options,[test/0]).

:- use_module(library('tcltk/tcltk')).
:- use_module(tk_test_aux).
:- use_module(library(aggregates)).

% Example to probe one of the options of predicate tk_new.
% You could change the name of the window.

test:-
	tk_new([name('pepe')],Interp),
	test_aux(Interp).

test_aux(Interp):-
	tcl_eval(Interp,'button .b -text "Say Hello"',_),
	tcl_eval(Interp,[button,'.c','-text',dq('Quit')],_),
	tcl_eval(Interp,'pack .b .c',_),
	tcl_eval(Interp,[bind,'.b','<ButtonPress-1>',
                    br([prolog_one_event,dq(write(execute(tk_test_aux:hello)))])],_),
	tcl_eval(Interp,[bind,'.c','<ButtonPress-1>',
	            br([prolog_one_event,dq(write(quit))])],_),
        tk_event_loop(Interp),
	tcl_delete(Interp).


text:
import {createIframePromise} from '../../../../testing/iframe';
import {platformFor} from '../../../../src/platform';
import {vsyncFor} from '../../../../src/vsync';
import {
    AmpAppBanner,
    AbstractAppBanner,
    AmpIosAppBanner,
    AmpAndroidAppBanner,
} from '../amp-app-banner';
import {xhrFor} from '../../../../src/xhr';
import {timerFor} from '../../../../src/timer';
import '../../../amp-analytics/0.1/amp-analytics';
import * as sinon from 'sinon';

describe('amp-app-banner', () => {

  let sandbox;
  let vsync;
  let platform;
  let isAndroid = false;
  let isIos = false;
  let isChrome = false;
  let isSafari = false;

  const meta = {
    content: 'app-id=828256236, app-argument=medium://p/cb7f223fad86',
  };
  const manifest = {
    href: 'https://example.com/manifest.json',
    content: {
      'prefer_related_applications': true,
      'related_applications': [
        {
          'platform': 'play',
          'id': 'com.medium.reader',
          'url': 'https://play.google.com/com.medium.reader',
        },
      ],
    },
  };

  function runTask(task, state) {
    if (task.measure) {
      task.measure(state);
    }
    if (task.mutate) {
      task.mutate(state);
    }
  }

  function getTestFrame() {
    return createIframePromise(true).then(iframe => {
      platform = platformFor(iframe.win);
      sandbox.stub(platform, 'isIos', () => isIos);
      sandbox.stub(platform, 'isAndroid', () => isAndroid);
      sandbox.stub(platform, 'isChrome', () => isChrome);
      sandbox.stub(platform, 'isSafari', () => isSafari);

      vsync = vsyncFor(iframe.win);
      sandbox.stub(vsync, 'runPromise', (task, state) => {
        runTask(task, state);
        return Promise.resolve();
      });
      sandbox.stub(vsync, 'run', runTask);
      return iframe;
    });
  }

  function getAppBanner(config = {}) {
    return getTestFrame().then(iframe => {
      const link = iframe.doc.createElement('link');
      link.setAttribute('rel', 'canonical');
      link.setAttribute('href', 'https://example.com/amps.html');
      iframe.doc.head.appendChild(link);

      if (config.meta) {
        const meta = iframe.doc.createElement('meta');
        meta.setAttribute('name', 'apple-itunes-app');
        meta.setAttribute('content', config.meta.content);
        iframe.doc.head.appendChild(meta);
      }

      const manifestObj = config.originManifest || config.manifest;
      if (manifestObj) {
        const rel = config.originManifest ? 'origin-manifest' : 'manifest';
        const manifest = iframe.doc.createElement('link');
        manifest.setAttribute('rel', rel);
        manifest.setAttribute('href', manifestObj.href);
        iframe.doc.head.appendChild(manifest);
        sandbox.mock(xhrFor(iframe.win)).expects('fetchJson')
            .returns(Promise.resolve(manifestObj.content));
      }

      const banner = iframe.doc.createElement('amp-app-banner');
      banner.setAttribute('layout', 'nodisplay');
      if (!config.noOpenButton) {
        const openButton = iframe.doc.createElement('button');
        openButton.setAttribute('open-button', '');
        banner.appendChild(openButton);
      }

      return iframe.addElement(banner);
    });
  }

  function testButtonMissing() {
    return getAppBanner({
      meta,
      manifest,
      noOpenButton: true,
    }).should.eventually.be.rejectedWith(/<button open-button> is required/);
  }

  function testAddDismissButton() {
    sandbox.stub(AbstractAppBanner.prototype, 'isDismissed', () => {
      return Promise.resolve(false);
    });
    sandbox.spy(AbstractAppBanner.prototype, 'addDismissButton_');
    sandbox.spy(AbstractAppBanner.prototype, 'updateViewportPadding_');
    return getAppBanner({meta, manifest}).then(banner => {
      expect(banner.parentElement).to.not.be.null;
      expect(AbstractAppBanner.prototype.addDismissButton_.called).to.be.true;
      expect(AbstractAppBanner.prototype.updateViewportPadding_.called)
          .to.be.true;
      expect(banner.style.display).to.be.equal('');
      expect(banner.style.visibility).to.be.equal('');
    });
  }

  function testRemoveIfDismissed() {
    sandbox.stub(AbstractAppBanner.prototype, 'isDismissed', () => {
      return Promise.resolve(true);
    });
    return getAppBanner().then(banner => {
      expect(banner.parentElement).to.be.null;
      expect(banner.style.display).to.be.equal('');
      expect(banner.style.visibility).to.be.equal('hidden');
    });
  }

  function testManifestPreconnectPreload(rel) {
    const config = {};
    config[rel] = manifest;
    return () => {
      return getAppBanner(config).then(banner => {
        const impl = banner.implementation_;
        sandbox.stub(impl.preconnect, 'url');
        sandbox.stub(impl.preconnect, 'preload');
        impl.preconnectCallback(true);
        expect(impl.preconnect.url.called).to.be.true;
        expect(impl.preconnect.url.callCount).to.equal(1);
        expect(impl.preconnect.url.calledWith('https://play.google.com'))
            .to.be.true;
        expect(impl.preconnect.preload.called).to.be.true;
        expect(impl.preconnect.preload.callCount).to.equal(1);
        expect(impl.preconnect.preload.calledWith(
            'https://example.com/manifest.json')).to.be.true;
      });
    };
  }

  function testManifestParseAndHrefs(rel) {
    const config = {};
    config[rel] = manifest;
    return () => {
      sandbox.spy(AbstractAppBanner.prototype, 'setupOpenButton_');
      return getAppBanner({manifest}).then(el => {
        expect(AbstractAppBanner.prototype.setupOpenButton_.calledWith(
            el.querySelector('button[open-button]'),
            'android-app://com.medium.reader/https/example.com/amps.html',
            'https://play.google.com/store/apps/details?id=com.medium.reader'
        )).to.be.true;
      });
    };
  }

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    platform = platformFor(window);
    sandbox.stub(platform, 'isIos', () => isIos);
    sandbox.stub(platform, 'isAndroid', () => isAndroid);
    sandbox.stub(platform, 'isChrome', () => isChrome);
    sandbox.stub(platform, 'isSafari', () => isSafari);
    isAndroid = false;
    isIos = false;
    isChrome = false;
    isSafari = false;
  });

  afterEach(() => {
    sandbox.restore();
  });

  describe('Choosing platform', () => {
    it('should upgrade to AmpIosAppBanner on iOS', () => {
      isIos = true;
      return getTestFrame().then(() => {
        const banner = new AmpAppBanner(document.createElement('div'));
        const newInstance = banner.upgradeCallback();
        expect(newInstance instanceof AmpIosAppBanner).to.be.true;
      });
    });

    it('should upgrade to AmpAndroidAppBanner on Android', () => {
      isAndroid = true;
      return getTestFrame().then(() => {
        const banner = new AmpAppBanner(document.createElement('div'));
        const newInstance = banner.upgradeCallback();
        expect(newInstance instanceof AmpAndroidAppBanner).to.be.true;
      });
    });

    it('should not upgrade if platform not supported', () => {
      return getTestFrame().then(() => {
        const banner = new AmpAppBanner(document.createElement('div'));
        expect(banner.upgradeCallback()).to.be.null;
      });
    });
  });

  describe('non-supported platform', () => {
    it('should remove the banner', () => {
      return getAppBanner().then(banner => {
        expect(banner.parentElement).to.be.null;
      });
    });
  });

  describe('iOS', () => {
    beforeEach(() => {
      isIos = true;
    });

    it('should preconnect to app store', () => {
      return getAppBanner().then(banner => {
        // Re-add to DOM so that we can call `preconnectCallback`.
        banner.ownerDocument.body.appendChild(banner);
        const impl = banner.implementation_;
        sandbox.stub(impl.preconnect, 'url');
        impl.preconnectCallback(true);
        expect(impl.preconnect.url.called).to.be.true;
        expect(impl.preconnect.url.callCount).to.equal(1);
        expect(impl.preconnect.url.calledWith('https://itunes.apple.com'))
            .to.be.true;
      });
    });

    it('should throw if open button is missing', testButtonMissing);

    it('should remove banner if meta is not provided', () => {
      return getAppBanner({meta: null}).then(banner => {
        expect(banner.parentElement).to.be.null;
      });
    });

    it('should remove banner if safari', () => {
      isSafari = true;
      return getAppBanner().then(banner => {
        expect(banner.parentElement).to.be.null;
      });
    });

    it('should add dismiss button and update padding', testAddDismissButton);

    it('should remove banner if already dismissed', testRemoveIfDismissed);

    it('should parse meta content and setup hrefs', () => {
      sandbox.spy(AbstractAppBanner.prototype, 'setupOpenButton_');
      return getAppBanner({meta}).then(el => {
        expect(AbstractAppBanner.prototype.setupOpenButton_.calledWith(
            el.querySelector('button[open-button]'),
            'medium://p/cb7f223fad86',
            'https://itunes.apple.com/us/app/id828256236'
        )).to.be.true;
      });
    });
  });

  describe('Android', () => {
    beforeEach(() => {
      isAndroid = true;
      isChrome = false;
    });

    it('should preconnect to play store and preload manifest',
        testManifestPreconnectPreload('manifest'));
    it('should preconnect to play store and preload origin-manifest',
        testManifestPreconnectPreload('originManifest'));

    it('should throw if open button is missing', testButtonMissing);
    it('should add dismiss button and update padding', testAddDismissButton);
    it('should remove banner if already dismissed', testRemoveIfDismissed);

    it('should remove banner if manifest is not provided', () => {
      return getAppBanner({manifest: null}).then(banner => {
        expect(banner.parentElement).to.be.null;
      });
    });

    it('should remove banner if origin-manifest is not provided', () => {
      return getAppBanner({originManifest: null}).then(banner => {
        expect(banner.parentElement).to.be.null;
      });
    });

    it('should remove banner if chrome', () => {
      isChrome = true;
      return getAppBanner().then(banner => {
        expect(banner.parentElement).to.be.null;
      });
    });

    it('should parse manifest and set hrefs',
        testManifestParseAndHrefs('manifest'));
    it('should parse manifest and set hrefs',
        testManifestParseAndHrefs('originManifest'));
  });

  describe('Abstract App Banner', () => {
    it('should setup click listener', () => {
      return createIframePromise(true).then(iframe => {
        const win = iframe.win;
        const doc = iframe.doc;
        const element = doc.createElement('div');
        doc.body.appendChild(element);
        const openButton = doc.createElement('button');
        element.appendChild(openButton);
        openButton.setAttribute('open-button', '');
        openButton.addEventListener = sandbox.spy();
        const banner = new AbstractAppBanner(element);
        banner.setupOpenButton_(openButton, 'open-button', 'install-link');
        expect(openButton.addEventListener.calledWith('click')).to.be.true;
        win.open = sandbox.spy();
        sandbox.stub(banner, 'redirectTopLocation_', () => {});
        banner.openButtonClicked_('open-button', 'install-link');
        expect(win.open.calledWith('open-button', '_top')).to.be.true;
        return timerFor(iframe.win).delay(() => {
          expect(banner.redirectTopLocation_.called)
              .to.be.true;
          expect(banner.redirectTopLocation_.calledWith('install-link'))
              .to.be.true;
        }, 2000);
      });
    });

    it('should create dismiss button and setup click listener', () => {
      return createIframePromise(true).then(iframe => {
        const win = iframe.win;
        const doc = iframe.doc;
        vsync = vsyncFor(win);
        sandbox.stub(vsync, 'run', runTask);
        const element = doc.createElement('div');
        element.id = 'banner1';
        element.getAmpDoc = () => iframe.ampdoc;
        doc.body.appendChild(element);
        const banner = new AbstractAppBanner(element);
        banner.addDismissButton_();

        const bannerTop = element.querySelector(
            'i-amp-app-banner-top-padding');
        expect(bannerTop).to.exist;
        const dismissBtn = element.querySelector(
            '.amp-app-banner-dismiss-button');
        expect(dismissBtn).to.not.be.null;
        expect(dismissBtn.parentElement).to.be.equal(element);
        dismissBtn.dispatchEvent(new Event('click'));
        expect(element.parentElement).to.be.null;
        return banner.isDismissed().then(value => {
          expect(value).to.be.true;
        });
      });
    });
  });
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace LicenseManagerLibrary.Licenses
{
    internal class SimpleModule : ILicenseModule
    {
        public string Name { get; set; }
        public IEnumerable<ILicenseModule> SubModules { get; set; }
        public IEnumerable<ILicenseFeature> Features { get; set; }

        public SimpleModule()
        {
            Name = string.Empty;
            SubModules = new List<ILicenseModule>();
            Features = new List<ILicenseFeature>();
        }
    }
}


text:
export default function (Vue, config) {
  Vue.prototype.$config = config
}


text:
namespace Pythia8 {

//==========================================================================

// The WeakShowerMEs provides ME's needed for W/Z emission in ISR or FSR.

class WeakShowerMEs {

public:

  // Constructor.
  WeakShowerMEs() {}

  // Calculate the 2 to 2 ME uG -> uG, up to a known overall factor.
  double getTchanneluGuGME(double sHat,double tHat,double uHat);

  // Calculate the 2 to 2 ME ud -> ud, up to a known overall factor.
  double getTchannelududME(double sHat,double tHat,double uHat);

  // Calculate the 2 to 2 ME uu -> uu, up to a known overall factor.
  double getTchanneluuuuME(double sHat,double tHat,double uHat);

  // Calculate the 2 to 3 ME uG -> uGZ, up to a known overall factor.
  double getTchanneluGuGZME(Vec4 p1,Vec4 p2,Vec4 p3,Vec4 p4,Vec4 p5);

  // Calculate the 2 to 3 ME ud -> udZ, up to a known overall factor,
  // and with the coupling between Z and d set to zero.
  double getTchannelududZME(Vec4 p1,Vec4 p2,Vec4 p3,Vec4 p4,Vec4 p5);

};

//==========================================================================

} // end namespace Pythia8

#endif // Pythia8_WeakShowerMEs_H


text:
//
//  SKImage.m
//  Sketch
//
//  Created by Nate Parrott on 6/26/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SKImage.h"
#import "SKElement.h"
#import "SKAppDelegate.h"

@implementation SKImage
@synthesize size=_size;
@synthesize elements=_elements;
@synthesize delegate=_delegate;
@synthesize bundlePath=_bundlePath;
@synthesize parentElement=_parentElement;

-(void)setup {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:SKAppDelegateShouldSaveData object:nil];
}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    [self setup];
    _elements = [aDecoder decodeObjectForKey:@"Elements"];
    self.size = [aDecoder decodeCGSizeForKey:@"Size"];
    self.infiniteSize = [aDecoder decodeBoolForKey:@"InfiniteSize"];
    self.parentElement = [aDecoder decodeObjectForKey:@"ParentElement"];
    return self;
}
-(id)init {
    self = [super init];
    [self setup];
    _elements = [NSMutableArray new];
    self.size = CGSizeMake(500, 500);
    return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_elements forKey:@"Elements"];
    [aCoder encodeCGSize:self.size forKey:@"Size"];
    [aCoder encodeBool:self.infiniteSize forKey:@"InfiniteSize"];
    [aCoder encodeObject:self.parentElement forKey:@"ParentElement"];
}
-(void)save {
    NSString* imageDir = [self.bundlePath stringByAppendingPathComponent:@"image"];
    [NSKeyedArchiver archiveRootObject:self toFile:imageDir];

    NSString* thumbnailDir = [self.bundlePath stringByAppendingPathComponent:@"thumbnail.png"];
    [UIImagePNGRepresentation([self thumbnailWithMaxDimension:SKDocumentThumbnailMaxDimension]) writeToFile:thumbnailDir atomically:NO];

}
#pragma mark Elements
-(NSArray*)elements {
    // do we really need the copy?
    return [_elements copy];
}
-(void)addElement:(SKElement*)element {
    [_elements addObject:element];
    element.parentImage = self;
    [self.delegate image:self didAddElement:element];
}
-(void)removeElement:(SKElement*)element {
    [_elements removeObject:element];
    element.parentImage = nil;
    [self.delegate image:self didRemoveElement:element];
}
#pragma mark Layout/sizing
@synthesize infiniteSize=_infiniteSize;
-(CGSize)size {
    if (self.infiniteSize) {
        CGSize size = _size;
        for (SKElement* el in self.elements) {
            size.width = MAX(size.width, el.frame.origin.x+el.frame.size.width);
            size.height = MAX(size.height, el.frame.origin.y+el.frame.size.height);
        }
        return size;
    } else {
        return _size;
    }
}
-(void)bringElementToFront:(SKElement*)element {
    [_elements removeObject:element];
    [_elements addObject:element];
}
-(void)sendElementToBack:(SKElement*)element {
    [_elements removeObject:element];
    [_elements insertObject:element atIndex:0];
}
#pragma mark Dirtying/drawing
-(void)didUpdateChild:(SKElement*)child {
    [self.parentElement didUpdate];

    [self.delegate image:self didUpdateElement:child];
}
-(void)drawRect:(CGRect)imageRect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //CGContextConcatCTM(ctx, CGAffineTransformMakeScale(scale, scale));
    //CGContextConcatCTM(ctx, CGAffineTransformMakeTranslation(-imageRect.origin.x, -imageRect.origin.y));
    for (SKElement* element in self.elements) {
        if (CGRectIntersectsRect(element.frame, imageRect)) {
            CGContextSaveGState(ctx);
            CGContextConcatCTM(ctx, CGAffineTransformMakeTranslation(element.frame.origin.x, element.frame.origin.y));
            [element _draw];
            CGContextRestoreGState(ctx);
            //[element drawAtScale:CGPointMake(1, 1)];
        }
    }
}
/*-(void)drawInRect:(CGRect)rect {
    CGFloat scale = MIN(rect.size.width/self.size.width, rect.size.height/self.size.height);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGSize size = CGSizeMake(self.size.width*scale, self.size.height*scale);
    CGContextConcatCTM(ctx, CGAffineTransformMakeTranslation((rect.size.width-size.width)/2, (rect.size.height-size.height)/2));
    CGContextConcatCTM(ctx, CGAffineTransformMakeScale(scale, scale));
    [self drawRect:CGRectMake(0, 0, self.size.width, self.size.height)];
}*/
-(UIImage*)thumbnailWithMaxDimension:(CGFloat)dimension {
    CGSize imageSize = self.size;
    CGFloat aspectRatio = self.size.width / self.size.height;
    CGSize thumbnailSize = aspectRatio > 1? CGSizeMake(dimension, dimension/aspectRatio) : CGSizeMake(dimension*aspectRatio, dimension);
    CGPoint scale = CGPointMake(thumbnailSize.width/imageSize.width, thumbnailSize.height/imageSize.height);
    UIGraphicsBeginImageContext(thumbnailSize);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextConcatCTM(ctx, CGAffineTransformMakeScale(scale.x, scale.y));
    [self drawRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
-(NSData*)PDFThumbnailWithMaxDimension:(CGFloat)dimension {
    CGSize imageSize = self.size;
    CGFloat aspectRatio = self.size.width / self.size.height;
    CGSize thumbnailSize = aspectRatio > 1? CGSizeMake(dimension, dimension/aspectRatio) : CGSizeMake(dimension*aspectRatio, dimension);
    CGPoint scale = CGPointMake(thumbnailSize.width/imageSize.width, thumbnailSize.height/imageSize.height);
    NSMutableData* data = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(data, CGRectMake(0, 0, thumbnailSize.width, thumbnailSize.height), nil);
    UIGraphicsBeginPDFPage();
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextConcatCTM(ctx, CGAffineTransformMakeScale(scale.x, scale.y));
    [self drawRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    UIGraphicsEndPDFContext();
    return data;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Accessibility Properties</title>
<link rel="stylesheet" type="text/css" href="../../../technotes/css/guide.css" />

Documentation Contents

Accessibility Properties

Java Accessibility Guide > Java Accessibility API (JAAPI) Programmer's Guide > Accessibility Properties

Available Properties

The <tt>javax.accessibility</tt> package provides the following
properties:

<tt>assistive_technologies</tt>

<tt>screen_magnifier_present</tt>

<tt>screen_reader_present</tt>

Loading Assistive Technologies

The <tt>assistive_technologies</tt> property specifies the
assistive technologies to load into the JVM. It takes a
comma-delimited list as input. For example, if you set this property to com.sun.java.accessibility.AccessBridge, then Java Access Bridge is enabled.

Indicating the Presence of a Screen Magnifier

When the <tt>screen_magnifier_present</tt> property is set to
<tt>true</tt>, it lets the Java platform libraries know that a
screen magnifier is present on the system. Application developers
can check this property, and if a screen magnifier is present,
developers should make sure their applications are compatible with
screen magnification. For example, on Microsoft Windows operating
systems, the reference implementation of the Java 2D API
checks this property and if <tt>true</tt>, turns off Microsoft
DirectDraw to avoid problems with the screen magnifier. (Some
screen magnifiers may not be able to magnify DirectDraw
graphics.)

Indicating the Presence of a Screen Reader

When the <tt>screen_reader_present</tt> property is set to
<tt>true</tt>, it lets the Java platform libraries know that a
screen reader is present on the system. Application developers can
check this property. If an application is self-voicing and a screen
reader is present, developers can turn off the self-voicing.

Setting Properties

You can set a property at run time or in a properties file. To
set a property at run time, enter a command such as the
following:

java -Djavax.accessibility.screen_magnifier_present=true foo.class

The reference implementation includes an
<tt>accessibility.properties</tt> file in the <tt>jre/lib</tt>
directory. To set a property in the
<tt>accessibility.properties</tt> file, add a line or lines such as
the following:

assistive_technologies=com.sun.java.accessibility.AccessBridge
screen_magnifier_present=true
screen_reader_present=true

Copyright
© 1993, 2015, Oracle and/or its affiliates. All rights
reserved.

Contact
Us


text:
<?php

namespace PhpBench\Expression\Func;

use PhpBench\Expression\Ast\ListNode;
use PhpBench\Expression\Ast\Node;
use PhpBench\Expression\Ast\NullNode;

final class FirstFunction
{
    public function __invoke(Node $list): Node
    {
        if (!$list instanceof ListNode) {
            return new NullNode();
        }

        $values = $list->nodes();
        $first = reset($values);

        if (!$first) {
            return new NullNode();
        }

        return $first;
    }
}


text:
1. install OS on VirtualBox(Orcle)
    1. downloads [VirtualBox(oracle)]().
    2. downloads [Ubuntu Desktop]().
    3. install Ubuntu on VM.

2. install a basic dev-tool.
    - install vim, fish shell, guake terminal, git via cmd.
    ```
    sudo apt-get update && sudo apt-get upgrade -y
    sudo apt-get install -y vim guake fish git
    ```

3. install a basic tool
    - upgrade OS, and install Visual studio Code via Ubuntu Software Center.
    - install whale, gitKraken, via www

4. install the Node.js
    ```
    curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
    sudo apt-get install -y nodejs
    sudo npm install -g npm
    ```

5. [set the python](https://stackoverflow.com/questions/15221473/how-do-i-update-pip-itself-from-inside-my-virtual-environment)
    - remove python2, and set python3 as python.

    _나중에 재설치할 일이 있으면 제거 하지말고 경로만 python3을 python으로 python를 python2로 변경해보자. python2를 지우고 재설치하니 python2이 되긴했다._

    ```
    sudo apt purge python2.7-minimal
    sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.5 1
    python --version
    python -m pip install -U pylint
    ```
    - install and upgrade pip.
    ```
    sudo apt install python-pip
    pip install --upgrade pip
    ```


text:
<?php

namespace Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Entity\CareNewsArticle
 *
 * InnoDB free: 9216 kB
 *
 * @ORM\Entity(repositoryClass="CareNewsArticleRepository")
 * @ORM\Table(name="care_news_article", indexes={@ORM\Index(name="item_no", columns={"nr"})})
 */
class CareNewsArticle
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $nr;

    /**
     * @ORM\Column(type="string", length=10)
     */
    protected $lang;

    /**
     * @ORM\Column(type="smallint")
     */
    protected $dept_nr;

    /**
     * @ORM\Column(type="text")
     */
    protected $category;

    /**
     * @ORM\Column(type="string", length=10)
     */
    protected $status;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $title;

    /**
     * @ORM\Column(type="text")
     */
    protected $preface;

    /**
     * @ORM\Column(type="text")
     */
    protected $body;

    /**
     * @ORM\Column(type="blob", nullable=true)
     */
    protected $pic;

    /**
     * @ORM\Column(type="string", length=4, nullable=true)
     */
    protected $pic_mime;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $art_num;

    /**
     * @ORM\Column(type="text")
     */
    protected $head_file;

    /**
     * @ORM\Column(type="text")
     */
    protected $main_file;

    /**
     * @ORM\Column(type="text")
     */
    protected $pic_file;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $author;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $submit_date;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $encode_date;

    /**
     * @ORM\Column(type="date")
     */
    protected $publish_date;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $modify_id;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $modify_time;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $create_id;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $create_time;

    public function __construct()
    {
    }

    /**
     * Set the value of nr.
     *
     * @param integer $nr
     * @return \Entity\CareNewsArticle
     */
    public function setNr($nr)
    {
        $this->nr = $nr;

        return $this;
    }

    /**
     * Get the value of nr.
     *
     * @return integer
     */
    public function getNr()
    {
        return $this->nr;
    }

    /**
     * Set the value of lang.
     *
     * @param string $lang
     * @return \Entity\CareNewsArticle
     */
    public function setLang($lang)
    {
        $this->lang = $lang;

        return $this;
    }

    /**
     * Get the value of lang.
     *
     * @return string
     */
    public function getLang()
    {
        return $this->lang;
    }

    /**
     * Set the value of dept_nr.
     *
     * @param integer $dept_nr
     * @return \Entity\CareNewsArticle
     */
    public function setDeptNr($dept_nr)
    {
        $this->dept_nr = $dept_nr;

        return $this;
    }

    /**
     * Get the value of dept_nr.
     *
     * @return integer
     */
    public function getDeptNr()
    {
        return $this->dept_nr;
    }

    /**
     * Set the value of category.
     *
     * @param string $category
     * @return \Entity\CareNewsArticle
     */
    public function setCategory($category)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get the value of category.
     *
     * @return string
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Set the value of status.
     *
     * @param string $status
     * @return \Entity\CareNewsArticle
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get the value of status.
     *
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set the value of title.
     *
     * @param string $title
     * @return \Entity\CareNewsArticle
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get the value of title.
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set the value of preface.
     *
     * @param string $preface
     * @return \Entity\CareNewsArticle
     */
    public function setPreface($preface)
    {
        $this->preface = $preface;

        return $this;
    }

    /**
     * Get the value of preface.
     *
     * @return string
     */
    public function getPreface()
    {
        return $this->preface;
    }

    /**
     * Set the value of body.
     *
     * @param string $body
     * @return \Entity\CareNewsArticle
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    /**
     * Get the value of body.
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Set the value of pic.
     *
     * @param string $pic
     * @return \Entity\CareNewsArticle
     */
    public function setPic($pic)
    {
        $this->pic = $pic;

        return $this;
    }

    /**
     * Get the value of pic.
     *
     * @return string
     */
    public function getPic()
    {
        return $this->pic;
    }

    /**
     * Set the value of pic_mime.
     *
     * @param string $pic_mime
     * @return \Entity\CareNewsArticle
     */
    public function setPicMime($pic_mime)
    {
        $this->pic_mime = $pic_mime;

        return $this;
    }

    /**
     * Get the value of pic_mime.
     *
     * @return string
     */
    public function getPicMime()
    {
        return $this->pic_mime;
    }

    /**
     * Set the value of art_num.
     *
     * @param boolean $art_num
     * @return \Entity\CareNewsArticle
     */
    public function setArtNum($art_num)
    {
        $this->art_num = $art_num;

        return $this;
    }

    /**
     * Get the value of art_num.
     *
     * @return boolean
     */
    public function getArtNum()
    {
        return $this->art_num;
    }

    /**
     * Set the value of head_file.
     *
     * @param string $head_file
     * @return \Entity\CareNewsArticle
     */
    public function setHeadFile($head_file)
    {
        $this->head_file = $head_file;

        return $this;
    }

    /**
     * Get the value of head_file.
     *
     * @return string
     */
    public function getHeadFile()
    {
        return $this->head_file;
    }

    /**
     * Set the value of main_file.
     *
     * @param string $main_file
     * @return \Entity\CareNewsArticle
     */
    public function setMainFile($main_file)
    {
        $this->main_file = $main_file;

        return $this;
    }

    /**
     * Get the value of main_file.
     *
     * @return string
     */
    public function getMainFile()
    {
        return $this->main_file;
    }

    /**
     * Set the value of pic_file.
     *
     * @param string $pic_file
     * @return \Entity\CareNewsArticle
     */
    public function setPicFile($pic_file)
    {
        $this->pic_file = $pic_file;

        return $this;
    }

    /**
     * Get the value of pic_file.
     *
     * @return string
     */
    public function getPicFile()
    {
        return $this->pic_file;
    }

    /**
     * Set the value of author.
     *
     * @param string $author
     * @return \Entity\CareNewsArticle
     */
    public function setAuthor($author)
    {
        $this->author = $author;

        return $this;
    }

    /**
     * Get the value of author.
     *
     * @return string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Set the value of submit_date.
     *
     * @param datetime $submit_date
     * @return \Entity\CareNewsArticle
     */
    public function setSubmitDate($submit_date)
    {
        $this->submit_date = $submit_date;

        return $this;
    }

    /**
     * Get the value of submit_date.
     *
     * @return datetime
     */
    public function getSubmitDate()
    {
        return $this->submit_date;
    }

    /**
     * Set the value of encode_date.
     *
     * @param datetime $encode_date
     * @return \Entity\CareNewsArticle
     */
    public function setEncodeDate($encode_date)
    {
        $this->encode_date = $encode_date;

        return $this;
    }

    /**
     * Get the value of encode_date.
     *
     * @return datetime
     */
    public function getEncodeDate()
    {
        return $this->encode_date;
    }

    /**
     * Set the value of publish_date.
     *
     * @param datetime $publish_date
     * @return \Entity\CareNewsArticle
     */
    public function setPublishDate($publish_date)
    {
        $this->publish_date = $publish_date;

        return $this;
    }

    /**
     * Get the value of publish_date.
     *
     * @return datetime
     */
    public function getPublishDate()
    {
        return $this->publish_date;
    }

    /**
     * Set the value of modify_id.
     *
     * @param string $modify_id
     * @return \Entity\CareNewsArticle
     */
    public function setModifyId($modify_id)
    {
        $this->modify_id = $modify_id;

        return $this;
    }

    /**
     * Get the value of modify_id.
     *
     * @return string
     */
    public function getModifyId()
    {
        return $this->modify_id;
    }

    /**
     * Set the value of modify_time.
     *
     * @param datetime $modify_time
     * @return \Entity\CareNewsArticle
     */
    public function setModifyTime($modify_time)
    {
        $this->modify_time = $modify_time;

        return $this;
    }

    /**
     * Get the value of modify_time.
     *
     * @return datetime
     */
    public function getModifyTime()
    {
        return $this->modify_time;
    }

    /**
     * Set the value of create_id.
     *
     * @param string $create_id
     * @return \Entity\CareNewsArticle
     */
    public function setCreateId($create_id)
    {
        $this->create_id = $create_id;

        return $this;
    }

    /**
     * Get the value of create_id.
     *
     * @return string
     */
    public function getCreateId()
    {
        return $this->create_id;
    }

    /**
     * Set the value of create_time.
     *
     * @param datetime $create_time
     * @return \Entity\CareNewsArticle
     */
    public function setCreateTime($create_time)
    {
        $this->create_time = $create_time;

        return $this;
    }

    /**
     * Get the value of create_time.
     *
     * @return datetime
     */
    public function getCreateTime()
    {
        return $this->create_time;
    }

    public function __sleep()
    {
        return array('nr', 'lang', 'dept_nr', 'category', 'status', 'title', 'preface', 'body', 'pic', 'pic_mime', 'art_num', 'head_file', 'main_file', 'pic_file', 'author', 'submit_date', 'encode_date', 'publish_date', 'modify_id', 'modify_time', 'create_id', 'create_time');
    }
}


text:
export default {
    movId: {
        domain: 'DO_ID',
        isRequired: false
    },
    shortSynopsis: {
        domain: 'DO_COMMENT',
        isRequired: true
    },
    synopsis: {
        domain: 'DO_COMMENT',
        isRequired: true
    }
};


text:
mySigningKey := []byte("AllYourBase")

claims := &jwt.RegisteredClaims{
	ExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)),
	Issuer:    "test",
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(mySigningKey)


text:
create table employee (
	id int primary key auto_increment,
    name varchar(25) not null,
    departmentId int default 1111,
    salary double
);

create table department(
	id int primary key,
    name varchar(22) not null,
	location varchar(100),
    constraint unq_name unique(name)
);

-- alter table employee
-- add constraint fk_emp_dept foreign key(departmentId)
-- references department(id);
--
-- ALTER TABLE `employee` DROP FOREIGN KEY `fk_emp_dept`;
-- ALTER TABLE `employee` DROP INDEX `fk_emp_dept` ;

insert into employee values(10,'Lucy',1000,22),(18,'Lura',1200,22),(16,'Kevin',1500,22);

describe employee;
desc employee;
show create table employee;

alter table `employee` default charset='utf8';
alter table `department` default charset='utf8';
alter table `Department` engine=innodb;

#重命名表
alter table `department` rename to `Department`;

alter table `Department`
change `name` `name` varchar(30) default null;

alter table `Department` add
`managerId` int(11)
after `id`;

alter table `Department` drop `managerId`;

# alter table <tableName> modify <columnName1> <definition> after <columnName2>;

alter table employee modify `departmentId` int after `id`;

#alter table drop <tableName> drop foreign key <foreignKeyName>;

-- drop table [if exists] table1,table2...
drop table if exists table2;

alter table table1 drop foreign key fk_emp_dept;

create schema company default charset='utf8';
use company;

create table office (
	id int(10) not null unique auto_increment,
    city varchar(50) not null,
    address varchar(50),
    country varchar(50) not null,
    postalCode varchar(15),
	primary key (id)
);
create table employee(
	id int(11) not null primary key auto_increment,
    lastName varchar(50) not null,
    firstName varchar(50) not null,
    mobile varchar(50) unique,
    officeCode int(10) not null,
    jobTitle varchar(50) not null,
    birth datetime not null,
    note varchar(255),
    sex varchar(5),
    constraint fk_office_id foreign key(officeCode) references office(id)
);

alter table employee modify mobile varchar(25) after officeCode;
alter table employee change birth employee_birth datetime;
alter table employee modify sex char(1) not null;
alter table employee drop note;
alter table emplotee add favoriate_activity varchar(100);

alter table employee drop foreign key fk_office_id;
drop table office;

alter table employee engine=innodb;
show create table employee;

alter table employee rename employee_info;

create schema market default charset='utf8';

create table customers (
	c_num          int(11)       primary key not null auto_increment,
	c_name         varchar(50),
	c_contact      varchar(50),
	c_city         varchar(50),
	c_birth        datetime      not null
);

alter table market rename customers;
alter table customers modify c_contact varchar(50) after c_birth;
alter table customers change c_name c_name varchar(70);
alter table customers change c_contact c_phone varchar(50);
alter table customers add c_gender char(1) after c_name;
alter table customers rename customers_info;
alter table customers_info rename customers;
alter table customers drop c_city;
alter table customers engine=myisam;

use market;
create table orders (
	o_num    int(11)   primary key auto_increment,
	o_date   date,
	c_id     int(11),
	constraint fk_c_id foreign key(c_id) references customers(c_num)
)engine=innodb default charset='utf8';
# innodb does not support full text index, myisam does not support foreign key;
alter table orders engine=innodb;

alter table orders drop foreign key fk_c_id;
alter table orders drop index fk_c_id;

#chapter 7

create table fruits (
    f_id    char(10)        not null,
    s_id    int             not null,
    f_name  char(255)       not null,
    f_price decimal(8,2)    not null,
    primary key(f_id)
);

insert into fruits (f_id,s_id,f_name,f_price)
    values
    ('a1',101,'apple',5.2),
    ('b1',101,'blackberry',10.2),
    ('bs1',102,'orange',11.2),
    ('bs2',105,'melon',8.2),
    ('t1',102,'banana',10.3),
    ('t2',102,'grape',5.3),
    ('o2',103,'coconut',9.2),
    ('c0',101,'cherry',3.2),
    ('a2',103,'apricot',2.2),
    ('l2',104,'lemon',6.4),
    ('b2',104,'berry',7.6),
    ('m1',106,'mango',15.7),
    ('m2',107,'xbabay',2.6),
    ('t4',105,'xbababa',3.6),
    ('m3',105,'xxtt',11.6),
    ('b5',107,'xxxx',3.6);

select f_id, f_name from fruits;
select * from fruits;

select f_name, f_price from fruits where f_price = 10.2;
select f_name, f_price from fruits where f_name = 'apple';
select f_name, f_price from fruits where f_price < 10.00;
select f_name, f_price from fruits where s_id not in (101,102) order by f_name;

select f_name, f_price from fruits where f_price between 2.00 and 10.20;
select f_name, f_price from fruits where f_price not between 2.00 and 10.20;

select f_id, f_name from fruits where f_name like 'b%';
select f_id, f_name from fruits where f_name like '%g%';
select f_id, f_name from fruits where f_name like 'b%y';
select f_id, f_name from fruits where f_name like '___g';

create table customer (
    c_id        int         not null auto_increment,
    c_name      char(50)    not null,
    c_address   char(50)    null,
    c_city      char(50)    null,
    c_zip       char(10)    null,
    c_contact   char(50)    null,
    c_email     char(255)   null
    primary key(c_id)
);
insert into customer (c_id, c_name, c_address, c_city, c_zip, c_contact, c_email)
    values  (10001,'RedHook','200 Street','TianJin','300000','LiMing','LiMing@163.com'),
            (10002,'Stars','333 fromage Lane','Dalian','116000','Zhangbo','Jerry@hotmail.com'),
            (10003,'Netbhood','1 Sunny Place','Qingdao','266000','LuoCong',NULL),
            (10004,'JOTO','829 Riverside Drive','Haikou','570000','YangShan','sam@hotmail.com');

select count(*) as cust_num from customer;
# is null
select c_id, c_name, c_email from customer where c_email is null;
select c_id, c_name, c_email from customer where c_email is not null;

select f_id, f_price, f_name from fruits where s_id = '101' and f_price >= 5;

select s_id, f_name, f_price from fruits where s_id = 101 or s_id = 102;
select s_id, f_name, f_price from fruits where s_id in (101,102);

select distinct s_id from fruits;
select f_name, f_price from fruits order by f_name desc , f_price asc;

select s_id, count(*) total from fruits group by s_id with rollup;
select s_id, group_concat(f_name) names from fruits group by s_id;

select s_id, group_concat(f_name) as names from fruits group by s_id having count(f_name) > 1;
select * from fruits group by s_id,f_name;

create table orderitems(
    o_num   int         not null,
    o_item  int         not null,
    f_id    char(10)    not null,
    quantity    int     not null,
    item_price  decimal(8,2)    not null,
    primary key (o_num,o_item)
);

insert into orderitems (o_num,o_item,f_id,quantity,item_price)
    values (30001,1,'a1',10,5.2),
    (30001,2,'b2',3,7.6),
    (30001,3,'bs1',5,11.2),
    (30001,4,'bs2',15,9.2),
    (30002,1,'b3',2,20.0),
    (30003,1,'c0',100,10),
    (30004,1,'o2',50,2.50),
    (30005,1,'c0',5,10),
    (30005,2,'b1',10,8.99),
    (30005,3,'a2',10,2.2),
    (30005,4,'m1',5,14.99);

select o_num, sum(quantity*item_price) as total
from orderitems group by o_num having total>=100 limit 1,3;

select * from fruits limit 4,3;

# use cluster functions
# avg() count() max() min() sum()

select count(c_email) cust_num from customer;

select o_num, count(f_id) total from orderitems group by o_num order by total desc;

select sum(quantity) totalAmount from orderitems where o_num=30005;
select o_num, sum(quantity) totalAmount from orderitems group by o_num order by totalAmount desc;

select avg(f_price) avg_price from fruits where s_id = 103;

# inner join

create table suppliers(
    s_id    int         not null auto_increment,
    s_name  char(50)    not null,
    s_city  char(50)    null,
    s_zip   char(10)    null,
    s_call  char(50)    not null,
    primary key (s_id)
);

insert into suppliers (s_id, s_name, s_city, s_zip, s_call)
    values (101,'FastFruit Inc.','TianJian','300000','48075'),
    (102,'LT suppliers','Chongqing','400000','44333'),
    (103,'ACME','Shanghai','200000','90046'),
    (104,'FNK Inc.','Zhongshan','528437','11111'),
    (105,'Good Set','Taiyuang','030000','22222'),
    (106,'Just Eat Ours','Beijing','010','45678'),
    (107,'DK Inc.','Zhengzhou','450000','33332');

select suppliers.s_id, s_name, f_name, f_price
from fruits, suppliers
where fruits.s_id = suppliers.s_id;

select suppliers.s_id, s_name, f_name, f_price
from fruits inner join suppliers
on fruits.s_id = suppliers.s_id;

select f1.f_id, f1.f_name
from fruits as f1, fruits as f2
where f1.s_id = f2.s_id and f2.f_id = 'a1';

create table orders (
    o_num   int     not null auto_increment,
    o_date  datetime    not null,
    c_id    int     not null,
    primary key(o_num)
);

insert into orders(o_num, o_date, c_id)
    values(30001,'2008-09-01',10001),
    (30002,'2008-09-12',10003),
    (30003,'2008-09-30',10004),
    (30004,'2008-10-03',10005),
    (30005,'2008-10-08',10001);

select customer.c_id, orders.o_num from customer left outer join orders
on customer.c_id = orders.c_id;

select customer.c_id, orders.o_num from customer right outer join orders
on customer.c_id = orders.c_id;

select customer.c_id, orders.o_num from customer inner join orders
on customer.c_id = orders.c_id and customer.c_id = 10001;

select suppliers.s_id,s_name,f_name, f_price
from fruits inner join suppliers
on fruits.s_id = suppliers.s_id
order by fruits.s_id;

select * from fruits where exists
(select s_name from suppliers where s_id = 107);

select * from fruits where f_price > 10.20 and exists
(select s_name from suppliers where s_id = 107);

select * from fruits where not exists
(select s_name from suppliers where s_id = 107);

select s_id, f_name from fruits where s_id in
(select s1.s_id from suppliers as s1 where s1.s_city = 'Tianjin');

# 'union all' keys all rows , but 'union' delete dupilcated rows;
select s_id,f_name,f_price from fruits where f_price < 9.0
union all
select s_id,f_name,f_price from fruits where s_id in (101,103);

select * from fruits where f_name regexp '^b';

create table employee (
	e_no 		int(11)		not null,
	e_name 		varchar(50)	not null,
	e_gender 	char(2),
	dept_no		int(11)		not null,
	e_job		varchar(50) not null,
	e_salary	int(11)		not null,
	hire_date	date 		not null,
	primary key(e_no),
	constraint fk_dept foreign key(dept_no) references department(d_no)
)engine=innodb default charset=utf8;

create table department (
	d_no 			int(11)	not null auto_increment,
	d_name 			varchar(50)	not null,
	d_location		varchar(100),
	primary key(d_no)
)engine=innodb default charset=utf8;

insert into department (d_no,d_name,d_location)
	values (10,'ACCOUNTING','Shanghai'),
	(20,'REFRESH','Beijing'),
	(30,'SALES','ShenZhen'),
	(40,'OPERATIONS','Fujian');

insert into employee values
	(1001,'SMITH','m',20,'CLERK',800,'2005-11-12'),
	(1002,'ALLEN','f',30,'SALESMAN',1600,'2003-05-12'),
	(1003,'WARD','f',30,'SALESMAN',1250,'2003-05-12'),
	(1004,'JONES','m',20,'MANAGER',2975,'1998-05-18'),
    (1005,'MARTIN','m',30,'SALESMAN',1250,'2001-06-12'),
    (1006,'BLAKE','f',30,'MANAGER',2850,'1997-02-15'),
    (1007,'CLARK','m',10,'MANAGER',2450,'2002-09-12'),
    (1008,'SCOTT','m',20,'ANALYST',3000,'2003-05-12'),
    (1009,'KING','f',10,'PRESIDENT',5000,'1995-01-01'),
    (1010,'TURNER','f',30,'SALESMAN',1500,'1997-10-12'),
    (1011,'ADAMS','m',20,'CLERK',1100,'1999-10-05'),
    (1012,'JAMES','f',30,'CLERK',950,'2008-06-15');

alter table department change de_no d_no int(11) primary key auto_increment;
alter table employee add constraint fk_dept foreign key(dept_no) references department(d_no);

alter table employee drop foreign key fk_dept;
alter table employee drop key fk_dept;

select e_no, e_name, e_salary from employee;
select * from employee where dept_no in (10,20);
select * from employee where e_salary between 800 and 2500;

select * from employee where dept_no = 20;

select dept_no, max(e_salary) from employee group by dept_no;

select d_no,d_location from department where d_no =
(select dept_no from employee where e_name = 'BLAKE');

select e_no,e_name,d_no,d_name,d_location
from employee inner join department
on dept_no=d_no;

select dept_no ,count(*) from employee group by dept_no;

select e_job,dept_no,sum(e_salary) from employee group by e_job,dept_no;

select dept_no, avg(e_salary) from employee group by dept_no;

select dept_no, avg(e_salary) avg_salary from employee group by dept_no order by avg_salary desc;

select e_name, dept_no,e_salary from employee order by dept_no asc, e_salary desc;

select * from employee where e_name regexp '^[as]';

select * from employee where year(curdate())-year(hire_date) >= 20;

select e_no,e_name,e_gender,year(curdate())-year(hire_date) work_year from employee where e_gender='f';

select * from employee limit 3,3;

select min(e_salary) from employee where e_job = 'SALESMAN';

select * from employee where e_name regexp '[NS]$';

select e.e_name, e.e_job
from employee e inner join department d
on e.dept_no = d.d_no and d.d_location = 'Beijing';

select * from employee left outer join department on dept_no = d_no;

select * from employee where year(hire_date) between 2001 and 2005
union
select * from employee where dept_no in (20,30);

select * from employee where e_name like '%a%';

select * from employee where e_name regexp '[TCM]';

#chapter 8 update

create table person(
    id      int unsigned not null auto_increment,
    name    char(40) not null default '',
    age     int not null default 0,
    info    char(50) null,
    primary key(id)
);

create table person_old(
    id      int unsigned not null auto_increment,
    name    char(40) not null default '',
    age     int not null default 0,
    info    char(50) null,
    primary key(id)
);

insert into person (id, name, age, info)
    values (1,'Green',21,'Lawyer'),
    (2,'Suse',22,'Dancer'),
    (3,'Mary',24,'Musician'),
    (4,'Willam',20,'Sports man'),
    (5,'Laura',25,NULL),
    (6,'Evans',27,'secretary'),
    (7,'Dale',22,'cook'),
    (8,'Edison',28,'singer'),
    (9,'Harry',21,'magician'),
    (10,'Harriet',19,'pianist')

insert into person_old values
    (11,'Harry',20,'student'),
    (12,'Beckham',31,'police');

insert into person(id,name,age,info)
    select id ,name,age,info from person_old;

# update
update person set age=15 ,name = 'LiMing' where id = 11;

delete from person where id =11;

delete from person;
truncate table person;

create table books (
    id          int(11)         primary key,
    name        varchar(50)     not null,
    authors     varchar(50)     not null,
    price       float           not null,
    pubdate     year            not null,
    note        varchar(50),
    num         int(11)         not null
);

insert into books (id,name,authors,price,pubdate,note,num)
    values  (1,'Tale of AAA','Dickes',23,1995,'novel',11),
            (2,'EmmaT','Jane lura',35,1993,'joke',22),
            (3,'Story of Jane','Jane Tim',40,2001,'novel',0),
            (4,'Lovery Day','George Byron',20,2005,'novel',30),
            (5,'Old Land','Honore Blade',30,2010,'law',0),
            (6,'The Battle','Upton Sara',33,1999,'medicine',40),
            (7,'Rose Hood','Richard Haggard',28,2008,'cartoon',28);

update books set price = price + 5 where note = 'novel';

update books set price = 40, not = 'drama' where name = 'EmmaT';

create table pet(
    id      int(11)         primary key auto_increment,
    name    varchar(20)     not null,
    owner   varchar(20),
    species varchar(20)     not null,
    sex     char(1)         not null,
    birth   year            not null,
    death   year
);

insert into pet (name,owner,species,sex,birth,death)
    values  ('Fluffy','Harold','cat','r',2003,2010),
            ('Claws','Gwen','cat','m',2004,NULL),
            ('Buffy',NULL,'dog','f',2009,NULL),
            ('Fang','Benny','dog','m',2000,NULL),
            ('Bowser','Diane','dog','m',2003,2009),
            ('Chirpy',NULL,'bird','f',2008,NULL);

update pet set owner = 'Kevin' where name = 'Fang';
update pet set owner = 'Duck' where owner is null;

delete from pet where death is not null;

truncate pet;

#chapter 9
-- create table table_name [col_name data_type]
--    [unique|fulltext|spatial] [index|key] [index_name] (col_name [length]) [asc|desc]

create table book (
    bookid int not null,
    bookname varchar(255) not null,
    authors varchar(255) not null,
    info varchar(255),
    comment varchar(255),
    publish_year year not null,
    primary key(bookid),
    index(publish_year)
);

explain select * from book where publish_year = 1990;

-- alter table table_name add [unique|fulltext|spatial] [index|key]
--    [index_name] (col_name[length],...) [asc|desc]

show index from table_name;

alter table book add index book_name_idx (bookname(30));
create index book_name_idx on book (bookname(30));
-- create [unique|fulltext|spatial] [index|key] index_name on table_name
--    (col_name[length],...) [asc|desc]

drop index index_name on table_name;
alter table book drop index index_name;

create table test_table1 (
    id          int(11)     not null auto_increment,
    name        char(100)   not null,
    address     char(100),
    description char(100),
    primary key(id)
);

alter table test_table1 add index idx_name_address(name(20),address(30));
create index idex_desc on test_table1 (description(30));

create table test_table2(
    id          int(11)     primary key auto_increment,
    firstName   char(50) not null,
    middleName  char(50) not null,
    lastName    char(50) not null,
    birth       date     not null,
    title       char(100)
);

create table writers(
    w_id    smallint(11)    primary key auto_increment,
    w_name  varchar(255)    not null,
    w_address   varchar(255),
    w_age   char(2) not null,
    w_note  varchar(255)
);

alter table writers engine=myisam;

create index UniqIdx on writers(w_id);

alter table writers add index nameIdx(w_name);

create index idx_address_age on writers (w_address,w_name);

create fulltext index ftIdx on writers (w_note);

drop index ftIdx on writers;

# chapter 11 view

create table student(
    s_id    int,
    name    varchar(40)
);

create table stu_info (
    s_id    int,
    s_class varchar(40),
    address varchar(40)
);

-- create [or replace] [algorithm = {undefined | merge | temptable}]
-- view view_name [(column_list)]
-- as select_statement
-- [with [cascaded | local] check option]

select * from information_schema.views;

create table stu (
    s_id    varchar(20)     not null,
    s_name  varchar(50)     not null,
    address varchar(50)     not null,
    tel     varchar(50)     not null,
    primary key(s_id)
);

insert into stu (s_id, s_name, address, tel)
    values  (1,'XiaoWang','Henan','0371-12345678'),
            (2,'XiaoLi','Hebei','13889072345'),
            (3,'XiaoTian','Henan','0371-12345670')

create table sign (
    s_id    int     primary key,
    s_name  varchar(20)     not null,
    s_sch   varchar(50)     not null,
    s_sign_sch  varchar(50) not null
);
insert into sign
    values  (1,'XiaoWang','Middle School1','Peking University'),
            (2,'XiaoLi','Middle School2','Tsinghua University'),
            (3,'XiaoTian','Middle School3','Tsinghua University');

create table stu_mark(
    s_id    int primary key,
    s_name  varchar(20)     not null,
    mark    int     not null
);

insert into stu_mark values
    (1,'XiaoWang',80),
    (2,'xiaoLi',71),
    (3,'XiaoTian',70);

create view beida (id,name,mark,sch) as
select stu_mark.s_id,stu_mark.s_name,stu_mark.mark,sign.s_sign_sch
from stu_mark, sign
where stu_mark.s_id = sign.s_id and stu_mark.mark>=41 and sign.s_sign_sch = 'Peking University';

create view qinghua (id,name,mark,sch) as
select stu_mark.s_id,stu_mark.s_name,stu_mark.mark,sign.s_sign_sch
from stu_mark, sign
where stu_mark.s_id = sign.s_id and stu_mark.mark>=40 and sign.s_sign_sch = 'Tsinghua University';

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `beida`
AS select `stu_mark`.`s_id` AS `id`,
`stu_mark`.`s_name` AS `name`,
`stu_mark`.`mark` AS `mark`,
`sign`.`s_sign_sch` AS `sch`
from (`stu_mark` join `sign`)
where ((`stu_mark`.`s_id` = `sign`.`s_id`)
and (`stu_mark`.`mark` >= 41)
and (`sign`.`s_sign_sch` = 'Peking University'));

# if all the info are null expect comment, the comment is 'view'
show table status like 'qinghua';

-- 1. create or replace view view1(a,b,c,d) as select....
-- 2. alter view view1 view1(a,b,c,d) as select....

drop view beida;
drop view qinghua;

-- create trigger trigger_name trigger_time trigger_event
-- on table_name for each row trigger_stmt;

create table account (id int primary key,amount decimal(10,2));

create trigger ins_num before insert on account for each row set @sum = @sum + NEW.amount;

/*
create trigger trigger_name [before|after] [insert|update|delete]
    on table_name for each row
    begin
        .....
    end
*/

show triggers;

create table myevent(
    id int(11) primary key auto_increment,
    evt_name char(20)
);

create trigger tig_update after update on account for each row
    insert into myevent (evt_name) values ('after update');

select * from information_schema.triggers where trigger_name = 'tig_update';

create trigger trig_insert after insert on account for each row
    insert into myevent (evt_name) values ('after insert');

insert into account values (6,3.00),(7,2.00);

drop trigger tig_update;

create table persons (name varchar(40) not null,num int(11) not null);
insert into persons values ('xiaoming',20),('xiaojun',69);

create table sales (name varchar(40) not null,sum int(11) not null);

create trigger num_sum after insert on persons for each row
    insert into sales values (new.name,7*new.num);

create trigger t1 after update on persons for each row (statement);


text:
/* Aloha Profiler
 * --------------
 * Provides a useful interface to profile some of Aloha components and their
 * methods.
 *
 * Potentially process intensive methods:
 *              Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes')
 *              Aloha.Profiler.profileAlohaComponent('Selection._updateSelection')
 */
window.define( [
	'aloha/core',
	'aloha/plugin',
	'aloha/editable',
	// 'aloha/sidebar',
	'aloha/selection',
	'aloha/markup',
	'aloha/contenthandlermanager',
	'aloha/floatingmenu',
	'aloha/console',
	'css!profiler/css/profiler'
], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup,
             ContentHandlerManager, FloatingMenu, console ) {
	// 'caller', 'callee', and 'arguments' properties may not be accessed on
	// strict mode functions or the arguments objects for calls to them
	//

	var jQuery = Aloha.jQuery,
	    profiledFunctions = [],

	    // get the arguments string literal of this function, and split it into
	    // an array of names
	    argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ),
	    argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [],
	    args = Array.prototype.slice.call( arguments );

	/**
	 * @param {String} path dot seperated path to resolve inside a given object
	 *                 or browser window
	 * @param {?Object} object inwhich to resolve a path. If no object is
	 *                  passed, the browser window object will be used instead
	 * @return {?} Object
	 */
	function resolvePath(path, obj) {
		if ( typeof path !== 'string' ) {
			return path;
		}

		if ( !obj || typeof obj !== 'object' ) {
			obj = window;
		}

		var parts = path.split( '.' ),
		    i = 0,
			j = parts.length;

		for ( ; i < j; ++i ) {
			obj = obj[ parts[ i ] ];
			if ( typeof obj === 'undefined' ) {
				console.error(
					'Aloha.Profiler',
					'Property "' + parts[ i ] + '" does not exist' +
						( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' )
				);

				return null;
			}
		}

		return obj;
	};

	function parseObjectPath( path, obj ) {
		if ( typeof path !== 'string' ) {
			return null;
		}

		var parts = path.split( '.' ),
		    pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ),
			prop;

		obj = resolvePath( pathToProp, obj );

		if ( !obj ) {
			return null;
		}

		if ( parts.length > 1 ) {
			var lastProp = parts[ parts.length - 1 ];
			if ( typeof obj[ lastProp ] === 'undefined' ) {
				console.error( 'Aloha.Profiler',
					'Property "' + lastProp + '" does not exist in object ' +
					pathToProp );
			} else {
				prop = lastProp;
			}
		}

		return {
			obj       : obj[ prop ],
			path      : path,
			parentObj : obj,
			propName  : prop
		};
	};

	var panel;
	function initSidebarPanel(sidebar) {
		sidebar.addPanel( {
			id       : 'aloha-devtool-profiler-panel',
			title    : 'Aloha Profiler',
			expanded : true,
			activeOn : true,
			content  : '' +
				'
' +
					'<input id="aloha-devtool-profiler-input" ' +
						'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' +
					'

' +
				'
',
			onInit   : function() {
				this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) {
					// Handle ENTER
					if ( event.keyCode === 13 ) {
						var input = jQuery( this );
						var value = input.val();
						if ( value ) {
							eval( value );
							PanelConsole.log( value );
							input.val( '' );
						}
					}
				} );
			}
		} );
		sidebar.show().open();
	};

	var PanelConsole = {
		log: function() {
			jQuery( '#aloha-devtool-profiler-console' )
				.prepend( '
' +
					Array.prototype.slice.call( arguments ).join( ' ' ) +
					'
' );
		}
	}

	Aloha.Profiler = Plugin.create( 'profiler', {

		/**
		 * Explose all dependencies to allow easy access. eg:
		 * If the 5th dependency was Markup, then:
		 * Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes')
		 * would start profiling the Markup.preProcessKeyStrokes method.
		 */
		loadedDependencies: Array.prototype.slice.call( arguments ),

		/**
		 * Provides a better interface to access various components of Aloha.
		 * eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes')
		 */
		alohaComponents: {},

		panel: null,

		/**
		 * Initializes Profiler plugin by populating alohaComponents with all
		 * arguments of our define function, mapping name, to object
		 */
		init: function() {
			var j = argNames.length;
			while ( --j >= 0 ) {
				this.alohaComponents[ argNames[ j ] ] = args[ j ];
			}

			var that = this;

			Aloha.ready( function() {
				if ( Aloha.Sidebar && Aloha.Sidebar.right ) {
					that.panel = initSidebarPanel( Aloha.Sidebar.right );
				}
			} );
		},

		log: function() {
			PanelConsole.log.apply( PanelConsole, arguments );
		},

		/**
		 * Shortcut to profile one of the Aloha components that was required by
		 * Aloha Profiler.
		 *
		 * @param {String} path
		 * @param {String} fnName
		 */
		profileAlohaComponent: function( path, fnName ) {
			var parts = parseObjectPath( path, this.alohaComponents );
			return this.profile( parts.parentObj, fnName || parts.propName );
		},

		/**
		 * @param {(Object|String)} obj object or path to object that contains
		 *                 the function we want to profile. Or the path to the
		 *                 function itself
		 * @param {String} fnName name of function inside obj, which we want to
		 *                 profile
		 * @param {?Function(Function, Array):Boolean} intercept functiont to
		 *                 call each time this method is invoked
		 */
		profile: function( obj, fnName, intercept ) {
			var path,
			    parts,
			    objIndex = -1,
			    i;

			if ( typeof obj === 'string' ) {
				parts = parseObjectPath( obj );
				obj = parts.parentObj;
				path = parts.path + ( fnName ? '.' + fnName : '' );
				if ( parts.propName ) {
					if ( typeof parts.obj === 'function' ) {
						fnName = parts.propName;
					} else if ( parts.obj === 'object' ) {
						obj = parts.obj;
					}
				}
			}

			if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) {
				return;
			}

			for ( i = 0; i < profiledFunctions.length; ++i ) {
				if ( profiledFunctions[ i ] === obj ) {
					objIndex = i;
					if ( profiledFunctions[ i ][ fnName ] ) {
						return;
					}
				}
			}

			var fn = obj[ fnName ];
			var that = this;

			// In IE typeof window.console.log returns "object!!!"
			if ( window.console && window.console.log ) {
				if ( objIndex === -1 ) {
					objIndex = profiledFunctions.push( obj ) - 1;
				}

				profiledFunctions[ objIndex ][ fnName ] = fn;

				obj[ fnName ] = function() {
					if ( typeof intercept === 'function' ) {
						intercept( fn, arguments );
					}

					// window.console.time( fnName );
					var start = +( new Date() );
					var returnValue = fn.apply( obj, arguments );

					// window.console.timeEnd( fnName );
					that.log( ( path || fnName ) + ': ' +
						( ( new Date() ) - start ) + 'ms' );

					return returnValue;
				};
			}
		},

		/**
		 * @return {String} "Aloha.Profiler"
		 */
		toString: function() {
			return 'Aloha.Profiler';
		}
	} );

	return Aloha.Profiler;
} );


text:
module HasBalance
  module Model
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def has_balance
        before_validation :check_balance_value

        unless included_modules.include? InstanceMethods
          include InstanceMethods
        end
      end
    end

    module InstanceMethods
      def currency
        I18n.t("has_balance.currency")
      end

      def printable_balance
        "#{self.balance.to_s} #{self.currency}"
      end

      def give_money!(amount)
        sql = "update users set balance=#{self.balance + amount.to_f} where id='#{self.id}'"
        connection.update(sql)
      end

      def take_money!(amount)
        sql = "update users set balance=#{self.balance - amount.to_f} where id='#{self.id}'"
        connection.update(sql)
      end

      def check_balance_value
        if self.balance >= 1000000
          self.errors.add(I18n.t("has_balance.balance"), I18n.t("has_balance.cannot_be_million"))
        end
      end
    end
  end
end


text:
"""The GeoNet NZ Volcano integration."""
from __future__ import annotations

from datetime import datetime, timedelta
import logging

from aio_geojson_geonetnz_volcano import GeonetnzVolcanoFeedManager
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
    CONF_LATITUDE,
    CONF_LONGITUDE,
    CONF_RADIUS,
    CONF_SCAN_INTERVAL,
    CONF_UNIT_SYSTEM,
    LENGTH_KILOMETERS,
    LENGTH_MILES,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.unit_conversion import DistanceConverter

from .config_flow import configured_instances
from .const import (
    DEFAULT_RADIUS,
    DEFAULT_SCAN_INTERVAL,
    DOMAIN,
    FEED,
    IMPERIAL_UNITS,
    PLATFORMS,
)

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                vol.Optional(CONF_LATITUDE): cv.latitude,
                vol.Optional(CONF_LONGITUDE): cv.longitude,
                vol.Optional(CONF_RADIUS, default=DEFAULT_RADIUS): vol.Coerce(float),
                vol.Optional(
                    CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
                ): cv.time_period,
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the GeoNet NZ Volcano component."""
    if DOMAIN not in config:
        return True

    conf = config[DOMAIN]

    latitude = conf.get(CONF_LATITUDE, hass.config.latitude)
    longitude = conf.get(CONF_LONGITUDE, hass.config.longitude)
    scan_interval = conf[CONF_SCAN_INTERVAL]

    identifier = f"{latitude}, {longitude}"
    if identifier in configured_instances(hass):
        return True

    hass.async_create_task(
        hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": SOURCE_IMPORT},
            data={
                CONF_LATITUDE: latitude,
                CONF_LONGITUDE: longitude,
                CONF_RADIUS: conf[CONF_RADIUS],
                CONF_SCAN_INTERVAL: scan_interval,
            },
        )
    )

    return True

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
    """Set up the GeoNet NZ Volcano component as config entry."""
    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN].setdefault(FEED, {})

    radius = config_entry.data[CONF_RADIUS]
    unit_system = config_entry.data[CONF_UNIT_SYSTEM]
    if unit_system == IMPERIAL_UNITS:
        radius = DistanceConverter.convert(radius, LENGTH_MILES, LENGTH_KILOMETERS)
    # Create feed entity manager for all platforms.
    manager = GeonetnzVolcanoFeedEntityManager(hass, config_entry, radius, unit_system)
    hass.data[DOMAIN][FEED][config_entry.entry_id] = manager
    _LOGGER.debug("Feed entity manager added for %s", config_entry.entry_id)
    await manager.async_init()
    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload an GeoNet NZ Volcano component config entry."""
    manager = hass.data[DOMAIN][FEED].pop(entry.entry_id)
    await manager.async_stop()
    return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

class GeonetnzVolcanoFeedEntityManager:
    """Feed Entity Manager for GeoNet NZ Volcano feed."""

    def __init__(self, hass, config_entry, radius_in_km, unit_system):
        """Initialize the Feed Entity Manager."""
        self._hass = hass
        self._config_entry = config_entry
        coordinates = (
            config_entry.data[CONF_LATITUDE],
            config_entry.data[CONF_LONGITUDE],
        )
        websession = aiohttp_client.async_get_clientsession(hass)
        self._feed_manager = GeonetnzVolcanoFeedManager(
            websession,
            self._generate_entity,
            self._update_entity,
            self._remove_entity,
            coordinates,
            filter_radius=radius_in_km,
        )
        self._config_entry_id = config_entry.entry_id
        self._scan_interval = timedelta(seconds=config_entry.data[CONF_SCAN_INTERVAL])
        self._unit_system = unit_system
        self._track_time_remove_callback = None
        self.listeners = []

    async def async_init(self):
        """Schedule initial and regular updates based on configured time interval."""

        await self._hass.config_entries.async_forward_entry_setups(
            self._config_entry, PLATFORMS
        )

        async def update(event_time):
            """Update."""
            await self.async_update()

        # Trigger updates at regular intervals.
        self._track_time_remove_callback = async_track_time_interval(
            self._hass, update, self._scan_interval
        )

        _LOGGER.debug("Feed entity manager initialized")

    async def async_update(self):
        """Refresh data."""
        await self._feed_manager.update()
        _LOGGER.debug("Feed entity manager updated")

    async def async_stop(self):
        """Stop this feed entity manager from refreshing."""
        for unsub_dispatcher in self.listeners:
            unsub_dispatcher()
        self.listeners = []
        if self._track_time_remove_callback:
            self._track_time_remove_callback()
        _LOGGER.debug("Feed entity manager stopped")

    @callback
    def async_event_new_entity(self):
        """Return manager specific event to signal new entity."""
        return f"geonetnz_volcano_new_sensor_{self._config_entry_id}"

    def get_entry(self, external_id):
        """Get feed entry by external id."""
        return self._feed_manager.feed_entries.get(external_id)

    def last_update(self) -> datetime | None:
        """Return the last update of this feed."""
        return self._feed_manager.last_update

    def last_update_successful(self) -> datetime | None:
        """Return the last successful update of this feed."""
        return self._feed_manager.last_update_successful

    async def _generate_entity(self, external_id):
        """Generate new entity."""
        async_dispatcher_send(
            self._hass,
            self.async_event_new_entity(),
            self,
            external_id,
            self._unit_system,
        )

    async def _update_entity(self, external_id):
        """Update entity."""
        async_dispatcher_send(self._hass, f"geonetnz_volcano_update_{external_id}")

    async def _remove_entity(self, external_id):
        """Ignore removing entity."""


text:
package com.ryctabo.test.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class HomeFragment extends Fragment {

    public HomeFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

}


text:
import React from 'react';
import * as _ from 'lodash';
import { observer } from 'mobx-react';

import { editor, generator, interactions, masks, layout } from '../core';
import { VOICE_COLORS, MUTED_COLOR, COLOR_PRIMARY } from '../core/theme';

import { Group } from './group';

export interface Props {
  width: number;
  height: number;
  labelWidth: number;
}

const VOICE_INITIALS = ['S', 'A', 'T', 'B'];

@observer
export class MaskLanes extends React.Component<Props> {
  renderLabels() {
    const { height, labelWidth } = this.props;

    return _.range(4).map(voiceIndex => {
      const laneHeight = height / 4;
      const y = voiceIndex * laneHeight;
      const isMuted = editor.isVoiceMuted(voiceIndex);
      const color = isMuted ? MUTED_COLOR : VOICE_COLORS[voiceIndex];
      return (
        <g
          key={`label_${voiceIndex}`}
          className="mask-lane-label"
          onClick={(e: React.MouseEvent<SVGGElement>) => {
            editor.toggleVoiceMute(voiceIndex);
          }}
        >
          <rect
            x={1}
            y={y + 1}
            height={laneHeight - 2}
            width={labelWidth - 2}
            fillOpacity={0}
            stroke={COLOR_PRIMARY}
            strokeWidth={0.5}
            rx="3"
          />
          <text
            x={layout.pianoRollWidth / 2 - 6}
            y={y + 16}
            height={laneHeight}
            width={labelWidth}
            fill={color}
          >
            {VOICE_INITIALS[voiceIndex]}
          </text>
        </g>
      );
    });
  }

  renderLanes() {
    const { height, width } = this.props;
    const laneHeight = height / 4;

    return _.range(4).map(voiceIndex => {
      const y = voiceIndex * laneHeight;
      const isMuted = editor.isVoiceMuted(voiceIndex);
      const color = isMuted ? MUTED_COLOR : VOICE_COLORS[voiceIndex];

      const candidateSequencesExist = generator.candidateSequences.length > 0;
      const mouseDownHandler = interactions.handleMaskLaneMouseDown(
        voiceIndex,
        candidateSequencesExist
      );

      return (
        <rect
          key={`lane_${voiceIndex}`}
          x={0}
          y={y}
          height={laneHeight}
          width={width}
          fill={color}
          fillOpacity={candidateSequencesExist ? 0.6 : 1}
          onMouseDown={mouseDownHandler}
        />
      );
    });
  }

  renderMasks() {
    const { height, width } = this.props;
    const laneHeight = height / 4;

    return _.range(4).map(voiceIndex => {
      const mask = masks.userMasks[voiceIndex];
      const y = voiceIndex * laneHeight;

      // Merge the mask indices into left/right bounds in order to draw
      // contiguous rectangles for masked regions.
      type Bound = { start: number; end: number };
      const maskBounds: Bound[] = [];

      let currentBound: Bound | null = null;
      mask.forEach((maskIndex, arrIndex) => {
        const neighborLeft =
          arrIndex > 0 && mask[arrIndex - 1] === maskIndex - 1;

        if (!currentBound || !neighborLeft) {
          currentBound = { start: maskIndex, end: maskIndex };
          maskBounds.push(currentBound);
          return;
        } else {
          currentBound.end = maskIndex;
        }
      });

      return maskBounds.map((bounds, boundsIndex) => {
        const BORDER = 2;

        const x = (width / editor.totalSixteenths) * bounds.start;
        const rectWidth =
          (width / editor.totalSixteenths) * (bounds.end - bounds.start + 1);
        const maskIndices = _.range(bounds.start, bounds.end + 1);

        const candidateSequencesExist = generator.candidateSequences.length > 0;

        const clickHandler = interactions.handleMaskRectClick(
          voiceIndex,
          maskIndices,
          candidateSequencesExist
        );

        const isMuted = editor.isVoiceMuted(voiceIndex);
        const color = isMuted ? MUTED_COLOR : VOICE_COLORS[voiceIndex];

        return (
          <>
            {candidateSequencesExist ? (
              <rect
                x={x}
                y={y}
                height={laneHeight}
                width={rectWidth}
                fill={color}
              />
            ) : null}
            <rect
              key={`lane_${voiceIndex}_mask_${boundsIndex}`}
              x={x + BORDER}
              y={y + BORDER}
              height={laneHeight - 2 * BORDER}
              width={rectWidth - 2 * BORDER}
              stroke={'white'}
              strokeWidth={2}
              fill={`url(#diagonal-stripe)`}
              fillOpacity={0.75}
              onClick={clickHandler}
              cursor={candidateSequencesExist ? 'pointer' : 'default'}
            />
          </>
        );
      });
    });
  }

  render() {
    const { labelWidth } = this.props;

    return (
      <Group>
        {this.renderLabels()}
        <Group x={labelWidth}>{this.renderLanes()}</Group>
        <Group x={labelWidth}>{this.renderMasks()}</Group>
      </Group>
    );
  }
}


text:
__author__ = 'Joe Linn'

import unittest
import pylastica
from tests.base import Base

class WildcardTest(unittest.TestCase, Base):
    def test_search_with_analyzer(self):
        client = self._get_client()
        index = client.get_index('test')
        index_params = {
            'analysis': {
                'analyzer': {
                    'lw': {
                        'type': 'custom',
                        'tokenizer': 'keyword',
                        'filter': ['lowercase']
                    }
                }
            }
        }
        index.create(index_params, True)
        doc_type = index.get_doc_type('test')
        mapping = pylastica.doc_type.Mapping(doc_type, {
            'name': {'type': 'string', 'store': 'no', 'analyzer': 'la'}
        })
        doc_type.mapping = mapping

        doc_type.add_document(pylastica.Document(1, {'name': 'San Diego'}))
        doc_type.add_document(pylastica.Document(2, {'name': 'San Luis Obispo'}))
        doc_type.add_document(pylastica.Document(3, {'name': 'San Francisco'}))
        doc_type.add_document(pylastica.Document(4, {'name': 'Chicago'}))
        doc_type.add_document(pylastica.Document(5, {'name': 'London'}))
        index.refresh()

        query = pylastica.query.Wildcard()
        query.set_value('name', 'sa*')
        result_set = doc_type.search(query)
        self.assertEqual(3, len(result_set))

        query = pylastica.query.Wildcard()
        query.set_value('name', 'ch*')
        result_set = doc_type.search(query)
        self.assertEqual(1, len(result_set))
        index.delete()

if __name__ == '__main__':
    unittest.main()


text:
<?php include "config/config.php"; ?>
<?php include "libraries/Database.php";   ?>
<?php include "helpers/format_helper.php";  ?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>The Learn PHP Blog</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/custom.css" rel="stylesheet">

          Home
          All Posts

<img src="images/logo.png"

The PHP Blog

PHP News, Tutorials, Videos and more.


text:
package com.armadialogcreator.util;

import org.jetbrains.annotations.NotNull;

/**
 @author Kayler
 @since 03/22/2017 */
public class TextRange {
	private int start;
	private int end;

	private TextRange(int start, int end) {
		this.start = start;
		this.end = end;
	}

	public int getStart() {
		return start;
	}

	public int getEnd() {
		return end;
	}

	public int length() {
		return end - start;
	}

	@NotNull
	public static TextRange fromRange(int start, int end) {
		testBounds(start, end);
		return new TextRange(start, end);
	}

	@NotNull
	public static TextRange fromLength(int start, int length) {
		int end = start + length;
		testBounds(start, end);
		return new TextRange(start, end);
	}

	@NotNull
	public static TextRange forString(@NotNull String s) {
		int end = s.length();
		return new TextRange(0, end);
	}

	private static void testBounds(int start, int end) {
		if (start < 0) {
			throw new IllegalArgumentException("start < 0");
		}
		if (end < 0) {
			throw new IllegalArgumentException("end < 0");
		}
		if (end < start) {
			throw new IllegalArgumentException("end < start");
		}
	}

}


text:
aerofiles.openair
=================

.. autoclass:: aerofiles.openair.Reader
   :members:
   :inherited-members:

.. autoclass:: aerofiles.openair.LowLevelReader
   :members:
   :inherited-members: