text:
<!doctype html>

    <meta charset="utf-8">
    <title>Data Voyager</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">


text:
@import url("jquery.ui.core.css");
@import url("jquery.ui.resizable.css");
@import url("jquery.ui.selectable.css");
@import url("jquery.ui.button.css");
@import url("jquery.ui.dialog.css");
@import url("jquery.ui.slider.css");
@import url("jquery.ui.tabs.css");

redpajama_set_name: RedPajamaGithub


text:
muzeiDir=~/Pictures/Muzei
mkdir -p $muzeiDir/Wallpaper
cd $muzeiDir

######Needed packages######
function notifytestLinux(){
  if ! [ "$(which notify-send)" ]
  then
    echo "Please install a notification server for a better experience."
  fi
}
function notifytestOSX(){
  if ! [ "$(which terminal-notifier)" ]
  then
    echo "Please install terminal-notifier for a better experience."
  fi
}
case "$OSTYPE" in
  linux* | *BSD*) notifytestLinux ;;
  darwin*)        notifytestOSX ;;
  *)              echo "Get a proper OS, kid." && exit ;;
esac
if ! [ "$(which jq)" ]
then
  echo "You need jq to use this."
  exit
fi

######Deleting old .xinitrc line for feh/hsetroot/nitrogen if it exists######
if [ -f ~/.xinitrc ]
then
  echo "Deleting old .xinitrc line..."
  if [ "$(cat ~/.xinitrc | grep '^hsetroot -cover')" ]
  then
    sed -i "/^hsetroot -cover/d" ~/.xinitrc
  elif [ "$(cat ~/.xinitrc | grep '^sh ~/.fehbg')" ]
  then
    sed -i "/^sh ~\/.fehbg/d" ~/.xinitrc
  elif [ "$(cat ~/.xinitrc | grep '^nitrogen --restore')" ]
  then
    sed -i "/^nitrogen --restore/d" ~/.xinitrc
  fi
fi

######Get the Muzei JSON and parse it######
curl -o muzei.json 'https://muzeiapi.appspot.com/featured?cachebust=1'
imageUri=`jq '.imageUri' $muzeiDir/muzei.json | sed s/\"//g`
imageFile=`basename $imageUri`
title=`jq '.title' $muzeiDir/muzei.json | sed s/\"//g`
byline=`jq '.byline' $muzeiDir/muzei.json | sed s/\"//g`

######Get the latest wallpaper######
cd Wallpaper
if [ -f $imageFile ]
then
  echo "File $imageFile exists."
else
  echo "File $imageFile does not exist, downloading..."
  curl -O $imageUri
fi

######Functions for autostarting feh, hsetroot and nitrogen######
function feh_xinitSet(){
  if ! [ -f ~/.xinitrc ] || ! [ "$(cat ~/.xinitrc | grep ^exec)" ]
  then
    echo "sh ~/.fehbg &" >> ~/.xinitrc
  else
    sed -i "s#^exec #sh ~/.fehbg \&\nexec #" ~/.xinitrc
  fi
}
function hsetroot_xinitSet(){
  if ! [ -f ~/.xinitrc ] || ! [ "$(cat ~/.xinitrc | grep ^exec)" ]
  then
    echo "hsetroot -cover $muzeiDir/Wallpaper/$imageFile &" >> ~/.xinitrc
  else
    sed -i "s#^exec #hsetroot -cover $muzeiDir/Wallpaper/$imageFile \&\nexec #" ~/.xinitrc
  fi
}
function nitrogen_xinitSet(){
  if ! [ -f ~/.xinitrc ] || ! [ "$(cat ~/.xinitrc | grep ^exec)" ]
  then
    echo "nitrogen --restore &" >> ~/.xinitrc
  else
    sed -i "s#^exec #nitrogen --restore \&\nexec #" ~/.xinitrc
  fi
}

######Set the wallpaper######
function setWallpaperLinux(){
  if [ "$(pidof gnome-settings-daemon)" ]
  then
    echo "Gnome-settings-daemons detected, setting wallpaper with gsettings..."
    gsettings set org.gnome.desktop.background picture-uri file://$muzeiDir/Wallpaper/$imageFile
  else
    if [ "$(which feh)" ]
    then
      echo "Gnome-settings-daemons not running, setting wallpaper with feh..."
      feh --bg-fill $muzeiDir/Wallpaper/$imageFile
      feh_xinitSet
    elif [ "$(which hsetroot)" ]
    then
      echo "Gnome-settings-daemons not running, setting wallpaper with hsetroot..."
      hsetroot -cover $muzeiDir/Wallpaper/$imageFile
      hsetroot_xinitSet
    elif [ "$(which nitrogen)" ]
    then
      echo "Gnome-settings-daemons not running, setting wallpaper with nitrogen..."
      nitrogen $muzeiDir/Wallpaper/$imageFile
      nitrogen_xinitSet
    else
      echo "You need to have either feh, hsetroot or nitrogen, bruhbruh."
      exit
    fi
  fi
}
function setWallpaperOSX(){
  defaults write com.apple.desktop Background "{default = {ImageFilePath='$muzeiDir/Wallpaper/$imageFile'; };}"
  killall Dock
#  osascript
#  tell application "Finder"
#    set desktop picture to file "$muzeiDir/Wallpaper/$imageFile"
#  end tell
}
case "$OSTYPE" in
  linux* | *BSD*) setWallpaperLinux ;;
  darwin*)        setWallpaperOSX ;;
esac

######Send a notification######
cd $muzeiDir
if [ -f MuzeiLogo.png ];
then
  echo "Logo already exists."
else
  echo "Logo doesn't exist, downloading..."
  curl -O "https://raw.github.com/Feminist-Software-Foundation/Muzei-Bash/master/MuzeiLogo.png"
fi
case "$OSTYPE" in
  linux* | *BSD*) notify-send "New wallpaper: '$title'" "$byline" -i $muzeiDir/MuzeiLogo.png ;;
  darwin*)        terminal-notifier -title "Muzei-Bash" -message "New wallpaper: '$title'" "$byline" ;;
esac

######Clean up old wallpapers######
echo "Cleaning up old files..."
find $muzeiDir/Wallpaper -ctime +30 -exec rm {} +


text:
namespace blink {
class WebMIDIAccessorClient;
}

namespace content {

class TestInterfaces;

class MockWebMIDIAccessor : public blink::WebMIDIAccessor {
public:
    explicit MockWebMIDIAccessor(blink::WebMIDIAccessorClient*, TestInterfaces*);
    virtual ~MockWebMIDIAccessor();

    // blink::WebMIDIAccessor implementation.
    virtual void startSession() OVERRIDE;
    virtual void sendMIDIData(unsigned portIndex,
                              const unsigned char* data,
                              size_t length,
                              double timestamp) OVERRIDE {}

    // WebTask related methods
    WebTaskList* mutable_task_list() { return &m_taskList; }

private:
    blink::WebMIDIAccessorClient* m_client;
    WebTaskList m_taskList;
    TestInterfaces* m_interfaces;

    DISALLOW_COPY_AND_ASSIGN(MockWebMIDIAccessor);
};

}  // namespace content

#endif  // CONTENT_SHELL_RENDERER_TEST_RUNNER_MOCKWEBMIDIACCESSOR_H_


text:
package com.soothsayer.authn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.soothsayer")
public class SoothsayerAuthNApplication {

    public static void main(String[] args) {
        SpringApplication.run(SoothsayerAuthNApplication.class, args);
    }
}


text:
using Xunit;

namespace LiveStream.Samples.Tests
{
    [Collection(nameof(LiveStreamFixture))]
    public class GetInputTest
    {
        private LiveStreamFixture _fixture;
        private readonly GetInputSample _getSample;

        public GetInputTest(LiveStreamFixture fixture)
        {
            _fixture = fixture;
            _getSample = new GetInputSample();
        }

        [Fact]
        public void GetsInput()
        {
            var result = _getSample.GetInput(
                _fixture.ProjectId, _fixture.LocationId, _fixture.TestInputId);
            Assert.Equal(_fixture.ProjectId, result.InputName.ProjectId);
            Assert.Equal(_fixture.LocationId, result.InputName.LocationId);
            Assert.Equal(_fixture.TestInputId, result.InputName.InputId);
        }
    }
}


text:
sigset_t signal_set;

void * signal_waiter(void *arg);
void sigint_handler(void);
void sigalrm_handler(void);

#endif


text:
package net.sf.serfj;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.serfj.config.ConfigFileIOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Main class. This servlet dispatches REST requests to controllers. It parses
 * the URL, extracting resources and resources' Ids so developer will be able to
 * get them in the method's controller.
 *
 * @author Eduardo Yáñez
 *
 */
public class RestServlet extends HttpServlet {

	private static final long serialVersionUID = 9209683558191927011L;

	/**
	 * Log.
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(RestServlet.class);

	/**
	 * Parameter for supply the HTTP request method that doesn't support the
	 * browsers (PUT and DELETE), but could be set to GET and POST too.
	 */
	private static final String HTTP_METHOD_PARAM = "http_method";

	/**
	 * Configuration.
	 */
	private Config config;

	/**
	 * URL manager.
	 */
	private UrlInspector urlInspector;

	private ServletHelper helper = new ServletHelper();

	/**
	 * Reads configuration from /serfj.properties.
	 *
	 * @throws javax.servlet.ServletException
	 */
	@Override
	public void init() throws ServletException {
		super.init();
		try {
			config = new Config("/config/serfj.properties");
		} catch (ConfigFileIOException e) {
			LOGGER.error("Can't load framework configuration", e);
			throw new ServletException(e);
		}
		urlInspector = new UrlInspector(config);
	}

	/**
	 * Parses the request to get information about what controller is trying to call, then
	 * invoke the action from that controller (if any), and finally gives an answer.

	 *

	 * Basically it only dispatchs the request to a controller.
	 */
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Eliminamos de la URI el contexto
		String url = request.getRequestURI().substring(request.getContextPath().length());
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("url => {}", url);
			LOGGER.debug("HTTP_METHOD => {}", request.getMethod());
			LOGGER.debug("queryString => {}", request.getQueryString());
			LOGGER.debug("Context [{}]", request.getContextPath());
		}

		HttpMethod requestMethod = HttpMethod.valueOf(request.getMethod());
		if (requestMethod == HttpMethod.POST) {
			String httpMethodParam = request.getParameter(HTTP_METHOD_PARAM);
			LOGGER.debug("param: http_method => {}", httpMethodParam);
			if (httpMethodParam != null) {
				requestMethod = HttpMethod.valueOf(httpMethodParam);
			}
		}
		// Getting all the information from the URL
		UrlInfo urlInfo = urlInspector.getUrlInfo(url, requestMethod);
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("URL info {}", urlInfo.toString());
		}
		// Calling the controller's action
		ResponseHelper responseHelper = new ResponseHelper(this.getServletContext(), request, response, urlInfo, config.getString(Config.VIEWS_DIRECTORY));
		helper.invokeAction(urlInfo, responseHelper);
		responseHelper.doResponse();
	}
}


text:
const Koa = require('koa')

const xmlParser = require('koa-xml-body')

const bodyParser = require('koa-bodyparser')

const app = new Koa()

const config = require('./config')

const router = require('./router')

app.use(xmlParser())

// 使用ctx.body解析中间件
app.use(bodyParser({
  extendTypes: {
    json: ['application/x-javascript'] // will parse application/x-javascript type body as a JSON string
  },
  onerror: function (err, ctx) {  // support custom error handle, if koa-bodyparser throw an error
    ctx.throw('body parse error', 422)
  }
}))

app.use(router.routes())

app.listen(config.port, () => {
  console.log('server start at http://localhost:' + config.port)
})


