text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 *
 * Generated from protobuf message google.cloud.compute.v1.TargetPoolInstanceHealth
 */
class TargetPoolInstanceHealth extends \Google\Protobuf\Internal\Message
{
    /**
     * Generated from protobuf field repeated .google.cloud.compute.v1.HealthStatus health_status = 380545845;
     */
    private $health_status;
    /**
     * [Output Only] Type of resource. Always compute#targetPoolInstanceHealth when checking the health of an instance.
     *
     * Generated from protobuf field optional string kind = 3292052;
     */
    private $kind = null;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Cloud\Compute\V1\HealthStatus[]|\Google\Protobuf\Internal\RepeatedField $health_status
     *     @type string $kind
     *           [Output Only] Type of resource. Always compute#targetPoolInstanceHealth when checking the health of an instance.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Compute\V1\Compute::initOnce();
        parent::__construct($data);
    }

    /**
     * Generated from protobuf field repeated .google.cloud.compute.v1.HealthStatus health_status = 380545845;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getHealthStatus()
    {
        return $this->health_status;
    }

    /**
     * Generated from protobuf field repeated .google.cloud.compute.v1.HealthStatus health_status = 380545845;
     * @param \Google\Cloud\Compute\V1\HealthStatus[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setHealthStatus($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Cloud\Compute\V1\HealthStatus::class);
        $this->health_status = $arr;

        return $this;
    }

    /**
     * [Output Only] Type of resource. Always compute#targetPoolInstanceHealth when checking the health of an instance.
     *
     * Generated from protobuf field optional string kind = 3292052;
     * @return string
     */
    public function getKind()
    {
        return isset($this->kind) ? $this->kind : '';
    }

    public function hasKind()
    {
        return isset($this->kind);
    }

    public function clearKind()
    {
        unset($this->kind);
    }

    /**
     * [Output Only] Type of resource. Always compute#targetPoolInstanceHealth when checking the health of an instance.
     *
     * Generated from protobuf field optional string kind = 3292052;
     * @param string $var
     * @return $this
     */
    public function setKind($var)
    {
        GPBUtil::checkString($var, True);
        $this->kind = $var;

        return $this;
    }

}


text:
<ExternalCallout name="EC-1">

  <GrpcConnection>
    <Server name="grpcserver"/>
    <!--
        For Apigee X, connecting to a service in Cloud Run, include an
        Authentication element like the following. Your Audience value will be
        different.

        Then, you will need to deploy the proxy with an account with "runAs"
        permissions, and specify a service account.
    -->

    <Authentication>
      <GoogleIDToken>
        <Audience>https://external-callout-2s6vjmoabq-uw.a.run.app</Audience>
        <IncludeEmail>false</IncludeEmail>
      </GoogleIDToken>
    </Authentication>

  </GrpcConnection>

  <TimeoutMs>5000</TimeoutMs>
  <Configurations>
    <Property name="with.request.content">true</Property>
    <Property name="with.request.headers">true</Property>
    <Property name="with.response.content">true</Property>
    <Property name="with.response.headers">true</Property>
  </Configurations>
</ExternalCallout>

redpajama_set_name: RedPajamaGithub


text:
from UnitTest import UnitTest

class Foo(object):
    def __init__(self):
        pass
    def bar(self):
        pass

class HashableTest(UnitTest):
    def testMethods(self):
        foo = Foo()
        dMethodToInt = {}
        dMethodToInt[foo.bar] = 5
        dMethodToInt[foo.bar] = 6
        dMethodToInt[foo.bar] = 7
        self.assertEquals(1, len(dMethodToInt.keys()),
                          'Bug #656 Hashing class methods is not supported')


text:
PDFKit makes adding text to documents quite simple, and includes many options
to customize the display of the output. Adding text to a document is as simple
as calling the `text` method.

    doc.text 'Hello world!'

Internally, PDFKit keeps track of the current X and Y position of text as it
is added to the document. This way, subsequent calls to the `text` method will
automatically appear as new lines below the previous line. However, you can
modify the position of text by passing X and Y coordinates to the `text`
method after the text itself.

    doc.text 'Hello world!', 100, 100

If you want to move down or up by lines, just call the `moveDown` or `moveUp`
method with the number of lines you'd like to move (1 by default).

## Line wrapping and justification

PDFKit includes support for line wrapping out of the box! If no options are
given, text is automatically wrapped within the page margins and placed in the
document flow below any previous text, or at the top of the page. PDFKit
automatically inserts new pages as necessary so you don't have to worry about
doing that for long pieces of text. PDFKit can also automatically wrap text
into multiple columns.

The text will automatically wrap unless you set the `lineBreak` option to `false`.
By default it will wrap to the page margin, but the `width` option allows
you to set a different width the text should be wrapped to.
If you set the `height` option, the text will be clipped to the number of
lines that can fit in that height.

When line wrapping is enabled, you can choose a text justification. There are
four options: `left` (the default), `center`, `right`, and `justify`. They
work just as they do in your favorite word processor, but here is an example
showing their use in a text box.

    lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus.  Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl.'

    doc.fontSize 8
    doc.text 'This text is left aligned. ' + lorem,
      width: 410
      align: 'left'

    doc.moveDown()
    doc.text 'This text is centered. ' + lorem,
      width: 410
      align: 'center'

    doc.moveDown()
    doc.text 'This text is right aligned. ' + lorem,
      width: 410
      align: 'right'

    doc.moveDown()
    doc.text 'This text is justified. ' + lorem,
      width: 410
      align: 'justify'

    # draw bounding rectangle
    doc.rect(doc.x, 0, 410, doc.y).stroke()

The output of this example, looks like this:

![2](images/alignments.png)

## Text styling

PDFKit has many options for controlling the look of text added to PDF
documents, which can be passed to the `text` method. They are enumerated
below.

