text:
module Grafeas
  module V1
    # Layer holds metadata specific to a layer of a Docker image.
    # @!attribute [rw] directive
    #   @return [::String]
    #     Required. The recovered Dockerfile directive used to construct this layer.
    #     See https://docs.docker.com/engine/reference/builder/ for more information.
    # @!attribute [rw] arguments
    #   @return [::String]
    #     The recovered arguments to the Dockerfile directive.
    class Layer
      include ::Google::Protobuf::MessageExts
      extend ::Google::Protobuf::MessageExts::ClassMethods
    end

    # A set of properties that uniquely identify a given Docker image.
    # @!attribute [rw] v1_name
    #   @return [::String]
    #     Required. The layer ID of the final layer in the Docker image's v1
    #     representation.
    # @!attribute [rw] v2_blob
    #   @return [::Array<::String>]
    #     Required. The ordered list of v2 blobs that represent a given image.
    # @!attribute [rw] v2_name
    #   @return [::String]
    #     Output only. The name of the image's v2 blobs computed via:
    #       [bottom] := v2_blob[bottom]
    #       [N] := sha256(v2_blob[N] + " " + v2_name[N+1])
    #     Only the name of the final blob is kept.
    class Fingerprint
      include ::Google::Protobuf::MessageExts
      extend ::Google::Protobuf::MessageExts::ClassMethods
    end

    # Basis describes the base image portion (Note) of the DockerImage
    # relationship. Linked occurrences are derived from this or an equivalent image
    # via:
    #   FROM <Basis.resource_url>
    # Or an equivalent reference, e.g., a tag of the resource_url.
    # @!attribute [rw] resource_url
    #   @return [::String]
    #     Required. Immutable. The resource_url for the resource representing the
    #     basis of associated occurrence images.
    # @!attribute [rw] fingerprint
    #   @return [::Grafeas::V1::Fingerprint]
    #     Required. Immutable. The fingerprint of the base image.
    class ImageNote
      include ::Google::Protobuf::MessageExts
      extend ::Google::Protobuf::MessageExts::ClassMethods
    end

    # Details of the derived image portion of the DockerImage relationship. This
    # image would be produced from a Dockerfile with FROM <DockerImage.Basis in
    # attached Note>.
    # @!attribute [rw] fingerprint
    #   @return [::Grafeas::V1::Fingerprint]
    #     Required. The fingerprint of the derived image.
    # @!attribute [rw] distance
    #   @return [::Integer]
    #     Output only. The number of layers by which this image differs from the
    #     associated image basis.
    # @!attribute [rw] layer_info
    #   @return [::Array<::Grafeas::V1::Layer>]
    #     This contains layer-specific metadata, if populated it has length
    #     "distance" and is ordered with [distance] being the layer immediately
    #     following the base image and [1] being the final layer.
    # @!attribute [rw] base_resource_url
    #   @return [::String]
    #     Output only. This contains the base image URL for the derived image
    #     occurrence.
    class ImageOccurrence
      include ::Google::Protobuf::MessageExts
      extend ::Google::Protobuf::MessageExts::ClassMethods
    end
  end
end


text:
#include "qasyncreader.h"
#include "qbasefilter.h"

QT_BEGIN_NAMESPACE

namespace Phonon
{
    namespace DS9
    {
        QAsyncReader::QAsyncReader(QBaseFilter *parent, const QVector<AM_MEDIA_TYPE> &mediaTypes) : QPin(parent, PINDIR_OUTPUT, mediaTypes)
        {
        }

        QAsyncReader::~QAsyncReader()
        {
        }

        STDMETHODIMP QAsyncReader::QueryInterface(REFIID iid, void **out)
        {
            if (!out) {
                return E_POINTER;
            }

            if (iid == IID_IAsyncReader) {
                AddRef();
                *out = static_cast<IAsyncReader*>(this);
                return S_OK;
            }

            return QPin::QueryInterface(iid, out);
        }

        STDMETHODIMP_(ULONG) QAsyncReader::AddRef()
        {
            return QPin::AddRef();
        }

        STDMETHODIMP_(ULONG) QAsyncReader::Release()
        {
            return QPin::Release();
        }

        STDMETHODIMP QAsyncReader::RequestAllocator(IMemAllocator *preferred, ALLOCATOR_PROPERTIES *prop,IMemAllocator **actual)
        {
            ALLOCATOR_PROPERTIES prop2;

            if (prop->cbAlign == 0) {
                prop->cbAlign = 1; //align on 1 char
            }

            if (preferred && preferred->SetProperties(prop, &prop2) == S_OK) {
                preferred->AddRef();
                *actual = preferred;
                return S_OK;
            }

            //we should try to create one memory allocator ourselves here
            return E_FAIL;
        }

        STDMETHODIMP QAsyncReader::Request(IMediaSample *sample,DWORD_PTR user)
        {
            QMutexLocker locker(&m_mutex);
            if (m_flushing) {
                return VFW_E_WRONG_STATE;
            }

            m_requestQueue.enqueue(AsyncRequest(sample, user));
            m_requestWait.wakeOne();
            return S_OK;
        }

        STDMETHODIMP QAsyncReader::WaitForNext(DWORD timeout, IMediaSample **sample, DWORD_PTR *user)
        {
            QMutexLocker locker(&m_mutex);
            if (!sample ||!user) {
                return E_POINTER;
            }

            //msdn says to return immediately if we're flushing but that doesn't seem to be true
            //since it triggers a dead-lock somewhere inside directshow (see task 258830)

            *sample = 0;
            *user = 0;

            if (m_requestQueue.isEmpty()) {
                if (m_requestWait.wait(&m_mutex, timeout) == false) {
                    return VFW_E_TIMEOUT;
                }
                if (m_requestQueue.isEmpty()) {
                    return VFW_E_WRONG_STATE;
                }
            }

            AsyncRequest r = m_requestQueue.dequeue();

            //at this point we're sure to have a request to proceed
            if (r.sample == 0) {
                return E_FAIL;
            }

            *sample = r.sample;
            *user = r.user;
            return syncReadAlignedUnlocked(r.sample);
        }

        STDMETHODIMP QAsyncReader::BeginFlush()
        {
            QMutexLocker locker(&m_mutex);
            m_flushing = true;
            m_requestWait.wakeOne();
            return S_OK;
        }

        STDMETHODIMP QAsyncReader::EndFlush()
        {
            QMutexLocker locker(&m_mutex);
            m_flushing = false;
            return S_OK;
        }

        STDMETHODIMP QAsyncReader::SyncReadAligned(IMediaSample *sample)
        {
            QMutexLocker locker(&m_mutex);
            return syncReadAlignedUnlocked(sample);
        }

        STDMETHODIMP QAsyncReader::SyncRead(LONGLONG pos, LONG length, BYTE *buffer)
        {
            QMutexLocker locker(&m_mutex);
            return read(pos, length, buffer, 0);
        }

        STDMETHODIMP QAsyncReader::syncReadAlignedUnlocked(IMediaSample *sample)
        {
            Q_ASSERT(!m_mutex.tryLock());

            if (!sample) {
                return E_POINTER;
            }

            REFERENCE_TIME start = 0,
                stop = 0;
            HRESULT hr = sample->GetTime(&start, &stop);
            if(FAILED(hr)) {
                return hr;
            }

            LONGLONG startPos = start / 10000000;
            LONG length = static_cast<LONG>((stop - start) / 10000000);

            BYTE *buffer;
            hr = sample->GetPointer(&buffer);
            if(FAILED(hr)) {
                return hr;
            }

            LONG actual = 0;
            read(startPos, length, buffer, &actual);

            return sample->SetActualDataLength(actual);
        }

    }
}

QT_END_NAMESPACE

redpajama_set_name: RedPajamaGithub


text:
/*
 * DeliveryHub
 *
 * DeliveryHub API
 *
 * OpenAPI spec version: 1.0.0
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;

namespace IO.Swagger.Model
{
    /// <summary>
    /// Digits-only string without leading '+' and other separators.  7XXXXXXXXXX for Russia. 3XXXXXXXXXX for Moldova. Refer E.164 for details.
    /// </summary>
    [DataContract]
    public partial class MobilePhone :  IEquatable<MobilePhone>, IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MobilePhone" /> class.
        /// </summary>
        [JsonConstructorAttribute]
        public MobilePhone()
        {
        }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class MobilePhone {\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            return this.Equals(obj as MobilePhone);
        }

        /// <summary>
        /// Returns true if MobilePhone instances are equal
        /// </summary>
        /// <param name="other">Instance of MobilePhone to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(MobilePhone other)
        {
            // credit: http://stackoverflow.com/a/10454552/677735
            if (other == null)
                return false;

            return false;
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;
                // Suitable nullity checks etc, of course :)
                return hash;
            }
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            yield break;
        }
    }

}


text:
using System;

using NUnit.Framework;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Esf;
using Org.BouncyCastle.Utilities.Test;

namespace Org.BouncyCastle.Asn1.Tests
{
    [TestFixture]
    public class CommitmentTypeQualifierUnitTest
        : SimpleTest
    {
        public override string Name
        {
			get { return "CommitmentTypeQualifier"; }
        }

		public override void PerformTest()
        {
            CommitmentTypeQualifier ctq = new CommitmentTypeQualifier(CommitmentTypeIdentifier.ProofOfOrigin);

            CheckConstruction(ctq, CommitmentTypeIdentifier.ProofOfOrigin, null);

            Asn1Encodable info = new DerObjectIdentifier("1.2");

            ctq = new CommitmentTypeQualifier(CommitmentTypeIdentifier.ProofOfOrigin, info);

            CheckConstruction(ctq, CommitmentTypeIdentifier.ProofOfOrigin, info);

            ctq = CommitmentTypeQualifier.GetInstance(null);

            if (ctq != null)
            {
                Fail("null GetInstance() failed.");
            }

            try
            {
                CommitmentTypeQualifier.GetInstance(new object());

                Fail("GetInstance() failed to detect bad object.");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }

        private void CheckConstruction(
            CommitmentTypeQualifier mv,
            DerObjectIdentifier commitmenttTypeId,
            Asn1Encodable qualifier)
        {
            CheckStatement(mv, commitmenttTypeId, qualifier);

			mv = CommitmentTypeQualifier.GetInstance(mv);

			CheckStatement(mv, commitmenttTypeId, qualifier);

			Asn1Sequence seq = (Asn1Sequence) Asn1Object.FromByteArray(
				mv.ToAsn1Object().GetEncoded());

			mv = CommitmentTypeQualifier.GetInstance(seq);

			CheckStatement(mv, commitmenttTypeId, qualifier);
        }

		private void CheckStatement(
            CommitmentTypeQualifier ctq,
            DerObjectIdentifier     commitmentTypeId,
            Asn1Encodable           qualifier)
        {
            if (!ctq.CommitmentTypeIdentifier.Equals(commitmentTypeId))
            {
                Fail("commitmentTypeIds don't match.");
            }

            if (qualifier != null)
            {
                if (!ctq.Qualifier.Equals(qualifier))
                {
                    Fail("qualifiers don't match.");
                }
            }
            else if (ctq.Qualifier != null)
            {
                Fail("qualifier found when none expected.");
            }
        }

        public static void Main(
            string[] args)
        {
            RunTest(new CommitmentTypeQualifierUnitTest());
        }

        [Test]
        public void TestFunction()
        {
            string resultText = Perform().ToString();

            Assert.AreEqual(Name + ": Okay", resultText);
        }
    }
}


text:
.cal-container .cal-table {
  border-collapse: collapse;
}
.cal-container .cal-table td,
.cal-container .something ul {
  color: #ffff00;
  text-transform: capitalize;
  background-color: #080808;
}


text:
var System = require('../../entities/systems/System');
var SystemBus = require('../../entities/SystemBus');
var Material = require('../../renderer/Material');
var ShaderLib = require('../../renderer/shaders/ShaderLib');
var Vector3 = require('../../math/Vector3');
var Ray = require('../../math/Ray');
var MathUtils = require('../../math/MathUtils');

/**
 * @extends System
 * @example-link http://code.gooengine.com/latest/visual-test/goo/entities/components/Dom3dComponent/Dom3dComponent-vtest.html Working example
 */