text:
package com.kotcrab.vis.editor.ui.scene.entityproperties.autotable;

import com.artemis.Component;
import com.artemis.Entity;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.kotcrab.vis.editor.proxy.EntityProxy;
import com.kotcrab.vis.editor.util.vis.EntityUtils;
import com.kotcrab.vis.runtime.util.autotable.ATEnumProperty;
import com.kotcrab.vis.runtime.util.autotable.EnumNameProvider;
import com.kotcrab.vis.ui.widget.VisTable;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/** @author Kotcrab */
public class EnumSelectBoxFragmentProvider extends AutoTableFragmentProvider<ATEnumProperty> {
	private ObjectMap<Field, EnumSelectBoxSet> enumSelectBoxes = new ObjectMap<>();

	@Override
	public void createUI (ATEnumProperty annotation, Class type, Field field) throws ReflectiveOperationException {
		String fieldName = annotation.fieldName().equals("") ? field.getName() : annotation.fieldName();

		Constructor constructor = annotation.uiNameProvider().getConstructor();
		EnumNameProvider nameProvider = (EnumNameProvider) constructor.newInstance();

		AutoTableEnumSelectBox selectBox = new AutoTableEnumSelectBox<>(type, nameProvider);
		selectBox.getSelection().setProgrammaticChangeEvents(false);
		selectBox.addListener(properties.getSharedSelectBoxChangeListener());
		enumSelectBoxes.put(field, new EnumSelectBoxSet(selectBox, nameProvider));

		VisTable table = new VisTable(true);
		table.add(fieldName);
		table.add(selectBox).expandX().fillX().left();
		uiTable.add(table).left().expandX().fillX().row();
	}

	@Override
	public void updateUIFromEntities (Array<EntityProxy> proxies, Class type, Field field) throws ReflectiveOperationException {
		EnumSelectBoxSet set = enumSelectBoxes.get(field);

		String commonValue = EntityUtils.getCommonString(proxies, AutoTableEnumSelectBox.INDETERMINATE,
				(Entity entity) -> {
					try {
						return set.enumNameProvider.getPrettyName((Enum) field.get(entity.getComponent(componentClass)));
					} catch (IllegalAccessException e) {
						throw new IllegalStateException(e);
					}
				});

		if (commonValue.equals(AutoTableEnumSelectBox.INDETERMINATE)) {
			set.selectBox.setIndeterminate(true);
		} else {
			set.selectBox.setIndeterminate(false);
			set.selectBox.setSelectedEnum((Enum) field.get(proxies.first().getEntities().first().getComponent(componentClass)));
		}
	}

	@Override
	public void setToEntities (Class type, Field field, Component component) throws ReflectiveOperationException {
		EnumSelectBoxSet set = enumSelectBoxes.get(field);

		if (set.selectBox.isIndeterminate() == false) {
			field.set(component, set.selectBox.getSelectedEnum());
		}
	}

	private static class EnumSelectBoxSet {
		public AutoTableEnumSelectBox selectBox;
		public EnumNameProvider enumNameProvider;

		public EnumSelectBoxSet (AutoTableEnumSelectBox selectBox, EnumNameProvider enumNameProvider) {
			this.selectBox = selectBox;
			this.enumNameProvider = enumNameProvider;
		}
	}
}


text:
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module unless amdModuleId is set
    define([], function () {
      return (factory());
    });
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory();
  } else {
    factory();
  }
}(this, function () {

$translateStaticFilesLoader.$inject = ['$q', '$http'];
angular.module('pascalprecht.translate')
/**
 * @ngdoc object
 * @name pascalprecht.translate.$translateStaticFilesLoader
 * @requires $q
 * @requires $http
 *
 * @description
 * Creates a loading function for a typical static file url pattern:
 * "lang-en_US.json", "lang-de_DE.json", etc. Using this builder,
 * the response of these urls must be an object of key-value pairs.
 *
 * @param {object} options Options object, which gets prefix, suffix, key, and fileMap
 */
.factory('$translateStaticFilesLoader', $translateStaticFilesLoader);

function $translateStaticFilesLoader($q, $http) {

  'use strict';

  return function (options) {

    if (!options || (!angular.isArray(options.files) && (!angular.isString(options.prefix) || !angular.isString(options.suffix)))) {
      throw new Error('Couldn\'t load static files, no files and prefix or suffix specified!');
    }

    if (!options.files) {
      options.files = [{
        prefix: options.prefix,
        suffix: options.suffix
      }];
    }

    var load = function (file) {
      if (!file || (!angular.isString(file.prefix) || !angular.isString(file.suffix))) {
        throw new Error('Couldn\'t load static file, no prefix or suffix specified!');
      }

      var fileUrl = [
        file.prefix,
        options.key,
        file.suffix
      ].join('');

      if (angular.isObject(options.fileMap) && options.fileMap[fileUrl]) {
        fileUrl = options.fileMap[fileUrl];
      }

      return $http(angular.extend({
        url: fileUrl,
        method: 'GET',
        params: ''
      }, options.$http))
        .then(function(result) {
          return result.data;
        }, function () {
          return $q.reject(options.key);
        });
    };

    var promises = [],
        length = options.files.length;

    for (var i = 0; i < length; i++) {
      promises.push(load({
        prefix: options.files[i].prefix,
        key: options.key,
        suffix: options.files[i].suffix
      }));
    }

    return $q.all(promises)
      .then(function (data) {
        var length = data.length,
            mergedData = {};

        for (var i = 0; i < length; i++) {
          for (var key in data[i]) {
            mergedData[key] = data[i][key];
          }
        }

        return mergedData;
      });
  };
}

$translateStaticFilesLoader.displayName = '$translateStaticFilesLoader';
return 'pascalprecht.translate';

}));


text:
// Author: jmarantz@google.com (Joshua Marantz)

#include "pagespeed/kernel/base/null_thread_system.h"

#include "base/logging.h"
#include "pagespeed/kernel/base/mock_timer.h"
#include "pagespeed/kernel/base/null_mutex.h"

namespace net_instaweb {

namespace {

const int64 kMockThreadId = 6765;

// Mock read-write-lock.  This does no locking.
class NullRWLock : public ThreadSystem::RWLock {
 public:
  NullRWLock() {}
  virtual ~NullRWLock();
  virtual bool ReaderTryLock() { return true; }
  virtual void ReaderLock() {}
  virtual void ReaderUnlock() {}
  virtual bool TryLock() { return true; }
  virtual void Lock() {}
  virtual void Unlock() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(NullRWLock);
};

class NullThreadId : public ThreadSystem::ThreadId {
 public:
  explicit NullThreadId(const NullThreadSystem* system)
      : id_(system->current_thread()),
        system_(system) {
  }

  virtual ~NullThreadId() {}

  virtual bool IsEqual(const ThreadId& that) const {
    return (id_ == dynamic_cast<const NullThreadId&>(that).id_);
  }

  virtual bool IsCurrentThread() const {
    return id_ == system_->current_thread();
  }

 private:
  int id_;
  const NullThreadSystem* system_;

  DISALLOW_COPY_AND_ASSIGN(NullThreadId);
};

}  // namespace

NullCondvarCapableMutex::~NullCondvarCapableMutex() {
}

NullRWLock::~NullRWLock() {
}

NullThreadSystem::~NullThreadSystem() {
}

NullCondvarCapableMutex* NullThreadSystem::NewMutex() {
  return new NullCondvarCapableMutex();
}

ThreadSystem::RWLock* NullThreadSystem::NewRWLock() {
  return new NullRWLock;
}

Timer* NullThreadSystem::NewTimer() {
  // TODO(jmarantz): consider removing the responsibility of creating timers
  // from the thread system.
  return new MockTimer(new NullMutex, 0);
}

ThreadSystem::ThreadId* NullThreadSystem::GetThreadId() const {
  return new NullThreadId(this);
}

ThreadSystem::ThreadImpl* NullThreadSystem::NewThreadImpl(Thread* wrapper,
                                                          ThreadFlags flags) {
  LOG(FATAL) << "Creating threads in null thread system not supported";
  return NULL;
}

NullCondvar::~NullCondvar() {
  // All actions should have been examined by the caller.
  if (!actions_.empty()) {
    LOG(FATAL) << "actions_ not empty: " << JoinCollection(actions_, " ");
  }
  // If caller set a callback for TimedWait() then they should also have
  // called TimedWait().
  CHECK(timed_wait_callback_ == NULL);
}

void NullCondvar::TimedWait(int64 timeout_ms) {
  actions_.push_back(StrCat("TimedWait(", IntegerToString(timeout_ms), ")"));
  if (timed_wait_callback_ != NULL) {
    timed_wait_callback_->Call();
    timed_wait_callback_ = NULL;
  }
}

GoogleString NullCondvar::ActionsSinceLastCall() {
  GoogleString response = JoinCollection(actions_, " ");
  actions_.clear();
  return response;
}

NullCondvar* NullCondvarCapableMutex::NewCondvar() {
  return new NullCondvar(this);
}

}  // namespace net_instaweb


text:
"""
can is an object-orient Controller Area Network interface module.

Modules include:

    :mod:`can.message`
        defines the :class:`~can.Message` class which is the
        lowest level of OO access to the library.

"""
import logging
log = logging.getLogger('can')

rc = dict(channel=0)

class CanError(IOError):
    pass

from can.CAN import BufferedReader, Listener, Printer, CSVWriter, SqliteWriter, set_logging_level
from can.message import Message
from can.bus import BusABC
from can.notifier import Notifier
from can.broadcastmanager import send_periodic, CyclicSendTaskABC, MultiRateCyclicSendTaskABC
from can.interfaces import interface


text:
from tastypie import authorization
from tastypie_mongoengine import resources, fields
from history.models import History, HistoryEntry

class EntryResource(resources.MongoEngineResource):
    class Meta:
        object_class = HistoryEntry
        ordering = ['-date_posted', ]

class HistoryResource(resources.MongoEngineResource):
    entries = fields.EmbeddedListField(of='history.resources.EntryResource', attribute='entries', full=True, null=True)

    class Meta:
        queryset = History.objects.all()
        allowed_methods = ('get', 'post', 'put', 'delete', 'patch')
        authorization = authorization.Authorization()
        excludes = ['active', 'classes', ]


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_log_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginStart="@dimen/activity_margin_start"
    android:layout_marginEnd="@dimen/activity_margin_end"
    android:fitsSystemWindows="false"
    android:orientation="vertical"
    tools:context="sk.henrichg.phoneprofilesplus.ActivityLogActivity" >

    <LinearLayout
        android:id="@+id/activity_log_liLa1"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingStart="10dp"
        android:paddingEnd="10dp" >

        <LinearLayout
            android:id="@+id/activity_log_liLa2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingStart="5dp"
            android:paddingEnd="5dp"
            android:paddingTop="10dp"
            android:paddingBottom="10dp">

            <TextView
                android:id="@+id/activity_log_header_color"
                android:layout_width="5dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="5dp"
                android:text="@string/empty_string"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/activity_log_header_log_date_time"
                android:layout_weight="0.27"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:text="@string/activity_log_header_log_time"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/activity_log_row_log_type_header"
                android:layout_weight="0.43"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:text="@string/activity_log_header_data_type"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/activity_log_header_log_data"
                android:layout_weight="0.30"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp"
                android:text="@string/activity_log_header_data"
                android:textStyle="bold"/>

            <!--
            <TextView
                android:id="@+id/activity_log_header_event_name"
                android:layout_weight="0.22"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp" />

            <TextView
                android:id="@+id/activity_log_header_profile_name"
                android:layout_weight="0.30"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="10dp" />
            -->

        </LinearLayout>

        <View
            android:id="@+id/activity_log_header_divider"
            android:layout_width="match_parent"
            android:layout_height="@dimen/divider_height"
            android:background="?attr/dialogDivider" />

    </LinearLayout>

    <ListView
        android:id="@+id/activity_log_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingStart="5dp"
        android:paddingEnd="5dp"
        android:choiceMode="singleChoice"
        android:clipToPadding="false"
        android:scrollbarStyle="outsideOverlay"
        android:divider="@android:color/transparent"
        android:listSelector="?attr/listViewItemBackground" />