* `lineBreak` - set to `false` to disable line wrapping all together
* `width` - the width that text should be wrapped to (by default, the page width minus the left and right margin)
* `height` - the maximum height that text should be clipped to
* `ellipsis` - the character to display at the end of the text when it is too long. Set to `true` to use the default character.
* `columns` - the number of columns to flow the text into
* `columnGap` - the amount of space between each column (1/4 inch by default)
* `indent` - the amount in PDF points (72 per inch) to indent each paragraph of text
* `paragraphGap` - the amount of space between each paragraph of text
* `lineGap` - the amount of space between each line of text
* `wordSpacing` - the amount of space between each word in the text
* `characterSpacing` - the amount of space between each character in the text
* `fill` - whether to fill the text (`true` by default)
* `stroke` - whether to stroke the text
* `link` - a URL to link this text to (shortcut to create an annotation)
* `underline` - whether to underline the text
* `strike` - whether to strike out the text
* `continued` - whether the text segment will be followed immediately by another segment. Useful for changing styling in the middle of a paragraph.
* `features` - an array of [OpenType feature tags](https://www.microsoft.com/typography/otspec/featuretags.htm) to apply. If not provided, a set of defaults is used.

Additionally, the fill and stroke color and opacity methods described in the
[vector graphics section](vector.html) are applied to text content as well.

* * *

Here is an example combining some of the options above, wrapping a piece of text into three columns, in a specified width and height.

    lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;'

    doc.text lorem,
      columns: 3
      columnGap: 15
      height: 100
      width: 465
      align: 'justify'

The output looks like this:

![3]()

## Text measurements

If you're working with documents that require precise layout, you may need to know the
size of a piece of text. PDFKit has two methods to achieve this: `widthOfString(text, options)`
and `heightOfString(text, options)`. Both methods use the same options described in the
Text styling section, and take into account the eventual line wrapping.

## Lists

The `list` method creates a bulleted list. It accepts as arguments an array of strings,
and the optional `x`, `y` position. You can create complex multilevel lists by using nested arrays.
Lists use the following additional options:
* `bulletRadius`
* `textIndent`
* `bulletIndent`

## Rich Text

As mentioned above, PDFKit supports a simple form of rich text via the `continued` option.
When set to true, PDFKit will retain the text wrapping state between `text` calls. This way,
when you call text again after changing the text styles, the wrapping will continue right
where it left off.

The options given to the first `text` call are also retained for subsequent calls after a
`continued` one, but of course you can override them.  In the following example, the `width`
option from the first `text` call is retained by the second call.

    doc.fillColor 'green'
       .text lorem.slice(0, 500),
         width: 465
         continued: yes
       .fillColor 'red'
       .text lorem.slice(500)

Here is the output:

![4]()

## Fonts

The PDF format defines 14 standard fonts that can be used in PDF documents. PDFKit supports each of them out of the box.
Besides Symbol and Zapf Dingbats this includes 4 styles (regular, bold, italic/oblique, bold+italic) of Helvetica,
Courier, and Times. To switch between standard fonts, call the `font` method with the corresponding Label:
* `'Courier'`
* `'Courier-Bold'`
* `'Courier-Oblique'`
* `'Courier-BoldOblique'`
* `'Helvetica'`
* `'Helvetica-Bold'`
* `'Helvetica-Oblique'`
* `'Helvetica-BoldOblique'`
* `'Symbol'`
* `'Times-Roman'`
* `'Times-Bold'`
* `'Times-Italic'`
* `'Times-BoldItalic'`
* `'ZapfDingbats'`

The PDF format also allows fonts to be embedded right in the document. PDFKit supports
embedding TrueType (`.ttf`), OpenType (`.otf`), WOFF, WOFF2, TrueType Collection (`.ttc`),
and Datafork TrueType (`.dfont`) fonts.

To change the font used to render text, just call the `font` method. If you
are using a standard PDF font, just pass the name to the `font` method.
Otherwise, pass the path to the font file, or a `Buffer` containing the font data.
If the font is a collection font (`.ttc` and `.dfont` files), meaning that it
contains multiple styles in the same file, you should pass the name of the style
to be extracted from the collection.

Here is an example showing how to set the font in each case.

    # Set the font size
    doc.fontSize(18)

    # Using a standard PDF font
    doc.font('Times-Roman')
       .text('Hello from Times Roman!')
       .moveDown(0.5)

    # Using a TrueType font (.ttf)
    doc.font('fonts/GoodDog.ttf')
       .text('This is Good Dog!')
       .moveDown(0.5)

    # Using a collection font (.ttc or .dfont)
    doc.font('fonts/Chalkboard.ttc', 'Chalkboard-Bold')
       .text('This is Chalkboard, not Comic Sans.')

The output of this example looks like this:

![5](images/fonts.png)

Another nice feature of the PDFKit font support, is the ability to register a
font file under a name for use later rather than entering the path to the font
every time you want to use it.

    # Register a font
    doc.registerFont('Heading Font', 'fonts/Chalkboard.ttc', 'Chalkboard-Bold')

    # Use the font later
    doc.font('Heading Font')
       .text('This is a heading.')

That's about all there is too it for text in PDFKit. Let's move on now to
images.


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace pharmacymansys
{
    public partial class ManageStock : Form
    {
        public ManageStock()
        {
            InitializeComponent();
        }
    }
}


text: require('telescope').load_extension 'file_browser'


text:
import logging
from flask_mail import Message

from server import mail

logger = logging.getLogger(__name__)

DEFAULT_SENDER = "no-reply@mediacloud.org"

def send_html_email(subject, recipients, text_body, html_body):
    msg = Message(_prefix_subject_line(subject),
                  sender=DEFAULT_SENDER,
                  recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    mail.send(msg)

def send_email(sender, recipients, subject, message):
    logger.debug('Sending mail '+sender+':'+subject)
    msg = Message(_prefix_subject_line(subject),
                  sender=sender,
                  recipients=recipients)
    msg.body = message
    mail.send(msg)

def _prefix_subject_line(subject):
    return "[Media Cloud] {}".format(subject)


text:
dropbox-album-export
====================

This script downloads contents of Dropbox albums.


text:
layout: post_by_tag
title: Monthly Reading List
tag: readinglist
permalink: /meta/tag/readinglist/
header-img: images/new/Exportiert_25.jpg
search_omit: true
---


text:
package es.agustruiz.deadpoolcomics.data.model.marvel;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Item_Marvel {

    @SerializedName("resourceURI")
    @Expose
    private String resourceURI;
    @SerializedName("name")
    @Expose
    private String name;

    public String getResourceURI() {
        return resourceURI;
    }

    public void setResourceURI(String resourceURI) {
        this.resourceURI = resourceURI;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
require "spec_helper"
require File.join(File.dirname(__FILE__), "..", "lib", "thumbnail")

describe Thumbnail do

  before do
    @id = "D80QdsFWdcQ"
    @slice = @id.slice(0,2)
    @container = File.join("lib", "public", "thumbs", @slice)
    @filename = File.join(@container, "#{@id}.png")
    @tmpfile    = File.open(File.join(File.dirname(__FILE__), "fixtures", "thumb.jpg"))
    @thumbnail = Thumbnail.new(@id, @tmpfile)
  end

  describe "#write" do
    it 'should create a simple png' do
      @thumbnail.write
      File.should exist(@filename)
    end

    it 'should include overlay filenames in filename' do
      @thumbnail.add_overlay
      @thumbnail.write
      File.should exist(File.join(@container, "#{@id}_overlay.png"))
    end

    it 'should be chainable' do
      @thumbnail.write.should be_kind_of(Thumbnail)
    end

    it 'should overwrite existing files' do
      FileUtils.cp(root_path.join("spec", "fixtures", "thumb.jpg"), @filename)
      existing = File.stat(@filename)
      @thumbnail.write
      existing.should_not eq File.stat(@filename)
    end

    describe 'subdirs' do
      before do
        @container = File.join("lib", "public", "thumbs")
        FileUtils.rm_rf(@container)
      end

      it 'should create the thumbs container dir' do
        @thumbnail.write
        File.should exist(@container)
      end

      it 'to a subdirectory of the first two characters of the id' do
        @thumbnail.write
        File.should exist(File.join(@container, @slice))
      end
    end
  end

  describe "#images" do
    it 'should be an ImageList' do
      @thumbnail.images.should be_kind_of Magick::ImageList
    end
    it 'should include the tmpfile' do
      expected = Magick::ImageList.new(@tmpfile.path)[0]
      @thumbnail.images.should include expected
    end
  end

  describe "#add_overlay" do
    before do
      @overlay_name = File.join("assets", "overlay.png")
      @expected = Magick::ImageList.new(@overlay_name)[0]
      @thumbnail.add_overlay
    end

    it 'should add files to ImageList stack' do
      @thumbnail.images.should include @expected
    end

    it 'should call combine the images to one' do
      Magick::Image.any_instance.should_receive(:composite).once.and_return(@expected)
      @thumbnail.write
    end

    it 'should be chainable' do
      @thumbnail.add_overlay.should be_kind_of(Thumbnail)
    end

    it 'should prefer an overlay-image from current dir' do
      assets_dir = File.join("/", "tmp", "assets")
      FileUtils.mkdir_p(assets_dir)
      FileUtils.cp(File.join("assets", "overlay.png"), File.join(assets_dir, "overlay.png"))
      Dir.stub(:pwd).and_return("/tmp")

      @thumbnail.add_overlay
      # Don't know how to fetch the current_filename or Filename from Magick::Image
      #  so using #inspect and regexing that.
      @thumbnail.images.last.inspect.should match %r{/tmp/assets/overlay\.png .*}

      FileUtils.rm_r(assets_dir)
    end

  end

  describe "uri_path" do
    it 'should return an absolute path from within "/public".' do
      @thumbnail.uri_path.should eq "/thumbs/#{@slice}/#{@id}.png"
    end
  end
end


text:
using System.Diagnostics;
using System.IO;
using Bloom;
using Bloom.Book;
using Bloom.CLI;
using BloomTemp;
using NUnit.Framework;

namespace BloomTests.CLI
{
	[TestFixture]
	public class HydrateBookCommandTests
	{
		private string _originalHtmlPath;
		private string _eventualHtmlPath;
		private TemporaryFolder _testFolder;
		private TemporaryFolder _bookFolder;

		[SetUp]
		public void Setup()
		{
			_testFolder = new TemporaryFolder("hydration test");
			_bookFolder = new TemporaryFolder(_testFolder,"original name");
			_originalHtmlPath = _bookFolder.Combine("original name.html");
			// We need the reference to basic book.css because that's where the list of valid page layouts lives,
			// and Bloom will force the book to A5Portrait if it can't verify that A5Landscape, Device16x9Landscape etc. are valid.
			File.WriteAllText(_originalHtmlPath,
				@"<link rel='stylesheet' href='Basic Book.css' type='text / css'></link>

								mudmen

							Story Book

							Copyright © 2016, Joe Author

							http://creativecommons.org/licenses/by/4.0/

							Some Acknowledgments

1st page

				");

			//NOTE: At the moment, if the bookTitle of the selected vernacular language does not match
			//the name of the file and folder, the hydration process will rename the book's folder and file,
			//just like opening it in Bloom does. At the moment, we set the name of the folder/file to be
			//the same as the title in the requested vernacular, so it isn't an issue. But further tests
			//could make it an issue. For now, these are the same:
			//_eventualHtmlPath = _testFolder.Combine("mudmen", "mudmen.htm");

			//decided that allowing a new name is just going to confuse the programs using this CLI, so
			//let's expect the program to NOT change the names for now.
			_eventualHtmlPath = _testFolder.Combine("original name", "original name.html");
		}

		[TearDown]
		public void TearDown()
		{
			_testFolder.Dispose();
		}

		[Test]
		public void BogusPath_Returns1()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters()
			{
				Path = "notAnywhere"
			});
			Assert.AreEqual(1, code);
		}

		[Test]
		public void PresetIsApp_A5LandscapeChangedToDevice16x9Landscape()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters()
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			var html = File.ReadAllText(_eventualHtmlPath);
			var xhtml = XmlHtmlConverter.GetXmlDomFromHtml(html);
			AssertThatXmlIn.Dom(xhtml).HasAtLeastOneMatchForXpath("//div[contains(@class,'bloom-page') and contains(@class,'Device16x9Landscape')]");
			Assert.That(!html.Contains("A5Landscape"));
		}

		///
		/// Eventually we need to have the app preset investigate whether to use the video xmatter or
		/// the (at this time, non-existant) book-app xmatter. For now, we expect it to assume we have
		/// a multimedia book.
		///
		[Test]
		public void PresetIsApp_XmatterSetToVideo()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters()
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			var html = File.ReadAllText(_eventualHtmlPath);
			Assert.That(html.Contains("Opening Screen"));
		}

		[Test]
		public void PresetIsApp_XMatterIsFilledIn()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters()
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			Debug.Write(File.ReadAllText(_eventualHtmlPath));
			var dom = XmlHtmlConverter.GetXmlDomFromHtml(File.ReadAllText(_eventualHtmlPath));

			AssertThatXmlIn.Dom(dom)
				.HasAtLeastOneMatchForXpath("//div[contains(@class,'bookTitle')]/div[contains(@class, 'bloom-editable') and contains(text(), 'mudmen')]");

			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-derived='copyright' and contains(text(),'Joe Author')]", 1);

			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book='originalAcknowledgments' and @lang='en' and contains(@class,'bloom-editable') and contains(text(),'Some Acknowledgments')]", 1);

			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book-attributes='frontCover' and @" + HtmlDom.musicAttrName
					+ "='audio/SoundTrack1.mp3' and @" + HtmlDom.musicVolumeName + "='0.17']", 2);

			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//div[contains(@class,'frontCover') and @" + HtmlDom.musicAttrName
					+ "='audio/SoundTrack1.mp3' and @" + HtmlDom.musicVolumeName + "='0.17']", 1);
		}

		[Test]
		public void PresetIsApp_StylesheetAreRelativePaths()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters()
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			Debug.Write(File.ReadAllText(_eventualHtmlPath));
			var dom = XmlHtmlConverter.GetXmlDomFromHtml(File.ReadAllText(_eventualHtmlPath));

			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//link[@href='basePage.css']",1);

			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//link[@href='languageDisplay.css']", 1);
			AssertThatXmlIn.Dom(dom)
				.HasSpecifiedNumberOfMatchesForXpath("//link[@href='Video-XMatter.css']", 1);
		}

		[Test]
		public void PresetIsApp_CreativeCommonsLicenseImageAdded()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			Assert.That(File.Exists(Path.Combine(Path.GetDirectoryName(_eventualHtmlPath), "license.png")));
		}

		[Test]
		public void SetsCorrectClassesForVernacularLanguage()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			AssertThatXmlIn.HtmlFile(_eventualHtmlPath)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book='contentLanguage1' and @lang='*' and text()='en']", 1);
			AssertThatXmlIn.HtmlFile(_eventualHtmlPath)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book='bookTitle' and @contenteditable='true' and @lang='en']", 1);
		}

		[Test]
		public void SetsCorrectClassesForNationalLanguages()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en",
				NationalLanguage1IsoCode = "fr",
				NationalLanguage2IsoCode = "sp"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			AssertThatXmlIn.HtmlFile(_eventualHtmlPath)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book='bookTitle' and @contenteditable='true' and @lang='fr' and contains(@class,'bloom-contentNational1')]", 1);
			AssertThatXmlIn.HtmlFile(_eventualHtmlPath)
				.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book='bookTitle' and @contenteditable='true' and @lang='sp' and contains(@class,'bloom-contentNational2')]", 1);
		}

		[Test]
		public void HasNoBloomPlayerScript_AddsOne()
		{
			var code = HydrateBookCommand.Handle(new HydrateParameters
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.AreEqual(0, code, "Should return an exit code of 0, meaning it is happy.");
			AssertThatXmlIn.HtmlFile(_eventualHtmlPath)
				.HasSpecifiedNumberOfMatchesForXpath("//head/script[contains(@src,'bloomPlayer.js')]",1);
		}

		[Test]
		public void AlreadyBloomPlayerScript_DoesNotAddOne()
		{
			//TODO
		}

		[Test]
		public void HasNoBloomPlayerFile_AddsOne()
		{
			var bloomPlayerPath = Path.Combine(Path.GetDirectoryName(_eventualHtmlPath), "bloomPlayer.js");
			Assert.False(File.Exists(bloomPlayerPath));
			HydrateBookCommand.Handle(new HydrateParameters
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.True(File.Exists(bloomPlayerPath));
		}

		[Test]
		public void AlreadyHasBloomPlayerFile_ReplacesIt()
		{
			var bloomPlayerPath = Path.Combine(Path.GetDirectoryName(_eventualHtmlPath), "bloomPlayer.js");
			File.WriteAllText(bloomPlayerPath, "Some initial text in the file");
			Assert.True(File.Exists(bloomPlayerPath));
			Assert.True(new FileInfo(bloomPlayerPath).Length < 100);
			HydrateBookCommand.Handle(new HydrateParameters
			{
				Path = _bookFolder.FolderPath,
				Preset = "app",
				VernacularIsoCode = "en"
			});
			Assert.True(new FileInfo(bloomPlayerPath).Length > 100);
		}
	}
}