function Dom3dSystem(renderer) {
	System.call(this, 'Dom3dSystem', ['TransformComponent', 'Dom3dComponent']);

	this.renderer = renderer;
	this.camera = null;

	SystemBus.addListener('goo.setCurrentCamera', function (newCam) {
		this.camera = newCam.camera;
	}.bind(this), true);

	this.playing = true;

	var frontMaterial = new Material(ShaderLib.simple);
	frontMaterial.blendState.blending = 'CustomBlending';
	frontMaterial.blendState.blendSrc = 'ZeroFactor';
	frontMaterial.blendState.blendDst = 'ZeroFactor';

	var backMaterial = new Material(ShaderLib.uber);
	backMaterial.uniforms.materialDiffuse = [0.5, 0.5, 0.5, 1];
	backMaterial.cullState.cullFace = 'Front';

	this.materials = [frontMaterial, backMaterial];

	// this.prefixes = ['', '-webkit-', '-moz-'];
	this.prefixes = ['', '-webkit-'];
	this.styleCache = new Map();

	this.precisionScale = 1000; // Thanks browsers
}

Dom3dSystem.prototype = Object.create(System.prototype);
Dom3dSystem.prototype.constructor = Dom3dSystem;

Dom3dSystem.prototype.init = function () {
	var ray = new Ray();
	var polygonVertices = [new Vector3(), new Vector3(), new Vector3(), new Vector3()];
	var offsets = [new Vector3(-0.5, -0.5, 0), new Vector3(-0.5, 0.5, 0), new Vector3(0.5, 0.5, 0), new Vector3(0.5, -0.5, 0)];
	var doPlanar = false;

	var doesIntersect = false;

	var that = this;
	var doPick = function (event) {
		var x, y;
		var domTarget = that.renderer.domElement;
		if (event.type === 'touchstart' || event.type === 'touchend' || event.type === 'touchmove') {
			x = event.changedTouches[0].pageX - domTarget.getBoundingClientRect().left;
			y = event.changedTouches[0].pageY - domTarget.getBoundingClientRect().top;
		} else {
			var rect = domTarget.getBoundingClientRect();
			x = event.clientX - rect.left;
			y = event.clientY - rect.top;
		}

		that.camera.getPickRay(x, y, that.renderer.domElement.offsetWidth, that.renderer.domElement.offsetHeight, ray);

		for (var i = 0; i < that._activeEntities.length; i++) {
			var entity = that._activeEntities[i];

			for (var j = 0; j < polygonVertices.length; j++) {
				var vec = polygonVertices[j];
				vec.set(offsets[j]);
				vec.applyPostPoint(entity.transformComponent.sync().worldTransform.matrix);
			}

			if (ray.intersects(polygonVertices, doPlanar, null, true)) {
				return true;
			}
		}

		return false;
	};

	var handlePick = function (event) {
		if (!that.camera || that._activeEntities.length === 0) {
			return false;
		}

		var intersects = doPick(event);

		if (intersects && !doesIntersect) {
			SystemBus.emit('goo.dom3d.enabled', true);
			that.renderer.domElement.style.pointerEvents = 'none';
			doesIntersect = true;
		} else if (!intersects && doesIntersect) {
			SystemBus.emit('goo.dom3d.enabled', false);
			that.renderer.domElement.style.pointerEvents = '';
			doesIntersect = false;
		}
	};

	var drag = false;
	document.addEventListener('mousedown', function (event) {
		if (!that.camera || that._activeEntities.length === 0) {
			return;
		}

		drag = !doPick(event);
	}, false);
	document.addEventListener('mouseup', function (event) {
		if (!that.camera || that._activeEntities.length === 0) {
			return;
		}

		drag = false;

		if (that.playing) {
			handlePick(event);
		}
	}, false);
	document.addEventListener('mousemove', function (event) {
		if (drag || !that.camera || that._activeEntities.length === 0) {
			return;
		}

		if (that.playing) {
			handlePick(event);
		}
	}, false);

	var rootDom = this.rootDom = document.createElement('div');
	this.renderer.domElement.parentNode.insertBefore(rootDom, this.renderer.domElement);

	rootDom.style.position = 'absolute';
	rootDom.style.overflow = 'hidden';
	rootDom.style.webkitUserSelect = 'none';
	rootDom.style.mozUserSelect = 'none';
	rootDom.style.msUserSelect = 'none';
	// rootDom.style.webkitTransformStyle = 'preserve-3d';
	// rootDom.style.mozTransformStyle = 'preserve-3d';
	rootDom.style.transformStyle = 'preserve-3d';
	rootDom.style.width = '100%';
	rootDom.style.height = '100%';
	rootDom.style.top = '0px';
	rootDom.style.bottom = '0px';
	rootDom.style.left = '0px';
	rootDom.style.right = '0px';

	var cameraDom = this.cameraDom = document.createElement('div');
	cameraDom.style.webkitUserSelect = 'none';
	cameraDom.style.mozUserSelect = 'none';
	cameraDom.style.msUserSelect = 'none';
	// cameraDom.style.webkitTransformStyle = 'preserve-3d';
	// cameraDom.style.mozTransformStyle = 'preserve-3d';
	cameraDom.style.transformStyle = 'preserve-3d';
	cameraDom.style.width = '100%';
	cameraDom.style.height = '100%';

	rootDom.appendChild(cameraDom);
};

Dom3dSystem.prototype.play = function () {
	this.playing = true;
};

Dom3dSystem.prototype.pause = function () {
};

Dom3dSystem.prototype.resume = Dom3dSystem.prototype.play;

Dom3dSystem.prototype.stop = function () {
	this.playing = false;

	SystemBus.emit('goo.dom3d.enabled', false);
	if (this.renderer.domElement) {
		this.renderer.domElement.style.pointerEvents = '';
	}
};

Dom3dSystem.prototype.getCameraCSSMatrix = function (matrix) {
	var elements = matrix.data;

	return 'matrix3d('
		+ elements[0] + ',' + (-elements[1]) + ',' + elements[2] + ',' + elements[3] + ','
		+ elements[4] + ',' + (-elements[5]) + ',' + elements[6] + ',' + elements[7] + ','
		+ elements[8] + ',' + (-elements[9]) + ',' + elements[10] + ',' + elements[11] + ','
		+ elements[12] * this.precisionScale + ',' + (-elements[13]) * this.precisionScale + ',' + elements[14] * this.precisionScale + ',' + elements[15] + ')';
};

Dom3dSystem.prototype.getEntityCSSMatrix = function (matrix) {
	var elements = matrix.data;

	return 'translate3d(-50%,-50%,0) matrix3d('
		+ elements[0] + ',' + elements[1] + ',' + elements[2] + ',' + elements[3] + ','
		+ (-elements[4]) + ',' + (-elements[5]) + ',' + (-elements[6]) + ',' + (-elements[7]) + ','
		+ elements[8] + ',' + elements[9] + ',' + elements[10] + ',' + elements[11] + ','
		+ elements[12] * this.precisionScale + ',' + elements[13] * this.precisionScale + ',' + elements[14] * this.precisionScale + ',' + elements[15] + ')';
};

Dom3dSystem.prototype.setStyle = function (element, property, style) {
	var cachedStyle = this.styleCache.get(element);

	if (style !== cachedStyle) {
		for (var j = 0; j < this.prefixes.length; j++) {
			element.style[this.prefixes[j] + property] = style;
		}
		this.styleCache.set(element, style);
	}
};

Dom3dSystem.prototype.inserted = function (entity) {
	var component = entity.dom3dComponent;
	component.meshRendererComponent.materials = this.materials;
};

Dom3dSystem.prototype.onPreRender = function () {
	var entities = this._activeEntities;
	var camera = this.camera;
	if (!camera || entities.length === 0) {
		return;
	}

	// lazy init
	if (this.renderer.domElement.parentNode && !this.rootDom) {
		this.init();
	}

	var width = this.renderer.viewportWidth / this.renderer.devicePixelRatio;
	var height = this.renderer.viewportHeight / this.renderer.devicePixelRatio;
	var fov = 0.5 / Math.tan(MathUtils.DEG_TO_RAD * camera.fov * 0.5) * height;

	this.setStyle(this.rootDom, 'perspective', fov + 'px');

	var viewMatrix = camera.getViewMatrix();
	var style = 'translate3d(0,0,' + fov + 'px) ' +
			this.getCameraCSSMatrix(viewMatrix) +
			' translate3d(' + (width / 2) + 'px,' + (height / 2) + 'px, 0)';
	this.setStyle(this.cameraDom, 'transform', style);

	for (var i = 0, l = entities.length; i < l; i++) {
		var entity = entities[i];
		var component = entity.dom3dComponent;
		var domElement = component.domElement;

		if (domElement.parentNode !== this.cameraDom) {
			this.cameraDom.appendChild(domElement);
		}

		// Do we really have to set this every time?
		if (component.hidden) {
			component.domElement.style.display = 'none';
			continue;
		} else {
			component.domElement.style.display = '';
		}

		if (!component.updated && !component._transformDirty) {
			continue;
		}
		component.updated = false;
		component._transformDirty = false;

		var worldTransform = entity.transformComponent.sync().worldTransform;
		style = this.getEntityCSSMatrix(worldTransform.matrix) +
				' scale(' + this.precisionScale / component.width +
				', ' + this.precisionScale / component.height + ')';
		this.setStyle(domElement, 'transform', style);
	}
};

