text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/search_result_item_cardview"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:layout_marginStart="@dimen/cardview_margin"
    android:layout_marginEnd="@dimen/cardview_margin"
    android:layout_marginTop="@dimen/cardview_margin"
    app:cardCornerRadius="8dp"
    app:cardElevation="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="72dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/search_result_item_image"
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:src="@drawable/example_avatar"/>

        <TextView
            android:id="@+id/search_result_item_text"
            android:layout_width="match_parent"
            android:layout_height="72dp"
            android:paddingStart="16dp"
            android:paddingEnd="16dp"
            android:maxLines="1"
            android:ellipsize="end"
            android:gravity="center_vertical"
            android:textSize="@dimen/search_result_item_font_size"
            android:textStyle="bold"
            android:text="charliealbright"/>

    </LinearLayout>

</android.support.v7.widget.CardView>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <import type="android.view.View" />

        <import type="com.adgvcxz.recyclerviewmodel.LoadingItemViewModel"/>

        <variable
            name="model"
            type="LoadingItemViewModel.Model" />

    </data>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="48dp">

        <ProgressBar
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_centerInParent="true"
            android:visibility="@{model.state != LoadingItemViewModel.State.failure ? View.VISIBLE : View.GONE}" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="加载失败 点击重试"
            android:visibility="@{model.state == LoadingItemViewModel.State.failure ? View.VISIBLE : View.GONE}" />

    </RelativeLayout>
</layout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <dependencies>
        <dependency>
            <groupId>sk.homisolutions.shotbox</groupId>
            <artifactId>ShotBoxToolsSet</artifactId>
            <version>0.1.0-Developing</version>
        </dependency>
    </dependencies>

    <parent>
        <groupId>sk.homisolutions.shotbox</groupId>
        <artifactId>ShotBoxProject</artifactId>
        <version>0.1.0-Developing</version>
    </parent>

    <packaging>jar</packaging>
    <artifactId>SNEM_SceneController_Testing_MockedController</artifactId>

</project>


text:
<?php

namespace JMS\I18nRoutingBundle\Router;

use Symfony\Component\HttpFoundation\Request;

/**
 * Interface for Locale Resolvers.
 *
 * A resolver implementation is triggered only if we match a route that is
 * available for multiple locales.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
interface LocaleResolverInterface
{
    /**
     * Resolves the locale in case a route is available for multiple locales.
     *
     * @param array $availableLocales
     *
     * @return string|null may return null if no suitable locale is found, may also
     *                        return a locale which is not available for the matched route
     */
    function resolveLocale(Request $request, array $availableLocales);
}


text:
<?php

namespace WebUIStats\Generator;

use Symfony\Component\Yaml\Yaml;

class Config
{
    static public function loadConfig($yml_config_file)
    {
        $config = Yaml::parse($yml_config_file);
        $config['output_path'] = realpath(dirname($yml_config_file)) . '/' . $config['output_path'];

        $screens = array();
        self::configExtractCharts($config, $screens);

        // load charts yml files
        $config_screens = array();
        foreach ($screens as $chart_file)
        {
            $config_screens[$chart_file] = Yaml::parse(realpath(dirname($yml_config_file)) . '/' . Config::filterJs($chart_file) . '.yml');
        }

        return array(
            'app' => $config,
            'screens' => $config_screens);
    }

    static protected function configExtractCharts($array, &$result)
    {
        foreach ($array as $key => $item)
        {
            if (is_array($item)) $r = self::configExtractCharts($item, $result);
            if ($key == 'screen') $result[] = $item;
        }
    }

    static public function filterJs($text)
    {
        return preg_replace('/[^ a-zA-Z0-9]/', '_', $text);
    }

}


text:
* Performance improvements for `SourceMapGenerator` and `SourceNode`. See issue
  #148 for some discussion and issues #150, #151, and #152 for implementations.

## 0.1.42

* Fix an issue where `SourceNode`s from different versions of the source-map
  library couldn't be used in conjunction with each other. See issue #142.

## 0.1.41

* Fix a bug with getting the source content of relative sources with a "./"
  prefix. See issue #145 and [Bug 1090768](bugzil.la/1090768).

* Add the `SourceMapConsumer.prototype.computeColumnSpans` method to compute the
  column span of each mapping.

* Add the `SourceMapConsumer.prototype.allGeneratedPositionsFor` method to find
  all generated positions associated with a given original source and line.

## 0.1.40

* Performance improvements for parsing source maps in SourceMapConsumer.

## 0.1.39

* Fix a bug where setting a source's contents to null before any source content
  had been set before threw a TypeError. See issue #131.

## 0.1.38

* Fix a bug where finding relative paths from an empty path were creating
  absolute paths. See issue #129.

## 0.1.37

* Fix a bug where if the source root was an empty string, relative source paths
  would turn into absolute source paths. Issue #124.

## 0.1.36

* Allow the `names` mapping property to be an empty string. Issue #121.

## 0.1.35

* A third optional parameter was added to `SourceNode.fromStringWithSourceMap`
  to specify a path that relative sources in the second parameter should be
  relative to. Issue #105.

* If no file property is given to a `SourceMapGenerator`, then the resulting
  source map will no longer have a `null` file property. The property will
  simply not exist. Issue #104.

* Fixed a bug where consecutive newlines were ignored in `SourceNode`s.
  Issue #116.

## 0.1.34

* Make `SourceNode` work with windows style ("\r\n") newlines. Issue #103.

* Fix bug involving source contents and the
  `SourceMapGenerator.prototype.applySourceMap`. Issue #100.

## 0.1.33

* Fix some edge cases surrounding path joining and URL resolution.

* Add a third parameter for relative path to
  `SourceMapGenerator.prototype.applySourceMap`.

* Fix issues with mappings and EOLs.

## 0.1.32

* Fixed a bug where SourceMapConsumer couldn't handle negative relative columns
  (issue 92).

* Fixed test runner to actually report number of failed tests as its process
  exit code.

* Fixed a typo when reporting bad mappings (issue 87).

## 0.1.31

* Delay parsing the mappings in SourceMapConsumer until queried for a source
  location.

* Support Sass source maps (which at the time of writing deviate from the spec
  in small ways) in SourceMapConsumer.

## 0.1.30

* Do not join source root with a source, when the source is a data URI.

* Extend the test runner to allow running single specific test files at a time.

* Performance improvements in `SourceNode.prototype.walk` and
  `SourceMapConsumer.prototype.eachMapping`.

* Source map browser builds will now work inside Workers.

* Better error messages when attempting to add an invalid mapping to a
  `SourceMapGenerator`.

## 0.1.29

* Allow duplicate entries in the `names` and `sources` arrays of source maps
  (usually from TypeScript) we are parsing. Fixes github issue 72.

## 0.1.28

* Skip duplicate mappings when creating source maps from SourceNode; github
  issue 75.

## 0.1.27

* Don't throw an error when the `file` property is missing in SourceMapConsumer,
  we don't use it anyway.

## 0.1.26

* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70.

## 0.1.25

* Make compatible with browserify

## 0.1.24

* Fix issue with absolute paths and `file://` URIs. See
  https://bugzilla.mozilla.org/show_bug.cgi?id=885597

## 0.1.23

* Fix issue with absolute paths and sourcesContent, github issue 64.

## 0.1.22

* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21.

## 0.1.21

* Fixed handling of sources that start with a slash so that they are relative to
  the source root's host.

## 0.1.20

* Fixed github issue #43: absolute URLs aren't joined with the source root
  anymore.

## 0.1.19

* Using Travis CI to run tests.

## 0.1.18

* Fixed a bug in the handling of sourceRoot.

## 0.1.17

* Added SourceNode.fromStringWithSourceMap.

## 0.1.16

* Added missing documentation.

* Fixed the generating of empty mappings in SourceNode.

## 0.1.15

* Added SourceMapGenerator.applySourceMap.

## 0.1.14

* The sourceRoot is now handled consistently.

## 0.1.13

* Added SourceMapGenerator.fromSourceMap.

## 0.1.12

* SourceNode now generates empty mappings too.