text:
import React, { Component } from 'react'

import styles from './loader.css'

const Loader = () => {
  return (
    <div className={styles.container}>
      Loading ...
    </div>
  )
}

export default Loader


text:
Record and Share Terminal Session with Showterm
======

![](https://www.maketecheasier.com/assets/uploads/2017/11/record-terminal-session.jpg)

You can easily record your terminal sessions with virtually all screen recording programs. However, you are very likely to end up with an oversized video file. There are several terminal recorders available in Linux, each with its own strengths and weakness. Showterm is a tool that makes it pretty easy to record terminal sessions, upload them, share, and embed them in any web page. On the plus side, you don't end up with any huge file to deal with.

Showterm is open source, and the project can be found on this [GitHub page][1].

 **Related** : [2 Simple Applications That Record Your Terminal Session as Video [Linux]][2]

### Installing Showterm for Linux

Showterm requires that you have Ruby installed on your computer. Here's how to go about installing the program.
```
gem install showterm
```

If you don't have Ruby installed on your Linux system:
```
sudo curl showterm.io/showterm > ~/bin/showterm
sudo chmod +x ~/bin/showterm
```

If you just want to run the application without installation:
```
bash <(curl record.showterm.io)
```

You can type `showterm --help` for the help screen. If a help page doesn't appear, showterm is probably not installed. Now that you have Showterm installed (or are running the standalone version), let us dive into using the tool to record.

 **Related** : [How to Record Terminal Session in Ubuntu][3]

### Recording Terminal Session

![showterm terminal][4]

Recording a terminal session is pretty simple. From the command line run `showterm`. This should start the terminal recording in the background. All commands entered in the command line from hereon are recorded by Showterm. Once you are done recording, press Ctrl + D or type `exit` in the command line to stop your recording.

Showterm should upload your video and output a link to the video that looks like http://showterm.io/<long alpha-numeric characters>. It is rather unfortunate that terminal sessions are uploaded right away without any prompting. Don't panic! You can delete any uploaded recording by entering `showterm --delete <recording URL>`. Before uploading your recordings, you'll have the chance to change the timing by adding the `-e` option to the showterm command. If by any chance a recording fails to upload, you can use `showterm --retry <script> <times>` to force a retry.

When viewing your recordings, the timing of the video can also be controlled by appending "#slow," "#fast," or "#stop" to the URL. Slow makes the video run at normal speed; fast doubles the speed; and stop, as the name suggests, stops the video.

Showterm terminal recordings can easily be embedded in web pages via iframes. This can be achieved by adding the iframe source to the showterm video URL as shown below.

![showtermio][5]

As an open source tool, Showterm allows for further customization. For instance, to run your own Showterm server, you need to run the command:
```
export SHOWTERM_SERVER=https://showterm.myorg.local/
```

so your client can communicate with it. Additional features can be added with little programming knowledge. The Showterm server project is available from this [GitHub page][1].

### Conclusion

In case you are thinking of sharing some command line tutorials with a colleague, be sure to remember Showterm. Showterm is text-based; hence, it will yield a relatively small-sized video compared to other screen recorders. The tool itself is pretty small in size - only a few kilobytes.

--------------------------------------------------------------------------------

via: https://www.maketecheasier.com/record-terminal-session-showterm/

作者:[Bruno Edoh][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://www.maketecheasier.com/author/brunoedoh/
[1]:https://github.com/ConradIrwin/showterm
[2]:https://www.maketecheasier.com/record-terminal-session-as-video/ (2 Simple Applications That Record Your Terminal Session as Video [Linux])
[3]:https://www.maketecheasier.com/record-terminal-session-in-ubuntu/ (How to Record Terminal Session in Ubuntu)
[4]:https://www.maketecheasier.com/assets/uploads/2017/11/showterm-interface.png (showterm terminal)
[5]:https://www.maketecheasier.com/assets/uploads/2017/11/showterm-site.png (showtermio)


text:
@class GrowlNotificationHistoryWindow;

@interface GrowlNotificationDatabase : GrowlAbstractDatabase {
   NSTimer *maintenanceTimer;

    NSTimer *periodicSaveTimer;

   NSDate *lastImageCheck;
   BOOL notificationsWhileAway;
   GrowlNotificationHistoryWindow *historyWindow;
}

+(GrowlNotificationDatabase *)sharedInstance;

@property (readonly) GrowlNotificationHistoryWindow *historyWindow;
@property (readonly) BOOL notificationsWhileAway;

-(NSArray*)mostRecentNotifications:(unsigned int)amount;

-(void)deleteSelectedObjects:(NSArray*)objects;
-(void)deleteAllHistory;

-(void)storeMaintenance:(NSTimer*)theTimer;
-(void)trimByDate;
-(void)trimByCount;
-(void)imageCacheMaintenance;
-(void)userReturnedAndClosedList;

// maintiance
-(void)setupMaintenanceTimers;
-(void)logNotificationWithDictionary:(NSDictionary*)noteDict;

-(void)showRollup;
-(void)hideRollup;

@end


text:
package us.gov.dod.standard.ssrf._3_1.antenna;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import us.gov.dod.standard.ssrf._3_1.Antenna;
import us.gov.dod.standard.ssrf._3_1.RFSystem;
import us.gov.dod.standard.ssrf._3_1.Receiver;
import us.gov.dod.standard.ssrf._3_1.Transmitter;
import us.gov.dod.standard.ssrf._3_1.metadata.domains.TString;
import us.gov.dod.standard.ssrf._3_1.metadata.lists.ListCAO;
import us.gov.dod.standard.ssrf._3_1.metadata.lists.ListUS2;
import us.gov.dod.standard.ssrf._3_1.multiple.Notation;

/**
 * UsingCountries (US) describes the countries that manufacture (Producing),
 * supply (Source), and use (Using) the Antenna.
 *

 * Element of
 * {@link Antenna}, {@link Notation}, {@link RFSystem}, {@link Receiver}, {@link Transmitter}
 *

 * Example:
 *

 * <UsingCountries>
 *   <CountryName cls="U">UZB</CountryName>
 *   <Role cls="U">Source</Role>
 * </UsingCountries>
 *

 *

 * @author Key Bridge LLC <developer@keybridge.ch>
 * @version 3.1.0, 03/30/2015
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UsingCountries", propOrder = {
  "countryName",
  "role"
})
public class UsingCountries {

  /**
   * US:CountryName - Country Name (Required)
   *

   * The designator for a specific country associated with the emitter that
   * transmits the subject Notation/Signal. Emitters commonly have more than one
   * user country associated with them.
   *

   * Format is L:CAO
   *

   * @since 3.1.0
   */
  @XmlElement(name = "CountryName", required = true)
  private TString countryName;
  /**
   * US:Role - Country Role (Optional)
   *

   * The role of the country associated with the emitter that transmits the
   * subject Notation/Signal.
   *

   * Format is L:US2
   *

   * @since 3.1.0
   */
  @XmlElement(name = "Role", required = false)
  private TString role;

  /**
   * Get the designator for a specific country associated with the emitter that
   * transmits the subject Notation/Signal. Emitters commonly have more than one
   * user country associated with them..
   *

   * @return the CountryName value in a {@link TString} data type
   * @since 3.1.0
   */
  public TString getCountryName() {
    return countryName;
  }

  /**
   * Set the designator for a specific country associated with the emitter that
   * transmits the subject Notation/Signal. Emitters commonly have more than one
   * user country associated with them..
   *

   * @param value the CountryName value in a {@link TString} data type
   * @since 3.1.0
   */
  public void setCountryName(TString value) {
    this.countryName = value;
  }

  /**
   * Determine if the CountryName is configured.
   *

   * If configured this method also inspects the {@link TString} wrapped value.
   *

   * @return TRUE if the field is set, FALSE if the field is null
   */
  public boolean isSetCountryName() {
    return (this.countryName != null ? this.countryName.isSetValue() : false);
  }

  /**
   * Get the role of the country associated with the emitter that transmits the
   * subject Notation/Signal..
   *

   * @return the Role value in a {@link TString} data type
   * @since 3.1.0
   */
  public TString getRole() {
    return role;
  }

  /**
   * Set the role of the country associated with the emitter that transmits the
   * subject Notation/Signal..
   *

   * @param value the Role value in a {@link TString} data type
   * @since 3.1.0
   */
  public void setRole(TString value) {
    this.role = value;
  }

  /**
   * Determine if the Role is configured.
   *

   * If configured this method also inspects the {@link TString} wrapped value.
   *

   * @return TRUE if the field is set, FALSE if the field is null
   */
  public boolean isSetRole() {
    return (this.role != null ? this.role.isSetValue() : false);
  }

  /**
   * Set the designator for a specific country associated with the emitter that
   * transmits the subject Notation/Signal. Emitters commonly have more than one
   * user country associated with them.
   *

   * @param value An instances of type {@link ListCAO}.
   * @return The current UsingCountries object instance.
   * @since 3.1.0
   */
  public UsingCountries withCountryName(ListCAO value) {
    setCountryName(new TString(value.value()));
    return this;
  }

  /**
   * Set the role of the country associated with the emitter that transmits the
   * subject Notation/Signal.
   *

   * @param value An instances of type {@link ListUS2}.
   * @return The current UsingCountries object instance.
   * @since 3.1.0
   */
  public UsingCountries withRole(ListUS2 value) {
    setRole(new TString(value.value()));
    return this;
  }

  /**
   * Get a string representation of this UsingCountries instance configuration.
   *

   * @return The current object instance configuration as a non-null String
   */
  @Override
  public String toString() {
    return "\n  UsingCountries {"
           + (countryName != null ? " countryName [" + countryName + "]" : "")
           + (role != null ? " role [" + role + "]" : "")
           + "}";
  }

  /**
   * Determine if the required fields in this SSRF data type instance are set.
   *

   * {@link UsingCountries} requires {@link TString CountryName}.
   *

   * Note that this method only checks for the presence of required information;
   * this method does not validate the information format.
   *

   * @return TRUE if required fields are set, otherwise FALSE
   */
  public boolean isSet() {
    return isSetCountryName();
  }

}


text:
package org.maera.plugin.util;

/**
 * String utility methods designed for memory / cpu efficiency
 */
public class EfficientStringUtils {
    /**
     * Test to see if a given string ends with some suffixes. Avoids the cost
     * of concatenating the suffixes together
     *
     * @param src      the source string to be tested
     * @param suffixes the set of suffixes
     * @return true if src ends with the suffixes concatenated together
     */
    public static boolean endsWith(final String src, final String... suffixes) {
        int pos = src.length();

        for (int i = suffixes.length - 1; i >= 0; i--) {
            final String suffix = suffixes[i];
            pos -= suffix.length();
            if (!src.startsWith(suffix, pos)) {
                return false;
            }
        }
        return true;
    }
}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :get_email
  if ENV["RAILS_ENV"] == "production"
    before_filter :ensure_domain
  end

  APP_DOMAIN = 'www.defriendalize.com'

  def ensure_domain
    if request.env['HTTP_HOST'] != APP_DOMAIN
      # HTTP 301 is a "permanent" redirect
      redirect_to "http://#{APP_DOMAIN}", :status => 301
    end
  end

  def get_email
    if session[:user_id]
      @user = User.find(session[:user_id], :select => "email, name, uid, id")
    end
  end

  def destroy_job
    @job = Delayed_Job.find(params[:id])
    @job.destroy

    respond_to do |format|
      format.html { redirect_to(users_path) }
      format.xml  { head :ok }
    end
  end

end


text:
module AccessingClassHierarchyProtocol

  module Protocol

    def all_subclasses
      ObjectSpace.each_object(Module).select { |klass| klass < self }
    end

    def all_concrete_subclasses
      all_subclasses.select &:is_concrete?
    end

    def is_concrete?
      all_subclasses.empty?
    end

  end

end


text:
\chapter{Operators}

\section{String Concatenation}

\section{Arithmetic}

\section{Boolean Algebra}

\section{Comparisons}


text:
Attentive local feature descriptor trained on photographs of landmarks.

<!-- task: image-others -->
<!-- asset-path: legacy -->
<!-- network-architecture: delf -->
<!-- fine-tunable: false -->
<!-- format: hub -->
<!-- colab: https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf_hub_delf_module.ipynb -->

## Overview

The DELF module takes an image as input and will describe noteworthy points
with vectors. The points and vectors can be used for large-scale image
retrieval, or for matching two images of the same landmark to obtain local
correspondences.

For more information about DELF, e.g. its architecture and applications, please
see the paper [1] and the [DELF project on GitHub]
(https://github.com/tensorflow/models/tree/master/research/delf).

#### Example use
```python
# Prepare an image tensor.
image = tf.image.decode_jpeg('my_image.jpg', channels=3)
image = tf.image.convert_image_dtype(image, tf.float32)

# Instantiate the DELF module.
delf_module = hub.Module("https://tfhub.dev/google/delf/1")

delf_inputs = {
  # An image tensor with dtype float32 and shape [height, width, 3], where
  # height and width are positive integers:
  'image': image,
  # Scaling factors for building the image pyramid as described in the paper:
  'image_scales': [0.25, 0.3536, 0.5, 0.7071, 1.0, 1.4142, 2.0],
  # Image features whose attention score exceeds this threshold will be
  # returned:
  'score_threshold': 100.0,
  # The maximum number of features that should be returned:
  'max_feature_num': 1000,
}

# Apply the DELF module to the inputs to get the outputs.
delf_outputs = delf_module(delf_inputs, as_dict=True)

# delf_outputs is a dictionary of named tensors:
# * delf_outputs['locations']: a Tensor with dtype float32 and shape [None, 2],
#   where each entry is a coordinate (vertical-offset, horizontal-offset) in
#   pixels from the top-left corner of the image.
# * delf_outputs['descriptors']: a Tensor with dtype float32 and shape
#   [None, 40], where delf_outputs['descriptors'][i] is a 40-dimensional
#   descriptor for the image at location delf_outputs['locations'][i].
```

#### Training
The feature extraction and attention weights were trained on the "full" and
"clean" subsets of the [data]
(http://download.europe.naverlabs.com/Computer-Vision-CodeandModels/annotations_landmarks.zip)
as introduced in the paper [2].

#### References
[1] Hyeonwoo Noh, Andre Araujo, Jack Sim, Tobias Weyand, Bohyung Han.
[Large-Scale Image Retrieval with Attentive Deep Local Features](https://arxiv.org/abs/1612.06321).
Proc. ICCV'17.

[2] Albert Gordo, Jon Almazan, Jerome Revaud, Diane Larlus.
[Deep Image Retrieval: Learning global representations for image search](https://arxiv.org/abs/1604.01325).
Proc. ECCV'16.


text:
summary: Ruby Together is now accepting proposals for open source project funding from any Ruby developer.
---

### Announcing open project proposals

This update doesn't fit exactly into our regular monthly news cycle, but we are excited to announce [project proposals](/projects).

Ruby Together is now accepting proposals for funded work on Ruby open source projects. Projects are expected to take between 20 and 200 hours, over three months. Proposals are now permanently open, and new projects will be selected for funding once per quarter. Selected projects and progress on those projects will be included in our [regular monthly updates](https://rubytogether.org/news/).

You don't need to have prior open source development experience to propose a project, and you can live anywhere in the world. The project selection committee will choose which projects to fund based on our existing budget, and Ruby Together will fund development work on chosen projects for three months.

Applications are open now. [Apply today](/projects)!


text:
pre.pure-highlightjs {
    background-color: transparent;!important;
    border: none;
    padding: 0;
}


text:
<ion-view view-title="Login">
    <ion-content padding="true" class="has-header">
        <form ng-submit="login()">

                    Username
                    <input type="text" ng-model="loginData.Username">

                    Password
                    <input type="password" ng-model="loginData.Password">

                    <button class="button button-block button-positive" type="submit">Log in</button>

        </form>
    </ion-content>
</ion-view>


text:
package com.intellij.spring.model.converters;

import javax.annotation.Nonnull;

import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.util.xml.GenericDomValue;

import javax.annotation.Nullable;

/**
 * @author Dmitry Avdeev
 */
public abstract class CreateElementQuickFixProvider<T>  {

  private final String myFamilyName;

  public CreateElementQuickFixProvider(String familyName) {

    myFamilyName = familyName;
  }

  public LocalQuickFix[] getQuickFixes(final GenericDomValue<T> value) {
    final LocalQuickFix fix = getQuickFix(value);
    return fix == null ? LocalQuickFix.EMPTY_ARRAY : new LocalQuickFix[] { fix };
  }

  @Nullable
  public LocalQuickFix getQuickFix(final GenericDomValue<T> value) {

    final String elementName = getElementName(value);
    if (!isAvailable(elementName, value)) {
      return null;
    }
    final GenericDomValue<T> copy = value.createStableCopy();

    return new LocalQuickFix() {

      @Nonnull
      public String getName() {
        return getFixName(elementName);
      }

      @Nonnull
      public String getFamilyName() {
        return myFamilyName;
      }

      public void applyFix(@Nonnull final Project project, @Nonnull final ProblemDescriptor descriptor) {
        apply(elementName, copy);
      }
    };
  }

  protected boolean isAvailable(String elementName, GenericDomValue<T> value) {
    return elementName != null && elementName.trim().length() > 0;
  }

  protected abstract void apply(String elementName, GenericDomValue<T> value);

  @Nonnull
  protected abstract String getFixName(String elementName);

  @Nullable
  protected String getElementName(@Nonnull final GenericDomValue<T> value) {
    return value.getStringValue();
  }
}


text:
char *template =
	"// AUTO-GENERATED by autogen.sh; DO NOT EDIT\n\n"
	"package runtime\n"
	"const defaultGoroot = `%s`\n"
	"const theVersion = \"%s\"\n";

void
main(void)
{
	print(template, getgoroot(), getgoversion());
	exits(0);
}


text:
class DockerMachineDriverVultr < Formula
  desc "Docker Machine driver plugin for Vultr Cloud"
  homepage "https://github.com/janeczku/docker-machine-vultr"
  url "https://github.com/janeczku/docker-machine-vultr/archive/v1.4.0.tar.gz"
  sha256 "00fb922126118a7b3e405b888f581fac798a3ebfd175d7f48a1f26d3e115878e"

  head "https://github.com/janeczku/docker-machine-vultr.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "391f3c42b495f904e4ee2ae48fe6075fe8198b6041c547a16f24c60bebfbabdb" => :sierra
    sha256 "4754852f855f0c6e0c188cc23614bc8b83e5da4398de211b1124775095b80aa3" => :el_capitan
    sha256 "af713bea18525c72510362c0765bcab4131badd9baa49bbad6628432016d92dd" => :yosemite
  end

  depends_on "go" => :build
  depends_on "godep" => :build
  depends_on "docker-machine" => :recommended

  def install
    ENV["GOPATH"] = buildpath
    (buildpath/"src/github.com/janeczku/docker-machine-vultr").install buildpath.children

    cd "src/github.com/janeczku/docker-machine-vultr" do
      system "make"
      bin.install "build/docker-machine-driver-vultr-v#{version}" => "docker-machine-driver-vultr"
    end
  end

  test do
    assert_match "--vultr-api-endpoint",
      shell_output("#{Formula["docker-machine"].bin}/docker-machine create --driver vultr -h")
  end
end


text:
/* Simple AJAX Code-Kit (SACK) */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */

function sack(file){
	this.AjaxFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n";
	this.requestFile = file;
	this.method = "POST";
	this.URLString = "";
	this.encodeURIString = true;
	this.execute = false;

	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err) {
				this.xmlhttp = null;
			}
		}
		if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
			this.xmlhttp = new XMLHttpRequest();
		if (!this.xmlhttp){
			this.failed = true;
		}
	};

	this.setVar = function(name, value){
		if (this.URLString.length < 3){
			this.URLString = name + "=" + value;
		} else {
			this.URLString += "&" + name + "=" + value;
		}
	}

	this.encVar = function(name, value){
		var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return varString;
	}

	this.encodeURLString = function(string){
		varArray = string.split('&');
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1){
				urlVars[0] = urlVars[0].substring(4);
			}
			varArray[i] = this.encVar(urlVars[0],urlVars[1]);
		}
	return varArray.join('&');
	}

	this.runResponse = function(){
		eval(this.response);
	}

	this.runAJAX = function(urlstring){
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert){
			alert(this.AjaxFailedAlert);
		} else {
			if (urlstring){
				if (this.URLString.length){
					this.URLString = this.URLString + "&" + urlstring;
				} else {
					this.URLString = urlstring;
				}
			}
			if (this.encodeURIString){
				var timeval = new Date().getTime();
				this.URLString = this.encodeURLString(this.URLString);
				this.setVar("rndval", timeval);
			}
			if (this.element) { this.elementObj = document.getElementById(this.element); }
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					var totalurlstring = this.requestFile + "?" + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
				}
				if (this.method == "POST"){
  					try {
						this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
					} catch (e) {}
				}

				this.xmlhttp.send(this.URLString);
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState){
						case 1:
							self.onLoading();
						break;
						case 2:
							self.onLoaded();
						break;
						case 3:
							self.onInteractive();
						break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							self.onCompletion();
							if(self.execute){ self.runResponse(); }
							if (self.elementObj) {
								var elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							self.URLString = "";
						break;
					}
				};
			}
		}
	};