</LinearLayout>


text:
let gameStateStart = false;
let gameStateInBox = false;
let gameWallRed = null;

let GameInit = function () {
  document.getElementById('buttonS').onmouseenter = function () {
    gameStateStart = true;
    gameStateInBox = true;
    document.getElementById('gameBox').className = 'game-box game-box-in-game';
    document.getElementById('gameState').innerHTML = 'In game!';
  };

  document.getElementById('buttonE').onmouseenter = function () {
    if (gameStateStart === false) {
      document.getElementById('gameState').innerHTML = 'Please start from \'S\'!';
    } else if (gameStateStart === true && gameStateInBox === false) {
      document.getElementById('gameState').innerHTML = 'Don\'t cheat, you should start from the \'S\' and move to the \'E\' inside the maze!';
    } else {
      document.getElementById('gameState').innerHTML = 'You win!';
    }
    gameStateStart = false;
    document.getElementById('gameBox').className = 'game-box';
  };

  document.getElementById('gameBox').onmouseleave = function () {
    gameStateInBox = false;
  };

  for (let x of document.getElementsByClassName('game-wall')) {
    x.onmouseover = function (e) {
      if (gameStateStart === true) {
        document.getElementById('gameState').innerHTML = 'You lose!';
        e.target.className = e.target.className + ' game-wall-red';
        gameWallRed = e.target;
        gameStateStart = false;
        document.getElementById('gameBox').className = 'game-box';
      }
    };

    x.onmouseout = function (e) {
      if (gameWallRed === e.target) {
        gameWallRed.className = gameWallRed.className.replace(' game-wall-red', '');
        gameWallRed = null;
      }
    }
  }
};

GameInit();


text:
class PrefService;
class Profile;

namespace policy {

class DeviceManagementService;
class UserCloudPolicyStore;

// UserCloudPolicyManager handles initialization of user policy for Chrome
// Profiles on the desktop platforms.
class UserCloudPolicyManager : public CloudPolicyManager {
 public:
  UserCloudPolicyManager(Profile* profile,
                         scoped_ptr<UserCloudPolicyStore> store);
  virtual ~UserCloudPolicyManager();

  // Initializes the cloud connection. |local_state| and
  // |device_management_service| must stay valid until this object is deleted or
  // DisconnectAndRemovePolicy() gets called. Virtual for mocking.
  virtual void Connect(PrefService* local_state,
                       scoped_ptr<CloudPolicyClient> client);

  // Shuts down the UserCloudPolicyManager (removes and stops refreshing the
  // cached cloud policy). This is typically called when a profile is being
  // disassociated from a given user (e.g. during signout). No policy will be
  // provided by this object until the next time Initialize() is invoked.
  void DisconnectAndRemovePolicy();

  // Returns true if the underlying CloudPolicyClient is already registered.
  // Virtual for mocking.
  virtual bool IsClientRegistered() const;

  // Register the CloudPolicyClient using the passed OAuth token. This contacts
  // the DMServer to mint a new DMToken.
  void RegisterClient(const std::string& access_token);

  // Creates a CloudPolicyClient for this client. Used in situations where
  // callers want to create a DMToken without actually initializing the
  // profile's policy infrastructure.
  static scoped_ptr<CloudPolicyClient> CreateCloudPolicyClient(
      DeviceManagementService* device_management_service);

 private:
  // The profile this instance belongs to.
  Profile* profile_;

  // Typed pointer to the store owned by UserCloudPolicyManager. Note that
  // CloudPolicyManager only keeps a plain CloudPolicyStore pointer.
  scoped_ptr<UserCloudPolicyStore> store_;

  DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManager);
};

}  // namespace policy

#endif  // CHROME_BROWSER_POLICY_USER_CLOUD_POLICY_MANAGER_H_


text:
var util = require('../util')
  , path = require('path');

describe('trans performance', function () {
    [ 'perf-test' ].forEach(function (name) {
        require(path.join(process.cwd(), 'test', 'perf', name))(util);
    });
});


text:
using ElectronicObserver.Data.Battle.Phase;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicObserver.Data.Battle {

	/// <summary>
	/// 戦闘情報を保持するデータの基底です。
	/// </summary>
	public abstract class BattleData : ResponseWrapper {

		protected int[] _resultHPs;
		/// <summary>
		/// 戦闘終了時の各艦のHP
		/// </summary>
		public ReadOnlyCollection<int> ResultHPs { get { return Array.AsReadOnly( _resultHPs ); } }

		protected int[] _attackDamages;
		/// <summary>
		/// 各艦の与ダメージ
		/// </summary>
		public ReadOnlyCollection<int> AttackDamages { get { return Array.AsReadOnly( _attackDamages ); } }

		public PhaseInitial Initial { get; protected set; }
		public PhaseSearching Searching { get; protected set; }

		public override void LoadFromResponse( string apiname, dynamic data ) {
			base.LoadFromResponse( apiname, (object)data );

			Initial = new PhaseInitial( this );
			Searching = new PhaseSearching( this );

			_resultHPs = Initial.InitialHPs.ToArray();
			if ( _attackDamages == null )
				_attackDamages = new int[_resultHPs.Length];

		}

		/// <summary>
		/// MVPを取得した艦のインデックス
		/// </summary>
		public int MVPShipIndex {
			get {
				int index = -1;
				int max = 1;
				for ( int i = 0; i < 6; i++ ) {
					if ( _attackDamages[i] >= max ) {
						max = _attackDamages[i];
						index = i;
					}
				}
				return index == -1 ? 0 : index;
			}
		}

		/// <summary>
		/// MVPを取得した艦
		/// </summary>
		public ShipData MVPShip {
			get {
				return Initial.FriendFleet.MembersInstance[MVPShipIndex];
			}
		}

		/// <summary>
		/// MVPを取得した艦のインデックス(随伴護衛部隊)
		/// </summary>
		public int MVPShipCombinedIndex {
			get {
				int index = -1;
				int max = 1;
				for ( int i = 0; i < 6; i++ ) {
					if ( _attackDamages[i + 12] >= max ) {
						max = _attackDamages[i + 12];
						index = i;
					}
				}
				return index == -1 ? 0 : index;
			}
		}

		/// <summary>
		/// MVPを取得した艦(随伴護衛部隊)
		/// </summary>
		public ShipData MVPShipCombined {
			get {
				return KCDatabase.Instance.Fleet[2].MembersInstance[MVPShipCombinedIndex];
			}
		}

		/// <summary>
		/// 前回の戦闘データからパラメータを引き継ぎます。
		/// </summary>
		internal void TakeOverParameters( BattleData prev ) {
			_attackDamages = (int[])prev._attackDamages.Clone();
		}

		/// <summary>
		/// 対応しているAPIの名前を取得します。
		/// </summary>
		public abstract string APIName { get; }

		[Flags]
		public enum BattleTypeFlag {
			Undefined = 0,
			Day,
			Night,
			Practice = 0x1000,
			Combined = 0x2000,
		}

		/// <summary>
		/// 戦闘モード
		/// </summary>
		public abstract BattleTypeFlag BattleType { get; }

	}

}


text:
import DS from 'ember-data';
import Ember from 'ember';

const { computed } = Ember;
const { attr, belongsTo, hasMany, Model } = DS;

/**
 * The rows property is what forms the grid from a list of cells.
 */

export default Model.extend({
  title:    attr('string'),
  workbook: belongsTo('workbook', { async: true }),
  cells:    hasMany('cell', { async: true }),
  rows:     computed('cells', function() {
    return this.get('cells').reduce( (accum, cell) => {
      let row = cell.get('row');
      if (accum[row]) {
        accum[row].push(cell);
      } else {
        accum[row] = [cell];
      }
      return accum;
    }, [])
    .map(row => row.sortBy('column'));
  })
});


text:
namespace lomse
{

//forward declarations
class ImoScore;
class ImoBarline;
class ImoClef;
class ImoKeySignature;
class ImoTimeSignature;
class ColStaffObjsEntry;

//-----------------------------------------------------------------------------------------
// StaffObjsCursor
// A cursor for traversing staff objects by timepos, all instruments in parallel. As the
// score is traversed, StaffObjsCursor provides information about context (current clef,
// key and time signature)
//-----------------------------------------------------------------------------------------

//#define _LOMSE_NO_BREAK_TIME  100000000000000.0f         //any too big value

class StaffObjsCursor
{
private:
    ColStaffObjs* m_pColStaffObjs;
    ColStaffObjsIterator m_it;
    ColStaffObjsIterator m_savedPos;
    int m_numInstruments;
    int m_numLines;
    int m_numStaves;
    bool m_fScoreIsEmpty;
    ImoBarline* m_pLastBarline;
    std::vector<int> m_staffIndex;
    std::vector<ColStaffObjsEntry*> m_clefs;
    std::vector<ColStaffObjsEntry*> m_keys;
    std::vector<ColStaffObjsEntry*> m_times;
    std::vector<int> m_octave_shifts;

public:
    StaffObjsCursor(ImoScore* pScore);

    //positioning
    void move_next();

    //position info
    inline bool is_end() { return m_it == m_pColStaffObjs->end(); }
    //bool change_of_measure();

    //access to info
    inline bool is_empty_score() { return m_fScoreIsEmpty; }
    inline TimeUnits anacrusis_missing_time() {
        return m_pColStaffObjs->anacrusis_missing_time();
    }
    inline TimeUnits anacrusis_extra_time() {
        return m_pColStaffObjs->anacrusis_extra_time();
    }
    int num_measures();
    TimeUnits score_total_duration();

    //access to current pointed object
    inline int num_instrument() { return (*m_it)->num_instrument(); }
    inline int staff() { return (*m_it)->staff(); }
    inline int line() { return (*m_it)->line(); }
    inline int measure() { return (*m_it)->measure(); }
    inline TimeUnits time() { return (*m_it)->time(); }
    inline ImoObj* imo_object() { return (*m_it)->imo_object(); }
    ImoStaffObj* get_staffobj();
    inline ColStaffObjsEntry* cur_entry() { return *m_it; }
    int staff_index() { return staff_index_for(num_instrument(), staff()); }

    //access next/prev object without moving cursor position
    inline ColStaffObjsEntry* next_entry() { return m_it.next(); }
    inline ColStaffObjsEntry* prev_entry() { return m_it.prev(); }
    TimeUnits next_staffobj_timepos();

    //context
    inline int get_num_instruments() { return m_numInstruments; }
    inline int get_num_lines() { return m_numLines; }
    inline int get_num_staves() { return m_numStaves; }
    int num_staves_for_instrument(int iInstr);
    ImoClef* get_clef_for_instr_staff(int iInstr, int iStaff);
    ImoClef* get_applicable_clef();
    ImoKeySignature* get_key_for_instr_staff(int iInstr, int iStaff);
    ImoKeySignature* get_applicable_key();
    ImoTimeSignature* get_applicable_time_signature();
    ImoTimeSignature* get_time_signature_for_instrument(int iInstr);
    int get_applicable_clef_type();
    int get_applicable_octave_shift();
    int get_clef_type_for_instr_staff(int iInstr, int iStaff);
    int get_applicable_key_type();
    int get_key_type_for_instr_staff(int iInstr, int iStaff);
    ColStaffObjsEntry* get_clef_entry_for_instr_staff(int iInstr, int iStaff);
    ColStaffObjsEntry* get_key_entry_for_instr_staff(int iInstr, int iStaff);
    ColStaffObjsEntry* get_time_entry_for_instrument(int iInstr);
    ColStaffObjsEntry* get_prolog_time_entry_for_instrument(int iInstr);
    std::vector<int> get_applicable_clefs_for_instrument(int iInstr);
    inline ImoBarline* get_previous_barline() { return m_pLastBarline; }