## 0.1.11

* Added name support to SourceNode.

## 0.1.10

* Added sourcesContent support to the customer and generator.


text:
package org.bouncycastle.cms.jcajce;

import java.security.PrivateKey;

import javax.crypto.SecretKey;

import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.jcajce.DefaultJcaJceHelper;
import org.bouncycastle.operator.SymmetricKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper;
import org.bouncycastle.operator.jcajce.JceSymmetricKeyUnwrapper;

class DefaultJcaJceExtHelper
    extends DefaultJcaJceHelper
    implements JcaJceExtHelper
{
    public JceAsymmetricKeyUnwrapper createAsymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, PrivateKey keyEncryptionKey)
    {
        return new JceAsymmetricKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey);
    }

    public SymmetricKeyUnwrapper createSymmetricUnwrapper(AlgorithmIdentifier keyEncryptionAlgorithm, SecretKey keyEncryptionKey)
    {
        return new JceSymmetricKeyUnwrapper(keyEncryptionAlgorithm, keyEncryptionKey);
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemySpawnPointScript : MonoBehaviour {

	public List<GameObject> enemyTypes;
	public float spawnDelay;

	private int enemiesLeft;
	private int enemyCountToSpawn;
	private float nextSpawnTime;

	public int level {
		get { return GameManagerScript.gameManager.level; }
	}

	public bool done {
		get {return enemiesLeft <= 0;}
	}

	void Update () {
		if (enemyCountToSpawn > 0 && Time.time > nextSpawnTime) {
			SpawnEnemy();
			enemyCountToSpawn--;
			nextSpawnTime = Time.time + spawnDelay;
		}
	}

	private int levelAddition {
		get { return GameManagerScript.gameManager ? GameManagerScript.gameManager.GetDifficultyAddition() : 0; }
	}

	public void StartWave() {
		SetSpawnPointParams();
		nextSpawnTime = Time.time + spawnDelay;
		enemiesLeft = enemyCountToSpawn;
	}

	public void SpawnedEnemyDefeated() {
		enemiesLeft--;
	}

	public void SetSpawnPointParams() {

		if (level < 3) {
			spawnDelay = 5.0f;
			enemyCountToSpawn = 3;

			enemyTypes.Clear();
			enemyTypes.Add(EnemyPool.enemyPool.Org);
			enemyTypes.Add(EnemyPool.enemyPool.Specty);
			enemyTypes.Add(EnemyPool.enemyPool.Snell);

		} else if (level < 6) {
			spawnDelay = 4.0f;
			enemyCountToSpawn = 3;

			enemyTypes.Clear();
			enemyTypes.Add(EnemyPool.enemyPool.Org);
			enemyTypes.Add(EnemyPool.enemyPool.Specty);
			enemyTypes.Add(EnemyPool.enemyPool.Snell);

		} else if (level < 9) {
			spawnDelay = 3.0f;
			enemyCountToSpawn = 3;

			enemyTypes.Clear();
			enemyTypes.Add(EnemyPool.enemyPool.Org);
			enemyTypes.Add(EnemyPool.enemyPool.Specty);
			enemyTypes.Add(EnemyPool.enemyPool.Snell);
		} else if (level < 12) {
			spawnDelay = 2.0f;
			enemyCountToSpawn = 3;

			enemyTypes.Clear();
			enemyTypes.Add(EnemyPool.enemyPool.Org);
			enemyTypes.Add(EnemyPool.enemyPool.Specty);
			enemyTypes.Add(EnemyPool.enemyPool.Snell);
		} else if (level < 15) {
			spawnDelay = 1.0f;
			enemyCountToSpawn = 3;

			enemyTypes.Clear();
			enemyTypes.Add(EnemyPool.enemyPool.Org);
			enemyTypes.Add(EnemyPool.enemyPool.Specty);
			enemyTypes.Add(EnemyPool.enemyPool.Snell);
		} else {
			spawnDelay = 0.0f;
			enemyCountToSpawn = 3;

			enemyTypes.Clear();
			enemyTypes.Add(EnemyPool.enemyPool.Org);
			enemyTypes.Add(EnemyPool.enemyPool.Specty);
			enemyTypes.Add(EnemyPool.enemyPool.Snell);
		}
	}

	private void SpawnEnemy() {
		if (enemyTypes.Count > 0) {
			int index = Random.Range(0, enemyTypes.Count);
			GameObject newEnemy = Object.Instantiate(enemyTypes[index]);
			EnemyScript enemy = newEnemy.GetComponent<EnemyScript>();
			newEnemy.transform.position = this.transform.position;
			enemy.SetSpawnPoint(this);
			enemy.SetLevel(level + levelAddition);
		}
		else {
			SpawnedEnemyDefeated();
		}
	}
}


text:
module.exports = function(o) {
  this.add('role:testing, domain:values, cmd:createTestData', function(m, r) {
    console.log('creating test data');

    const seneca = this;

    function addDays(date, days) {
      date.setDate(date.getDate() + days);
      return date;
    }

    const currentYear = new Date().getFullYear();
    const currentYearStart = () => new Date(currentYear, 0, 1);
    const nextYearStart = () => new Date(currentYear + 1, 0, 1);

    for (var i = 1; i <= m.count; i++) {
      const instance = {
        date1: addDays(currentYearStart(), Math.floor(Math.random() * 364 + 1)),
        date2: addDays(nextYearStart(), Math.floor(Math.random() * 364 + 1)),
        int1: Math.floor(Math.random() * 100 + 1),
        int2: Math.floor(Math.random() * 100 + 1),
        string: 'Item ' + i
      };

      seneca.act(
        {
          role: 'entitiesCommand',
          domain: 'values',
          cmd: 'create',
          instance: instance
        },
        err => {
          if (err) r(err);
        }
      );
    }

    return r();
  });
};


text:
type Response = {
  requestId: number,
  result: unknown,
  error: Error|null,
};

type Event = {
  event: string,
};

type Message = MessageEvent<Response|Event>;

export class ExtensionEndpoint {
  private readonly port: MessagePort;
  private nextRequestId: number = 0;
  private pendingRequests: Map<number, {
    resolve: (arg: unknown) => void,
    reject: (error: Error) => void,
  }>;

  constructor(port: MessagePort) {
    this.port = port;
    this.port.onmessage = this.onResponse.bind(this);
    this.pendingRequests = new Map();
  }

  sendRequest<ReturnType>(method: string, parameters: unknown): Promise<ReturnType> {
    return new Promise((resolve, reject) => {
      const requestId = this.nextRequestId++;
      this.pendingRequests.set(requestId, {resolve: resolve as (arg: unknown) => void, reject});
      this.port.postMessage({requestId, method, parameters});
    });
  }

  protected disconnect(): void {
    for (const {reject} of this.pendingRequests.values()) {
      reject(new Error('Extension endpoint disconnected'));
    }
    this.pendingRequests.clear();
    this.port.close();
  }

  private onResponse({data}: Message): void {
    if ('event' in data) {
      this.handleEvent(data);
      return;
    }
    const {requestId, result, error} = data;
    const pendingRequest = this.pendingRequests.get(requestId);
    if (!pendingRequest) {
      console.error(`No pending request ${requestId}`);
      return;
    }
    this.pendingRequests.delete(requestId);
    if (error) {
      pendingRequest.reject(new Error(error.message));
    } else {
      pendingRequest.resolve(result);
    }
  }

  protected handleEvent(_event: Event): void {
    throw new Error('handleEvent is not implemented');
  }
}


text:
set -e

BASE_DIR=$(pwd)

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

if [[ -z "${GRADLE_TASK}" ]]; then
  echo "GRADLE_TASK must be set. exiting..."
  exit 1
fi

ROOT_DIR=$(pwd)
BUILD_DATE=$(date +%s)

DEFAULT_GRADLE_TASK_OPTIONS="--console=plain --no-daemon"

SSHKEY_FILE="instance-data/sshkey"
SSH_OPTIONS="-i ${SSHKEY_FILE} -o ConnectionAttempts=60 -o StrictHostKeyChecking=no"

INSTANCE_IP_ADDRESS="$(cat instance-data/instance-ip-address)"

SET_JAVA_HOME="export JAVA_HOME=/usr/lib/jvm/java-${JAVA_BUILD_VERSION}-openjdk-amd64"

GRADLE_COMMAND="./gradlew \
    ${DEFAULT_GRADLE_TASK_OPTIONS} \
    clean runAll"

echo "${GRADLE_COMMAND}"
ssh ${SSH_OPTIONS} geode@${INSTANCE_IP_ADDRESS} "mkdir -p tmp && cd geode && ${SET_JAVA_HOME} && ${GRADLE_COMMAND}"


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="sort-i18n.js" type="NodeJSConfigurationType" nameIsGenerated="true" path-to-js-file="sort-i18n.js" working-dir="$PROJECT_DIR$/embedded-apps/tools">
    <method v="2" />
  </configuration>
</component>


text:
package com.jaxsen.xianghacaipu.ui.cook.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jaxsen.xianghacaipu.R;
import com.jaxsen.xianghacaipu.R2;
import com.jaxsen.xianghacaipu.ui.cook.bean.JXMenuList;

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

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/4/10.
 */

public class JXMenuAdapter extends RecyclerView.Adapter<JXMenuAdapter.ViewHolder> {
    private Context mContext;
    private LayoutInflater inflater;
    private List<JXMenuList.DataBean.DishsBean> mData;

    public JXMenuAdapter(Context mContext, List<JXMenuList.DataBean.DishsBean> mData) {
        if (mData != null) {
            this.mData = mData;
        } else {
            this.mData = new ArrayList<>();
        }
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
    }

    public void updateDinner(List<JXMenuList.DataBean.DishsBean> mData) {
        if (mData != null) {
            this.mData.clear();
            this.mData.addAll(mData);
            notifyDataSetChanged();
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.item_jxmenu, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Glide.with(mContext).load(mData.get(position).getImg()).into(holder.image);
          int  isFine = mData.get(position).getIsFine();
        if (isFine==2) {
            holder.jh.setVisibility(View.VISIBLE);
        } else if (isFine==1) {
            holder.jh.setVisibility(View.GONE);
        }
        holder.name.setText(mData.get(position).getName());
        holder.allClick.setText(mData.get(position).getAllClick()+"浏览");
        holder.favorites.setText(mData.get(position).getFavorites()+"收藏");
        holder.nickName.setText(mData.get(position).getCustomer().getNickName());
    }

    @Override
    public int getItemCount() {
        return mData != null ? mData.size() : 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R2.id.item_jxmenu_dishs_image)
        ImageView image;
        @BindView(R2.id.item_jxmenu_dishs_jh)
        TextView jh;
        @BindView(R2.id.item_jxmenu_dishs_allClick)
        TextView allClick;
        @BindView(R2.id.item_jxmenu_dishs_favorites)
        TextView favorites;
        @BindView(R2.id.item_jxmenu_dishs_nickName)
        TextView nickName;
        @BindView(R2.id.item_jxmenu_dishs_name)
        TextView name;
        @BindView(R2.id.item_jxmenu_dishs_like)
        CheckBox like;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}


text:
package travel.izi.api.model.enumeration;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import java.util.HashMap;
import java.util.Map;

/**
 * Quiz types.
 */
public enum QuizType {

    /**
     * A form of quiz when the end-user is asked to select one answer from an answers list where
     * one answer is marked as correct.
     */
    Choice("choice"),

    /**
     * A form of quiz when the end-user is asked to enter answer and API client checks
     * correctness form the list of possible answers.
     */
    Enter("enter");

    private final String value;

    private QuizType(String value) {
        this.value = value;
    }

    @JsonValue
    @Override
    public String toString() {
        return this.value;
    }

    private static final Map<String, QuizType> STRING_MAPPING = new HashMap<>();

    static {
        for (QuizType via : QuizType.values()) {
            STRING_MAPPING.put(via.toString(), via);
        }
    }

    @SuppressWarnings("unused")
    @JsonCreator
    public static QuizType fromValue(String value) {
        return STRING_MAPPING.get(value);
    }

}


text:
namespace mozc {

class Mmap {
 public:
  Mmap();
  ~Mmap() { Close(); }

  bool Open(const char *filename, const char *mode = "r");
  void Close();

  // Following mlock/munlock related functions work based on target environment.
  // In the case of Android, Native Client, Windows, we don't want to call
  // actual functions, so these functions do nothing and return -1. In other
  // cases, these functions call actual mlock/munlock functions and return it's
  // result.
  // On Android, page-out is probably acceptable because
  // - Smaller RAM on the device.
  // - The storage is (usually) solid state thus page-in/out is expected to
  //   be faster.
  // On Linux, in the kernel version >= 2.6.9, user process can mlock. In older
  // kernel, it fails if the process is running in user priviledge.
  // TODO(team): Check in mac that mlock is really necessary.
  static int MaybeMLock(const void *addr, size_t len);
  static int MaybeMUnlock(const void *addr, size_t len);

#ifndef MOZC_USE_PEPPER_FILE_IO
  char &operator[](size_t n) { return *(text_ + n); }
  char operator[](size_t n) const { return *(text_ + n); }
  char *begin() { return text_; }
  const char *begin() const { return text_; }
  char *end() { return text_ + size_; }
  const char *end() const { return text_ + size_; }
#else  // MOZC_USE_PEPPER_FILE_IO
  char &operator[](size_t n) { return *(text_.get() + n); }
  char operator[](size_t n) const { return *(text_.get() + n); }
  char *begin() { return text_.get(); }
  const char *begin() const { return text_.get(); }
  char *end() { return text_.get() + size_; }
  const char *end() const { return text_.get() + size_; }
#endif  // MOZC_USE_PEPPER_FILE_IO

  size_t size() const { return size_; }

#ifdef MOZC_USE_PEPPER_FILE_IO
  // Save the data in memory to the file.
  bool SyncToFile();
#endif  // MOZC_USE_PEPPER_FILE_IO

 private:
#ifndef MOZC_USE_PEPPER_FILE_IO
  char *text_;
#else  // MOZC_USE_PEPPER_FILE_IO
  string filename_;
  std::unique_ptr<char[]> text_;
  bool write_mode_;
#endif  // MOZC_USE_PEPPER_FILE_IO
  size_t size_;

  DISALLOW_COPY_AND_ASSIGN(Mmap);
};

}  // namespace mozc

#endif  // MOZC_BASE_MMAP_H_


text:
package com.lee.democollection;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.widget.EditText;

import com.lee.democollection.service.MessengerService;
import com.lee.democollection.utils.LogUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by allen on 2017/5/14.
 */

public class MessengerActivity extends BaseActivity {

    @BindView(R.id.et_text)
    EditText etText;

    private Messenger serviceMessenger;

    private Messenger clientMessenger = new Messenger(new ClientHandler());

    private class ClientHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MessengerService.COMMAND_SEND_MESSAGE:
                    Bundle data = msg.getData();
                    LogUtils.e("收到服务端回执-->>" + data.getString("data"));
                    break;
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_messenger;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        bind();
    }

    private void bind(){
        bindService(new Intent(this, MessengerService.class), connection, Service.BIND_AUTO_CREATE);
    }

    @OnClick(R.id.btn_send)
    void clickSend(){
        if(serviceMessenger != null){
            Message msg = Message.obtain();
            msg.what = MessengerService.COMMAND_RECEIVE_MESSAGE;
            Bundle data = new Bundle();
            data.putString("data", etText.getText().toString().trim());
            msg.setData(data);
            msg.replyTo = clientMessenger;
            try {
                serviceMessenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unbindService(connection);
    }

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LogUtils.e("service connected");
            serviceMessenger = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.e("service disconnected");
            serviceMessenger = null;
        }
    };
}


text:
\documentclass[a4paper,11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage[affil-it]{authblk}
\usepackage{enumerate}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{hyperref}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{cancel}
\usepackage[usenames, dvipsnames]{color}
\usepackage{tikz}
\usepackage[labelfont=bf]{caption}
\usepackage{subcaption} %Multiple images
\usepackage{multicol} % Multiple columns
\usepackage{float}
\usepackage{cleveref}
\usepackage{relsize} % bigger math symbols
\usepackage[margin=1.1in]{geometry}
\usepackage[titletoc,toc,title]{appendix}
\usepackage{enumitem}
\usepackage{etoolbox}
\usepackage{mdframed} %frame theorems
\usetikzlibrary{calc}
\numberwithin{equation}{section}

% Footnotes with symbols

\makeatletter
\def\@fnsymbol#1{\ensuremath{\ifcase#1\or \dagger\or \ddagger\or
   \mathsection\or \mathparagraph\or \|\or **\or \dagger\dagger
   \or \ddagger\ddagger \else\@ctrerr\fi}}