this.createAJAX();
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef DEVICE_BLUETOOTH_TEST_MOCK_BLUETOOTH_ADAPTER_H_
#define DEVICE_BLUETOOTH_TEST_MOCK_BLUETOOTH_ADAPTER_H_

#include <memory>
#include <string>
#include <vector>

#include "base/callback.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_discovery_session.h"
#include "device/bluetooth/test/mock_bluetooth_device.h"
#include "testing/gmock/include/gmock/gmock.h"

#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
#include "device/bluetooth/bluetooth_low_energy_scan_filter.h"
#endif  // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)

namespace device {

class MockBluetoothAdapter : public BluetoothAdapter {
 public:
  class Observer : public BluetoothAdapter::Observer {
   public:
    Observer(scoped_refptr<BluetoothAdapter> adapter);

    Observer(const Observer&) = delete;
    Observer& operator=(const Observer&) = delete;

    ~Observer() override;

    MOCK_METHOD2(AdapterPresentChanged, void(BluetoothAdapter*, bool));
    MOCK_METHOD2(AdapterPoweredChanged, void(BluetoothAdapter*, bool));
    MOCK_METHOD2(AdapterDiscoveringChanged, void(BluetoothAdapter*, bool));
    MOCK_METHOD2(DeviceAdded, void(BluetoothAdapter*, BluetoothDevice*));
    MOCK_METHOD2(DeviceChanged, void(BluetoothAdapter*, BluetoothDevice*));
    MOCK_METHOD2(DeviceRemoved, void(BluetoothAdapter*, BluetoothDevice*));
    MOCK_METHOD3(GattCharacteristicValueChanged,
                 void(BluetoothAdapter*,
                      BluetoothRemoteGattCharacteristic*,
                      const std::vector<uint8_t>&));