    //helper
    void staff_index_to_instr_staff(int idx, int* iInstr, int* iStaff);
    inline int staff_index_for(int iInstr, int iStaff) {
        return m_staffIndex[iInstr] + iStaff;
    }

    //iterators management
    void go_back_to_saved_position();
    void save_position();

protected:
    void initialize_clefs_keys_times(ImoScore* pScore);
    void save_clef();
    void save_key_signature();
    void save_time_signature();
    void save_barline();
    void save_octave_shift_at_start(ImoStaffObj* pSO);
    void save_octave_shift_at_end(ImoStaffObj* pSO);

};

}   //namespace lomse

#endif    // __LOMSE_SYSTEM_CURSOR_H__


text:
namespace lamure
{
namespace pvs
{

class visibility_test
{
public:
	virtual ~visibility_test() {}

	virtual int initialize(int& argc, char** argv) = 0;
	virtual void test_visibility(grid* visibility_grid) = 0;
	virtual void shutdown() = 0;

	virtual bounding_box get_scene_bounds() const = 0;
};

}
}

#endif


text:
layout: page
title: "Regular Expressons"
# What topic does this page belong to?
group: bash
# Relative ordering of lessons within a topic
order: 4
#script: /javascripts/mypage.js
#scripts:
#  - /javascripts/one.js
#  - /javascripts/two.js
---

{% include toc.md %}

# Regular Expressons
{:.ui.dividing.header.no_toc}

Regular expressions, or "regex" are a _very_ powerful tool for searching and
processing text. At a high level, regular expressions are a way of defining
_patterns_ of text to operate on. Certain tools use regular expressions to take
these patterns and do something with them.

## Regex Syntax

Unfortunately, the syntax of regular expressions is not standardized. Every tool
that includes support for regular expressions implements a different set of
features and syntax. Luckily, there are some very common themes that appear in
most implementations. Where there is ambiguity between implementations, though,
we'll use the syntax used by `grep` and `sed`, two Unix tools that make heavy
use of regular expressions

### TL;DR

If you take only two things away from this discussion of regexs, let them be
this:

- `.`: matches _any single character_ (i.e., _once_)
- `<pattern>*`: matches `<pattern>` _zero or more times_

Read on to learn what these things mean and why they're cool!

Also, a lot of special regex characters are also special bash characters. To
ensure that your regex gets passed along to `grep` and `sed` in tact, you'll
almost always want to surround it in single quotes. See [Strings][strings] for
more information.

### Plain Patterns

There are a ton of special characters that you can use in regular expressions,
which we'll take a look at later. If you don't use any of these characters
(like plain word characters, numbers, some punctuation), the regular expression
will match exactly what you typed.

| Regex   | Matches                |
| -----   | -------                |
| `Hello` | Hello world!    |
| `9001`  | it's over 9001! |
{:.ui.striped.table}

__Note__: Most regular expressions are case sensitive by default.
{:.ui.info.message}

### Quantifiers (`*`, `\{n,m\}`)

Now we're getting into the special characters. Some special characters allow you
to specify _how many times_ a pattern should be repeated when trying to perform
a match.

- `<pattern>*`: matches _zero or more_ occurrences of `<pattern>`
- `<pattern>\{n,m\}`: matches _at least n and at most m_ occurrences of `<pattern>`
  - if `n` is omitted, it is assumed to be 0
  - if `m` is omitted, it is assumed to be infinity

By default, regexs are _greedy_: if the number of times they can repeat and
still match a pattern is ambiguous, they consume as many characters as they can.

| Regex         | Matches                                             |
| -----         | -------                                             |
| `help*`       | hel, help, ..., helpppppp, ... |
| `help\{1,2\}` | help, helpp                           |
{:.ui.striped.table}

__Note__: Single characters are treated as whole patterns. If the pattern you
want to repeat has more than one character, wrap the pattern in `\(...\)`.

### Character Classes (`[...]`)

Sometimes, we want a pattern to match any character from a set of characters. To
do this, we can define character classes. Simply put all the characters that you
want to potentially match inside `[...]`. You can also use hyphens (-) to
specify all characters within a range of characters.

| Regex       | Matches                                          |
| -----       | -------                                          |
| `[abc]`     | a, b, or c (a single character)                  |
| `[a-z]`     | any lowercase alphabetic character (ASCII order) |
| `[^abc]`    | any character __except__ a, b, or c              |
| `[A-Za-z_]` | any alphabetic character or an underscore        |
{:.ui.striped.table}

__Note__: Most characters which would otherwise be special characters do not need to
be escaped inside a character class.
{:.ui.info.message}

There are a lot of handy, "prebuilt" character classes that you can use without
using square braces:

| Regex | Matches                                        |
| ----- | -------                                        |
| `.`   | any character                                  |
| `\d`  | any digit                                      |
| `\w`  | any "word" character (letters and underscores) |
| `\s`  | any whitespace character (spaces, tabs)        |
{:.ui.striped.table}

For more character classes, see `man 7 re_format`.

### And more!

It would take far longer than this to fully list every regex feature, but those
listed here are often more than enough. For more information on regexs, Googling
helps a lot. And please, don't try to memorize regex syntax, except for `.` and
`*`! It's best just to look up the syntax for whatever tool you're using when
you're using it.

## Searching the Text of Files (grep)

The first tool we'll talk about, `grep`, is used to search the contents of files
for lines matching a regular expression. It's syntax is

~~~
$ grep <regex> [<file> ...]
~~~

Including one or more files is optional; if left out, `grep` accepts it's input on
`stdin`.

Normally, because the special characters used in regular expressions are often
special characters in bash too, it's best to enclose the pattern in single
quotes.

## Replacing Text (sed)

Another common thing to do is to replace text matching a certain pattern with
another string. The Unix tool `sed` has a feature that lets us accomplish this.
(In fact, `sed` can do [many more things][sed], but we'll just be looking at the find
and replace features). It's syntax (for our use cases specifically) is:

{% highlight bash %}
# Replace the first occurence of "<find>" on each line with "<replace>"
$ sed -e 's/<find>/<replace>/' [<file> ...]

# Replace the all occurences of "<find>" on each line with "<replace>"
$ sed -e 's/<find>/<replace>/g' [<file> ...]
{% endhighlight %}

As with `grep`, including one or more files is optional. It reads from `stdin`
when no file is specified.

## Example

There are tons of use cases for `sed` and `grep`, so to give you a taste of how
it works, we'll walk through a single, real world example: parsing the names of
the course staff from a text file.

Let's say I have the data about the instructors in the following format, but
all I want are their names.

{% highlight yaml %}
# file: staff.yml
staff:
  - id: jzimmerm
    domain: andrew
    name: Josh Zimmerman
  - id: jxc
    domain: cs
    name: Jacobo Carrasquel
  - id: nmunson
    domain: andrew
    name: Nick Munson
  - id: jezimmer
    domain: andrew
    name: Jake Zimmerman
  - id: dringwal
    domain: andrew
    name: Dan Ringwalt
  - id: mjmurphy
    domain: andrew
    name: Michael Murphy
{% endhighlight %}

Interestingly, all the relevant lines start with the same pattern! First let's
see if we can just print these lines. By searching for all lines that match the
pattern `name:` with `grep`, we can filter out lines that we don't even want to
consider:

{% highlight bash %}
$ grep 'name:' staff.yml
    name: Josh Zimmerman
    name: Jacobo Carrasquel
    name: Nick Munson
    name: Jake Zimmerman
    name: Dan Ringwalt
    name: Michael Murphy
{% endhighlight %}

Cool, now we just need to get rid of everything but the actual names. If you
notice, there are a few parts that each line has in common: some arbitrary
amount of whitespace at the beginning of the line, the literal text 'name: ',
and the actual name. We want to get rid of the first two of these parts, which
we can do using `sed`:

{% highlight bash %}
# pipe output of grep into sed
$ grep 'name:' staff.yml | sed -e 's/^ *name: //'
Josh Zimmerman
Jacobo Carrasquel
Nick Munson
Jake Zimmerman
Dan Ringwalt
Michael Murphy
{% endhighlight %}

Whoa, that's it! Let's break down what we just did.

First, we piped the output of our previous `grep` command into `sed`. This is so
that we only perform substitution on the lines that it makes sense to---the
lines containing 'name:'.