Dom3dSystem.prototype.cleanup = function () {
	System.prototype.cleanup.apply(this, arguments);

	if (this.rootDom.parentNode !== null) {
		this.rootDom.parentNode.removeChild(this.rootDom);
	}
};

module.exports = Dom3dSystem;


text:
package com.tocong.mymobilesafe.chapter04;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.tocong.mymobilesafe.R;
import com.tocong.mymobilesafe.chapter04.adapter.AppManagerAdapter;
import com.tocong.mymobilesafe.chapter04.entity.AppInfo;
import com.tocong.mymobilesafe.chapter04.utils.AppInfoParse;

import java.util.ArrayList;
import java.util.List;

public class AppMnaagerActivity extends Activity implements View.OnClickListener {
    private TextView mPhoneMemoryTV;
    private TextView mSDMemoryTV;
    private ListView mListView;
    private List<AppInfo> appInfos;
    private List<AppInfo> userAppInfos = new ArrayList<AppInfo>();
    private List<AppInfo> systemAppInfos = new ArrayList<AppInfo>();
    private AppManagerAdapter adapter;
    private UninstallReceiver receiver;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 10:
                    if (adapter == null) {
                        adapter = new AppManagerAdapter(AppMnaagerActivity.this, userAppInfos, systemAppInfos);

                    }
                    mListView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    break;
                case 15:
                    adapter.notifyDataSetChanged();
                    break;
            }

        }
    };
    private TextView mAPPNumtv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_mnaager);
        receiver = new UninstallReceiver();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addDataScheme("package");
        registerReceiver(receiver, intentFilter);
        initView();
    }

    /*
    * 初始化控件
    * */

    private void initView() {
        findViewById(R.id.rl_titlebar).setBackgroundColor(getResources().getColor(R.color.bright_yellow));
        ImageView mLeftImgv = (ImageView) findViewById(R.id.imgv_leftbtn);
        mLeftImgv.setOnClickListener(this);
        mLeftImgv.setImageResource(R.mipmap.back);
        ((TextView) findViewById(R.id.tv_title)).setText("软件管家");
        mPhoneMemoryTV = (TextView) findViewById(R.id.tv_phonememory_appmanager);
        mSDMemoryTV = (TextView) findViewById(R.id.tv_sdmemory_appmanager);
        mAPPNumtv = (TextView) findViewById(R.id.tv_appnumber);
        mListView = (ListView) findViewById(R.id.lv_appmanager);

        getMemoryFromPhone();
        initData();
        initListener();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.imgv_leftbtn:
                finish();
                break;
        }
    }

    /*
    * 初始化数据
    * */

    private void initData() {
        appInfos = new ArrayList<AppInfo>();
        new Thread() {
            @Override
            public void run() {
                super.run();
                appInfos.clear();
                userAppInfos.clear();
                systemAppInfos.clear();
                appInfos.addAll(AppInfoParse.getAppInfos(AppMnaagerActivity.this));
                for (AppInfo appInfo : appInfos) {
                    if (appInfo.isUserApp()) {

                        userAppInfos.add(appInfo);
                    } else {
                        systemAppInfos.add(appInfo);

                    }

                }
                handler.sendEmptyMessage(10);
            }
        }.start();

    }

    private void initListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (adapter != null) {
                    new Thread() {

                        @Override
                        public void run() {
                            super.run();
                            AppInfo mappInfo = (AppInfo) adapter.getItem(position);
                            boolean flag = mappInfo.isSelected();
                            //先将集合中所有条目的AppInfo变为未选中状态
                            for (AppInfo appInfo : userAppInfos) {
                                appInfo.setSelected(false);
                            }
                            for (AppInfo appInfo : systemAppInfos) {
                                appInfo.setSelected(false);
                            }
                            if (mappInfo != null) {
                                //如果已经选中,则变为未选中
                                if (flag) {
                                    mappInfo.setSelected(false);
                                } else {
                                    mappInfo.setSelected(true);
                                }
                              handler.sendEmptyMessage(15);
                            }

                        }
                    }.start();

                }

            }
        });

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem >= userAppInfos.size() + 1) {
                    mAPPNumtv.setText("系统程序:" + systemAppInfos.size() + "个");

                } else {
                    mAPPNumtv.setText("用户程序:" + userAppInfos.size() + "个");

                }
            }
        });

    }

    /*
    * 拿到手机和sd剩余容量
    * */
    private void getMemoryFromPhone() {

        long avail_sd = Environment.getExternalStorageDirectory().getFreeSpace();
        long avail_rom = Environment.getDataDirectory().getFreeSpace();
        //格式化内存
        String str_avail_sd = Formatter.formatFileSize(this, avail_sd);
        String str_avail_rom = Formatter.formatFileSize(this, avail_rom);
        mPhoneMemoryTV.setText("剩余手机内存" + str_avail_sd);
        mSDMemoryTV.setText("剩余sd卡内存" + str_avail_sd);
    }

    class UninstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            initData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        receiver = null;
    }
}


text:
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
from twisted.internet.defer import inlineCallbacks
from twisted.internet import reactor
from autobahn.wamp import auth
from types import FunctionType
import traceback
import sys
from contextlib import contextmanager

class TestRunner(object):

    def __init__(self, test_cases, url, realm, quiet=False, test=False, user=None, secret=None):
        self.total_tests = 0
        self.total_errors = 0
        self.total_failures = 0
        self.total_passes = 0

        self.quiet = quiet
        self.test = test
        self.test_fail = False

        self.test_cases = test_cases
        self.test_case_number = 0
        self.url = url
        self.realm = realm

        self.auth_user = user
        self.auth_secret = secret

    def run(self):
        if len(self.test_cases) > 0:
            test_case = self.test_cases[0]
            test_case.connect(url=self.url, realm=self.realm, test_runner=self)

            if self.test is False:
                reactor.run()

    def report_test_results(self, tests, errors, failures, passes):
        self.total_tests += tests
        self.total_errors += errors
        self.total_failures += failures
        self.total_passes += passes

        self.test_case_number += 1
        if self.test_case_number < len(self.test_cases):
            test_case = self.test_cases[self.test_case_number]
            test_case.connect(url=self.url, realm=self.realm, test_runner=self)
        elif self.test is False:
            reactor.stop()