   private:
    const scoped_refptr<BluetoothAdapter> adapter_;
  };

  MockBluetoothAdapter();

  bool IsInitialized() const override { return true; }

  void Initialize(base::OnceClosure callback) override;
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
  void Shutdown() override;
#endif
  MOCK_METHOD1(AddObserver, void(BluetoothAdapter::Observer*));
  MOCK_METHOD1(RemoveObserver, void(BluetoothAdapter::Observer*));
  MOCK_CONST_METHOD0(GetAddress, std::string());
  MOCK_CONST_METHOD0(GetName, std::string());
  MOCK_METHOD3(SetName,
               void(const std::string& name,
                    base::OnceClosure callback,
                    ErrorCallback error_callback));
  MOCK_CONST_METHOD0(IsPresent, bool());
  MOCK_CONST_METHOD0(IsPowered, bool());
  MOCK_CONST_METHOD0(CanPower, bool());
  MOCK_METHOD3(SetPowered,
               void(bool powered,
                    base::OnceClosure callback,
                    ErrorCallback error_callback));
  MOCK_CONST_METHOD0(IsDiscoverable, bool());
  MOCK_METHOD3(SetDiscoverable,
               void(bool discoverable,
                    base::OnceClosure callback,
                    ErrorCallback error_callback));
  MOCK_CONST_METHOD0(IsDiscovering, bool());
  MOCK_METHOD2(
      StartScanWithFilter_,
      void(const BluetoothDiscoveryFilter*,
           base::OnceCallback<void(/*is_error=*/bool,
                                   UMABluetoothDiscoverySessionOutcome)>&
               callback));
  MOCK_METHOD2(
      UpdateFilter_,
      void(const BluetoothDiscoveryFilter*,
           base::OnceCallback<void(/*is_error=*/bool,
                                   UMABluetoothDiscoverySessionOutcome)>&
               callback));
  MOCK_METHOD1(StopScan, void(DiscoverySessionResultCallback callback));
  MOCK_METHOD3(SetDiscoveryFilterRaw,
               void(const BluetoothDiscoveryFilter*,
                    const base::RepeatingClosure& callback,
                    DiscoverySessionErrorCallback& error_callback));
  MOCK_CONST_METHOD0(GetDevices, BluetoothAdapter::ConstDeviceList());
  MOCK_METHOD1(GetDevice, BluetoothDevice*(const std::string& address));
  MOCK_CONST_METHOD1(GetDevice,
                     const BluetoothDevice*(const std::string& address));
  MOCK_CONST_METHOD0(GetUUIDs, UUIDList());
  MOCK_METHOD2(AddPairingDelegate,
               void(BluetoothDevice::PairingDelegate* pairing_delegate,
                    enum PairingDelegatePriority priority));
  MOCK_METHOD1(RemovePairingDelegate,
               void(BluetoothDevice::PairingDelegate* pairing_delegate));
  MOCK_METHOD0(DefaultPairingDelegate, BluetoothDevice::PairingDelegate*());
  MOCK_METHOD4(CreateRfcommService,
               void(const BluetoothUUID& uuid,
                    const ServiceOptions& options,
                    CreateServiceCallback callback,
                    CreateServiceErrorCallback error_callback));
  MOCK_METHOD4(CreateL2capService,
               void(const BluetoothUUID& uuid,
                    const ServiceOptions& options,
                    CreateServiceCallback callback,
                    CreateServiceErrorCallback error_callback));
  MOCK_CONST_METHOD1(GetGattService,
                     BluetoothLocalGattService*(const std::string& identifier));
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
  MOCK_METHOD3(SetServiceAllowList,
               void(const UUIDList& uuids,
                    base::OnceClosure callback,
                    ErrorCallback error_callback));
  MOCK_METHOD0(GetLowEnergyScanSessionHardwareOffloadingStatus,
               LowEnergyScanSessionHardwareOffloadingStatus());
  MOCK_METHOD2(
      StartLowEnergyScanSession,
      std::unique_ptr<BluetoothLowEnergyScanSession>(
          std::unique_ptr<BluetoothLowEnergyScanFilter> filter,
          base::WeakPtr<BluetoothLowEnergyScanSession::Delegate> delegate));
#endif  // BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
  MOCK_METHOD4(
      ConnectDevice,
      void(const std::string& address,
           const absl::optional<BluetoothDevice::AddressType>& address_type,
           ConnectDeviceCallback callback,
           ErrorCallback error_callback));

#endif