Then, we used `sed` to find a replace a pattern. Notice that the replacement
pattern is empty (there's nothing between the `//`). We do this because
deleting text is the same as finding and replacing with nothing.

Now let's look at the pattern we crafted for sed: `/^ *name: /`. The first
character is something we haven't seen yet. It just matches the beginning of a
line, so we know that the text we find doesn't come in the middle of a word or
name. Next, we say to match a space, repeated zero or more times. This takes
care of matching all the indentation in the file. After this we match `'name: '`
just like with `grep`.

Finally, by replacing this pattern with nothing, we've removed everything but
the names, which is what we wanted.

## References

This page has been far from comprehensive. Here are some resources that can help
when learning how to use regexs:

- [Regular Expressions 101][regex101]
  - Online regular expression visualizer and quick reference
  - Explains why a regex works the way it does
  - Quick reference of common patterns and examples
  - support for PRCE (Perl-compatible regex), Python, and JavaScript flavors
  - Neither grep nor sed flavors, but close
- [Regular-Expressions.info][regex-info]
  - Start with the [QuickStart][regex-info-qs]
  - In depth tutorial about regular expressions
- `man 7 re_format`
  - Man page for regular expression formats

## Going Further

- [Sed - An Introduction and Tutorial][sed]
  - A very comprehensive but readable introduction to sed

[strings]: {{ '/topics/bash/strings/' | prepend: site.baseurl }}
[sed]: http://www.grymoire.com/Unix/Sed.html
[regex101]: https://regex101.com/
[regex-info]: http://www.regular-expressions.info/
[regex-info-qs]: http://www.regular-expressions.info/quickstart.html


text:
import { combineReducers } from 'redux';
import facebookThreads from './facebookThreadsReducer';
import facebookUsers from './facebookUsersReducer';
import {routerReducer} from 'react-router-redux';

const rootReducer = combineReducers({
  facebookThreads,
  facebookUsers,
  routing: routerReducer
});

export default rootReducer;


text:
<template>
    <require from="./em-chat-channel-members-mgr.css"></require>

频道成员|分组管理

                成员管理
                分组管理

                        频道成员(${channel.members.length})

                            <input type="hidden" name="members">

                                    ${item.name ? item.name : item.username}

                                用户名
                                姓名
                                邮箱

                                登录
                                状态

                                ${item.username}
                                ${item.name} ${item | online:onlines}
                                ${item.mails}

                                    <span ui-pp data-html="${item.level ? '职位: ' + item.level + '
' : ''} ${item.phone ? '座机: ' + item.phone + '
' : ''} ${item.mobile ? '手机: ' + item.mobile + '
' : ''} ${item.place ? '位置: ' + item.place + '
' : ''} ${item.hobby ? '爱好: ' + item.hobby : ''}">

                                ${item.lastLoginDate | timeago}

启用中

已停用

                        添加频道分组

                                <input type="text" value.bind="name" name="name" placeholder="标识(小写字母数组-_组合)">

                                <input type="text" value.bind="title" name="title" placeholder="描述(可选)">

                                <button title="添加频道分组" click.delegate="addHandler()" class="circular ui icon blue button ${isSending ? 'disabled' : ''}" type="button"></button>

                                标识
                                描述

                                成员
                                操作

                                ${item.name}

                                        <input type="text" value.bind="item.name" placeholder="分组标识">

                                ${item.title}

                                        <input type="text" value.bind="item.title" placeholder="分组描述">

                                        <input type="hidden" name="members">

                                                ${member.name ? member.name : member.username}

                                    <button if.bind="item.creator.username == loginUser.username || channel.owner.username == loginUser.username" show.bind="!item.isEditing" click.delegate="editHandler(item)" class="mini ui button">
                                        编辑
                                    </button>
                                    <button if.bind="item.creator.username == loginUser.username || channel.owner.username == loginUser.username" click.delegate="updateHandler(item)" show.bind="item.isEditing" class="mini green ui button">
                                        更新
                                    </button>

                                    删除

确认删除

</template>


text:
import struct
import logging
from six.moves import cPickle as pickle

def send(fd, o):
    d = pickle.dumps(o)
    fd.send(struct.pack('>I', len(d)) + d)

def recv(fd):
    d = fd.recv(struct.calcsize('>I'))
    assert len(d) == struct.calcsize('>I'), repr(d)
    size, = struct.unpack('>I', d)
    return pickle.loads(fd.recv(size))

def setup_logger(logger):
    FORMAT = '%(asctime)-11s [%(levelname)s] [%(name)-9s] %(message)s'
    formatter = logging.Formatter(FORMAT)
    logger.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    return logger


text:
import schema from './schema.js';
import resolvers from './resolvers.js';
import createLoaders from './loaders.js';
import CoverArtArchiveClient from './client.js';
import { ONE_DAY } from '../../util.js';

export default {
  name: 'Cover Art Archive',
  description: `Retrieve cover art images for releases from the [Cover Art
Archive](https://coverartarchive.org/).`,
  extendContext(context, { coverArtClient, coverArtArchive = {} } = {}) {
    const client = coverArtClient || new CoverArtArchiveClient(coverArtArchive);
    const cacheSize = parseInt(
      process.env.COVER_ART_ARCHIVE_CACHE_SIZE ||
        process.env.GRAPHBRAINZ_CACHE_SIZE ||
        8192,
      10
    );
    const cacheTTL = parseInt(
      process.env.COVER_ART_ARCHIVE_CACHE_TTL ||
        process.env.GRAPHBRAINZ_CACHE_TTL ||
        ONE_DAY,
      10
    );
    return {
      ...context,
      // Add the client instance directly onto `context` for backwards
      // compatibility.
      coverArtClient: client,
      loaders: {
        ...context.loaders,
        ...createLoaders({ client, cacheSize, cacheTTL }),
      },
    };
  },
  extendSchema: {
    schemas: [schema],
    resolvers,
  },
};


text:
'use strict';

var _expect = require('expect');

var _generateValidator = require('../generateValidator');

var _generateValidator2 = _interopRequireDefault(_generateValidator);

var _plain = require('../structure/plain');

var _plain2 = _interopRequireDefault(_plain);

var _expectations = require('../structure/plain/expectations');

var _expectations2 = _interopRequireDefault(_expectations);

var _immutable = require('../structure/immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _expectations3 = require('../structure/immutable/expectations');

var _expectations4 = _interopRequireDefault(_expectations3);

var _addExpectations = require('./addExpectations');

var _addExpectations2 = _interopRequireDefault(_addExpectations);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var describeGenerateValidator = function describeGenerateValidator(name, structure, expect) {
  var fromJS = structure.fromJS;

  var required = function required(value) {
    return value == null ? 'Required' : undefined;
  };
  var minValue = function minValue(min) {
    return function (value) {
      return value && value < min ? 'Too low' : undefined;
    };
  };

  describe(name, function () {
    it('should return a function', function () {
      var validator = (0, _generateValidator2.default)({}, structure);
      expect(validator).toBeA('function');
    });

    it('should always pass validation when no validators given', function () {
      var validator = (0, _generateValidator2.default)({}, structure);
      expect(validator(fromJS({}))).toEqual({});
      expect(validator(fromJS({
        foo: 42,
        bar: 43
      }))).toEqual({});
    });

    it('should validate simple fields', function () {
      var requiredSpy = (0, _expect.createSpy)(required).andCallThrough();
      var minValueSpy = (0, _expect.createSpy)(minValue(4)).andCallThrough();
      var validator = (0, _generateValidator2.default)({
        foo: requiredSpy,
        bar: minValueSpy
      }, structure);

      expect(requiredSpy).toNotHaveBeenCalled();
      expect(minValueSpy).toNotHaveBeenCalled();

      var values1 = fromJS({});
      var result = validator(values1);
      expect(requiredSpy).toHaveBeenCalled();
      expect(requiredSpy.calls.length).toBe(1);
      expect(requiredSpy.calls[0].arguments[0]).toBe(undefined);
      expect(requiredSpy.calls[0].arguments[1]).toEqual(values1);
      expect(minValueSpy).toHaveBeenCalled();
      expect(minValueSpy.calls.length).toBe(1);
      expect(minValueSpy.calls[0].arguments[0]).toBe(undefined);
      expect(minValueSpy.calls[0].arguments[1]).toEqual(values1);
      expect(result).toEqual({
        foo: 'Required'
      });

      var values2 = fromJS({
        foo: 'Hello',
        bar: 3
      });
      var result2 = validator(values2);
      expect(requiredSpy.calls.length).toBe(2);
      expect(requiredSpy.calls[1].arguments[0]).toBe('Hello');
      expect(requiredSpy.calls[1].arguments[1]).toEqual(values2);
      expect(minValueSpy.calls.length).toBe(2);
      expect(minValueSpy.calls[1].arguments[0]).toBe(3);
      expect(minValueSpy.calls[1].arguments[1]).toEqual(values2);
      expect(result2).toEqual({
        bar: 'Too low'
      });

      var values3 = fromJS({
        foo: 'Hello',
        bar: 4
      });
      var result3 = validator(values3);
      expect(requiredSpy.calls.length).toBe(3);
      expect(requiredSpy.calls[2].arguments[0]).toBe('Hello');
      expect(requiredSpy.calls[2].arguments[1]).toEqual(values3);
      expect(minValueSpy.calls.length).toBe(3);
      expect(minValueSpy.calls[2].arguments[0]).toBe(4);
      expect(minValueSpy.calls[2].arguments[1]).toEqual(values3);
      expect(result3).toEqual({});
    });

    it('should validate deep fields', function () {
      var requiredSpy = (0, _expect.createSpy)(required).andCallThrough();
      var minValueSpy = (0, _expect.createSpy)(minValue(4)).andCallThrough();
      var validator = (0, _generateValidator2.default)({
        'deep.foo': requiredSpy,
        'even.deeper.bar': minValueSpy
      }, structure);

      expect(requiredSpy).toNotHaveBeenCalled();
      expect(minValueSpy).toNotHaveBeenCalled();

      var result = validator(fromJS({}));
      expect(requiredSpy).toHaveBeenCalled();
      expect(requiredSpy.calls.length).toBe(1);
      expect(requiredSpy.calls[0].arguments[0]).toBe(undefined);
      expect(requiredSpy.calls[0].arguments[1]).toEqual(fromJS({}));
      expect(minValueSpy).toHaveBeenCalled();
      expect(minValueSpy.calls.length).toBe(1);
      expect(minValueSpy.calls[0].arguments[0]).toBe(undefined);
      expect(minValueSpy.calls[0].arguments[1]).toEqual(fromJS({}));
      expect(result).toEqual({
        deep: {
          foo: 'Required'
        }
      });

      var values2 = fromJS({
        deep: {
          foo: 'Hello'
        },
        even: {
          deeper: {
            bar: 3
          }
        }
      });
      var result2 = validator(values2);
      expect(requiredSpy.calls.length).toBe(2);
      expect(requiredSpy.calls[1].arguments[0]).toBe('Hello');
      expect(requiredSpy.calls[1].arguments[1]).toEqual(values2);
      expect(minValueSpy.calls.length).toBe(2);
      expect(minValueSpy.calls[1].arguments[0]).toBe(3);
      expect(minValueSpy.calls[1].arguments[1]).toEqual(values2);
      expect(result2).toEqual({
        even: {
          deeper: {
            bar: 'Too low'
          }
        }
      });

      var values3 = fromJS({
        deep: {
          foo: 'Hello'
        },
        even: {
          deeper: {
            bar: 4
          }
        }
      });
      var result3 = validator(values3);
      expect(requiredSpy.calls.length).toBe(3);
      expect(requiredSpy.calls[2].arguments[0]).toBe('Hello');
      expect(requiredSpy.calls[2].arguments[1]).toEqual(values3);
      expect(minValueSpy.calls.length).toBe(3);
      expect(minValueSpy.calls[2].arguments[0]).toBe(4);
      expect(minValueSpy.calls[2].arguments[1]).toEqual(values3);
      expect(result3).toEqual({});
    });

    it('should accept multiple validators', function () {
      var requiredSpy = (0, _expect.createSpy)(required).andCallThrough();
      var minValueSpy = (0, _expect.createSpy)(minValue(4)).andCallThrough();
      var validator = (0, _generateValidator2.default)({
        foo: [requiredSpy, minValueSpy]
      }, structure);

      expect(requiredSpy).toNotHaveBeenCalled();
      expect(minValueSpy).toNotHaveBeenCalled();

      var values1 = fromJS({});
      var result1 = validator(values1);
      expect(requiredSpy).toHaveBeenCalled();
      expect(requiredSpy.calls.length).toBe(1);
      expect(requiredSpy.calls[0].arguments[0]).toBe(undefined);
      expect(requiredSpy.calls[0].arguments[1]).toEqual(values1);
      expect(minValueSpy).toNotHaveBeenCalled(); // because required errored
      expect(result1).toEqual({
        foo: 'Required'
      });

      var values2 = fromJS({ foo: '3' });
      var result2 = validator(values2);
      expect(requiredSpy.calls.length).toBe(2);
      expect(requiredSpy.calls[1].arguments[0]).toBe('3');
      expect(requiredSpy.calls[1].arguments[1]).toEqual(values2);
      expect(minValueSpy).toHaveBeenCalled();
      expect(minValueSpy.calls.length).toBe(1);
      expect(minValueSpy.calls[0].arguments[0]).toBe('3');
      expect(minValueSpy.calls[0].arguments[1]).toEqual(values2);
      expect(result2).toEqual({
        foo: 'Too low'
      });

      var values3 = fromJS({ foo: '4' });
      var result3 = validator(values3);
      expect(requiredSpy.calls.length).toBe(3);
      expect(requiredSpy.calls[2].arguments[0]).toBe('4');
      expect(requiredSpy.calls[2].arguments[1]).toEqual(values3);
      expect(minValueSpy.calls.length).toBe(2);
      expect(minValueSpy.calls[1].arguments[0]).toBe('4');
      expect(minValueSpy.calls[1].arguments[1]).toEqual(values3);
      expect(result3).toEqual({});
    });
  });
};

describeGenerateValidator('generateValidator.plain', _plain2.default, (0, _addExpectations2.default)(_expectations2.default));
describeGenerateValidator('generateValidator.immutable', _immutable2.default, (0, _addExpectations2.default)(_expectations4.default));


text:
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_emg as upmEmg

def main():
    # Tested with the EMG Muscle Signal Reader Sensor Module
    # Instantiate a EMG on analog pin A0
    myEMG = upmEmg.EMG(0)

    ## Exit handlers ##
    # This stops python from printing a stacktrace when you hit control-C
    def SIGINTHandler(signum, frame):
        raise SystemExit

    # This lets you run code on exit, including functions from myEMG
    def exitHandler():
        print("Exiting")
        sys.exit(0)

    # Register exit handlers
    atexit.register(exitHandler)
    signal.signal(signal.SIGINT, SIGINTHandler)

    print("Calibrating....")
    myEMG.calibrate()

    while (1):
        print(myEMG.value())
        time.sleep(.1)

if __name__ == '__main__':
    main()


text:
class AddFileToReviews < ActiveRecord::Migration
  def change
    add_column :reviews, :filename, :string
    add_column :reviews, :extension, :string
  end
end


text:
#region Using Statements
using System.IO;

using Cake.Core;
using Cake.Core.IO;
using Cake.Testing;

using Cake.AWS.S3;
#endregion

namespace Cake.AWS.CloudFront.Tests
{
    internal static class CakeHelper
    {
        #region Methods
        public static ICakeEnvironment CreateEnvironment()
        {
            var environment = FakeEnvironment.CreateWindowsEnvironment();
            environment.WorkingDirectory = Directory.GetCurrentDirectory();
            environment.WorkingDirectory = environment.WorkingDirectory.Combine("../../../");

            return environment;
        }

        public static IS3Manager CreateS3Manager()
        {
            return new S3Manager(new FileSystem(), CakeHelper.CreateEnvironment(), new DebugLog());
        }

        public static ICloudFrontManager CreateCloudFrontManager()
        {
            return new CloudFrontManager(CakeHelper.CreateEnvironment(), new DebugLog());
        }
        #endregion
    }
}


text:
package com.wangjie.androidbucket.support.recyclerview.layoutmanager;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import com.wangjie.androidbucket.support.recyclerview.listener.OnRecyclerViewScrollLocationListener;
import com.wangjie.androidbucket.utils.ABTextUtil;

import java.util.Arrays;

/**
 * Author: wangjie
 * Email: tiantian.china.2@gmail.com
 * Date: 1/19/15.
 */
public class ABaseStaggeredGridLayoutManager extends StaggeredGridLayoutManager implements RecyclerViewScrollManager.OnScrollManagerLocation {
    private static final String TAG = ABaseStaggeredGridLayoutManager.class.getSimpleName();

    private RecyclerViewScrollManager recyclerViewScrollManager;

    public void setOnRecyclerViewScrollListener(RecyclerView recyclerView, OnRecyclerViewScrollLocationListener onRecyclerViewScrollLocationListener) {
        ensureRecyclerViewScrollManager();
        recyclerViewScrollManager.setOnRecyclerViewScrollLocationListener(onRecyclerViewScrollLocationListener);
        recyclerViewScrollManager.setOnScrollManagerLocation(this);
        recyclerViewScrollManager.registerScrollListener(recyclerView);
    }

    public ABaseStaggeredGridLayoutManager(int spanCount, int orientation) {
        super(spanCount, orientation);
    }

    public boolean isScrolling() {
        if (null != recyclerViewScrollManager) {
            return recyclerViewScrollManager.isScrolling();
        }
        return false;
    }

    public RecyclerViewScrollManager getRecyclerViewScrollManager() {
        ensureRecyclerViewScrollManager();
        return recyclerViewScrollManager;
    }
    private void ensureRecyclerViewScrollManager(){
        if (null == recyclerViewScrollManager) {
            recyclerViewScrollManager = new RecyclerViewScrollManager();
        }
    }

    @Override
    public boolean isTop(RecyclerView recyclerView) {
        int[] into = findFirstVisibleItemPositions(null);
        return !ABTextUtil.isEmpty(into) && 0 == into[0];
    }

    @Override
    public boolean isBottom(RecyclerView recyclerView) {
        int into[] = findLastCompletelyVisibleItemPositions(null);
        int lastPosition = recyclerView.getAdapter().getItemCount() - 1;
        Arrays.sort(into);
        return !ABTextUtil.isEmpty(into) && lastPosition == into[into.length - 1];
    }
}


text:
package org.liquibase.maven.plugins;

import liquibase.logging.LogMessageFilter;
import liquibase.logging.Logger;
import liquibase.logging.core.AbstractLogService;
import liquibase.logging.core.AbstractLogger;
import org.apache.maven.plugin.logging.Log;

import java.util.logging.Level;

public class MavenLogService extends AbstractLogService {

    private final Log rootLog;
    private MavenLogger mavenLogger;

    public MavenLogService(Log log) {
        this.rootLog = log;
    }

    @Override
    public int getPriority() {
        return PRIORITY_NOT_APPLICABLE;
    }

    @Override
    public Logger getLog(Class clazz) {
        if (this.mavenLogger == null) {
            this.mavenLogger = new MavenLogger(rootLog);
        }
        return this.mavenLogger;
    }

    private static class MavenLogger extends AbstractLogger {

        private final Log mavenLog;

        public MavenLogger(Log log) {
            this.mavenLog = log;
        }

        @Override
        public void log(Level level, String message, Throwable e) {
            if (level == Level.OFF) {
                return;
            }

            if (level.equals(Level.SEVERE)) {
                mavenLog.error(message, e);
            } else if (level.equals(Level.WARNING)) {
                mavenLog.warn(message, e);
            } else if (level.equals(Level.INFO)) {
                mavenLog.info(message, e);
            } else if (level.equals(Level.FINE) || level.equals(Level.FINER) || level.equals(Level.FINEST)) {
                mavenLog.debug(message, e);
            } else if (level.equals(Level.CONFIG)) {
                mavenLog.debug(message, e);
            }
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace OpenCFP\Test\Integration;

interface TransactionalTestCase
{
}


text:
{#-
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you 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.
-#}
<div{{attrs|default({}, true)|xmlattr}}>
  {% if artifact %}
    {{artifact.html_text|safe}}
  {% else %}
    {{text}}
  {% endif %}
</div>


text:
require 'test_helper'

class CanTableTest < ActiveSupport::TestCase

  test "CanTable module exists" do
    assert_kind_of Module, CanTable
  end

  test "can_table method is defined" do
    assert ApplicationController.method_defined?(:can_table),
           "can_table should be defined"
  end

  test "cancancan can be retrieved" do
    assert Ability.new(""), "Ability should be created"
  end

end


text:
package com.lfk.justweengine.Anim;

import com.lfk.justweengine.Engine.GameTimer;

/**
 * 判断生死
 *
 * @author liufengkai
 *         Created by liufengkai on 15/12/5.
 */
public class AliveAnimation extends BaseAnim {
    private int liftTime;
    private GameTimer timer;

    public AliveAnimation(int liftTime) {
        this.liftTime = liftTime;
        this.timer = new GameTimer();
        animating = true;
        animType = AnimType.ALIVE;
    }

    @Override
    public boolean adjustAlive(boolean ori) {
        if (liftTime > 0 && timer.stopWatch(liftTime)) {
            ori = false;
        }
        return ori;
    }
}


text:
import { Injectable } from '@angular/core';
import { Http,Response, Headers, RequestOptions } from '@angular/http';
import { CommonService } from '../providers/common.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class CredentialService {
  public baseUrl: string = "";
  login: any = false;
  headers: any;
  access_token: string;
  private loggedIn = false;
  constructor(private http: Http, private conf: CommonService) {

    this.loggedIn = !!localStorage.getItem('access_token');
    if(this.loggedIn){
      this.conf.updateBaseUrl();
    }
    this.baseUrl = this.conf.baseUrl;
  }

  resetLoginStatus() {
    this.login = false;
  }

  isLoggedIn() {
    let access_token = localStorage.getItem("access_token");
    if (access_token) {
      return !this.login;
    } else {
      return this.login;
    }
  }

  verifyUser(data: Object) {
    this.baseUrl = this.conf.baseUrl;
    return this.http.post(this.baseUrl + "/login", data)
                    .map(this.extractData)
                    .catch(this.handleError);
  }

  logOut(){
    this.conf.resetBaseUrl();
    localStorage.clear();
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

  private handleError(error: Response | any) {
    return Observable.throw(error.status);
  }
}


text:
public class GarageMain {

	public static void main(String[] args) {

		//inicializar los componentes de la applicacion

		//4 clientes

		//5 vehiculos

		//30 plazas de garaje

		//1 garaje

		inicializarComponentes();

	}

	public static void inicializarComponentes(){

	}

}


text:
// Start of user code Copyright

// End of user code

package eu.scott.warehouse.domains.mission;

import org.eclipse.lyo.oslc4j.core.model.OslcConstants;

// Start of user code imports
// End of user code

public interface MissionDomainConstants
{
    // Start of user code user constants
    // End of user code

    public static String MISSIONONTOLOGY_DOMAIN = "http://ontology.cf.ericsson.net/mission_ontology/";
    public static String MISSIONONTOLOGY_NAMSPACE = "http://ontology.cf.ericsson.net/mission_ontology/";
    public static String MISSIONONTOLOGY_NAMSPACE_PREFIX = "mission";

    public static String AGENTREQUEST_PATH = "agentRequest";
    public static String AGENTREQUEST_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String AGENTREQUEST_LOCALNAME = "AgentRequest"; //localName of the rdfs:class the resource describes
    public static String AGENTREQUEST_TYPE = AGENTREQUEST_NAMESPACE + AGENTREQUEST_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String COMPOSITESELECTOR_PATH = "compositeSelector";
    public static String COMPOSITESELECTOR_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String COMPOSITESELECTOR_LOCALNAME = "CompositeSelector"; //localName of the rdfs:class the resource describes
    public static String COMPOSITESELECTOR_TYPE = COMPOSITESELECTOR_NAMESPACE + COMPOSITESELECTOR_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String DEREGISTRATIONREQUEST_PATH = "deregistrationRequest";
    public static String DEREGISTRATIONREQUEST_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String DEREGISTRATIONREQUEST_LOCALNAME = "DeregistrationRequest"; //localName of the rdfs:class the resource describes
    public static String DEREGISTRATIONREQUEST_TYPE = DEREGISTRATIONREQUEST_NAMESPACE + DEREGISTRATIONREQUEST_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String DIRECTSELECTOR_PATH = "directSelector";
    public static String DIRECTSELECTOR_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String DIRECTSELECTOR_LOCALNAME = "DirectSelector"; //localName of the rdfs:class the resource describes
    public static String DIRECTSELECTOR_TYPE = DIRECTSELECTOR_NAMESPACE + DIRECTSELECTOR_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String GOAL_PATH = "goal";
    public static String GOAL_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String GOAL_LOCALNAME = "Goal"; //localName of the rdfs:class the resource describes
    public static String GOAL_TYPE = GOAL_NAMESPACE + GOAL_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String LOCATION_PATH = "location";
    public static String LOCATION_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String LOCATION_LOCALNAME = "Location"; //localName of the rdfs:class the resource describes
    public static String LOCATION_TYPE = LOCATION_NAMESPACE + LOCATION_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String LOCATIONSELECTOR_PATH = "locationSelector";
    public static String LOCATIONSELECTOR_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String LOCATIONSELECTOR_LOCALNAME = "LocationSelector"; //localName of the rdfs:class the resource describes
    public static String LOCATIONSELECTOR_TYPE = LOCATIONSELECTOR_NAMESPACE + LOCATIONSELECTOR_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String MISSION_PATH = "mission";
    public static String MISSION_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String MISSION_LOCALNAME = "Mission"; //localName of the rdfs:class the resource describes
    public static String MISSION_TYPE = MISSION_NAMESPACE + MISSION_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String MOVEGOAL_PATH = "moveGoal";
    public static String MOVEGOAL_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String MOVEGOAL_LOCALNAME = "MoveGoal"; //localName of the rdfs:class the resource describes
    public static String MOVEGOAL_TYPE = MOVEGOAL_NAMESPACE + MOVEGOAL_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String REGISTRATIONREQUEST_PATH = "registrationRequest";
    public static String REGISTRATIONREQUEST_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String REGISTRATIONREQUEST_LOCALNAME = "RegistrationRequest"; //localName of the rdfs:class the resource describes
    public static String REGISTRATIONREQUEST_TYPE = REGISTRATIONREQUEST_NAMESPACE + REGISTRATIONREQUEST_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String SELECTOR_PATH = "selector";
    public static String SELECTOR_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String SELECTOR_LOCALNAME = "Selector"; //localName of the rdfs:class the resource describes
    public static String SELECTOR_TYPE = SELECTOR_NAMESPACE + SELECTOR_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String TYPESELECTOR_PATH = "typeSelector";
    public static String TYPESELECTOR_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String TYPESELECTOR_LOCALNAME = "TypeSelector"; //localName of the rdfs:class the resource describes
    public static String TYPESELECTOR_TYPE = TYPESELECTOR_NAMESPACE + TYPESELECTOR_LOCALNAME; //fullname of the rdfs:class the resource describes
    public static String WILDCARDSELECTOR_PATH = "wildcardSelector";
    public static String WILDCARDSELECTOR_NAMESPACE = MISSIONONTOLOGY_NAMSPACE; //namespace of the rdfs:class the resource describes
    public static String WILDCARDSELECTOR_LOCALNAME = "WildcardSelector"; //localName of the rdfs:class the resource describes
    public static String WILDCARDSELECTOR_TYPE = WILDCARDSELECTOR_NAMESPACE + WILDCARDSELECTOR_LOCALNAME; //fullname of the rdfs:class the resource describes
}


text:
package io.github.marktony.espresso.mvp.addpackage;

import io.github.marktony.espresso.mvp.BasePresenter;
import io.github.marktony.espresso.mvp.BaseView;

/**
 * Created by lizhaotailang on 2017/2/10.
 */

public interface AddPackageContract {

    interface View extends BaseView<Presenter> {

        void showNumberExistError();

        void showNumberError();

        void setProgressIndicator(boolean loading);

        void showPackagesList();

        void showNetworkError();

    }

    interface Presenter extends BasePresenter {

        void savePackage(String number, String name, int color);

    }

}


text:
package alma.acs.logging.engine.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import alma.acs.logging.engine.parser.ACSLogParser;
import alma.acs.logging.engine.parser.ACSLogParserFactory;
import alma.acs.util.StopWatch;

import com.cosylab.logging.engine.LogMatcher;
import com.cosylab.logging.engine.ACS.ACSRemoteErrorListener;
import com.cosylab.logging.engine.ACS.ACSRemoteLogListener;
import com.cosylab.logging.engine.ACS.ACSRemoteRawLogListener;
import com.cosylab.logging.engine.log.ILogEntry;

/**
 * An helper class to perform synchronous I/O operations like load and save.
 *

 * Load and save methods are executed in a synchronous way i.e. they do not return
 * until the I/O is terminated (or an exception occurs).
 *

 * Intermediate results useful to monitor the progress of the I/O are communicated
 * to the listeners implementing the IOProgressListener interface.
 *

 * The load and save methods of this class are synchronized but I would not say
 * that this class is thread safe because it does not hold and lock the objects it receives
 * as parameters like for example the BufferReader and the BufferWriter.
 * So thread safety must be ensured by the owner of such objects.
 *
Loading

 * The loading is performed through one of the overloaded loadLogs methods.
 * The bytes read and the number of the logs successfully read are sent to the listeners
 * implementing the IOProgressListener interface.
 * If there are filters, an audience or a discard level defined, then each log is checked
 * before being sent to the listener.
 *
 *
Saving

 *  The saving of logs can be done by passing a Collection  of logs or an Iteratorto one of the
 *  overloaded saveLogs methods.
 *  Such methods communicates the progress to the listener implementing the
 *  IOProgressListener interface.
 *

 *  Saving logs by passing the name of the file does not require any extra steps.
 *

 *  Saving logs by passing a BufferedWriter is always a three steps procedure:
 *

 *
call the prepareSaveFile to write XML header
 *
save the logs by calling one of the saveLogs or the saveLog
 *
execute Save to add the closing XML tags, flush and close the buffer
 *

 *

 * Load and save can be very long operations. To stop an I/O, the stopIO()
 * must be executed.
 *
 * @author acaproni
 *
 */
public class IOHelper extends LogMatcher {

	/**
	 * GZipLogOutStream subclass GZIPOutputStream to set the compression level.
	 *
	 * @author acaproni
	 *
	 */
	public class GZipLogOutStream extends GZIPOutputStream {

		/**
		 * Constructor
		 *
		 * @param stream The stream for writing compressed logs into
		 * @param level The compression level
		 *
		 * @throws IOException
		 *
		 * @see {@link Deflater}
		 */
		public GZipLogOutStream(OutputStream stream, int level) throws IOException {
			super(stream);
			super.def.setLevel(level);
		}

		/**
		 * Constructor using the default compression level
		 *
		 * @param stream The stream for writing compressed logs into
		 * @throws IOException
		 */
		public GZipLogOutStream(OutputStream stream) throws IOException {
			super(stream,DEFAULT_COMPRESSION_LEVEL);
		}
	}

	/**
	 * Constructor
	 *
	 * @throws Exception In case of errors building the parser
	 */
	public IOHelper() throws Exception {
		parser=ACSLogParserFactory.getParser();
	}

	/**
	 * The default compression level while saving files
	 */
	public static final int DEFAULT_COMPRESSION_LEVEL = 5;

	/**
	 * Signal that a load or a save must be stopped
	 */
	protected volatile boolean stopped=false;

	/**
	 * The parser
	 */
	private final ACSLogParser parser;

	/**
	 * Inject the log into the engine
	 *
	 * @param logStr The string representation of the log
	 * @param logListener The listener i.e. the callback for each new log to add
	 */
	private void injectLog (
			StringBuilder logStr,
			ACSRemoteLogListener logListener,
			ACSRemoteRawLogListener rawLogListener,
			ACSRemoteErrorListener errorListener) {
		if (errorListener==null || (logListener==null && rawLogListener==null)) {
			throw new IllegalArgumentException("Listeners can't be null");
		}
		if (logListener!=null) {
			ILogEntry log=null;
			try {
				log = parser.parse(logStr.toString().trim());
			} catch (Exception e) {
				errorListener.errorReceived(logStr.toString().trim());
				System.err.println("Exception parsing a log: "+e.getMessage()+" ["+logStr+"]");
				e.printStackTrace(System.err);
				return;
			}
			if (match(log)) {
				logListener.logEntryReceived(log);
			}
		}
		if (rawLogListener!=null) {
			rawLogListener.xmlEntryReceived(logStr.toString().trim());
		}
	}

	/**
	 * Load the logs from the file with the given name.
	 *

	 * The logs are sent to the ACSRemoteLogListener and /or
	 * to the ACSRemoteRawLogListener.
	 *
	 * @param fileName The name of the file to read logs from
	 * @param logListener The callback for each new log read from the IO
	 * @param rawLogListener The callback for each new XML log read from the IO
	 * @param errorListener The listener for errors
	 * @param progressListener The listener to be notified about the bytes read
	 * @param gzip If true the file to read is compressed in GZIP format
	 * @return The length of the file to read
	 * @throws IOException In case of an IO error while reading the file
	 * @throws Exception In case of error building the parser
	 */
	public synchronized long loadLogs(
			String fileName,
			ACSRemoteLogListener logListener,
			ACSRemoteRawLogListener rawLogListener,
			ACSRemoteErrorListener errorListener,
			IOPorgressListener progressListener,
			boolean gzip) throws IOException, Exception {
		if (fileName==null || fileName.isEmpty()) {
			throw new IllegalArgumentException("Invalid file name: "+fileName);
		}
		if (progressListener==null) {
			throw new IllegalArgumentException("The progress listener can't be null");
		}
		File f = new File(fileName);
		InputStream inStream = new FileInputStream(f);
		BufferedReader reader;
		if (gzip) {
			InputStreamReader inStreamReader= new InputStreamReader(new GZIPInputStream(inStream));
			reader = new BufferedReader(inStreamReader);
		} else {
			reader = new BufferedReader(new InputStreamReader(inStream));
		}
		loadLogs(reader, logListener, rawLogListener, errorListener,progressListener);
		return f.length();
	}

	/**
	 * Load the logs from the file with the given name.
	 *

	 * The logs are sent to the ACSRemoteLogListener and /or
	 * to the ACSRemoteRawLogListener.
	 *

	 * The file can be compressed (GZIP) or plain.
	 * Compressed file names must terminate with .gz while
	 * plain XML file names must end with .xml.
	 *
	 * @param fileName The name of the file to read logs from.
	 * 					fileName must terminate with .gz or .xml (case insensitive)
	 * @param logListener The callback for each new log read from the IO
	 * @param rawLogListener The callback for each new XML log read from the IO
	 * @param errorListener The listener for errors
	 * @param progressListener The listener to be notified about the bytes read
	 * @return The length of the file to read
	 * @throws IOException In case of an IO error while reading the file
	 * @throws Exception In case of error building the parser
	 */
	public synchronized long loadLogs(
			String fileName,
			ACSRemoteLogListener logListener,
			ACSRemoteRawLogListener rawLogListener,
			ACSRemoteErrorListener errorListener,
			IOPorgressListener progressListener) throws IOException, Exception {
		String name = fileName.toLowerCase();
		if (!name.endsWith(".gz") && !name.endsWith(".xml")) {
			throw new IllegalArgumentException("File name must end with .gz or .xml");
		}
		return loadLogs(fileName, logListener, rawLogListener, errorListener, progressListener,name.endsWith(".gz"));
	}

	/**
	 * Load the logs from the given BufferedReader.
	 *

	 * The logs are sent to the ACSRemoteLogListener and /or
	 * to the ACSRemoteRawLogListener.
	 *
	 * @param reader The reader to read logs from
	 * @param logListener The callback for each new log read from the IO
	 * @param rawLogListener The callback for each new XML log read from the IO
	 * @param errorListener The listener for errors
	 * @param progressListener The listener to be notified about the bytes read
	 *
	 * @throws IOException In case of an IO error while reading the file
	 */
	public synchronized void loadLogs(
			BufferedReader reader,
			ACSRemoteLogListener logListener,
			ACSRemoteRawLogListener rawLogListener,
			ACSRemoteErrorListener errorListener,
			IOPorgressListener progressListener) throws IOException {
		if (reader==null || errorListener==null) {
			throw new IllegalArgumentException("Parameters can't be null");
		}
		if (logListener==null && rawLogListener==null) {
			throw new IllegalArgumentException("No log listeners defined");
		}
		if (progressListener==null) {
			throw new IllegalArgumentException("The progress listener can't be null");
		}

		stopped=false;

		// The "clever" buffer
		LogStringBuffer buffer = new LogStringBuffer();

		// Read one char per iteration
		int chRead;

		// Count the bytes read
		int bytesRead=0;

		int logRecordsRead = 0;

		// Here the buffer writes the XML of each log
		StringBuilder xmlStr = new StringBuilder();

		/**
		 * The size of the buffer
		 */
		final int size=16384;

		/**
		 * The buffer of data read from the file
		 */
		char[] buf =new char[size];

		/**
		 * The cursor to scan the buffer (circular)
		 */
		int actualPos=-1;

		/**
		 * When it is 0, then we have to read another block from the file
		 */
		int bytesInBuffer=0;

		StopWatch stopWatch = new StopWatch();

		// This thread is very CPU demanding so we want to give other
		// threads a chance to run too...
		int yelder=0;

		while (true && !stopped) {
			// Read a block from the file if the buffer is empty
			if (bytesInBuffer==0) {
				bytesInBuffer = reader.read(buf,0,size);
			}
			if (bytesInBuffer<=0) { // EOF
				break;
			}
			bytesInBuffer--;
			actualPos=(actualPos+1)%size;
			chRead=buf[actualPos];

			bytesRead++;
			buffer.append((char)chRead,xmlStr);
			if (xmlStr.length()>0) {
				// A new log has been found
				injectLog(xmlStr,logListener, rawLogListener, errorListener);
				logRecordsRead++;
				xmlStr.delete(0, xmlStr.length());
				progressListener.bytesRead(bytesRead);
				if (logRecordsRead%25==0) {
					progressListener.logsRead(logRecordsRead);
				}
			}
			yelder=(yelder++)%5000;
			if (yelder==0) {
				Thread.yield();
			}
		}
		System.out.println("XML log record import finished with " + logRecordsRead + " records in " +
					stopWatch.getLapTimeMillis()/1000 + " seconds.");
	}

	/**
	 * Write the XML header in the buffered writer
	 *
	 * @param bw
	 * @throws IOException
	 */
	public synchronized void writeHeader(BufferedWriter wBuffer) throws IOException {
		if (wBuffer==null) {
			throw new IllegalArgumentException("The BufferedWriter can't be null");
		}
		String header = new String("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<Log>\n\n");
		wBuffer.write(header, 0,header.length());
	}

	/**
	 * Terminate the saving.
	 *

	 * This method must executed when the save terminates.
	 * It does the following:
	 *

	 *
write the closing XML tags
	 *
flush the output file
	 *
close the file
	 *

	 * @param outBuffer The file to close
	 * @param close If true the BufferedWriter is closed
	 * @throws IOException In case of an IO error
	 */
	public synchronized void terminateSave(BufferedWriter outBuffer, boolean close) throws IOException {
		String str = new String("</Log>");
		outBuffer.write(str,0,str.length());
		outBuffer.flush();
		if (close) {
			outBuffer.close();
		}
	}

	/**
	 * Save a log in the passed file
	 *
	 * @param outbuf The buffered writer where the logs have to be stored
	 * @param log The log to save
	 * @param progressListener The listener to be notified about the bytes written
	 * @throws IOException In case of an IO error while writing logs into the file
	 */
	public synchronized int saveLog(BufferedWriter outBuf, ILogEntry log) throws IOException {
		if (outBuf==null) {
			throw new IllegalArgumentException("BufferedWriter can't be null");
		}
		if (log==null) {
			throw new IllegalArgumentException("The log can't be null");
		}
		String str = log.toXMLString()+"\n";
		outBuf.write(str,0,str.length());
		return str.length();
	}

	/**
	 * Save a collection of logs on disk
	 *
	 * @param fileName The name of the file to store logs into
	 * @param logs The non empty collection of logs to save
	 * @param progressListener The listener to be notified about the number of bytes written
	 * @param append

if true if the logs in the collection must be appended to an existing file

	 *
if false and the file aredy exists, it is deleted before writing
	 *

	 * @param gzip If true the file is compressed (GZIP) with the default compression level
	 * @throws IOException In case of error writing
	 */
	public synchronized void saveLogs(
			String fileName,
			Collection<ILogEntry> logs,
			IOPorgressListener progressListener,
			boolean append,
			boolean gzip) throws IOException {
		saveLogs(fileName, logs, progressListener,append,gzip,DEFAULT_COMPRESSION_LEVEL);
	}

	/**
	 * Save a collection of logs on disk
	 *
	 * @param fileName The name of the file to store logs into
	 * @param logs The non empty collection of logs to save
	 * @param progressListener The listener to be notified about the number of bytes written
	 * @param append

if true if the logs in the collection must be appended to an existing file

	 *
if false and the file aredy exists, it is deleted before writing
	 *

	 * @param gzip If true the file is compressed (GZIP)
	 * @param compressionLevel The compressionLevel for GZIP compression (0..9);
	 * 			ignored if gzip is is false>/code>
	 * @throws IOException In case of error writing
	 */
	public synchronized void saveLogs(
			String fileName,
			Collection<ILogEntry> logs,
			IOPorgressListener progressListener,
			boolean append,
			boolean gzip,
			int compressionLevel) throws IOException {
		if (logs==null || logs.isEmpty()) {
			throw new IllegalArgumentException("No logs to save");
		}
		if (progressListener==null) {
			throw new IllegalArgumentException("The progress listener can't be null");
		}
		Iterator<ILogEntry> iterator = logs.iterator();
		saveLogs(fileName, iterator, progressListener,append,gzip,compressionLevel);
	}

	/**
	 * Save a collection of logs on a BufferedWriter.
	 *

	 * The buffer must be initialized and terminated i.e. the prepareSaveFile
	 * and the terminateSave are not executed by this method.
	 *
	 * @param outBuffer The writer to write logs into
	 * @param logs The non empty collection of logs to save
	 * @param progressListener The listener to be notified about the number of bytes written
	 * @param gzip If true the file is compressed (GZIP)
	 * @throws IOException In case of error writing
	 */
	public synchronized void saveLogs(BufferedWriter outBuffer, Collection<ILogEntry> logs, IOPorgressListener progressListener) throws IOException {
		if (logs==null || logs.isEmpty()) {
			throw new IllegalArgumentException("No logs to save");
		}
		if (progressListener==null) {
			throw new IllegalArgumentException("The progress listener can't be null");
		}
		Iterator<ILogEntry> iterator = logs.iterator();
		saveLogs(outBuffer, iterator, progressListener);
	}

	/**
	 * Save the logs available through an Iterator.
	 *
	 * @param filename The name of the file to write logs into
	 * @param logs The non empty collection of logs to save
	 * @param progressListener The listener to be notified about the number of bytes written
	 * @param append

if true if the logs in the collection must be appended to an existing file

	 *
if false and the file already exists, it is deleted before writing
	 *

	 * @param gzip If true the file is compressed (GZIP) with the default compression level
	 * @throws IOException In case of error writing
	 */
	public synchronized void saveLogs(
			String fileName,
			Iterator<ILogEntry>iterator,
			IOPorgressListener progressListener,
			boolean append,
			boolean gzip) throws IOException {
		saveLogs(fileName, iterator, progressListener, append, gzip,DEFAULT_COMPRESSION_LEVEL);
	}

	/**
	 * Save the logs available through an Iterator.
	 *
	 * @param filename The name of the file to write logs into
	 * @param logs The non empty collection of logs to save
	 * @param progressListener The listener to be notified about the number of bytes written
	 * @param append

if true if the logs in the collection must be appended to an existing file

	 *
if false and the file already exists, it is deleted before writing
	 *

	 * @param gzip If true the file is compressed (GZIP)
	 * @param compressionLevel The compressionLevel for GZIP compression (0..9);
	 * 			ignored if gzip is false>/code>
	 * @throws IOException In case of error writing
	 */
	public synchronized void saveLogs(
			String fileName,
			Iterator<ILogEntry>iterator,
			IOPorgressListener progressListener,
			boolean append,
			boolean gzip,
			int compressionLevel) throws IOException {
		if (iterator==null || !iterator.hasNext()) {
			throw new IllegalArgumentException("No logs to save");
		}
		if (progressListener==null) {
			throw new IllegalArgumentException("The progress listener can't be null");
		}

		BufferedWriter writer = getBufferedWriter(fileName, append,gzip, compressionLevel);

		writeHeader(writer);
		saveLogs(writer, iterator,progressListener);
		terminateSave(writer,true);
	}

	/**
	 * Create a BufferedWriter to save logs into
	 *
	 * @param fileName The name of the file to write logs into
	 * @param append

if true if the logs in the collection must be appended to an existing file

	 *
if false and the file already exists, it is deleted before writing
	 *

	 * @param gzip If true the file is compressed (GZIP)
	 * @param compressionLevel The compressionLevel for GZIP compression (0..9);
	 * 			ignored if gzip is false>/code>
	 *
	 * @return the BufferedWriter to save logs into the file of the given name
	 */
	public synchronized BufferedWriter getBufferedWriter(String fileName, boolean append, boolean gzip, int compressionLevel)
	throws FileNotFoundException, IOException{
		OutputStream outStream=new FileOutputStream(fileName,append);
		BufferedWriter writer;
		if (gzip) {
			outStream = new GZipLogOutStream(outStream,compressionLevel);
		}
		writer = new BufferedWriter(new OutputStreamWriter(outStream));

		return writer;
	}

	/**
	 * Create a BufferedWriter to save logs into.
	 *

	 * In case of compressed files, the default compression level is used
	 *
	 * @param fileName The name of the file to write logs into
	 * @param append

if true if the logs in the collection must be appended to an existing file

	 *
if false and the file already exists, it is deleted before writing
	 *

	 * @param gzip If true the file is compressed (GZIP) with the default level
	 *
	 * @return the BufferedWriter to save logs into the file of the given name
	 */
	public synchronized BufferedWriter getBufferedWriter(String fileName, boolean append, boolean gzip)
	throws FileNotFoundException, IOException{
		return getBufferedWriter(fileName, append, gzip,DEFAULT_COMPRESSION_LEVEL);
	}

	/**
	 * Return the reader to get logs from
	 *

	 * The reader can be compressed (GZIP) or not depending on the
	 * extension of the file name (i.e. ".gz" or ".xml").
	 *
	 * @param fileName The name of the file to read
	 * @return the reader to get logs from
	 */
	public synchronized BufferedReader getBufferedReader(String fileName) throws FileNotFoundException, IOException {
		String name = fileName.toLowerCase();
		if (!name.endsWith(".gz") && !name.endsWith(".xml")) {
			throw new IllegalArgumentException("File name must end with .gz or .xml");
		}

		File f = new File(fileName);
		InputStream inStream = new FileInputStream(f);
		if (name.endsWith(".gz")) {
			InputStreamReader inStreamReader= new InputStreamReader(new GZIPInputStream(inStream));
			return new BufferedReader(inStreamReader);
		} else {
			return new BufferedReader(new InputStreamReader(inStream));
		}
	}

	/**
	 * Save a collection of logs on a BufferedWriter.
	 *

	 * The buffer must be initialized and terminated i.e. the prepareSaveFile
	 * and the terminateSave are not executed by this method.
	 *
	 * @param outBuf The buffer to write logs into
	 * @param logs The non empty collection of logs to save
	 * @param progressListener The listener to be notified about the number of bytes written
	 * @throws IOException In case of error writing
	 */
	public synchronized void saveLogs(
			BufferedWriter outBuf,
			Iterator<ILogEntry> iterator,
			IOPorgressListener progressListener) throws IOException {
		if (iterator==null || !iterator.hasNext()) {
			throw new IllegalArgumentException("No logs to save");
		}
		if (progressListener==null) {
			throw new IllegalArgumentException("The progress listener can't be null");
		}
		stopped=false;
		long len=0;
		int logsWritten=0;
		while (iterator.hasNext() && !stopped) {
			ILogEntry log = iterator.next();
			len+=saveLog(outBuf, log);
			progressListener.bytesWritten(len);
			progressListener.logsWritten(++logsWritten);
		}
	}

	/**
	 * Call this method if you wish to interrupt a load or a save.
	 *

	 * Load and save are executed synchronously so this method has to be called by a separate
	 * thread.
	 * A typical example is the "Abort" button of a dialog: when the user presses such a button, this method
	 * is invoked by the swing thread.
	 */
	public void stopIO() {
		stopped=true;
	}
}