class TestCase(ApplicationSession):

    WAMPCRA = u"wampcra"

    test_runner = None
    quiet = False

    def is_quiet(self):
        test_runner = self.get_test_runner()
        if test_runner is not None:
            return test_runner.quiet or self.__class__.quiet
        else:
            return self.__class__.quiet

    def get_test_runner(self):
        return self.__class__.test_runner

    def __init__(self, config):
        super(TestCase, self).__init__(config)

        self.errors = 0
        self.failures = 0
        self.tests = 0
        self.passes = 0

        self.test_fail = False

    def reset(self):
        self.errors = 0
        self.failures = 0
        self.passes = 0
        self.tests = 0

        self.test_fail = False

    def onConnect(self):
        if self.get_test_runner().auth_user is not None:
            self.join(self.config.realm, [u"wampcra"], unicode(self.get_test_runner().auth_user))
        else:
            super(TestCase, self).onConnect()

    def onChallenge(self, challenge):
        if challenge.method == u"wampcra":
            signature = auth.compute_wcs(
                unicode(self.get_test_runner().auth_secret).encode('utf8'),
                challenge.extra['challenge'].encode('utf8')
            )
            return signature.decode('ascii')
        else:
            raise Exception("don't know how to handle authmethod {}".format(challenge.method))

    @inlineCallbacks
    def onJoin(self, details):

        # Setup the class
        self.reset()
        self.__class__.setUpClass()

        for method_name in [x for x, y in self.__class__.__dict__.items() if type(y) == FunctionType]:

            if not method_name.startswith("test_"):
                continue

            self.tests += 1
            self.test_fail = False

            self.setUp()

            try:
                yield getattr(self, method_name)()
            except BaseException, e:
                traceback.print_exc()
                self._error(str(e))

            self.tearDown()

        # Teardown the class
        self.__class__.tearDownClass()

        # Report Done
        self.get_test_runner().report_test_results(
            tests=self.tests,
            errors=self.errors,
            failures=self.failures,
            passes=self.passes
        )

        if self.get_test_runner().test is False:
            # Disconnect
            print "Disconnecting from the Session"
            self.disconnect()

    @classmethod
    def connect(cls, url=None, realm=None, test_runner=None, user=None, secret=None):
        print "Connecting to the url: '%s', realm: '%s'" % (url, realm)

        cls.test_runner = test_runner

        runner = ApplicationRunner(url=url, realm=realm)
        runner.run(cls, start_reactor=False)

    @classmethod
    def setUpClass(cls):
        """
        Run once before the test suite is run
        :return: Nothing
        """
        pass

    @classmethod
    def tearDownClass(cls):
        """
        Run once after the test suite is run
        :return: Nothing
        """
        pass

    def setUp(self):
        """
        Run once before each test is run
        :return: Nothing
        """
        pass

    def tearDown(self):
        """
        Run once after each test is run
        :return: Nothing
        """
        pass

    def assertEqual(self, a, b, msg=None):
        """
        Asserts that a value is equal to another value
        :param a: The value
        :param b: The other value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if a != b:
            if msg is None:
                msg = "Expected '%s' to equal '%s'" % (a, b)
            return self._fail(msg)
        else:
            return self._pass()

    def assertNotEqual(self, a, b, msg=None):
        """
        Asserts that a value is equal to another value
        :param a: The value
        :param b: The other value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if a == b:
            if msg is None:
                msg = "Expected '%s' to not equal '%s'" % (a, b)
            return self._fail(msg)
        else:
            return self._pass()

    def assertIsNone(self, a, msg=None):
        """
        Asserts that a value is None
        :param a: The value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if a is not None:
            if msg is None:
                msg = "'%s' should be 'None'" % a
            return self._fail(msg)
        else:
            return self._pass()

    def assertIsNotNone(self, a, msg=None):
        """
        Asserts that a value is not None
        :param a: The value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if a is None:
            if msg is None:
                msg = "'%s' should not be 'None'" % a
            return self._fail(msg)
        else:
            return self._pass()

    def assertTrue(self, a, msg=None):
        """
        Asserts that a value is True
        :param a: The value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if a is not True:
            if msg is None:
                msg = "'%s' should be 'True'" % a
            return self._fail(msg)
        else:
            return self._pass()

    def assertFalse(self, a, msg=None):
        """
        Asserts that a value is False
        :param a: The value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if a is not False:
            if msg is None:
                msg = "'%s' should be 'False'" % a
            return self._fail(msg)
        else:
            return self._pass()

    def assertGreater(self, a, b, msg=None):
        """
        Asserts that a value is greater than another value
        :param a: The value
        :param b: The other value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if not a > b:
            if msg is None:
                msg = "'%s' should be greater than '%s'" % (a, b)
            return self._fail(msg)
        else:
            return self._pass()

    def assertGreaterEqual(self, a, b, msg=None):
        """
        Asserts that a value is greater than or equal to another value
        :param a: The value
        :param b: The other value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if not a >= b:
            if msg is None:
                msg = "'%s' should be greater than or equal to '%s'" % (a, b)
            return self._fail(msg)
        else:
            return self._pass()

    def assertLess(self, a, b, msg=None):
        """
        Asserts that a value is less than another value
        :param a: The value
        :param b: The other value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if not a < b:
            if msg is None:
                msg = "'%s' should be less than '%s'" % (a, b)
            return self._fail(msg)
        else:
            return self._pass()

    def assertLessEqual(self, a, b, msg=None):
        """
        Asserts that a value is less than or equal to another value
        :param a: The value
        :param b: The other value
        :param msg: Custom message on failure
        :return: True is the assertion passed
        """
        if not a <= b:
            if msg is None:
                msg = "'%s' should be less than or equal to '%s'" % (a, b)
            return self._fail(msg)
        else:
            return self._pass()

    @contextmanager
    def assertRaises(self, exception_class, msg=None):
        """
        Asserts that a block of code raises an exception
        :param exception_class: The type of class expected
        :param msg: Custom message on failure
        """
        success = False
        exc = None
        try:
            yield exception_class
        except BaseException, e:
            print >> sys.stderr, e
            exc = e

        if exc is not None:
            if issubclass(exc.__class__, exception_class):
                success = True

        if success is False:
            if msg is None:
                msg = "method should raise exception of type '%s'" % exception_class.__name__
            self._fail(msg)
        else:
            self._pass()

    def _pass(self):
        self.passes += 1
        return True

    def _fail(self, message):
        # Can't exit since running in reactor so just suppress additional failures
        if self.test_fail is False:
            if self.is_quiet() is False:
                stack = traceback.extract_stack()[-3:-1]
                path, line, test, instr = stack[0]
                print >> sys.stderr, "\nFailure in %s: '%s'" % (test, message)
                print >> sys.stderr, "    File: %s:%s" % (path, line)
                print >> sys.stderr, "    Check: %s" % instr
            self.failures += 1
        self.test_fail = True
        return False

    def _error(self, message):
        if self.is_quiet() is False:
            stack = traceback.extract_stack()[-3:-1]
            path, line, test, instr = stack[0]
            print >> sys.stderr, "\nError in %s: '%s'" % (test, message)
            print >> sys.stderr, "    File: %s:%s" % (path, line)
            print >> sys.stderr, "    Check: %s" % instr
        self.errors += 1
        return False

def main(test_cases=None, url=None, realm=None, user=None, secret=None, quiet=False, test=False):
    """
    Runs the test cases.  Example of use is as follows

    import wamptest
    from twisted.internet.defer import inlineCallbacks
    from autobahn.twisted.util import sleep

    class ExampleTestCase(wamptest.TestCase):

        @inlineCallbacks
        def test_1(self):
            result = yield self.call("com.example.add", 1, 2)
            self.assertEqual(3, result)

        def receive_update(self, update=None):
            self.update = update

        @inlineCallbacks
        def test_2(self):
            self.subscribe(self.receive_update, topic="com.example.update")

            # Trigger update

            yield sleep(2)

            self.assertEqual("test", self.update)

    result = wamptest.main(
        test_cases=[ExampleTestCase],
        url="ws://router.example.com",
        realm="realm1"
    )

    exit(result)

    :param test_cases: Array of the test cases
    :param url: The url of the router
    :param realm: The realm of the router
    :param user: The user to authenticate as (wampcra)
    :param secret: The secret for the user (wampcra)
    :param quiet: True if silencing logging
    :return: number of total errors and failures
    """

    if test_cases is None:
        test_cases = []

    if url is None:
        print "Connection 'url' must be defined."
        return 1

    if realm is None:
        print "Connection 'realm' must be defined."
        return 1

    # Run the tests
    test_runner = TestRunner(test_cases, url, realm, quiet=quiet, test=test, user=user, secret=secret)
    test_runner.run()

    # Print the results
    if quiet is False:
        heading = "\nResult:"
        if test_runner.total_tests == 0:
            print >> sys.stderr, heading, "UNKNOWN"
        elif (test_runner.total_errors + test_runner.total_failures) == 0:
            print >> sys.stderr, heading, "PASSED"
        else:
            print >> sys.stderr, heading, "FAILED"

        print >> sys.stderr, "    Tests: %d" % test_runner.total_tests
        print >> sys.stderr, "    Passes: %d" % test_runner.total_passes
        print >> sys.stderr, "    Failures: %d" % test_runner.total_failures
        print >> sys.stderr, "    Errors: %d" % test_runner.total_errors

    return test_runner.total_errors + test_runner.total_failures


text:
package org.consumersunion.stories.server.api;

import javax.ws.rs.core.Response.Status;

import com.jayway.restassured.response.Response;

import static com.jayway.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;

public class QuestionnaireCorsApiTest extends ApiTestCase {
    public void testCors() {
        Response response = given().options("/rest/questionnaire/some-permalink");

        assertThat(response.getStatusCode()).isEqualTo(Status.OK.getStatusCode());
        assertThat(response.getHeader("Access-Control-Allow-Origin")).isEqualTo("*");
        assertThat(response.getHeader("Access-Control-Allow-Methods")).isEqualTo("POST, GET, UPDATE, DELETE, OPTIONS");
        assertThat(response.getHeader("Access-Control-Allow-Headers")).isEqualTo(
                "content-type, x-http-method-override");
    }
}


text:
#include "PutSplunkHTTP.h"
#include "QuerySplunkIndexingStatus.h"
#include "SplunkHECProcessor.h"
#include "core/PropertyBuilder.h"
#include "core/Resource.h"

// FIXME(fgerlits): we need to put all these static definitions in a single file so that they are executed in this order at runtime
// when https://issues.apache.org/jira/browse/MINIFICPP-1825 is closed, these definitions should be moved back to the cpp file of the class to which they belong

namespace org::apache::nifi::minifi::extensions::splunk {

// SplunkHECProcessor

const core::Property SplunkHECProcessor::Hostname(core::PropertyBuilder::createProperty("Hostname")
    ->withDescription("The ip address or hostname of the Splunk server.")
    ->isRequired(true)->build());

const core::Property SplunkHECProcessor::Port(core::PropertyBuilder::createProperty("Port")
    ->withDescription("The HTTP Event Collector HTTP Port Number.")
    ->withDefaultValue<int>(8088, core::StandardValidators::get().PORT_VALIDATOR)->isRequired(true)->build());

const core::Property SplunkHECProcessor::Token(core::PropertyBuilder::createProperty("Token")
    ->withDescription("HTTP Event Collector token starting with the string Splunk. For example \'Splunk 1234578-abcd-1234-abcd-1234abcd\'")
    ->isRequired(true)->build());

const core::Property SplunkHECProcessor::SplunkRequestChannel(core::PropertyBuilder::createProperty("Splunk Request Channel")
    ->withDescription("Identifier of the used request channel.")->isRequired(true)->build());

const core::Property SplunkHECProcessor::SSLContext(core::PropertyBuilder::createProperty("SSL Context Service")
    ->withDescription("The SSL Context Service used to provide client certificate "
                      "information for TLS/SSL (https) connections.")
    ->isRequired(false)->withExclusiveProperty("Hostname", "^http:.*$")
    ->asType<minifi::controllers::SSLContextService>()->build());

// PutSplunkHTTP

const core::Property PutSplunkHTTP::Source(core::PropertyBuilder::createProperty("Source")
    ->withDescription("Basic field describing the source of the event. If unspecified, the event will use the default defined in splunk.")
    ->supportsExpressionLanguage(true)->build());

const core::Property PutSplunkHTTP::SourceType(core::PropertyBuilder::createProperty("Source Type")
    ->withDescription("Basic field describing the source type of the event. If unspecified, the event will use the default defined in splunk.")
    ->supportsExpressionLanguage(true)->build());

const core::Property PutSplunkHTTP::Host(core::PropertyBuilder::createProperty("Host")
    ->withDescription("Basic field describing the host of the event. If unspecified, the event will use the default defined in splunk.")
    ->supportsExpressionLanguage(true)->build());

const core::Property PutSplunkHTTP::Index(core::PropertyBuilder::createProperty("Index")
    ->withDescription("Identifies the index where to send the event. If unspecified, the event will use the default defined in splunk.")
    ->supportsExpressionLanguage(true)->build());

const core::Property PutSplunkHTTP::ContentType(core::PropertyBuilder::createProperty("Content Type")
    ->withDescription("The media type of the event sent to Splunk. If not set, \"mime.type\" flow file attribute will be used. "
                      "In case of neither of them is specified, this information will not be sent to the server.")
    ->supportsExpressionLanguage(true)->build());

const core::Relationship PutSplunkHTTP::Success("success", "FlowFiles that are sent successfully to the destination are sent to this relationship.");
const core::Relationship PutSplunkHTTP::Failure("failure", "FlowFiles that failed to be sent to the destination are sent to this relationship.");

REGISTER_RESOURCE(PutSplunkHTTP, Processor);

// QuerySplunkIndexingStatus

const core::Property QuerySplunkIndexingStatus::MaximumWaitingTime(core::PropertyBuilder::createProperty("Maximum Waiting Time")
    ->withDescription("The maximum time the processor tries to acquire acknowledgement confirmation for an index, from the point of registration. "
                      "After the given amount of time, the processor considers the index as not acknowledged and transfers the FlowFile to the \"unacknowledged\" relationship.")
    ->withDefaultValue<core::TimePeriodValue>("1 hour")->isRequired(true)->build());

const core::Property QuerySplunkIndexingStatus::MaxQuerySize(core::PropertyBuilder::createProperty("Maximum Query Size")
    ->withDescription("The maximum number of acknowledgement identifiers the outgoing query contains in one batch. "
                      "It is recommended not to set it too low in order to reduce network communication.")
    ->withDefaultValue<uint64_t>(1000)->isRequired(true)->build());

const core::Relationship QuerySplunkIndexingStatus::Acknowledged("acknowledged",
    "A FlowFile is transferred to this relationship when the acknowledgement was successful.");

const core::Relationship QuerySplunkIndexingStatus::Unacknowledged("unacknowledged",
    "A FlowFile is transferred to this relationship when the acknowledgement was not successful. "
    "This can happen when the acknowledgement did not happened within the time period set for Maximum Waiting Time. "
    "FlowFiles with acknowledgement id unknown for the Splunk server will be transferred to this relationship after the Maximum Waiting Time is reached.");

const core::Relationship QuerySplunkIndexingStatus::Undetermined("undetermined",
    "A FlowFile is transferred to this relationship when the acknowledgement state is not determined. "
    "FlowFiles transferred to this relationship might be penalized. "
    "This happens when Splunk returns with HTTP 200 but with false response for the acknowledgement id in the flow file attribute.");

const core::Relationship QuerySplunkIndexingStatus::Failure("failure",
    "A FlowFile is transferred to this relationship when the acknowledgement was not successful due to errors during the communication, "
    "or if the flowfile was missing the acknowledgement id");

REGISTER_RESOURCE(QuerySplunkIndexingStatus, Processor);

}  // namespace org::apache::nifi::minifi::extensions::splunk


text:
var watcher = require("./lib/index");

var items = [];

watcher.watchRegistry(items, 1000).on("item:add", function (item) {
    console.log("ADDED");
}).on("item:removed" ,function () {
    console.log("REMOVED");
}).on("item:updated", function () {
    console.log("UPDATED");
});

setInterval(function () {
    watcher.addItem(items, {id: 123});
}, 900);


text:
//
//  CTFeedbackViewController.m
//  CTFeedbackDemo
//
//  Created by 和泉田 領一 on 2013/10/31.
//  Copyright (c) 2013年 CAPH. All rights reserved.
//

#import "CTFeedbackViewController.h"
#import "CTFeedbackCell.h"
#import "CTFeedbackCellItem.h"
#import "CTFeedbackTopicsViewController.h"
#include <sys/sysctl.h>
#import "NSBundle+CTFeedback.h"
#import <MessageUI/MessageUI.h>
#import "MMDrawerBarButtonItem.h"
#import "UIViewController+MMDrawerController.h"

static NSString * const kOHSemail = @"";
static NSString * const kMAINTemail = @"";

typedef NS_ENUM(NSInteger, CTFeedbackSection){
    CTFeedbackSectionEmail = 0,
    CTFeedbackSectionInput,
    CTFeedbackSectionScreenshot,
    CTFeedbackSectionDeviceInfo,
    CTFeedbackSectionAppInfo
};

@interface CTFeedbackViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate>

@property (nonatomic, readonly) NSUInteger selectedTopicIndex;

@property (nonatomic, strong) NSArray *cellItems;

@property (nonatomic, readonly) NSArray *emailCellItems;
@property (nonatomic, readonly) NSArray *inputCellItems;
@property (nonatomic, readonly) NSArray *deviceInfoCellItems;
@property (nonatomic, readonly) NSArray *appInfoCellItems;
@property (nonatomic, readonly) NSArray *additionCellItems;
@property (nonatomic, strong) CTFeedbackTopicCellItem *topicCellItem;
@property (nonatomic, strong) CTFeedbackContentCellItem *contentCellItem;
@property (nonatomic, strong) CTFeedbackFieldCellItem *emailCellItem;
@property (nonatomic, strong) CTFeedbackAdditionInfoCellItem *additionCellItem;
@property (nonatomic, readonly) NSString *mailBody;
@property (nonatomic, readonly) NSData *mailAttachment;
@property (nonatomic, readonly) NSData *screenshotAttachment;
@property (nonatomic, assign) BOOL previousNavigationBarHiddenState;
@property (nonatomic, strong) UIPopoverController *popoverController;
@end

@implementation CTFeedbackViewController

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = self.previousNavigationBarHiddenState;
}

+ (CTFeedbackViewController *)controllerWithTopics:(NSArray *)topics localizedTopics:(NSArray *)localizedTopics
{
    return [[CTFeedbackViewController alloc] initWithTopics:topics localizedTopics:localizedTopics];
}

+ (NSArray *)defaultTopics
{
    return @[
             @"OHS Report",
             @"Maintenance Report",
             @"Other"
    ];
}

+ (NSArray *)defaultLocalizedTopics
{
    return @[
             @"OHS Report",
             @"Maintenance Report",
             @"Other"
    ];
}

- (instancetype)initWithTopics:(NSArray *)topics localizedTopics:(NSArray *)localizedTopics
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        self.topics = topics;
        self.localizedTopics = localizedTopics;
        self.useHTML = NO;
        self.hidesAppNameCell = YES;
        self.hidesAppBuildCell = YES;
        self.hidesAppVersionCell = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = CTFBLocalizedString(@"Feedback");

    [self.tableView registerClass:[CTFeedbackCell class] forCellReuseIdentifier:[CTFeedbackTopicCellItem reuseIdentifier]];
    [self.tableView registerClass:[CTFeedbackCell class] forCellReuseIdentifier:[CTFeedbackContentCellItem reuseIdentifier]];
    [self.tableView registerClass:[CTFeedbackCell class] forCellReuseIdentifier:[CTFeedbackFieldCellItem reuseIdentifier]];
    [self.tableView registerClass:[CTFeedbackCell class] forCellReuseIdentifier:[CTFeedbackInfoCellItem reuseIdentifier]];
    [self.tableView registerClass:[CTFeedbackCell class] forCellReuseIdentifier:[CTFeedbackAdditionInfoCellItem reuseIdentifier]];

    self.cellItems = @[self.emailCellItems, self.inputCellItems, self.additionCellItems];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:CTFBLocalizedString(@"Mail") style:UIBarButtonItemStylePlain target:self action:@selector(sendButtonTapped:)];

   [self setupLeftMenuButton];
}

-(void)setupLeftMenuButton{
    MMDrawerBarButtonItem * leftDrawerButton = [[MMDrawerBarButtonItem alloc] initWithTarget:self action:@selector(leftDrawerButtonPress:)];
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];
}

-(void)leftDrawerButtonPress:(id)sender{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

-(void)doubleTap:(UITapGestureRecognizer*)gesture{
    [self.mm_drawerController bouncePreviewForDrawerSide:MMDrawerSideLeft completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.previousNavigationBarHiddenState = self.navigationController.navigationBarHidden;
    if (self.navigationController.navigationBarHidden) {
        self.navigationController.navigationBarHidden = NO;
    }
/*
	if(self.navigationController != nil){
		if( [self.navigationController viewControllers][0] == self){
			self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonTapped:)];
		}else{
			// Keep the standard back button instead of "Cancel"
			self.navigationItem.leftBarButtonItem = nil;
		}
	} else {
		self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonTapped:)];
	}*/
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [self.contentCellItem removeObserver:self forKeyPath:@"cellHeight"];
}

#pragma mark - Key value observing

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change
                       context:(void *)context
{
    if ([keyPath isEqualToString:@"cellHeight"]) {
        [self.tableView beginUpdates];
        [self.tableView endUpdates];
    }
}

#pragma mark -

- (void)cancelButtonTapped:(id)sender
{
    if(self.navigationController != nil){
        if( [self.navigationController viewControllers][0] == self){
            // Can't pop, just dismiss
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            // Can be popped
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)setTopics:(NSArray *)topics
{
    _topics = topics;

    self.selectedTopic = _topics.count >= 1 ? _topics[0] : @"";
}

- (NSUInteger)selectedTopicIndex
{
    return [self.topics indexOfObject:self.selectedTopic];
}

- (NSArray *)emailCellItems
{
    self.emailCellItem = [CTFeedbackFieldCellItem new];
    self.emailCellItem.textField.placeholder = CTFBLocalizedString(@"E-mail");
    self.emailCellItem.textField.keyboardType = UIKeyboardTypeEmailAddress;
    return @[self.emailCellItem];
}

- (NSArray *)inputCellItems
{
    NSMutableArray *result = [NSMutableArray array];

    __weak CTFeedbackViewController *weakSelf = self;

    self.topicCellItem = [CTFeedbackTopicCellItem new];
    self.topicCellItem.topic = self.localizedTopics[self.selectedTopicIndex];
    self.topicCellItem.action = ^(CTFeedbackViewController *sender) {
        CTFeedbackTopicsViewController *topicsViewController = [[CTFeedbackTopicsViewController alloc] initWithStyle:UITableViewStyleGrouped];
        topicsViewController.topics = sender.topics;
        topicsViewController.localizedTopics = sender.localizedTopics;
        topicsViewController.action = ^(NSString *selectedTopic) {
            weakSelf.selectedTopic = selectedTopic;
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:CTFeedbackSectionInput];
            CTFeedbackTopicCellItem *cellItem = weakSelf.cellItems[(NSUInteger)indexPath.section][(NSUInteger)indexPath.row];
            cellItem.topic = weakSelf.localizedTopics[weakSelf.selectedTopicIndex];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        };

        [sender.navigationController pushViewController:topicsViewController animated:YES];
    };
    if (!self.hidesTopicCell) {
        [result addObject:self.topicCellItem];
    }

    self.contentCellItem = [CTFeedbackContentCellItem new];
    [self.contentCellItem addObserver:self forKeyPath:@"cellHeight" options:NSKeyValueObservingOptionNew context:nil];
    [result addObject:self.contentCellItem];

    return result.copy;
}

- (NSArray *)additionCellItems{
    NSMutableArray *result = [NSMutableArray array];

	__weak CTFeedbackViewController *weakSelf = self;

	self.additionCellItem = [CTFeedbackAdditionInfoCellItem new];
    self.additionCellItem.value = CTFBLocalizedString(@"Additional detail");
    self.additionCellItem.action = ^(CTFeedbackViewController *sender){
        if( [weakSelf.contentCellItem.textView isFirstResponder] ) {
            [weakSelf.contentCellItem.textView resignFirstResponder];
        }

		UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:weakSelf
                                                        cancelButtonTitle:CTFBLocalizedString(@"Cancel")
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:CTFBLocalizedString(@"Camera"), CTFBLocalizedString(@"PhotoLibrary"), nil];
		[choiceSheet showInView:weakSelf.view];
    };

    [result addObject:self.additionCellItem];

    return [result copy];
}

- (NSArray *)deviceInfoCellItems
{
    NSMutableArray *result = [NSMutableArray array];

    CTFeedbackInfoCellItem *platformItem = [CTFeedbackInfoCellItem new];
    platformItem.title = CTFBLocalizedString(@"Device");
    platformItem.value = self.platformString;
    [result addObject:platformItem];

    CTFeedbackInfoCellItem *systemVersionItem = [CTFeedbackInfoCellItem new];
    systemVersionItem.title = CTFBLocalizedString(@"iOS");
    systemVersionItem.value = self.systemVersion;
    [result addObject:systemVersionItem];

    return result.copy;
}

- (NSArray *)appInfoCellItems
{
    NSMutableArray *result = [NSMutableArray array];

    if (!self.hidesAppNameCell) {
        CTFeedbackInfoCellItem *nameItem = [CTFeedbackInfoCellItem new];
        nameItem.title = CTFBLocalizedString(@"Name");
        nameItem.value = self.appName;
        [result addObject:nameItem];
    }

    if (!self.hidesAppVersionCell) {
        CTFeedbackInfoCellItem *versionItem = [CTFeedbackInfoCellItem new];
        versionItem.title = CTFBLocalizedString(@"Version");
        versionItem.value = self.appVersion;
        [result addObject:versionItem];
    }

    if (!self.hidesAppBuildCell) {
        CTFeedbackInfoCellItem *buildItem = [CTFeedbackInfoCellItem new];
        buildItem.title = CTFBLocalizedString(@"Build");
        buildItem.value = self.appBuild;
        [result addObject:buildItem];
    }

    return result.copy;
}

- (NSString *)platform
{
    int mib[2];
    size_t len;
    char *machine;

    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);

    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    return platform;
}

- (NSString *)platformString
{
    NSString *platform = [self platform];

    // Reading a file with platform names
    // http://theiphonewiki.com/wiki/Models
    NSBundle *bundle = [NSBundle feedbackBundle];
    NSString *filePath = [bundle pathForResource:@"PlatformNames" ofType:@"plist"];
    NSDictionary *platformNamesDic = [NSDictionary dictionaryWithContentsOfFile:filePath];

    // Changing a platform name to a human readable version
    platform = platformNamesDic[platform] ?: platform;

    return platform;
}

- (NSString *)systemVersion
{
    return [UIDevice currentDevice].systemVersion;
}

- (NSString *)appName
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]?
    [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]:
    [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
}

- (NSString *)appVersion
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

- (NSString *)appBuild
{
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
}

- (NSString *)_mailSubject
{
    if (self.mailSubject != nil && self.mailSubject.length > 0) {
        return self.mailSubject;
    }
    return [NSString stringWithFormat:@"%@: %@", self.appName, self.topics[self.selectedTopicIndex]];
}

- (NSString *)mailBody
{
    NSString *content = self.contentCellItem.textView.text;
    NSString *body;

    if (self.useHTML) {
        body = [NSString stringWithFormat:@"\

%@

\

\

Device:	%@
\

iOS:	%@
\

App:	%@
\

Version:	%@
\

Build:	%@
\

",
                [content stringByReplacingOccurrencesOfString:@"\n" withString:@"
"],
                self.platformString,
                self.systemVersion,
                self.appName,
                self.appVersion,
                self.appBuild];
    } else {
        body = [NSString stringWithFormat:@"%@\n\n\nDevice: %@\niOS: %@\nApp: %@\nVersion: %@\nBuild: %@",
                content,
                self.platformString,
                self.systemVersion,
                self.appName,
                self.appVersion,
                self.appBuild];
    }

    if (self.additionalDiagnosticContent) {
        body = [body stringByAppendingString:self.additionalDiagnosticContent];
    }

    return body;
}
#pragma mark - Convert image

static NSString * const MIME_TYPE_JPEG = @"image/jpeg";
static NSString * const ATTACHMENT_FILENAME = @"screenshot.jpg";

- (NSData *)mailAttachment{
    return UIImageJPEGRepresentation(self.additionCellItem.screenImage, 0.5);
}

- (NSData *)screenshotAttachment {
    return UIImageJPEGRepresentation(self.screenshot, 0.5);
}

#pragma mark - send email
- (void)sendButtonTapped:(id)sender
{
    if (self.useCustomCallback) {
        NSAssert(self.delegate, @"No delegate provided");
        if (self.delegate && [self.delegate respondsToSelector:@selector(feedbackViewController:didFinishWithCustomCallback:topic:content:attachment:)]) {
            [self.delegate feedbackViewController:self didFinishWithCustomCallback:self.emailCellItem.textField.text topic:self._mailSubject content:self.contentCellItem.textView.text.length ? self.mailBody : nil attachment:[UIImage imageWithData:self.mailAttachment]];
        }
    } else if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
        controller.mailComposeDelegate = self;
        //[controller setToRecipients:self.toRecipients];
        if ([self.selectedTopic isEqualToString:@"OHS Report"]) {
            NSArray *toRecipients = @[kOHSemail];
            [controller setToRecipients:toRecipients];
        }
        else if ([self.selectedTopic isEqualToString:@"Maintenance Report"]) {
            NSArray *toRecipients2 = @[kMAINTemail];

            [controller setToRecipients:toRecipients2];
        }
        else
        {
            NSArray *toRecipients3 = @[kOHSemail];
            [controller setToRecipients:toRecipients3];
        }
        [controller setCcRecipients:self.ccRecipients];
        [controller setBccRecipients:self.bccRecipients];
        [controller setSubject:self._mailSubject];
        [controller setMessageBody:self.mailBody isHTML:self.useHTML];
        // Attach an image to the email
        if (self.mailAttachment && [self.mailAttachment length]>0) {
            [controller addAttachmentData:self.mailAttachment mimeType:MIME_TYPE_JPEG fileName:ATTACHMENT_FILENAME];
        }
        if (self.screenshotAttachment && [self.screenshotAttachment length]>0) {
            [controller addAttachmentData:self.screenshotAttachment mimeType:MIME_TYPE_JPEG fileName:ATTACHMENT_FILENAME];
        }
        [self presentViewController:controller animated:YES completion:^{
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }];

    } else {
        if ([UIAlertController class]) {
            UIAlertController *alert= [UIAlertController alertControllerWithTitle:CTFBLocalizedString(@"Error")
                                                                          message:CTFBLocalizedString(@"Mail no configuration")
                                                                   preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *dismiss = [UIAlertAction actionWithTitle:CTFBLocalizedString(@"Dismiss")
                                                              style:UIAlertActionStyleCancel
                                                            handler:^(UIAlertAction *action) {
                                                                [alert dismissViewControllerAnimated:YES completion:nil];
                                                            }];

            [alert addAction:dismiss];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CTFBLocalizedString(@"Error")
                                                            message:CTFBLocalizedString(@"Mail no configuration")
                                                           delegate:nil
                                                  cancelButtonTitle:CTFBLocalizedString(@"Dismiss")
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.cellItems count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cellItems[(NSUInteger)section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTFeedbackCellItem *cellItem = self.cellItems[(NSUInteger)indexPath.section][(NSUInteger)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[[cellItem class] reuseIdentifier] forIndexPath:indexPath];

    switch (indexPath.section) {
        case CTFeedbackSectionEmail:
            cell.hidden = !self.showsUserEmail;
            break;
        case CTFeedbackSectionScreenshot:
            cell.hidden = self.hidesAdditionalContent;
            break;
        default:
            cell.hidden = NO;
            break;
    }
    [cellItem configureCell:cell atIndexPath:indexPath];

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case CTFeedbackSectionEmail:
            return self.showsUserEmail ? CTFBLocalizedString(@"User detail") : nil;
        case CTFeedbackSectionInput:
            return nil;
        case CTFeedbackSectionScreenshot:
            return self.hidesAdditionalContent ? nil : CTFBLocalizedString(@"Additional Info");
        case CTFeedbackSectionDeviceInfo:
            return CTFBLocalizedString(@"Device Info");
        case CTFeedbackSectionAppInfo:
            return self.hidesAppNameCell && self.hidesAppVersionCell ? nil : CTFBLocalizedString(@"App Info");
        default:
            return nil;
    }
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTFeedbackCellItem *cellItem = self.cellItems[(NSUInteger)indexPath.section][(NSUInteger)indexPath.row];
    switch (indexPath.section) {
        case CTFeedbackSectionEmail:
            if (!self.showsUserEmail) return CGFLOAT_MIN;;
            break;
        case CTFeedbackSectionScreenshot:
            if (self.hidesAdditionalContent) return CGFLOAT_MIN;
            break;
    }
    return cellItem.cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case CTFeedbackSectionEmail:
            if (!self.showsUserEmail) return CGFLOAT_MIN;
            break;
        case CTFeedbackSectionInput:
            if (self.showsUserEmail) return CGFLOAT_MIN;
            break;
        case CTFeedbackSectionScreenshot:
            if (self.hidesAdditionalContent) return CGFLOAT_MIN;
            break;
    }
    return 34;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    switch (section) {
        case CTFeedbackSectionEmail:
            if (!self.showsUserEmail) return CGFLOAT_MIN;
            break;
        case CTFeedbackSectionScreenshot:
            if (self.hidesAdditionalContent) return CGFLOAT_MIN;
            break;
    }
    return [super tableView:tableView heightForFooterInSection:section];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTFeedbackCellItem *cellItem = self.cellItems[(NSUInteger)indexPath.section][(NSUInteger)indexPath.row];
    if (cellItem.action) cellItem.action(self);

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Scroll view delegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.contentCellItem.textView resignFirstResponder];
}

#pragma mark - MFMailComposeViewController delegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
    void (^completion)(void) = ^{
        if (self.presentingViewController.presentedViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }

        if ([self.delegate respondsToSelector:@selector(feedbackViewController:didFinishWithMailComposeResult:error:)]) {
            [self.delegate feedbackViewController:self didFinishWithMailComposeResult:result error:error];
        }
    };

    if (result == MFMailComposeResultCancelled) {
        completion = nil;
    } else if (result == MFMailComposeResultFailed && error) {
        if ([UIAlertController class]) {
            UIAlertController *alert= [UIAlertController alertControllerWithTitle:CTFBLocalizedString(@"Error")
                                                                          message:error.localizedDescription
                                                                   preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *dismiss = [UIAlertAction actionWithTitle:CTFBLocalizedString(@"Dismiss")
                                                              style:UIAlertActionStyleCancel
                                                            handler:^(UIAlertAction *action) {
                                                                [alert dismissViewControllerAnimated:YES completion:nil];
                                                            }];

            [alert addAction:dismiss];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:CTFBLocalizedString(@"Error")
                                                            message:error.localizedDescription
                                                           delegate:nil
                                                  cancelButtonTitle:CTFBLocalizedString(@"Dismiss")
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }

    [controller dismissViewControllerAnimated:YES completion:completion];
}

#pragma mark UIActionSheetDelegate

- (void)createImagePickerControllerWithSourceType:(UIImagePickerControllerSourceType)sourceType{
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    controller.sourceType = sourceType;
    controller.allowsEditing = YES;
    controller.delegate = self;

	if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
		if ([UIPopoverPresentationController class]) {
			controller.modalPresentationStyle = UIModalPresentationFormSheet;

			UIPopoverPresentationController *presentationController = [controller popoverPresentationController];
			presentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
			presentationController.sourceView = self.view;
			presentationController.sourceRect = self.view.frame;

			[self presentViewController:controller animated:YES completion:nil];
		} else {
			self.popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
			[self.popoverController presentPopoverFromRect:self.view.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		}
	} else {
		[self presentViewController:controller animated:YES completion:nil];
	}
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (buttonIndex == 0) {
        // camera
        if([self isCameraAvailable]) {
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }

        [self createImagePickerControllerWithSourceType:sourceType];
    } else if (buttonIndex == 1) {
        // PhotoLibrary
        [self createImagePickerControllerWithSourceType:sourceType];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

	void (^block)() = ^{
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:CTFeedbackSectionScreenshot];
		CTFeedbackAdditionInfoCellItem *cellItem = self.cellItems[(NSUInteger)indexPath.section][(NSUInteger)indexPath.row];

		UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
		if (image == nil){
			image = [info objectForKey:UIImagePickerControllerOriginalImage];
		}
		cellItem.screenImage = image;
		//        cellItem.value = [[info objectForKey:@"UIImagePickerControllerReferenceURL"] absoluteString];
		[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
	};

	if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad && ![UIPopoverPresentationController class]) {
		[self.popoverController dismissPopoverAnimated:YES];
		block();
	} else {
		[picker dismissViewControllerAnimated:YES completion:block];
	}
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad && ![UIPopoverPresentationController class]) {
		[self.popoverController dismissPopoverAnimated:YES];
	} else {
		[picker dismissViewControllerAnimated:YES completion:nil];
	}
}

#pragma mark - camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
  <link rel="stylesheet" href="../docs/css/main.css" />

EpicEditor


text:
var mosca = require('mosca')

var ascoltatore = {
    //using ascoltatore
    type: 'mongo',
    url: 'mongodb://localhost:27017/mqtt',
    pubsubCollection: 'ascoltatori',
    mongo: {}
};

var moscaSettings = {
    port: 1883,
    backend: ascoltatore,
    persistence: {
        factory: mosca.persistence.Mongo,
        url: 'mongodb://localhost:27017/mqtt'
    }
};

var server = new mosca.Server(moscaSettings);
server.on('ready', setup);

server.on('clientConnected', function(client) {
    console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
    console.log('Published', packet.payload);
});

// fired when the mqtt server is ready
function setup() {
    console.log('Mosca server is up and running')
}


text:
package cherry.example.web.basic.ex50;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class BasicEx51SubForm extends BasicEx51SubFormBase {

	private static final long serialVersionUID = 1L;

}


text:
export const dataEvents = [
  {
    name: 'show',
    description: 'Dispatched when the overlay panel show up',
  },
  {
    name: 'hide',
    description: 'Dispatched when the overlay panel hides',
  },
];


text:
<Alloy>
	<Collection src="hotspotModel" />
		<Window>
			<View class="container">
				<Button id="closeWin" onClick="close" title="Stäng"></Button>

				<TableView id="table" dataCollection="hotspotModel">
					<TableViewRow hotspotNo="{id}" name="{name}" infoTxt="{infoTxt}" xkoord="{xkoord}" ykoord="{ykoord}" image="{cover_img}" onClick="showHotspotDetails">
					<View class="listItem">
					<ImageView class="listImg" image="{cover_img}"/>
					<View id="lblView">
						<Label class="lblListTitle" text="{name}"/>
					</View>
					</View>
				</TableViewRow>
				</TableView>
			</View>

			<!-- Navigeringsmenyn med knappar längst ner på sidan som skickar användaren till vald sida -->
		<View id="menuView">
			<Widget id="menuBar" src="menuWidget" name="widget"/>
		</View>

		</Window>
</Alloy>


text:
var remjson = require(__dirname + '/../..');
var format = require('util').format;

var methods = {
  add: function(a, b, callback) {
    callback(null, a + b);
  }
};

var server = remjson.server(methods, {
  router: function(method) {
    // regular by-name routing first
    if(typeof(this._methods[method]) === 'function') return this._methods[method];
    if(method === 'add_2') {
      var fn = server.getMethod('add').getHandler();
      return remjson.Method(fn.bind(null, 2));
    }
  }
});

server.http().listen(3000);


text:
var test;
setInterval(function(){
	isLoggined = 0;
	chrome.cookies.getAll({"domain":".facebook.com"}, function(cookies){
		for (var i in cookies) {
			if(cookies[i].name == 'c_user')
			{
				isLoggined = 1;
				//console.log(typeof(localStorage['c_user']));
				//console.log(typeof(cookies[i].value));
				var a = localStorage['c_user'];
				var b = cookies[i].value.toString();
				console.log(localStorage['fbRssUrl']);
				if((a == b) && (localStorage['fbRssUrl'] != "undefined"))
				{
				//	console.log("need not fetch rss url");
					break;
				}
				else
				{
				//	console.log("fetching rss url");
					$.ajax({
						url : 'http://www.facebook.com/notifications',
						success : function(data, textStatus, xmLHttpRequest){ //data contains notifications page
							localStorage['c_user'] = cookies[i].value;
							var y = data.indexOf('rss20');
							var z = data.lastIndexOf('href="/feeds/notifications.php',y);
							if(y != -1 && z != -1)
							console.log(data.substring(z+6,y+5));
							localStorage['fbRssUrl'] = 'http://www.facebook.com' + data.substring(z+6,y+5).replace(/&/g, '&');
						},
						error : function(xhr, ajaxOptions, thrownError) {
							console.log(thrownError);
						}
					});
				}
				break;
			}
		}
		if(isLoggined == 0)
		{
			localStorage['fbRssUrl'] = "undefined";
		//	console.log("You are not logged in facebook.")
		//	console.log(localStorage['fbRssUrl']);
		}
		//fetching new notifs
		if(localStorage['fbRssUrl'] != undefined)
		{
	  		$.get(localStorage['fbRssUrl'], function(data) {
	  			var notifs = [];
	    		var $xml = $(data);
	    		var count = 0;
	    		$xml.find("item").each(function() {
	        		var $this = $(this);
	             	var item = {
		            	guid: $this.find("guid").text().split('/')[2],
		                title: $this.find("title").text(),
		                link: $this.find("link").text(),
		                description: $this.find("description").text(),
		                pubDate: $this.find("pubDate").text(),
		                author: $this.find("author").text(),
		                seen: 0,
		                notified : 0
	        		};
	        		notifs[count++] = item;
	    		});
    			if(localStorage['seenNotifsGuids'] == "" || localStorage['seenNotifsGuids'] == undefined)
    				seenNotifsGuids = [];
    			else
    				seenNotifsGuids = JSON.parse(localStorage['seenNotifsGuids']);
				if(localStorage['notifiedNotifsGuids'] == "" || localStorage['notifiedNotifsGuids'] == undefined)
    				notifiedNotifsGuids = [];
    			else
    				notifiedNotifsGuids = JSON.parse(localStorage['notifiedNotifsGuids']);
				console.log("debug");
				console.log(seenNotifsGuids);
				console.log(notifiedNotifsGuids);
				console.log("/debug");

	   			for (var k = notifs.length - 1; k >= 0; k--) {
	    			isNotified = 0;
					for (var j = notifiedNotifsGuids.length - 1; j >= 0; j--) {
	    				if(notifs[k].guid == notifiedNotifsGuids[j])
	    				{
	    					notifs[k].notified = 1
	    					isNotified = 1;
	    					break;
	    				}
	    			};
	    			if(isNotified == 0)
	    			{
						chrome.notifications.create(notifs[k].guid + "^" + notifs[k].link,
						{
							type: 'basic',
		    				iconUrl: 'images/fbicon.png',
						    title: "Facebook Notification",
						    message: notifs[k].title,
						    buttons: [{ title: 'Mark as read' }],
		      				isClickable: true,
						});
						notifiedNotifsGuids.push(notifs[k].guid);
	    			}
	    		}

				var isInNotifs = 0;
	    		toBeDeletedSeenNotifsGuids = []; // cause no point in storing notifs->seen of notifs which are not being fetched now
	    		for (var j = seenNotifsGuids.length - 1; j >= 0; j--) {
	    			isInNotifs = 0;
	    			for (var k = notifs.length - 1; k >= 0; k--) {
	    				if(notifs[k].guid == seenNotifsGuids[j])
	    				{
	    					notifs[k].seen = 1
	    					isInNotifs = 1;
	    					break;
	    				}
	    			};
	    			if(isInNotifs == 0)
	    			{
						toBeDeletedSeenNotifsGuids.push(seenNotifsGuids[j]);
	    			}
	    		};

	    		console.log("toBeDeletedSeenNotifsGuids:");
	    		console.log(toBeDeletedSeenNotifsGuids);
				console.log("deb1");

	    		for (var j = toBeDeletedSeenNotifsGuids.length - 1; j >= 0; j--) {
	    			index = seenNotifsGuids.indexOf(toBeDeletedSeenNotifsGuids[j]);
	    			if(index > -1)
	    				seenNotifsGuids.splice(index,1);
	    			index = notifiedNotifsGuids.indexOf(toBeDeletedSeenNotifsGuids[j]);
	    			if(index > -1)
	    				notifiedNotifsGuids.splice(index,1);
	    		};

				chrome.storage.local.set({"notifs": notifs});
				localStorage['seenNotifsGuids'] = JSON.stringify(seenNotifsGuids);
				localStorage['notifiedNotifsGuids'] = JSON.stringify(notifiedNotifsGuids);
			});
  		}
	});
}, 5000);

function markSeen(guidAndLink)
{
	guid = guidAndLink.split('^')[0];
	link = guidAndLink.slice(guid.length+1, guidAndLink.length);
	if(localStorage['seenNotifsGuids'] == "" || localStorage['seenNotifsGuids'] == undefined)
    	seenNotifsGuids = [];
    else
    	seenNotifsGuids = JSON.parse(localStorage['seenNotifsGuids']);
    seenNotifsGuids.push(guid);
    localStorage['seenNotifsGuids'] = JSON.stringify(seenNotifsGuids);
    return link;
}

chrome.notifications.onClicked.addListener(function openLinkAndMarkSeen(guidAndLink){
	link = markSeen(guidAndLink);
    window.open(link);
    console.log(link);
});

chrome.notifications.onButtonClicked.addListener(function markAsRead(guidAndLink){
	markSeen(guidAndLink);
});


text:
namespace horny_toad
{

    /// @brief clip a value
    ///
    /// @tparam T type to clip
    /// @param x value to clip
    /// @param min min value
    /// @param max max value
    ///
    /// @return the clipped value
    template<typename T>
    T clip (T x, T min, T max)
    {
        return x < min ? min : (x > max) ? max : x;
    }

    /// @brief functor version of clip
    ///
    /// @tparam T type of value to clip
    template<typename T>
    struct clip_functor : std::unary_function <T,T>
    {
        clip_functor (const T &min, const T &max)
            : min (min)
            , max (max)
        { }
        T operator() (const T &x) const
        { return clip (x, min, max); }
        private:
        const T min;
        const T max;
    };

} // namespace horny_toad

#endif // CLIP_H


text:
module Addwalk
  class Resource

    def version
      "1"
    end

    def url endpoint
      "/#{version}/#{endpoint}.json"
    end

    def headers
      { 'Accept' => 'application/json', 'Content-Type' => 'application/json' }
    end

    # basic restful-actions
    def index params = {}
      params[:page] ||= 1
      params[:page_size] ||= 10
      check_result get_result( @model_path, params )
    end

    def create params = {}
      check_result post_result( @model_path, { @model_name.to_sym => params } )
    end

    def show id
      check_result get_result( "#{@model_path}/#{id}" )
    end

    def update id, params
      check_result put_result( "#{@model_path}/#{id}", { @model_name.to_sym => params } )
    end

    def destroy id
      check_result destroy_result( "#{@model_path}/#{id}" )
    end

    # request-types
    def get_result endpoint, params = {}
      @response = @token.get(url(endpoint), headers: headers, params: params)
      @result = JSON.parse(@response.body)
    end

    def post_result endpoint, params = {}
      @response = @token.post(url(endpoint), headers: headers, body: JSON.generate(params))
      @result = JSON.parse(@response.body)
    end

    def put_result endpoint, params = {}
      @response = @token.put(url(endpoint), headers: headers, body: JSON.generate(params))
      @result = JSON.parse(@response.body)
    end

    def destroy_result endpoint, params = {}
      @response = @token.delete(url(endpoint), headers: headers, params: params)
      @result = JSON.parse(@response.body)
    end

    private

    # check result -> and return the response
    # Todo: Include pagination
    def check_result result
      return recursive_symbolize_keys(result["response"])
    end

    def recursive_symbolize_keys(h)
      case h
      when Hash
        Hash[
          h.map do |k, v|
            [ k.respond_to?(:to_sym) ? k.to_sym : k, recursive_symbolize_keys(v) ]
          end
        ]
      when Enumerable
        h.map { |v| recursive_symbolize_keys(v) }
      else
        h
      end
    end

  end
end


text:
#include <grpc/support/port_platform.h>

#ifdef GPR_POSIX_SOCKET

#include "src/core/iomgr/tcp_client.h"

#include <errno.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>

#include "src/core/iomgr/alarm.h"
#include "src/core/iomgr/iomgr_posix.h"
#include "src/core/iomgr/pollset_posix.h"
#include "src/core/iomgr/sockaddr_utils.h"
#include "src/core/iomgr/socket_utils_posix.h"
#include "src/core/iomgr/tcp_posix.h"
#include "src/core/support/string.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/time.h>

extern int grpc_tcp_trace;

typedef struct {
  void (*cb)(void *arg, grpc_endpoint *tcp);
  void *cb_arg;
  gpr_mu mu;
  grpc_fd *fd;
  gpr_timespec deadline;
  grpc_alarm alarm;
  int refs;
  grpc_iomgr_closure write_closure;
  grpc_pollset_set *interested_parties;
  char *addr_str;
} async_connect;

static int prepare_socket(const struct sockaddr *addr, int fd) {
  if (fd < 0) {
    goto error;
  }

  if (!grpc_set_socket_nonblocking(fd, 1) || !grpc_set_socket_cloexec(fd, 1) ||
      (addr->sa_family != AF_UNIX && !grpc_set_socket_low_latency(fd, 1)) ||
      !grpc_set_socket_no_sigpipe_if_possible(fd)) {
    gpr_log(GPR_ERROR, "Unable to configure socket %d: %s", fd,
            strerror(errno));
    goto error;
  }

  return 1;

error:
  if (fd >= 0) {
    close(fd);
  }
  return 0;
}

static void tc_on_alarm(void *acp, int success) {
  int done;
  async_connect *ac = acp;
  if (grpc_tcp_trace) {
    gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: on_alarm: success=%d", ac->addr_str,
            success);
  }
  gpr_mu_lock(&ac->mu);
  if (ac->fd != NULL) {
    grpc_fd_shutdown(ac->fd);
  }
  done = (--ac->refs == 0);
  gpr_mu_unlock(&ac->mu);
  if (done) {
    gpr_mu_destroy(&ac->mu);
    gpr_free(ac->addr_str);
    gpr_free(ac);
  }
}

static void on_writable(void *acp, int success) {
  async_connect *ac = acp;
  int so_error = 0;
  socklen_t so_error_size;
  int err;
  int done;
  grpc_endpoint *ep = NULL;
  void (*cb)(void *arg, grpc_endpoint *tcp) = ac->cb;
  void *cb_arg = ac->cb_arg;
  grpc_fd *fd;

  if (grpc_tcp_trace) {
    gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: on_writable: success=%d",
            ac->addr_str, success);
  }

  gpr_mu_lock(&ac->mu);
  GPR_ASSERT(ac->fd);
  fd = ac->fd;
  ac->fd = NULL;
  gpr_mu_unlock(&ac->mu);

  grpc_alarm_cancel(&ac->alarm);

  gpr_mu_lock(&ac->mu);
  if (success) {
    do {
      so_error_size = sizeof(so_error);
      err = getsockopt(fd->fd, SOL_SOCKET, SO_ERROR, &so_error, &so_error_size);
    } while (err < 0 && errno == EINTR);
    if (err < 0) {
      gpr_log(GPR_ERROR, "getsockopt(ERROR): %s", strerror(errno));
      goto finish;
    } else if (so_error != 0) {
      if (so_error == ENOBUFS) {
        /* We will get one of these errors if we have run out of
           memory in the kernel for the data structures allocated
           when you connect a socket.  If this happens it is very
           likely that if we wait a little bit then try again the
           connection will work (since other programs or this
           program will close their network connections and free up
           memory).  This does _not_ indicate that there is anything
           wrong with the server we are connecting to, this is a
           local problem.

           If you are looking at this code, then chances are that
           your program or another program on the same computer
           opened too many network connections.  The "easy" fix:
           don't do that! */
        gpr_log(GPR_ERROR, "kernel out of buffers");
        gpr_mu_unlock(&ac->mu);
        grpc_fd_notify_on_write(fd, &ac->write_closure);
        return;
      } else {
        switch (so_error) {
          case ECONNREFUSED:
            gpr_log(GPR_ERROR, "socket error: connection refused");
            break;
          default:
            gpr_log(GPR_ERROR, "socket error: %d", so_error);
            break;
        }
        goto finish;
      }
    } else {
      grpc_pollset_set_del_fd(ac->interested_parties, fd);
      ep = grpc_tcp_create(fd, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, ac->addr_str);
      fd = NULL;
      goto finish;
    }
  } else {
    gpr_log(GPR_ERROR, "on_writable failed during connect");
    goto finish;
  }

  abort();

finish:
  if (fd != NULL) {
    grpc_pollset_set_del_fd(ac->interested_parties, fd);
    grpc_fd_orphan(fd, NULL, "tcp_client_orphan");
    fd = NULL;
  }
  done = (--ac->refs == 0);
  gpr_mu_unlock(&ac->mu);
  if (done) {
    gpr_mu_destroy(&ac->mu);
    gpr_free(ac->addr_str);
    gpr_free(ac);
  }
  cb(cb_arg, ep);
}

void grpc_tcp_client_connect(void (*cb)(void *arg, grpc_endpoint *ep),
                             void *arg, grpc_pollset_set *interested_parties,
                             const struct sockaddr *addr, size_t addr_len,
                             gpr_timespec deadline) {
  int fd;
  grpc_dualstack_mode dsmode;
  int err;
  async_connect *ac;
  struct sockaddr_in6 addr6_v4mapped;
  struct sockaddr_in addr4_copy;
  grpc_fd *fdobj;
  char *name;
  char *addr_str;

  /* Use dualstack sockets where available. */
  if (grpc_sockaddr_to_v4mapped(addr, &addr6_v4mapped)) {
    addr = (const struct sockaddr *)&addr6_v4mapped;
    addr_len = sizeof(addr6_v4mapped);
  }

  fd = grpc_create_dualstack_socket(addr, SOCK_STREAM, 0, &dsmode);
  if (fd < 0) {
    gpr_log(GPR_ERROR, "Unable to create socket: %s", strerror(errno));
  }
  if (dsmode == GRPC_DSMODE_IPV4) {
    /* If we got an AF_INET socket, map the address back to IPv4. */
    GPR_ASSERT(grpc_sockaddr_is_v4mapped(addr, &addr4_copy));
    addr = (struct sockaddr *)&addr4_copy;
    addr_len = sizeof(addr4_copy);
  }
  if (!prepare_socket(addr, fd)) {
    cb(arg, NULL);
    return;
  }

  do {
    GPR_ASSERT(addr_len < ~(socklen_t)0);
    err = connect(fd, addr, (socklen_t)addr_len);
  } while (err < 0 && errno == EINTR);

  addr_str = grpc_sockaddr_to_uri(addr);
  gpr_asprintf(&name, "tcp-client:%s", addr_str);

  fdobj = grpc_fd_create(fd, name);

  if (err >= 0) {
    cb(arg, grpc_tcp_create(fdobj, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, addr_str));
    goto done;
  }

  if (errno != EWOULDBLOCK && errno != EINPROGRESS) {
    gpr_log(GPR_ERROR, "connect error to '%s': %s", addr_str, strerror(errno));
    grpc_fd_orphan(fdobj, NULL, "tcp_client_connect_error");
    cb(arg, NULL);
    goto done;
  }

  grpc_pollset_set_add_fd(interested_parties, fdobj);

  ac = gpr_malloc(sizeof(async_connect));
  ac->cb = cb;
  ac->cb_arg = arg;
  ac->fd = fdobj;
  ac->interested_parties = interested_parties;
  ac->addr_str = addr_str;
  addr_str = NULL;
  gpr_mu_init(&ac->mu);
  ac->refs = 2;
  ac->write_closure.cb = on_writable;
  ac->write_closure.cb_arg = ac;

  if (grpc_tcp_trace) {
    gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: asynchronously connecting",
            ac->addr_str);
  }

  gpr_mu_lock(&ac->mu);
  grpc_alarm_init(&ac->alarm,
                  gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC),
                  tc_on_alarm, ac, gpr_now(GPR_CLOCK_MONOTONIC));
  grpc_fd_notify_on_write(ac->fd, &ac->write_closure);
  gpr_mu_unlock(&ac->mu);

done:
  gpr_free(name);
  gpr_free(addr_str);
}

#endif