\makeatother

\renewcommand{\thefootnote}{\fnsymbol{footnote}}

%Styling for code
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2
}

\lstset{style=mystyle}

% Cool letters
\input{Typocaps.fd}

% Footer
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\cfoot{\fontsize{15pt}{15pt}\usefont{U}{Typocaps}{xl}{n}
gigantium humeris insidentes}

% Big Pictures
\usepackage[export]{adjustbox}

% Enviroment for theorems
\newmdtheoremenv[frametitle=Teorema]{theo}{Theorem}

% Circled words
\newcommand{\circled}[2][]{%
  \tikz[baseline=(char.base)]{%
    \node[shape = circle, draw, inner sep = 1pt]
    (char) {\phantom{\ifblank{#1}{#2}{#1}}};%
    \node at (char.center) {\makebox[0pt][c]{#2}};}}
\robustify{\circled}

%Appendices in spanish
\renewcommand{\appendixname}{Ap\'endices}
\renewcommand{\appendixtocname}{Ap\'endices}
\renewcommand{\appendixpagename}{Ap\'endices}

%Zero delimiter
\newcommand{\zerodel}{.\kern-\nulldelimiterspace}

%Columns separation
\setlength{\columnsep}{1cm}

%Indentation
\setlength{\parindent}{0ex}

%Multiple References

\crefrangelabelformat{equation}{(#3#1#4--#5\crefstripprefix{#1}{#2}#6)}

\usepackage{xparse}

%Boxes

\newcommand*{\boxcolor}{blue}
\makeatletter
\renewcommand{\boxed}[1]{\textcolor{\boxcolor}{%
\tikz[baseline={([yshift=-1ex]current bounding box.center)}] \node [rectangle, minimum width=1ex,rounded corners,draw] {\normalcolor\m@th$\displaystyle#1$};}}
 \makeatother

%Constantes
\newcommand{\euler}{\mathrm{e}}
\newcommand{\im}{i}

%Lemas, teoremas, definiciones y pruebas
\newcommand{\definicion}{\textbf{Definición: }}
\newcommand{\lema}{\textbf{Lema: }}
\newcommand{\teorema}{\textbf{Teorema: }}
\newcommand{\prueba}{\textbf{Prueba: }}
\newcommand{\proposicion}{\textbf{Proposición: }}
\newcommand{\corolario}{\textbf{Corolario: }}

% Definición de las secciones y su numeración

\makeatletter
\def\@seccntformat#1{%
  \expandafter\ifx\csname c@#1\endcsname\c@section\else
  \csname the#1\endcsname\quad
  \fi}
\makeatother

\begin{document}

\begin{titlepage}
\thispagestyle{fancy}

\newcommand{\HRule}{\rule{\linewidth}{0.5mm}} % Defines a new command for the horizontal lines, change thickness here

\center % Center everything on the page

%----------------------------------------------------------------------------------------
%	HEADING SECTIONS
%----------------------------------------------------------------------------------------

\textsc{\LARGE Universidad Nacional Autónoma de México}\\[0.3cm] % Name of your university/college

%----------------------------------------------------------------------------------------
%	LOGO SECTION
%----------------------------------------------------------------------------------------

\includegraphics[scale=0.17]{unam}

%----------------------------------------------------------------------------------------
%	SUBHEADING SECTIONS
%----------------------------------------------------------------------------------------

\textsc{\Large Electrodinámica Clásica}\\[0.3cm] % Major heading such as course name
\textsc{\large Semestre 2016-II}\\[0.3cm] % Minor heading such as course title
\textsc{\large 7 de abril de 2016}\\ % Minor heading such as course title

%----------------------------------------------------------------------------------------
%	TITLE SECTION
%----------------------------------------------------------------------------------------

\HRule \\[0.1cm]
{ \huge \bfseries Tarea \# 7. \\ Ondas electromagnéticas, técnicas de medición y problemas avanzados.}\\ % Title of your document
\HRule \\[0.1cm]

%----------------------------------------------------------------------------------------
%	AUTHOR SECTION
%----------------------------------------------------------------------------------------
\setcounter{footnote}{0}
\center
\large
\emph{Autor:} \\ % Your name
\Large Favio \textsc{Vázquez}\footnote[1]{\href{mailto:favio.vazquez@correo.nucleares.unam.mx}{favio.vazquez@correo.nucleares.unam.mx}}
\\[0.7cm]
%----------------------------------------------------------------------------------------
%	COOL IMAGE SECTION
%----------------------------------------------------------------------------------------

\includegraphics[scale=0.37]{escherEncuentro}

%----------------------------------------------------------------------------------------

\vfill % Fill the rest of the page with whitespace

\end{titlepage}

% ---------------------------------------------------------------------------------------
%         HEADER
%----------------------------------------------------------------------------------------

\fancyhead[L]{Favio Vázquez}
\fancyhead[R]{\thepage}

%----------------------------------------------------------------------------------------
\setcounter{footnote}{0}
\renewcommand*{\thefootnote}{\arabic{footnote}}
%----------------------------------------------------------------------------------------

%----------------------------------------------------------------------------------------
%%			BEGIN DOCUMENT
%----------------------------------------------------------------------------------------

\section{Problema 1}

Explica en que consisten las siguientes técnicas para medir el índice de refracción complejo:

\begin{itemize}
 \item Elipsometría.
 \item Reflectancia, absorbancia y transmitancia.
 \item Técnica de Corbino.
 \item EELS (electron energy loss spectroscopy).
 \item REELS (reflection electron energy loss spectroscopy).
\end{itemize}

\vspace{.3cm}

\underline{Solución:} \vspace{.3cm}

\textbf{Elipsometría}: La elipsometría es una técnica que mide el cambio en los
estados de polarización de la luz reflejada en la superficie de una muestra. Los
valores medidos son expresados como $\Psi$ y $\Delta$. Estos valores están relacionados
con la tasa de los coeficientes de reflexión de Fresnel, $R_P$ y $R_S$ para la
luz polarizada de tipo $P$ y $S$ respectivamente, y esta relación se expresa
en la siguiente ecuación

\begin{equation}
 \tan{\Psi} \euler^{i\Delta} = \frac{R_P}{R_S}.
\end{equation}

Debido a que la elipsometría mide la tasa de los dos valores, puede ser altamente
precisa y muy reproducible. De la ecuación anterior vemos que la tasa es un
número complejo, por lo que contiene la información de la fase contenida en $\Delta$,
que hace que la medición sea muy sensible.

\vspace{.3cm}

\textbf{Reflectancia, absorbancia y transmitancia}: La reflectancia $\rho$ está definida
por la tasa de potencia radiante reflejada a la potencia radiante incidente. Para
un cierto elemento de área $dA$ de la superficie reflectante, la potencia
radiante incidente diferencial está dada por la irradiancia de la superficie
$E_e$ multiplicada por la el tamaño del elemento de superficie, entonces

\begin{equation}
 dF_{e,\text{incidente}} = E_e dA,
\end{equation}

y la potencia radiante reflectada diferencial está dada por la exitancia $M_e$,
multiplicada por el tamaño del elemento de superficie,

\begin{equation}
 dF_{e,\text{reflejada}} = M_e dA,
\end{equation}

por lo tanto

\begin{equation}
 \rho = \frac{dF_{e,\text{reflejada}}}{dF_{e,\text{incidente}}} =
 \frac{M_e \cancel{dA}}{E_e \cancel{dA}} = \frac{M_3}{E_e}.
\end{equation}

La reflectancia total es luego subdividida en reflectancia regular $\rho_r$ y
reflectancia difusa $\rho_d$, que están dadas por las tasa de potencia radiante
reflejada regular y la tasa de potencia radiante reflejada difusa a la potencia
radiante incidente. De es esta definición debe ser obvio que

\begin{equation}
 \rho =  \rho_r + \rho_d.
\end{equation}

La transmitancia de un medio está definida por la tasa de potencia radiante transmitida
por la potencia radiante incidente. La transmitancia es luego subdividida en
transmitancia regular $\tau_r$ y transmitancia difusa $\tau_d$. que están dadas por
las tasa de potencia radiante transmitida regular y la tasa de potencia
radiante transmitida difusa a la potencia radiante incidente. De nuevo

\begin{equation}
 \tau =  \tau_r + \tau_d.
\end{equation}

La absorbancia de un medio es definida por el radio de potencia radiante absorbida
por la potencia radiante incidente.

\vspace{.3cm}

Al estar definidas como tasas de los valores de potencia radiante, la reflectancia,
transmitancia y absorbancia son adimensionales. Estas cantidades son usadas
para describir propiedades ópticas de los materiales, como el índice de refracción.
Comúnmente estas cantidades se aplican a radiación compleja, pero también pueden
utilizarse para radiación monocromática.

\vspace{.3cm}

\textbf{Técnica de Corbino}: Esta técnica fue desarrollada para proveer la
respuesta dependiente de las frecuencias  para el rango espectral de microondas. Ha
sido usada para dar información importante sobre superconductores de alta
temperatura, fermiones persados, gafas de electrones y películas superconductoras
delgadas. En esta técnica uno mide los coeficientes de reflexión complejos desde
una muestra de película fina que termina una línea de transmisión coaxial.
Típicamente, el contacto eléctrico es hecho presionando un adaptador de microondas
modificado contra la muestra con almohadillas de oro en forma de dona, que
empareja las dimensiones radiales de la línea coaxial.

\vspace{.3cm}

\textbf{EELS (electron energy loss spectroscopy)}: EELS es una técnica analítica que
mide los cambios en la energía cinética de los electrones luego de que han interactuado
con un espécimen. Cuando se hace en un microscopio electrónico de transmisión
moderno, EELS es capaz de dar información estructural y química de un sólido, con
una resolución espacial a nivel atómico en casos favorables. La resolución energética
es típicamente 1 eV pero puede acercase a 0.1 eV si se usa un haz de electrones
monocromático.

\vspace{.3cm}

Algunos de los electrones se someterán a dispersión inlástica, que significa que
perderán energía y sus caminos serán pequeñamente deflectados aleatoriamente. La
cantidad de energía perdida puede ser medida mediante un espectrómetro electrónico
e interpretada en términos de qué causó la pérdida de energía. Entre estas interacciones
inelásticas están las ionizaciones de capas internas, que son particularmente
útiles para detectar los componentes elementales de los materiales. Para estudiar
superficies, EELS es usualmente usada con bajas energía de incidencia.

\vspace{.3cm}

\textbf{REELS (reflection electron energy loss spectroscopy)}: REELS es una combinación
de EELS con microscopía electrónica de reflexión (REM), en la que un haz de electrones
de alta energía es incidente a un ángulo de brillo sobre la superficie. Se utiliza
para estudiar la pérdida de energía de estructuras ``near-edge'' y pérdida de energía
extendida en estructuras finas de superficies de cristales. También es
utilizada para detectar cambios relativos en los cambio de estado de densidades
en superficies.

\section{Problema 2}

Utilizando la transformada de Fourier,encontrar la dependencia en la frecuencia de las siguientes suceptibilidades:

\begin{itemize}
 \item $\chi(t) = \chi_0 \delta(t)$
 \item $\chi(t) = \chi_0\theta(t)$ es la función de Heaviside.
 \item $\chi(t) = \chi_0\delta(t)\sen(\omega_0 t)$.
\end{itemize}

\vspace{.3cm}

\underline{Solución:} \vspace{.3cm}

De la definición de la transformada de Fourier tenemos, para $\chi(t) = \chi_0 \delta(t)$

\begin{align}
\begin{split}
 F[\chi(t)] &= \frac{\chi_0}{\sqrt{2\pi}} \int_{-\infty}^\infty \delta(t) \euler^{-i
 \omega t} dt \\
 &= \frac{\chi_0}{\sqrt{2\pi}}\euler^0 \\
 &= \frac{\chi_0}{\sqrt{2\pi}}.
\end{split}
\end{align}

Para $\chi(t) = \chi_0\theta(t)$

\begin{align}
 \begin{split}
  F[\chi(t)] &= \chi_0 F[\theta(t)] \\
  &= \chi_0\left[- \frac{i}{2\pi\omega} + \sqrt{\frac{\pi}{2}}\delta(\omega) \right].
 \end{split}
\end{align}

Y para $\chi(t) = \chi_0\delta(t)\sen(\omega_0 t)$

\begin{align}
\begin{split}
 F[\chi(t)] &= \frac{\chi_0}{\sqrt{2\pi}} \int_{-\infty}^\infty \delta(t) \sen{\omega_0t}
 dt \\
 &= \frac{\chi_0}{\sqrt{2\pi}}\sen{(0)} \\
 &= 0.
\end{split}
\end{align}

\section{Problema 3}

Utilizando el modelo de Lorentz para la función dieléctrica muestra que

$$
\int_0^\infty d\omega \omega \text{Im}(\epsilon(\omega)) = \frac{\omega_p^2}{8}.
$$

En CGS.

\vspace{.3cm}

\underline{Solución:} \vspace{.3cm}

La parte imaginaria de la función dieléctrica en el modelo de Lorentz es igual a

\begin{equation}
 \text{Im}(\epsilon(\omega)) = \frac{\omega \omega_p^2 \Gamma}{(\omega_0^2 - \omega^2)^2
 + \omega^2 \Gamma^2},
\end{equation}

entonces

\begin{align}
\begin{split}
 \int_0^\infty d\omega \omega \text{Im}(\epsilon(\omega)) &=
 \int_0^\infty d\omega \frac{\omega^2 \omega_p^2 \Gamma}{(\omega_0^2 - \omega^2)^2
 + \omega^2 \Gamma^2}
\end{split}
\end{align}

Esta integral al introducirla en \texttt{Wolfram Alpha} a partir de una interfaz
con \texttt{Mathematica} produjo el siguiente resultado (luego lo cotejé
con una tabla de integración, y unas notas de un profesor disponibles en
\href{http://www.phys.ufl.edu/~tanner/notes.pdf}{http://www.phys.ufl.edu/~tanner/notes.pdf})

\begin{equation}
 \int_0^\infty d\omega \omega \text{Im}(\epsilon(\omega)) = \frac{\omega_p^2}{4\pi}
 \left[\frac{\pi}{2}\right],
\end{equation}

siendo $\pi/2$ el resultado de la integral luego de un cambio de variable y usando
propiedades trigonométricas. Al simplificar obtenemos el resultado deseado

\begin{equation}
 \boxed{\int_0^\infty d\omega \omega \text{Im}(\epsilon(\omega)) = \frac{\omega_p^2}{8}}.
\end{equation}

\section{Problema 4}

Plasmones-polaritones de superficie. Supongan que para $z > 0$ hay un metal descrito por el modelo de plasma. Es decir

$$
\epsilon(\omega) = 1 - \frac{\omega_p^2}{\omega^2}.
$$

Para $z < 0$ hay vacío. Es decir la superficie que divide el metal del vacío es el plano $x - y$.

\begin{itemize}
 \item ¿Qué es un plasmón-polaritón de superficie?
 \item Encontrar la relación de dispersión para el plasmón.
\end{itemize}

\vspace{.3cm}

\underline{Solución:} \vspace{.3cm}

Un plasmón polaritón de superficie (PPS) son ondas electromagnéticas de frecuencia
infrarroja o visible, que viajan a lo largo de una interfaz metal-dieléctrico o
metal-aire. El término PSS explica que la onda involucra movimiento de cargas en
el metal (``plasmón de superficie'') y ondas electromagnéticas en el aire
o dieléctrico (``polariton'').

\vspace{.3cm}

Para demostrar la condición para su existencia haremos una deducción para un
sistema semi-infinito y un acercamiento clásico. Consideremos entonces un modelo
clásico que consiste en dos medios no-magnéticos semi-infinitos con funciones
dieléctricas (dependientes del tiempo) locales $\epsilon_1$ y $\epsilon_2$
separados por una interfaz plana en $z = 0$. Las ecuaciones de Maxwell en la
ausencia de fuentes externas pueden ser expresadas como

\begin{equation}
 \pmb{\nabla} \times \mathbf{H}_i = \epsilon_i \frac{1}{c} \frac{\partial}{\partial t}
 \mathbf{E}_i,
\end{equation}

\begin{equation}
 \pmb{\nabla} \times \mathbf{E}_i = - \frac{1}{c} \frac{\partial}{\partial t}
 \mathbf{H}_i,
\end{equation}

\begin{equation}
 \pmb{\nabla} \cdot (\epsilon_i \mathbf{E}_i) = 0,
\end{equation}

\begin{equation}
 \pmb{\nabla} \cdot \mathbf{H} = 0.
\end{equation}

Donde el índice $i$ describe el medio: $i = 1$ en $z < 0$ y $i = 2$ en $z > 0$. Si
escogemos el eje $x$ como la dirección de propagación, tenemos que

\begin{equation}
 \mathbf{E}_i = (E_{i_x},0,E_{i_z}) \euler^{-\kappa_i|z|} \euler^{i(q_i x - \omega t)},
\end{equation}

y

\begin{equation}
 \mathbf{H}_i = (0,E_{i_y},0) \euler^{-\kappa_i|z|} \euler^{i(q_i x - \omega t)},
\end{equation}

donde $q_i$ representa la magnitud de un vector de onda que es paralelo a la
superficie. Introduciendo estas ecuaciones en las ecuaciones de Maxwell, obtenemos

\begin{equation}
 i \kappa_1 H_{1_y} = \frac{\omega}{c} \epsilon_1 E_{1_x},
\end{equation}

\begin{equation}
 i \kappa_2 H_{2_y} = - \frac{\omega}{c} \epsilon_2 E_{2_x},
\end{equation}

y

\begin{equation}
 \kappa_i = \sqrt{q_i^2 - \epsilon_i \frac{\omega^2}{c^2}}.
\end{equation}

Las condiciones de frontera implican que las componentes de los campos magnéticos
y eléctricos paralelos a la superficie deben ser continuos. Entonces tenemos

\begin{equation}
 \frac{\kappa_1}{\epsilon_1} H_{1_y} + \frac{\kappa_2}{\epsilon_2} H_{2_y} = 0,
\end{equation}

y

\begin{equation}
 H_{1_y} - H_{2_y} = 0,
\end{equation}

que tiene soluciones solo si el determinante es cero, i.e.

\begin{equation}
 \frac{\epsilon_1}{\kappa_1} + \frac{\epsilon_2}{\kappa_2} = 0.
\end{equation}

Esta es la condición de plasmón de superficie. Esta expresión puede escribirse como

\begin{equation}
 q(\omega) = \frac{\omega}{c} \sqrt{\frac{\epsilon_1\epsilon_2}{\epsilon_1 +
 \epsilon_2}},
\end{equation}

donde $\omega/c$ representa la magnitud del vector de onda de luz. En el caso
de un metal semi-infinito de Drude en el vacío tenemos que $\epsilon_2 = 1$ y
tenemos que

\begin{equation}
 \epsilon_1 = 1 - \frac{\omega_p^2}{\omega(\omega + i\eta)},
\end{equation}

$\eta$ una infinitesimal positiva. Entonces, en este caso tenemos

\begin{equation}
 \boxed{q(\omega) = \frac{\omega}{c}\sqrt{\frac{\omega^2 - \omega_p^2}{2\omega^2 -
 \omega_p^2}}}.
\end{equation}

Esta es la ecuación de dispersión para el plasmón superficie, y la expresión
final para el plasmón polaritón de superficie viene dada por

\begin{equation}
 \boxed{\omega^2(q) = \omega_p^2/2 + c^2q^2 - \sqrt{\omega_p^4/4 + c^4q^4}}.
\end{equation}

\end{document}


text:
package ru.apermyakov.strategy;

/**
* Class for paint triangle shape.
*
* @author apermyakov
* @since 16.10.2017
* @version 1.0
*/
public class Triangle implements Shape {

	/**
	* Class for build triangle shape.
	*
	* @author apermyakov
	* @since 16.10.2017
	* @version 1.0
	* @return build triangle to string
	*/
	public String pic() {
		StringBuilder picture = new StringBuilder();
		picture.append("+++++++");
		picture.append(System.getProperty("line.separator"));
		picture.append("+++x+++");
		picture.append(System.getProperty("line.separator"));
		picture.append("++xxx++");
		picture.append(System.getProperty("line.separator"));
		picture.append("+xxxxx+");
		picture.append(System.getProperty("line.separator"));
		picture.append("+++++++");
		return picture.toString();
	}
}


text:
#include "htmlboardgenerator.h"
#include "gkchess_piece.h"
#include "gkchess_board.h"
#include "gkchess_square.h"
#include <QXmlStreamWriter>

NAMESPACE_GKCHESS;

static QString __generate_table_style(const HtmlBoardGenerator::HtmlFormattingOptions &f)
{
    GUTIL_UNUSED(f);
    return "text-align:center;"
            "border-spacing:1pt;"
            "font-family:'Arial Unicode MS';"
            "border-collapse:collapse;"
            "border-color:#FFFFFFFF;"
            "border-style:solid;"
            "border-width:0pt 0pt 0pt 0pt;";
}

static QString __generate_row_style(const HtmlBoardGenerator::HtmlFormattingOptions &)
{
    return "vertical-align:bottom;";
}

static QColor __get_square_color(Square const &s, const HtmlBoardGenerator::HtmlFormattingOptions &f)
{
    QColor ret;
    if(s.IsDarkSquare())
        ret = f.DarkSquareColor;
    else
        ret = f.LightSquareColor;
    return ret;
}

static QString __generate_cell_style(const Square &s, const HtmlBoardGenerator::HtmlFormattingOptions &f)
{
    return QString("width:%1pt;"
                   "height:%2pt;"
                   "border-collapse:collapse;"
                   "border-color:#FFFFFFFF;"
                   "border-style:solid;"
                   "border-width:%3pt %3pt %3pt %3pt;"
                   "background-color:#%4;")
            .arg(f.SquareSize)
            .arg(f.SquareSize)
            .arg(f.BorderSize)
            .arg(0x00FFFFFF & __get_square_color(s, f).rgb(), 6, 16, QChar('0'));
}

static QString __generate_piece_style(Piece const &, const HtmlBoardGenerator::HtmlFormattingOptions &f)
{
    return QString("font-size:%1pt;"
                   "color:#%2")
            .arg(f.PieceSize)
            .arg(0x00FFFFFF & f.PieceColor.rgb(), 6, 16, QChar('0'));
}

HtmlBoardGenerator::HtmlFormattingOptions::HtmlFormattingOptions()
    :HumanReadable(true),
      PieceColor(::Qt::black),
      LightSquareColor(::Qt::white),
      DarkSquareColor(::Qt::gray),
      SquareSize(40),
      BorderSize(1),
      PieceSize(30),
      IndexSize(15)
{}

QString HtmlBoardGenerator::GenerateHtml(const Board &b, const HtmlFormattingOptions &f)
{
    QString html;
    if(b.ColumnCount() > 0 && b.RowCount() > 0)
    {
        QXmlStreamWriter sw(&html);
        sw.setAutoFormatting(f.HumanReadable);

        sw.writeStartElement("table");
        sw.writeAttribute("style", __generate_table_style(f));

        // Write each row to html
        for(int i = b.RowCount() - 1; 0 <= i; --i)
        {
            sw.writeStartElement("tr");
            sw.writeAttribute("style", __generate_row_style(f));

            // Write the row number:
            sw.writeStartElement("td");
            sw.writeAttribute("style",
                              QString("vertical-align:middle;width:12pt;font-size:%1pt;")
                              .arg(f.IndexSize));
            sw.writeCharacters(QString("%1").arg(i + 1));
            sw.writeEndElement(); //td

            // Iterate through the columns and write each cell
            for(int j = 0; j < b.ColumnCount(); ++j)
            {
                Square const &s( b.SquareAt(j, i) );

                sw.writeStartElement("td");
                sw.writeAttribute("style", __generate_cell_style(s, f));

                // Put a piece in the square if there is one
                Piece const &p = s.GetPiece();
                if(!p.IsNull())
                {
                    sw.writeStartElement("span");
                    sw.writeAttribute("style", __generate_piece_style(p, f));
                    sw.writeEntityReference(QString("#%1").arg(p.UnicodeValue()));
                    sw.writeEndElement(); //span
                }
                else
                {
                    // Need to write an empty piece to force the xml stream writer to write a
                    //  close tag for the cell
                    sw.writeCharacters(" ");
                }

                sw.writeEndElement();
            }

            sw.writeEndElement(); //tr
        }

        // Write the last row which holds the column letters
        sw.writeStartElement("tr");
        {
            // Empty cell
            sw.writeStartElement("td");
            sw.writeCharacters("");
            sw.writeEndElement(); //td

            char letter = 'a';
            for(int i = 0; i < b.RowCount(); ++i, ++letter)
            {
                sw.writeStartElement("td");
                sw.writeAttribute("style", QString("font-size:%1pt;").arg(f.IndexSize));
                sw.writeCharacters(QString::fromUtf8(&letter, 1));
                sw.writeEndElement(); //td
            }
        }
        sw.writeEndElement(); //tr

        sw.writeEndElement(); //table
        sw.writeEndElement(); //html
    }
    return html;
}

END_NAMESPACE_GKCHESS;


text:
package com.bosi.chineseclass.db;

import java.util.List;

public interface IDbOperation {

	public boolean  saveData(EntityBase mEntity);

	public <T extends  List<? extends EntityBase>> T selectDataFromDb(String sql);

	public boolean deleteDataFromDb(String sql);

	public boolean updateDataFromDb(String sql);

}


text:
$buffer: 0.5em;
$space: 0.25em;

.container {
  position: absolute;
  z-index: 10;
  right: $buffer;
  bottom: $buffer;
  left: $buffer;
  max-width: 50em;
  border: 2px solid #428bca;
  margin-right: auto;
  margin-left: auto;
  background: white;
}

.notification {
  display: flex;
}

.notificationContent {
  padding: $space 0 $space $space;
}

.close {
  composes: -buttonReset from './shared.module.css';
  padding: $space;
  background: #e1e1db;
  cursor: pointer;
}


text:
package goja

type weakMap uint64

type weakMapObject struct {
	baseObject
	m weakMap
}

func (wmo *weakMapObject) init() {
	wmo.baseObject.init()
	wmo.m = weakMap(wmo.val.runtime.genId())
}

func (wm weakMap) set(key *Object, value Value) {
	key.getWeakRefs()[wm] = value
}

func (wm weakMap) get(key *Object) Value {
	return key.weakRefs[wm]
}

func (wm weakMap) remove(key *Object) bool {
	if _, exists := key.weakRefs[wm]; exists {
		delete(key.weakRefs, wm)
		return true
	}
	return false
}

func (wm weakMap) has(key *Object) bool {
	_, exists := key.weakRefs[wm]
	return exists
}

func (r *Runtime) weakMapProto_delete(call FunctionCall) Value {
	thisObj := r.toObject(call.This)
	wmo, ok := thisObj.self.(*weakMapObject)
	if !ok {
		panic(r.NewTypeError("Method WeakMap.prototype.delete called on incompatible receiver %s", r.objectproto_toString(FunctionCall{This: thisObj})))
	}
	key, ok := call.Argument(0).(*Object)
	if ok && wmo.m.remove(key) {
		return valueTrue
	}
	return valueFalse
}

func (r *Runtime) weakMapProto_get(call FunctionCall) Value {
	thisObj := r.toObject(call.This)
	wmo, ok := thisObj.self.(*weakMapObject)
	if !ok {
		panic(r.NewTypeError("Method WeakMap.prototype.get called on incompatible receiver %s", r.objectproto_toString(FunctionCall{This: thisObj})))
	}
	var res Value
	if key, ok := call.Argument(0).(*Object); ok {
		res = wmo.m.get(key)
	}
	if res == nil {
		return _undefined
	}
	return res
}

func (r *Runtime) weakMapProto_has(call FunctionCall) Value {
	thisObj := r.toObject(call.This)
	wmo, ok := thisObj.self.(*weakMapObject)
	if !ok {
		panic(r.NewTypeError("Method WeakMap.prototype.has called on incompatible receiver %s", r.objectproto_toString(FunctionCall{This: thisObj})))
	}
	key, ok := call.Argument(0).(*Object)
	if ok && wmo.m.has(key) {
		return valueTrue
	}
	return valueFalse
}

func (r *Runtime) weakMapProto_set(call FunctionCall) Value {
	thisObj := r.toObject(call.This)
	wmo, ok := thisObj.self.(*weakMapObject)
	if !ok {
		panic(r.NewTypeError("Method WeakMap.prototype.set called on incompatible receiver %s", r.objectproto_toString(FunctionCall{This: thisObj})))
	}
	key := r.toObject(call.Argument(0))
	wmo.m.set(key, call.Argument(1))
	return call.This
}

func (r *Runtime) needNew(name string) *Object {
	return r.NewTypeError("Constructor %s requires 'new'", name)
}

func (r *Runtime) getPrototypeFromCtor(newTarget, defCtor, defProto *Object) *Object {
	if newTarget == defCtor {
		return defProto
	}
	proto := newTarget.self.getStr("prototype", nil)
	if obj, ok := proto.(*Object); ok {
		return obj
	}
	return defProto
}

func (r *Runtime) builtin_newWeakMap(args []Value, newTarget *Object) *Object {
	if newTarget == nil {
		panic(r.needNew("WeakMap"))
	}
	proto := r.getPrototypeFromCtor(newTarget, r.global.WeakMap, r.global.WeakMapPrototype)
	o := &Object{runtime: r}

	wmo := &weakMapObject{}
	wmo.class = classWeakMap
	wmo.val = o
	wmo.extensible = true
	o.self = wmo
	wmo.prototype = proto
	wmo.init()
	if len(args) > 0 {
		if arg := args[0]; arg != nil && arg != _undefined && arg != _null {
			adder := wmo.getStr("set", nil)
			adderFn := toMethod(adder)
			if adderFn == nil {
				panic(r.NewTypeError("WeakMap.set in missing"))
			}
			iter := r.getIterator(arg, nil)
			i0 := valueInt(0)
			i1 := valueInt(1)
			if adder == r.global.weakMapAdder {
				iter.iterate(func(item Value) {
					itemObj := r.toObject(item)
					k := itemObj.self.getIdx(i0, nil)
					v := nilSafe(itemObj.self.getIdx(i1, nil))
					wmo.m.set(r.toObject(k), v)
				})
			} else {
				iter.iterate(func(item Value) {
					itemObj := r.toObject(item)
					k := itemObj.self.getIdx(i0, nil)
					v := itemObj.self.getIdx(i1, nil)
					adderFn(FunctionCall{This: o, Arguments: []Value{k, v}})
				})
			}
		}
	}
	return o
}

func (r *Runtime) createWeakMapProto(val *Object) objectImpl {
	o := newBaseObjectObj(val, r.global.ObjectPrototype, classObject)

	o._putProp("constructor", r.global.WeakMap, true, false, true)
	r.global.weakMapAdder = r.newNativeFunc(r.weakMapProto_set, nil, "set", nil, 2)
	o._putProp("set", r.global.weakMapAdder, true, false, true)
	o._putProp("delete", r.newNativeFunc(r.weakMapProto_delete, nil, "delete", nil, 1), true, false, true)
	o._putProp("has", r.newNativeFunc(r.weakMapProto_has, nil, "has", nil, 1), true, false, true)
	o._putProp("get", r.newNativeFunc(r.weakMapProto_get, nil, "get", nil, 1), true, false, true)

	o._putSym(SymToStringTag, valueProp(asciiString(classWeakMap), false, false, true))

	return o
}

func (r *Runtime) createWeakMap(val *Object) objectImpl {
	o := r.newNativeConstructOnly(val, r.builtin_newWeakMap, r.global.WeakMapPrototype, "WeakMap", 0)

	return o
}

func (r *Runtime) initWeakMap() {
	r.global.WeakMapPrototype = r.newLazyObject(r.createWeakMapProto)
	r.global.WeakMap = r.newLazyObject(r.createWeakMap)

	r.addToGlobal("WeakMap", r.global.WeakMap)
}


text:
""" Bootstraps instance of Docker container for PRISONER demonstration.
Requests Facebook app ID and secret, shows url for demo app
"""
import platform

root_path = "/usr/bin/prisoner-demo/" # docker
#root_path = "" # local

if __name__ == "__main__":
    print "PRISONER Demonstration"
    print "======================"

    print "Before running this experiment, please register an app with the Facebook Developers dashboard <https://developers.facebook.com/apps/>."

    print "Provide localhost as the Site URL and app domain on your app's settings page."

    print "For more information about getting started, see the documentation for this demo at http://prisoner.cs.st-andrews.ac.uk/docs/<TODO>."

    print "\n Enter the App ID for your Facebook app:"
    app_id = raw_input()

    print "Enter the App Secret for your Facebook app:"
    app_secret = raw_input()

    print "\n Enter the API key for your Twitter app:"
    twitter_key = raw_input()

    print "Enter the App Secret for your Twitter app:"
    twitter_secret = raw_input()

    replacements = {'$APP_ID':app_id, "$APP_SECRET":app_secret,
    "$TWITTER_KEY":twitter_key, "$TWITTER_SECRET": twitter_secret}
    lines = []
    with open('%sstatic/policy/design_src.xml' % root_path) as infile:
        for line in infile:
            for src, target in replacements.iteritems():
                line = line.replace(src, target)
            lines.append(line)
    with open('%sstatic/policy/design.xml' % root_path, "w") as outfile:
        for line in lines:
            outfile.write(line)

    print "Policy updated. Now starting PRISONER..."


text:
namespace VB.PowerManager.View
{
    using System;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Windows.Forms;
    using Annotations;
    using Interfaces;

    public sealed class MenuItemProxy : IMenuItemProxy
    {
        private readonly MenuItem menuItem;

        private readonly Action action;

        public MenuItemProxy(string name, Action action)
        {
            this.menuItem = new MenuItem(name);
            Click += OnClick;

            this.action = action;

            this.Hash = this.GetHashCode();
        }

        public int Hash { get; set; }

        public event EventHandler Click
        {
            add
            {
                menuItem.Click += value;
            }
            remove
            {
                menuItem.Click -= value;
            }
        }

        public object GetRealObject()
        {
            return menuItem;
        }

        public void PerformClick()
        {
            menuItem.PerformClick();
        }

        public bool Checked
        {
            get
            {
                return menuItem.Checked;
            }

            set
            {
                menuItem.Checked = value;
            }
        }

        public bool RadioCheck
        {
            get
            {
                return menuItem.RadioCheck;
            }

            set
            {
                menuItem.RadioCheck = value;
            }
        }

        public void Update()
        {
            Checked = false;
        }

        public void Dispose()
        {
            Click -= OnClick;
        }

        [NotifyPropertyChangedInvocator]
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private void OnClick(object sender, EventArgs eventArgs)
        {
            action.Invoke();

            Checked = true;

            OnPropertyChanged();
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}


text:
/**
 * Page Component for Template Page
 */

// Import Node Packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';

// Import Local Components
import TemplateContainer from './containers/TemplateContainer';

// Import Helpers

// Component Metadata
const propTypes = {
  template: PropTypes.string.isRequired,
};

const defaultProps = {
  template: "Hello World",
};

// Component Class for Template Page
class TemplatePage extends Component {

  /**
   * Other Class Methods
   */

  /**
   * React Functions
   */
  constructor (props) {
    super(props);

    // Member Variables
    this.state = {
      template: "template",
    };

    // Function Bindings
    this.render = this.render.bind(this);

  } // end constructor

  /**
   * Click and Event Handlers
   */

  /**
   * Getter Methods
   */

  /**
   * Other Render Methods
   */

  /**
   * Render Function
   */
  render () {
    return <Template />;
  } // end render

}

TemplatePage.propTypes = propTypes;
TemplatePage.defaultProps = defaultProps;

export default TemplatePage;


text:
using System.ComponentModel.DataAnnotations;

namespace Vulcan.Core.Auth.Models
{
    public class ApiUser
    {
        public long Id { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        [Range(6, int.MaxValue)]
        public int? TokenExpireTimeMinutes { get; set; }
        public bool IsSystem { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string DisplayName { get; set; }
    }
}


text:
package org.drools.workbench.screens.workitems.backend.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.drools.workbench.screens.workitems.service.WorkItemsEditorService;
import org.guvnor.structure.server.config.ConfigGroup;
import org.guvnor.structure.server.config.ConfigItem;
import org.guvnor.structure.server.config.ConfigType;
import org.guvnor.structure.server.config.ConfigurationService;
import org.jbpm.process.core.WorkDefinition;

/**
 * Class to load Work Definitions from configuration
 */
public class ConfigWorkDefinitionsLoader {

    @Inject
    private ConfigurationService configurationService;

    public Map<String, WorkDefinition> loadWorkDefinitions() {
        //Find all configured WIDs
        final Map<String, WorkDefinition> workDefinitions = new HashMap<String, WorkDefinition>();
        final List<ConfigGroup> configGroups = configurationService.getConfiguration( ConfigType.EDITOR );
        if ( configGroups == null || configGroups.isEmpty() ) {
            return workDefinitions;
        }

        //Load configured WIDs
        final List<String> definitions = new ArrayList<String>();
        for ( ConfigGroup configGroup : configGroups ) {
            if ( WorkItemsEditorService.WORK_ITEM_DEFINITION.equals( configGroup.getName() ) ) {
                for ( ConfigItem configItem : configGroup.getItems() ) {
                    definitions.add( configGroup.getConfigItemValue( configItem.getName() ) );
                }
            }
        }

        //Parse MVEL expressions into model
        workDefinitions.putAll( WorkDefinitionsParser.parse( definitions ) );

        return workDefinitions;
    }

}


text:
module KnapsackPro
  module Client
    module API
      class Action
        attr_reader :endpoint_path, :http_method, :request_hash

        def initialize(args)
          @endpoint_path = args.fetch(:endpoint_path)
          @http_method = args.fetch(:http_method)
          @request_hash = args.fetch(:request_hash)
        end
      end
    end
  end
end


text:
using System;
using System.Linq;

namespace FamousQuoteQuiz.Data.Repositories
{
    public interface IRepository<T> : IDisposable
    {
        IQueryable<T> All();

        T GetById(int id);

        void Add(T entity);

        void Update(T entity);

        void Delete(T entity);

        void Delete(int id);

        void Detach(T entity);

        int SaveChanges();
    }
}


text:
package org.ccim.wenli;

import org.apache.cordova.Config;
import org.apache.cordova.CordovaActivity;
import android.os.Bundle;

public class ReadActivity extends CordovaActivity {

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

        super.loadUrl(Config.getStartUrl());
    }

}