  // BluetoothAdapter is supposed to manage the lifetime of BluetoothDevices.
  // This method takes ownership of the MockBluetoothDevice. This is only for
  // convenience as far testing is concerned and it's possible to write test
  // cases without using these functions.
  void AddMockDevice(std::unique_ptr<MockBluetoothDevice> mock_device);
  std::unique_ptr<MockBluetoothDevice> RemoveMockDevice(
      const std::string& address);
  BluetoothAdapter::ConstDeviceList GetConstMockDevices();
  BluetoothAdapter::DeviceList GetMockDevices();

  // The observers are maintained by the default behavior of AddObserver() and
  // RemoveObserver(). Test fakes can use this function to notify the observers
  // about events.
  base::ObserverList<device::BluetoothAdapter::Observer>::Unchecked&
  GetObservers() {
    return observers_;
  }

 protected:
  base::WeakPtr<BluetoothAdapter> GetWeakPtr() override;
  bool SetPoweredImpl(bool powered) override;
  void StartScanWithFilter(
      std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
      DiscoverySessionResultCallback callback) override;
  void UpdateFilter(std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
                    DiscoverySessionResultCallback callback) override;
  void RegisterAdvertisement(
      std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data,
      CreateAdvertisementCallback callback,
      AdvertisementErrorCallback error_callback) override;
#if defined(OS_CHROMEOS) || defined(OS_LINUX)
  void SetAdvertisingInterval(
      const base::TimeDelta& min,
      const base::TimeDelta& max,
      base::OnceClosure callback,
      AdvertisementErrorCallback error_callback) override;
  void ResetAdvertising(base::OnceClosure callback,
                        AdvertisementErrorCallback error_callback) override;
#endif
  ~MockBluetoothAdapter() override;

  MOCK_METHOD1(RemovePairingDelegateInternal,
               void(BluetoothDevice::PairingDelegate* pairing_delegate));

  std::vector<std::unique_ptr<MockBluetoothDevice>> mock_devices_;

  // This must be the last field in the class so that weak pointers are
  // invalidated first.
  base::WeakPtrFactory<MockBluetoothAdapter> weak_ptr_factory_{this};
};

}  // namespace device

#endif  // DEVICE_BLUETOOTH_TEST_MOCK_BLUETOOTH_ADAPTER_H_


text:
/**
 * OdenOSConfigImplTest.java
 * (C) 2013,2015, Hitachi, Ltd.
 */
package org.o3project.mlo.server.impl.rpc.service;

import static org.junit.Assert.*;

import java.io.File;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.o3project.mlo.server.impl.logic.ConfigProviderImpl;
import org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl;
import org.o3project.mlo.server.logic.ConfigProvider;

/**
 * OdenOSConfigImplTest
 *
 */
public class OdenOSConfigImplTest {

	private static final String DATA_PATH = "src/test/resources/org/o3project/mlo/server/rpc/service/data";
	private static final String DATA_FILE_001 = "odenos.config.001.properties";
	private static final String DATA_FILE_002 = "odenos.config.002.properties";

	private ConfigProvider configProvider;
	private OdenOSConfigImpl obj;

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
		setupDefaultObj(DATA_FILE_001);
	}

	/**
	 * @throws java.lang.Exception
	 */
	@After
	public void tearDown() throws Exception {
		configProvider = null;
		obj = null;
	}

	private void setupDefaultObj(String fileName) {
		File propFile = new File(DATA_PATH, fileName);
		configProvider = new ConfigProviderImpl("default.mlo-srv.properties", propFile.getAbsolutePath());
		obj = new OdenOSConfigImpl();
		obj.setConfigProvider(configProvider);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#setConfigProvider(org.o3project.mlo.server.logic.ConfigProvider)}.
	 */
	@Test
	public void testSetConfigProvider() {
		try {
			obj.setConfigProvider(configProvider);
			assertTrue(true);
		} catch (Throwable th) {
			fail();
		}
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getRemoteSystemManagerId()}.
	 */
	@Test
	public void testGetRemoteSystemManagerId() {
		String actual = obj.getRemoteSystemManagerId();
		String expected = "myRemoteSystemManager";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getRemoteSystemManagerHost()}.
	 */
	@Test
	public void testGetRemoteSystemManagerHost() {
		String actual = obj.getRemoteSystemManagerHost();
		String expected = "123.456.789.1";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getRemoteSystemManagerPort()}.
	 */
	@Test
	public void testGetRemoteSystemManagerPort() {
		Integer actual = obj.getRemoteSystemManagerPort();
		Integer expected = 9991;
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getComponentManagerId()}.
	 */
	@Test
	public void testGetComponentManagerId() {
		String actual = obj.getComponentManagerId();
		String expected = "myComponentManager";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getComponentManagerHost()}.
	 */
	@Test
	public void testGetComponentManagerHost() {
		String actual = obj.getComponentManagerHost();
		String expected = "123.456.789.2";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getComponentManagerPort()}.
	 */
	@Test
	public void testGetComponentManagerPort() {
		Integer actual = obj.getComponentManagerPort();
		Integer expected = 9992;
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getComponentManagerBaseUri()}.
	 */
	@Test
	public void testGetComponentManagerBaseUri_notSpecified() {
		String actual = obj.getComponentManagerBaseUri();
		String expected = "odenos://123.456.789.2:9992/myComponentManager";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getComponentManagerBaseUri()}.
	 */
	@Test
	public void testGetComponentManagerBaseUri_specified() {
		setupDefaultObj(DATA_FILE_002);
		String actual = obj.getComponentManagerBaseUri();
		String expected = "odenos:/myHost:9994/thatComponentManager";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getLauncherHost()}.
	 */
	@Test
	public void testGetLauncherHost() {
		String actual = obj.getLauncherHost();
		String expected = "123.456.789.3";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getLauncherPort()}.
	 */
	@Test
	public void testGetLauncherPort() {
		Integer actual = obj.getLauncherPort();
		Integer expected = 9993;
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getNetworkComponentIdL2()}.
	 */
	@Test
	public void testGetNetworkComponentIdL2() {
		String actual = obj.getNetworkComponentIdL2();
		String expected = "myNetworkComponentL2";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getNetworkComponentIdL012()}.
	 */
	@Test
	public void testGetNetworkComponentIdL012() {
		String actual = obj.getNetworkComponentIdL012();
		String expected = "myNetworkComponentL012";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getNetworkComponentPath()}.
	 */
	@Test
	public void testGetNetworkComponentPath() {
		String actual = obj.getNetworkComponentPath();
		String expected = "components/myNetworkComponentL2";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getPTDriverId()}.
	 */
	@Test
	public void testGetPTDriverId() {
		String actual = obj.getPTDriverId();
		String expected = "myPacketTransportDriver";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getPTDriverPath()}.
	 */
	@Test
	public void testGetPTDriverPath() {
		String actual = obj.getPTDriverPath();
		String expected = "components/myPacketTransportDriver";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getConnectionId()}.
	 */
	@Test
	public void testGetConnectionId() {
		String actual = obj.getConnectionId();
		String expected = "myConnection";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getConnectionType()}.
	 */
	@Test
	public void testGetConnectionType() {
		String actual = obj.getConnectionType();
		String expected = "myType";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getConnectionState()}.
	 */
	@Test
	public void testGetConnectionState() {
		String actual = obj.getConnectionState();
		String expected = "myState";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link org.o3project.mlo.server.impl.rpc.service.OdenOSConfigImpl#getConnectionPath()}.
	 */
	@Test
	public void testGetConnectionPath() {
		String actual = obj.getConnectionPath();
		String expected = "connections/myConnection";
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link OdenOSConfigImpl#isAvailableCreateL2()}.
	 */
	@Test
	public void testIsAvailableCreateL2() {
		Boolean actual = obj.isAvailableCreateL2();
		Boolean expected = Boolean.FALSE;
		assertEquals(expected, actual);
	}

	/**
	 * Test method for {@link OdenOSConfigImpl#isAvailableReqLinkEstablishedCompletion()}.
	 */
	@Test
	public void testIsAvailableReqLinkEstablishedCompletion() {
		Boolean actual = obj.isAvailableReqLinkEstablishedCompletion();
		Boolean expected = Boolean.TRUE;
		assertEquals(expected, actual);
	}

}


text:
Aplikacja do automatycznego wyszukiwania przedmiotów w serwisie Allegro (wykorzystująca WebAPI) w paru prostych krokach:
1. Dodaj nowy cel
2. Określ dokładne kryteria wyszukiwania
3. Poczekaj na notyfikację o nowym przedmiocie w serwisie Allegro, który spełnia twoje kryteria

Allegro WebAPI http://allegro.pl/webapi

Zadaniem aplikacji jest znalezienie przedmiotu z okrelonymi kryteriami takimi jak:
- cena
- kategoria
- oferta Kup Teraz/Licytacja
- dynamiczne filtry dla danej kategorii

Wykorzystywane biblioteki:
- com.squareup.picasso:picasso:2.5.2
- com.alexgilleran:icesoap:1.1.1
- io.realm:realm-gradle-plugin:3.0.0


text:
package org.jerlang.stdlib.erl_internal;

import org.jerlang.erts.erlang.Error;
import org.jerlang.type.Atom;
import org.jerlang.type.Boolean;
import org.jerlang.type.Integer;
import org.jerlang.type.List;
import org.jerlang.type.Term;

public class ErlInternalCompOp {

    private ErlInternalCompOp() {
    }

    public static Term dispatch(List params) {
        switch (params.length()) {
        case 2:
            Atom opName = params.head().toAtom();
            params = params.tail();
            Integer arity = params.head().toInteger();
            return comp_op_2(opName, arity);
        default:
            throw Error.badarg;
        }
    }

    /**
     * Returns `true` if `opName/arity` is a comparison operator, otherwise `false`.
     *
     * http://www.erlang.org/doc/man/erl_internal.html#comp_op-2
     */
    public static Term comp_op_2(Atom opName, Integer arity) {
        switch (opName.toString() + "/" + arity) {
        case "==/2":
        case "/=/2":
        case "=</2":
        case "</2":
        case ">=/2":
        case ">/2":
        case "=:=/2":
        case "=/=/2":
            return Boolean.am_true;
        default:
            return Boolean.am_false;
        }
    }

}


text:
package sdtemplate

import (
	"text/template"
	"io"
	"path/filepath"
	"regexp"
)

type Template struct {
	template *template.Template;
	Spec     *TemplateSpec;
	FileName string;
}

// Create new config and populate it from environment
func NewTemplate(filePath string) (*Template, error) {

	// parse spec
	spec, err := ParseSpecFile(filePath)
	if err != nil {
		return nil, err
	}

	// get base filename as reference for the template
	fileName := filepath.Base(filePath)

	// create template
	goTpl := template.New(fileName)
	goTpl.Funcs(TemplateFuncMap)
	goTpl.Parse(spec.Template)

	// assemble object
	tpl := Template{
		Spec:     spec,
		template: goTpl,
		FileName: fileName,
	}

	return &tpl, err
}

func (tpl *Template) Execute(wr io.Writer, data interface{}) error {
	return tpl.template.Execute(wr, data)
}

// remove comments from templates
// TODO make use of this again
func (tpl *Template) cleanTemplateOutput(contents string) (string) {

	regexCleanComments, err := regexp.Compile("(?m:^\\s*#.*$\n)")
	if err != nil {
		panic(err)
	}

	/*
	regexCleanEmptyLines, err := regexp.Compile("(?m:^\\s*$\\n)")
	if err != nil {
		panic(err)
	}
	*/

	return regexCleanComments.ReplaceAllString(contents, "")
	// return regexCleanEmptyLines.ReplaceAllString(regexCleanComments.ReplaceAllString(contents, ""), "\n")
}


text:
package client

const (
	HEALTHCHECK_STATE_TYPE = "healthcheckState"
)

type HealthcheckState struct {
	Resource

	HealthState string `json:"healthState,omitempty" yaml:"health_state,omitempty"`

	HostId string `json:"hostId,omitempty" yaml:"host_id,omitempty"`
}

type HealthcheckStateCollection struct {
	Collection
	Data   []HealthcheckState `json:"data,omitempty"`
	client *HealthcheckStateClient
}

type HealthcheckStateClient struct {
	rancherClient *RancherClient
}

type HealthcheckStateOperations interface {
	List(opts *ListOpts) (*HealthcheckStateCollection, error)
	Create(opts *HealthcheckState) (*HealthcheckState, error)
	Update(existing *HealthcheckState, updates interface{}) (*HealthcheckState, error)
	ById(id string) (*HealthcheckState, error)
	Delete(container *HealthcheckState) error
}

func newHealthcheckStateClient(rancherClient *RancherClient) *HealthcheckStateClient {
	return &HealthcheckStateClient{
		rancherClient: rancherClient,
	}
}

func (c *HealthcheckStateClient) Create(container *HealthcheckState) (*HealthcheckState, error) {
	resp := &HealthcheckState{}
	err := c.rancherClient.doCreate(HEALTHCHECK_STATE_TYPE, container, resp)
	return resp, err
}

func (c *HealthcheckStateClient) Update(existing *HealthcheckState, updates interface{}) (*HealthcheckState, error) {
	resp := &HealthcheckState{}
	err := c.rancherClient.doUpdate(HEALTHCHECK_STATE_TYPE, &existing.Resource, updates, resp)
	return resp, err
}

func (c *HealthcheckStateClient) List(opts *ListOpts) (*HealthcheckStateCollection, error) {
	resp := &HealthcheckStateCollection{}
	err := c.rancherClient.doList(HEALTHCHECK_STATE_TYPE, opts, resp)
	resp.client = c
	return resp, err
}

func (cc *HealthcheckStateCollection) Next() (*HealthcheckStateCollection, error) {
	if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
		resp := &HealthcheckStateCollection{}
		err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
		resp.client = cc.client
		return resp, err
	}
	return nil, nil
}

func (c *HealthcheckStateClient) ById(id string) (*HealthcheckState, error) {
	resp := &HealthcheckState{}
	err := c.rancherClient.doById(HEALTHCHECK_STATE_TYPE, id, resp)
	if apiError, ok := err.(*ApiError); ok {
		if apiError.StatusCode == 404 {
			return nil, nil
		}
	}
	return resp, err
}

func (c *HealthcheckStateClient) Delete(container *HealthcheckState) error {
	return c.rancherClient.doResourceDelete(HEALTHCHECK_STATE_TYPE, &container.Resource)
}


text:
package com.intellij.codeInsight.intention.impl;

import com.intellij.codeInspection.util.OptionalRefactoringUtil;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.util.LambdaRefactoringUtil;
import com.intellij.refactoring.util.RefactoringUtil;
import com.siyeh.ig.psiutils.ExpressionUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Objects;

public class StreamRefactoringUtil {
  static boolean isRefactoringCandidate(PsiExpression expression, boolean requireExpressionLambda) {
    if(expression instanceof PsiLambdaExpression) {
      PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)expression;
      return lambdaExpression.getParameterList().getParametersCount() == 1 &&
             (!requireExpressionLambda || LambdaUtil.extractSingleExpressionFromBody(lambdaExpression.getBody()) != null);
    } else if(expression instanceof PsiMethodReferenceExpression) {
      PsiMethodReferenceExpression methodRef = (PsiMethodReferenceExpression)expression;
      return methodRef.resolve() != null && LambdaRefactoringUtil.canConvertToLambdaWithoutSideEffects(methodRef);
    }
    return false;
  }

  @NotNull
  public static String generateMapOperation(PsiVariable variable, @Nullable PsiType outType, PsiElement mapper) {
    String shortcutMappingMethod = getShortcutMappingMethod(variable, outType, mapper);
    if (shortcutMappingMethod != null) return shortcutMappingMethod.isEmpty() ? "" : "." + shortcutMappingMethod + "()";
    PsiType inType = variable.getType();
    String operationName = getMapOperationName(inType, outType);
    if(outType != null && mapper instanceof PsiArrayInitializerExpression) {
      mapper = RefactoringUtil.convertInitializerToNormalExpression((PsiExpression)mapper, outType);
    }
    String typeArgument = mapper instanceof PsiExpression ? OptionalRefactoringUtil.getMapTypeArgument((PsiExpression)mapper, outType) : "";
    return "." + typeArgument + operationName +
           "(" + variable.getName() + "->" + mapper.getText() + ")";
  }

  /**
   * Returns the shortcut mapping method name
   *
   * @param variable mapper input variable
   * @param outType  output type of the mapper
   * @param mapper   mapper code
   * @return shortcut mapping name ("boxed", "asLongStream", "asDoubleStream") if applicable, empty string if it's
   * ditto mapping (no mapping is necessary at all) and null if no shortcut is applicable for given mapper
   */
  @Nullable
  public static String getShortcutMappingMethod(PsiVariable variable, @Nullable PsiType outType, PsiElement mapper) {
    if (!(mapper instanceof PsiExpression)) return null;
    PsiExpression expression = PsiUtil.skipParenthesizedExprDown(((PsiExpression)mapper));
    PsiType inType = variable.getType();
    if (expression instanceof PsiTypeCastExpression && inType instanceof PsiPrimitiveType && Objects.equals(expression.getType(), outType)) {
      expression = ((PsiTypeCastExpression)expression).getOperand();
    }
    if (ExpressionUtils.isReferenceTo(expression, variable)) {
      if (!(outType instanceof PsiPrimitiveType)) {
        return inType instanceof PsiPrimitiveType ? "boxed" : "";
      }
      if (outType.equals(inType)) {
        return "";
      }
      if (PsiType.LONG.equals(outType) && PsiType.INT.equals(inType)) {
        return "asLongStream";
      }
      if (PsiType.DOUBLE.equals(outType) && (PsiType.LONG.equals(inType) || PsiType.INT.equals(inType))) {
        return "asDoubleStream";
      }
    }
    return null;
  }

  /**
   * Returns name of the Stream API mapping operation which maps from inType to outType (assuming both types are supported by Stream API)
   *
   * @param inType input stream element type
   * @param outType output stream element type
   * @return a name of the mapping operation like "map" or "mapToLong".
   */
  @NotNull
  public static String getMapOperationName(PsiType inType, @Nullable PsiType outType) {
    if(outType instanceof PsiPrimitiveType) {
      if(!outType.equals(inType)) {
        if(PsiType.INT.equals(outType)) {
          return "mapToInt";
        } else if(PsiType.LONG.equals(outType)) {
          return "mapToLong";
        } else if(PsiType.DOUBLE.equals(outType)) {
          return "mapToDouble";
        }
      }
    } else if(inType instanceof PsiPrimitiveType) {
      return "mapToObj";
    }
    return "map";
  }

  @Nullable
  public static String getFlatMapOperationName(PsiType inType, PsiType outType) {
    if (!(inType instanceof PsiPrimitiveType)) {
      if (PsiType.INT.equals(outType)) {
        return "flatMapToInt";
      }
      else if (PsiType.LONG.equals(outType)) {
        return "flatMapToLong";
      }
      else if (PsiType.DOUBLE.equals(outType)) {
        return "flatMapToDouble";
      }
    } else if (!inType.equals(outType)) return null;
    return "flatMap";
  }
}


text:
<?php
require "dbConnect.php";

$sql = "select userID, loggedin, player from users;";

$result = mysqli_query($con,$sql);
$response = array();
//if the query's number of rows is greater than 0
if(mysqli_num_rows($result)>0){
//fetch the results of the query and store in row for each row until the loop ends
	foreach($result as $row) {
		$userID = $row['userID'];
		$loggedin = $row['loggedin'];
		$player = $row['player'];
		//if user is logged in and is the active player, change to inactive
		if($loggedin == 1 && $player == 1){
			$sql = "update users set player = 0 where userID ='".$userID."'";
			$result = mysqli_query($con,$sql);
		}
		//if user is logged in and is the inactive player, change to active
		else if($loggedin == 1 && $player == 0){
			$sql = "update users set player = 1 where userID ='".$userID."'";
			$result = mysqli_query($con,$sql);
		}
	}
	//selects the user who is the active player
	$sql = "select userID from users where player = 1";
	$result = mysqli_query($con,$sql);
	if(mysqli_num_rows($result)>0){
		$row = mysqli_fetch_row($result);
		$userID = $row[0];
		$code = "new_turn";
		$message = "".$userID." turn";
		//code is the first object of response array
		array_push($response, array('code' => $code));
		array_push($response, array('message'=>$message));
		// making the array for a JSON object
		echo json_encode($response);
	}
	else{
		$code = "player_failed";
		$message = "Error";
		array_push($response,array('code'=>$code));
		array_push($response,array('message'=>$message));

		//The code and message is turned in a JSON object and outputted
		echo json_encode($response);
	}
}
mysqli_close($con);

?>


text:
---
layout: post
title:  "谈谈DeviceID安全的获取方式"
date:   2016-06-11 00:00:00
categories: iOS
published: true
---

```
/** 获取设备标识符 */
+ (NSString *)deviceId;
```

大部分App都需要获取设备标识符用于统计及区分设备,必要的情况可以锁掉对应的设备。

我们现在常用的取值方式有:UDID、MAC Address、OpenUDID、IDFA、IDFV、IMEI等,不同的取值方式各有利弊,不太明白的自己搜索下,如何让一个值一直保存切升级系统都不变呢?一般使用KeyChain,大概的代码如下:

```
--伪代码
NSString *deviceId = [MFSKeyChain objectForKey:@"deviceId"];
        if (!deviceId.length) {
            deviceId = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceId"];
            if (!deviceId.length) {
                deviceId = [[UIDevice currentDevice] identifierForVendor].UUIDString;
                if (!deviceId.length) {
                    deviceId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
                    if (!deviceId.length) {
                        deviceId = @"备选方案,Token等";
                    }
                }
            }
        }
        if (deviceId.length) {
            [MFSKeyChain setObject:deviceId forKey:keyChain_Key];
            [[NSUserDefaults standardUserDefaults] setObject:deviceId forKey:@"deviceId"];
        }
        return deviceId ?: @"";

```

这样的代码用了很长一段时间都没有问题,但是不知道从什么时候起,不同的设备出现了多个deviceId(至今未查出问题所在),并且不好排查,更新逻辑后至今未发现新的问题。

```
--伪代码(大概是这个样子)
NSString *const kMFSIdentifierCacheDeviceIdKey = @"com.imfong.Device.cacheKey";
NSString *const kMFSIdentifierUserDeviceIdKey = @"com.imfong.deviceId.defaultkey";
NSString *const kMFSIdentifierKeyChainKey = @"com.imfong.deviceId.KeyChain.Key";

+ (NSString *)deviceId
{
    NSString *cacheDeviceId = [cacheManager() objectForKey:kMFSIdentifierCacheDeviceIdKey];
    NSString *userDeviceId = [userDefaults() objectForKey:kMFSIdentifierUserDeviceIdKey];
    //缓存和UserDefaults数据一致,验证通过
    if (cacheDeviceId.length && userDeviceId.length && [cacheDeviceId isEqualToString:userDeviceId]) {
        return cacheDeviceId;
    }
    else {
        NSString *keyChain_Key = kMFSIdentifierKeyChainKey;
        NSString *deviceId = [MFSKeyChain objectForKey:keyChain_Key];
        if (!deviceId.length) {
            deviceId = cacheDeviceId;
            if (!deviceId.length) {
                deviceId = [[UIDevice currentDevice] identifierForVendor].UUIDString;
                if (!deviceId.length) {
                    deviceId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] ?: @"";
                    if (!deviceId.length) {
                        deviceId = @"devicePushToken值";
                    }
                }
            }
        }
        if (deviceId.length) {
            [MFSKeyChain setObject:deviceId forKey:keyChain_Key];
            [cacheManager() setObject:deviceId forKey:kMFSIdentifierCacheDeviceIdKey duration:-9];
            [userDefaults() setObject:deviceId forKey:kMFSIdentifierUserDeviceIdKey];
        }
        return deviceId ?: @"";
    }
}

#pragma mark -
static MFSCacheManager *cacheManager() {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[MFSCacheManager alloc] initWithSuiteName:@"com.imfong.Identifier.Cache"];
    });
    return instance;
}

static NSUserDefaults *userDefaults() {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NSUserDefaults alloc] initWithSuiteName:@"com.imfong.Identifier.userDefaults"];
    });
    return instance;
}
```

将deviceId加密(最好2种加密方式)后保存到本地的2个地方,需要的时候取出来对比,相同证明没有篡改(全部被篡改就证明你的App太不安全了)直接使用,不同则使用KeyChain或者其他的方法获取并保存本地。
这种方式在用户正常使用的情况下,不删除App的系统升级也可以正常保持deviceId的正确,在新系统中只要打开一次,KeyChain就会记录新值,删掉App重新下载也是不会变的,当然,漏洞还会有,并不是完美方案。


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================
// Shuffling.
// ==========================================================================

#ifndef SEQAN_RANDOM_RANDOM_SHUFFLE_H_
#define SEQAN_RANDOM_RANDOM_SHUFFLE_H_

namespace seqan {

// ===========================================================================
// Forwards, Tags.
// ===========================================================================

// ===========================================================================
// Classes
// ===========================================================================

// ===========================================================================
// Metafunctions
// ===========================================================================

// ===========================================================================
// Functions
// ===========================================================================

/*!
 * @fn shuffle
 * @headerfile <seqan/random.h>
 * @brief Shuffle the given container.
 *
 * @signature void shuffle(container, rng);
 *
 * @param[in,out] container The container to shuffle.
 * @param[in,out] rng       The random number generator to use.
 */

template <typename TContainer, typename TRNG>
void shuffle(TContainer & container, TRNG & rng)
{
    SEQAN_CHECKPOINT;
    typedef typename Position<TContainer>::Type TPosition;
    typedef typename Value<TContainer>::Type TValue;

    TValue tmp;
    for (TPosition i = 0, iend = length(container); i < iend; ++i) {
        Pdf<Uniform<TPosition> > uniformDist(i, iend - 1);
        TPosition j = pickRandomNumber(rng, uniformDist);
        // swap
        move(tmp, container[i]);
        move(container[i], container[j]);
        move(container[j], tmp);
    }
}

}  // namespace seqan

#endif  // SEQAN_RANDOM_RANDOM_SHUFFLE_H_


text:
'use strict';

const ListStyles = {
  listContainer: {
    borderTopWidth: 1,
    borderBottomWidth: 1,
    borderColor: '#E6E6E6',
    backgroundColor: '#fff'
  },
  listItem: {
    flexDirection: 'row',
    paddingTop: 12,
    paddingBottom: 12,
    marginLeft: 10,
    paddingRight: 10,
    borderTopWidth: 1,
    borderColor: '#E6E6E6',
  },
  listItemWithoutBorder: {
    flexDirection: 'row',
    paddingTop: 10,
    paddingBottom: 10,
    marginLeft: 10,
    paddingRight: 10,
    borderColor: '#E6E6E6',
  },
  listItemImageWrap: {
    marginRight: 10,
    alignItems: 'center',
  },
  listItemImage: {
    width: 30,
    height: 30,
    borderRadius: 3
  },
  listItemIcon: {
    width: 30,
    height: 30,
    paddingLeft: 2
  },
  listItemContent: {
    flex: 1
  },
  listItemContentTitle: {
    flexDirection: 'row',
  },
  listItemContentDesc: {
    marginTop: 5
  }
};

export default ListStyles;