text:
package com.hack23.cia.web.impl.ui.application.views.user.politician.pagemode;

import java.util.List;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;

import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeBallotDecisionPoliticianEmbeddedId;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeBallotDecisionPoliticianEmbeddedId_;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeBallotDecisionPoliticianSummary;
import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommitteeBallotDecisionPoliticianSummary_;
import com.hack23.cia.model.internal.application.data.politician.impl.ViewRiksdagenPolitician;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.views.common.labelfactory.LabelFactory;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PoliticianPageMode;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.UserViews;
import com.hack23.cia.web.impl.ui.application.views.pageclicklistener.PageItemPropertyClickListener;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

/**
 * The Class BallotDecisionSummaryPageModContentFactoryImpl.
 */
@Component
public final class PoliticianBallotDecisionSummaryPageModContentFactoryImpl
		extends AbstractPoliticianPageModContentFactoryImpl {

	private static final String BALLOT_ID = "ballotId";
	private static final String[] COLUMN_ORDER = { "voteDate", "rm", "org", "committeeReport", "title",
			"subTitle", "winner", "embeddedId.concern", "embeddedId.issue", "vote", "won", "rebel", "noWinner",
			"approved", "partyApproved", "againstProposalNumber", "againstProposalParties", "totalVotes",
			"partyTotalVotes", "yesVotes", "partyYesVotes", "noVotes", "partyNoVotes", "partyAbstainVotes",
			"abstainVotes", "partyAbsentVotes", "absentVotes", "bornYear", "partyAvgBornYear", "avgBornYear",
			"ballotType", "decisionType", BALLOT_ID };
	private static final String COMMITTEE_BALLOT_DECISION_POLITICIAN_SUMMARY = "Committee Ballot Decision Politician Summary";
	private static final String[] HIDE_COLUMNS = { "label", "endNumber", "publicDate", "createdDate",
			"embeddedId", "partyNoWinner", "partyPercentageYes", "partyPercentageNo", "partyPercentageAbsent",
			"partyPercentageAbstain", "percentageYes", "percentageNo", "percentageAbsent", "percentageAbstain",
			"firstName", "lastName", "party", BALLOT_ID, "decisionType", "ballotType", "againstProposalNumber" };
	private static final PageItemPropertyClickListener LISTENER = new PageItemPropertyClickListener(
			UserViews.BALLOT_VIEW_NAME, BALLOT_ID);
	private static final String[] NESTED_PROPERTIES = { "embeddedId.concern", "embeddedId.issue" };

	/**
	 * Instantiates a new politician ballot decision summary page mod content
	 * factory impl.
	 */
	public PoliticianBallotDecisionSummaryPageModContentFactoryImpl() {
		super();
	}

	@Secured({ "ROLE_ANONYMOUS", "ROLE_USER", "ROLE_ADMIN" })
	@Override
	public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
		final VerticalLayout panelContent = createPanelContent();

		final String pageId = getPageId(parameters);

		final ViewRiksdagenPolitician viewRiksdagenPolitician = getItem(parameters);

		getPoliticianMenuItemFactory().createPoliticianMenuBar(menuBar, pageId);

		LabelFactory.createHeader2Label(panelContent, PoliticianPageMode.BALLOTDECISIONSUMMARY.toString());

		final DataContainer<ViewRiksdagenCommitteeBallotDecisionPoliticianSummary, ViewRiksdagenCommitteeBallotDecisionPoliticianEmbeddedId> committeeBallotDecisionPartyDataContainer = getApplicationManager()
				.getDataContainer(ViewRiksdagenCommitteeBallotDecisionPoliticianSummary.class);

		final List<ViewRiksdagenCommitteeBallotDecisionPoliticianSummary> decisionPartySummaryList = committeeBallotDecisionPartyDataContainer
				.findOrderedByPropertyListByEmbeddedProperty(
						ViewRiksdagenCommitteeBallotDecisionPoliticianSummary.class,
						ViewRiksdagenCommitteeBallotDecisionPoliticianSummary_.embeddedId,
						ViewRiksdagenCommitteeBallotDecisionPoliticianEmbeddedId.class,
						ViewRiksdagenCommitteeBallotDecisionPoliticianEmbeddedId_.intressentId, pageId,
						ViewRiksdagenCommitteeBallotDecisionPoliticianSummary_.voteDate);

		getGridFactory().createBasicBeanItemNestedPropertiesGrid(panelContent,
				ViewRiksdagenCommitteeBallotDecisionPoliticianSummary.class, decisionPartySummaryList,
				COMMITTEE_BALLOT_DECISION_POLITICIAN_SUMMARY, NESTED_PROPERTIES, COLUMN_ORDER, HIDE_COLUMNS, LISTENER,
				BALLOT_ID, null);

		pageCompleted(parameters, panel, pageId, viewRiksdagenPolitician);

		return panelContent;

	}

	@Override
	public boolean matches(final String page, final String parameters) {
		return NAME.equals(page) && parameters.contains(PoliticianPageMode.BALLOTDECISIONSUMMARY.toString());
	}
}


text:
input[type="file"] {
    display: none;
}

.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    font-weight: bold;
}

.card {
    align-content: center;
}

input {
    margin: 8px;
}

.filters {
    float: right;
}

redpajama_set_name: RedPajamaGithub


text:
class UsersController < ApplicationController
  before_action :get_user, except: [:index, :create, :login, :logout]
  respond_to :html, :json

  def index
    @user = User.all
    respond_with(@users) do |format|
      format.json { render :json => @user.as_json }
      format.html
    end
  end

  def create
    @user = User.find_or_create_by(uid: user_params[:uid], name: user_params[:name])
    if @user
      render json: @user.as_json, status: :ok
    else
      render json: {user: @user.errors, status: :no_content}
    end
  end

  def login
    # puts !!!!!! "#{user_params[:uid]}"
    @user = User.find_by(uid: user_params[:uid])
    cookies[:user_id] = @user.uid
    if @user.save
      render json: @user.as_json, status: :ok
    else
      render json: {user: @user.errors, status: :no_content}
    end
  end

  def logout
    cookies.delete :user_id
    redirect_to '/'
  end

  def show
    respond_with(@user.as_json)
  end

  def update
    if @user.update_attributes(user_params)
      render json: @user.as_json, status: :ok
    else
      render json: {user: @user.errors, status: :unprocessable_entity}
    end
  end

  def destroy
    @user.destroy
    render json: {status: :ok}
  end

  private

  def user_params
     unless params["user"]["addresses"].blank?
       params["user"]["addresses_attributes"] = params["user"]["addresses"]
       params["user"].delete("addresses")
     end
     params.fetch(:user, {}).permit(:first_name, :last_name, :email, :phone, :uid, :name,
                                    :addresses_attributes => [:id, :street1, :street2, :city, :state, :country, :zipcode, :_destroy, :user_id])
   end

  def get_user
    @user = User.find(params[:id])
    render json: {status: :not_found} unless @user
  end

end


text:
<?php
namespace Topxia\Service\Testpaper\Dao\Impl;

use Topxia\Service\Common\BaseDao;
use Topxia\Service\Testpaper\Dao\TestpaperResultDao;

class TestpaperResultDaoImpl extends BaseDao implements TestpaperResultDao
{
    protected $table = 'testpaper_result';

    public function getTestpaperResult($id)
    {
        $sql = "SELECT * FROM {$this->table} WHERE id = ? LIMIT 1";
        return $this->getConnection()->fetchAssoc($sql, array($id)) ?: null;
    }

    public function findTestpaperResultsByIds(array $ids)
    {
    }

    public function findTestpaperResultByTestpaperIdAndUserIdAndActive($testpaperId, $userId)
    {
        $sql = "SELECT * FROM {$this->table} WHERE testId = ? AND userId = ? AND active = 1 ORDER BY id DESC ";
        return $this->getConnection()->fetchAssoc($sql, array($testpaperId, $userId));
    }

    public function findTestPaperResultsByTestIdAndStatusAndUserId($testpaperId, array $status, $userId)
    {
        $marks = str_repeat('?,', count($status) - 1).'?';
        array_push($status, $testpaperId, $userId);
        $sql = "SELECT * FROM {$this->table} WHERE `status` IN ({$marks}) AND `testId` = ? AND `userId` = ? ORDER BY id DESC LIMIT 1";
        return $this->getConnection()->fetchAssoc($sql, $status) ?: null;
    }

    public function findTestPaperResultsByStatusAndTestIds($ids, $status, $start, $limit)
    {
        if (empty($ids)) {
            return array();
        }

        $marks = str_repeat('?,', count($ids) - 1).'?';

        array_push($ids, $status);

        $this->filterStartLimit($start, $limit);
        $sql = "SELECT * FROM {$this->table} WHERE `testId` IN ({$marks}) AND `status` = ? ORDER BY endTime DESC LIMIT {$start}, {$limit}";
        return $this->getConnection()->fetchAll($sql, $ids) ?: array();
    }

    public function findTestPaperResultCountByStatusAndTestIds($ids, $status)
    {
        if (empty($ids)) {
            return null;
        }

        $marks = str_repeat('?,', count($ids) - 1).'?';

        array_push($ids, $status);

        $sql = "SELECT COUNT(id) FROM {$this->table} WHERE `testId` IN ({$marks}) AND `status` = ?";
        return $this->getConnection()->fetchColumn($sql, $ids);
    }

    public function findTestPaperResultsByStatusAndTeacherIds($ids, $status, $start, $limit)
    {
        if (empty($ids)) {
            return array();
        }

        $marks = str_repeat('?,', count($ids) - 1).'?';

        array_push($ids, $status);

        $this->filterStartLimit($start, $limit);
        $sql = "SELECT * FROM {$this->table} WHERE `checkTeacherId` IN ({$marks}) AND `status` = ? ORDER BY endTime DESC LIMIT {$start}, {$limit}";
        return $this->getConnection()->fetchAll($sql, $ids) ?: array();
    }

    public function findTestPaperResultCountByStatusAndTeacherIds($ids, $status)
    {
        if (empty($ids)) {
            return null;
        }

        $marks = str_repeat('?,', count($ids) - 1).'?';

        array_push($ids, $status);

        $sql = "SELECT COUNT(id) FROM {$this->table} WHERE `checkTeacherId` IN ({$marks}) AND `status` = ?";
        return $this->getConnection()->fetchColumn($sql, $ids);
    }

    public function findTestPaperResultsByUserId($id, $start, $limit)
    {
        $this->filterStartLimit($start, $limit);
        $sql = "SELECT * FROM {$this->table} WHERE `userId` = ? ORDER BY beginTime DESC LIMIT {$start}, {$limit}";
        return $this->getConnection()->fetchAll($sql, array($id)) ?: array();
    }

    public function findTestPaperResultsCountByUserId($id)
    {
        $sql = "SELECT COUNT(id) FROM {$this->table} WHERE `userId` = ?";
        return $this->getConnection()->fetchColumn($sql, array($id));
    }

    public function searchTestpaperResults($conditions, $sort, $start, $limit)
    {
        $builder = $this->_createSearchQueryBuilder($conditions)
            ->select('*')
            ->orderBy($sort[0], $sort[1])
            ->setFirstResult($start)
            ->setMaxResults($limit);
        return $builder->execute()->fetchAll() ?: array();
    }

    public function searchTestpaperResultsCount($conditions)
    {
        $builder = $this->_createSearchQueryBuilder($conditions)
            ->select('COUNT(id)');

        return $builder->execute()->fetchColumn(0);
    }

    public function addTestpaperResult($fields)
    {
        $affected = $this->getConnection()->insert($this->table, $fields);

        if ($affected <= 0) {
            throw $this->createDaoException('Insert testpaperResult error.');
        }

        return $this->getTestpaperResult($this->getConnection()->lastInsertId());
    }

    public function updateTestpaperResult($id, $fields)
    {
        $this->getConnection()->update($this->table, $fields, array('id' => $id));
        return $this->getTestpaperResult($id);
    }

    public function updateTestpaperResultActive($testId, $userId)
    {
        $sql = "UPDATE {$this->table} SET `active` = 0 WHERE `testId` = ? AND `userId` = ? AND `active` = 1";
        return $this->getConnection()->executeQuery($sql, array($testId, $userId));
    }

    public function updateTestResultsByTarget($target, $fields)
    {
        $this->getConnection()->update($this->table, $fields, array('target' => $target));
    }

    public function deleteTestpaperResultByTestpaperId($testpaperId)
    {
        $sql = "DELETE FROM {$this->table} WHERE testId = ?";
        return $this->getConnection()->executeUpdate($sql, array($testpaperId));
    }

    public function deleteTestpaperResultByTestpaperIdAndStatus($testpaperId, $status)
    {
        $sql = "DELETE FROM {$this->table} WHERE `testId` = ? AND `status` = ?";
        return $this->getConnection()->executeUpdate($sql, array($testpaperId, $status));
    }

    public function searchTestpapersScore($conditions)
    {
        $builder = $this->_createSearchQueryBuilder($conditions)
            ->select('sum(score)');

        return $builder->execute()->fetchColumn(0);
    }

    protected function _createSearchQueryBuilder($conditions)
    {
        $conditions = array_filter($conditions);

        $builder = $this->createDynamicQueryBuilder($conditions)
            ->from($this->table, 'testpaper_result')
            ->andWhere('id = :id')
            ->andWhere('checkTeacherId = :checkTeacherId')
            ->andWhere('paperName = :paperName')
            ->andWhere('testId = :testId')
            ->andWhere('testId IN ( :testIds )')
            ->andWhere('userId = :userId')
            ->andWhere('score = :score')
            ->andWhere('objectiveScore = :objectiveScore')
            ->andWhere('subjectiveScore = :subjectiveScore')
            ->andWhere('rightItemCount = :rightItemCount')
            ->andWhere('status = :status');

        return $builder;
    }
}


text:
import PropTypes from 'prop-types';
import React from 'react';

export const Panel = props => {
  const { children, bgColor, style, onClick } = props;
  const className = `${bgColor} text-gray-200 text-center p-8 rounded-xl`;

  return (
    <div className={className} style={style} onClick={onClick}>
      {children}
    </div>
  );
};

Panel.defaultProps = {
  bgColor: 'bg-gray-700',
};

Panel.propTypes = {
  children: PropTypes.node,
  bgColor: PropTypes.string,
  style: PropTypes.object,
  onClick: PropTypes.func,
};


text:
var crypto =  require('crypto');
var User = require('../modules/user.js');
var Post = require('../modules/post.js');
var fs = require('fs');

module.exports = function(app){

  app.get('/', function (req, res){
    var page = req.query.p ? parseInt(req.query.p) : 1,
      category = req.query.category || null,
      query = {};

    if(category && category.toLowerCase() != 'null'){
      query.category = category;
    }

    console.log('开始查找文章');
    Post.getTen(query, page, function (err, posts, total){
      if(err){
        posts = [];
      }
      console.log('找到文章'+posts.length+'篇,开始返回');
      res.render('index', {
        title : '范子冬的个人博客',
        posts : posts,
        page : page,
        category : category,
        isFirstPage : page === 1,
        isLastPage : (page - 1) * 10 + posts.length === total,
        user : req.session.user,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      });
      console.log('返回完毕');
    });
  });

  app.get('/login', checkNotLogin);
  app.get('/login', function (req, res){
    res.render('login', {
      title:'登录',
      user : req.session.user,
      success : req.flash('success').toString(),
      error : req.flash('error').toString()
    });
  });

  app.post('/login', checkNotLogin);
  app.post('/login', function (req, res){
    //获取用户名和密码
    var md5 = crypto.createHash('md5');
    var username = req.body.username,
      password = md5.update(req.body.password).digest('hex');
    //检查用户是否存在
    User.get(username, function(err, user){
      if(!user){
        req.flash('error', '该用户不存在');
        console.log('该用户不存在');
        return res.redirect('/login');
      }
      //检查密码是否一致
      console.log(user.password)
      if(password !== user.password){
        req.flash('error', '密码错误');
        console.log('密码错误');
        return res.redirect('/login');
      }
      //用户名和密码均正确
      req.session.user = user;
      req.flash('success', '登录成功!');
      console.log('密码成功');
      res.redirect('/management');
    });
  });

  app.get('/management', checkLogin);
  app.get('/management', function (req, res){
    //admin可以获取所有文章,其余用户可以看到自己的所有文章,每次最多展示10篇
    var page = req.query.p ? parseInt(req.query.p) : 1,
      currentUserName = req.session.user.name,
      query = {};
    if(currentUserName !== 'admin'){
      query.username = currentUserName;
    }
    Post.getTen(query, page, function (err, posts, total){
      if(err){
        req.flash('error', err);
        return res.redirect('back');
      }
      res.render('management', {
        title:'范子冬的个人博客',
        posts : posts,
        page : page,
        isFirstPage : page === 1,
        isLastPage : (page - 1) * 10 + posts.length === total,
        user : req.session.user,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      });
    });
  });

  app.get('/management/posts', checkLogin);
  app.get('/management/posts', function (req, res){
    //admin可以获取所有文章,其余用户可以看到自己的所有文章,每次最多展示10篇
    var page = req.query.page ? parseInt(req.query.page) : 1,
      currentUserName = req.session.user.name,
      query = {};
    if(currentUserName !== 'admin'){
      query.username = currentUserName;
    }
    Post.getTen(query, page, function (err, posts, total){
      if(err){
        req.flash('error', err);
        return res.redirect('back');
      }
      res.render('posts_management', {
        title:'文章管理',
        posts : posts,
        page : page,
        isFirstPage : page === 1,
        isLastPage : (page - 1) * 10 + posts.length === total,
        totalPage : total/10+1,
        user : req.session.user,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      });
    });
  });

  app.get('/management/addPost', checkLogin);
  app.get('/management/addPost', function (req, res){
    res.render('addPost', {
      title : '发布文章',
      user : req.session.user,
      success : req.flash('success').toString(),
      error : req.flash('error').toString()
    });
  });

  app.post('/management/addPost', checkLogin);
  app.post('/management/addPost', function (req, res){
    console.log('开始保存文章');
    console.log(req.body.content);
    var post = {
      username : req.session.user.name,
      title : req.body.title,
      category : req.body.category,
      titleImgPath : '',
      tags : [req.body.tag1, req.body.tag2, req.body.tag3],
      content : req.body.content
    };
    for(var i in req.files){
      if (req.files[i].size == 0){
        // 使用同步方式删除一个文件
        fs.unlinkSync(req.files[i].path);
        console.log('Successfully removed an empty file!');
      } else {
        var target_path = './public/images/' + req.files[i].name;
        // 使用同步方式重命名一个文件
        fs.renameSync(req.files[i].path, target_path);
        console.log('Successfully renamed a file!');
        post.titleImgPath = '/images/' + req.files[i].name;
      }
      break;
    }
    var post = new Post(post);
    post.save(function(err){
      if(err){
        req.flash('error', '发布文章失败!')
        return res.redirect('/management/posts');
      }
      req.flash('success', '发布文章成功!');
      res.redirect('/management/posts');
    });
  });

  app.get('/management/editPost', checkLogin);
  app.get('/management/editPost', function (req, res){
    var postId = req.query._id;
    Post.getOne(postId, false, function (err, post){
      if(err){
        console.log('未找到相应文章');
        req.flash('error', err);
        return res.redirect('back');
      }
      res.render('editPost', {
        title : '编辑文章',
        post : post,
        user : req.session.user,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      });
    })
  });

  app.post('/management/editPost', checkLogin);
  app.post('/management/editPost', function (req, res){
    //查看题图有没有被修改
    var titleImgPath = null,
      post = {
      title : req.body.title,
      category : req.body.category,
      tags : [req.body.tag1, req.body.tag2, req.body.tag3],
      content : req.body.content
    };
    for(var i in req.files){
      if (req.files[i].size == 0){
        // 使用同步方式删除一个文件
        fs.unlinkSync(req.files[i].path);
        console.log('Successfully removed an empty file!');
      } else {
        var target_path = './public/images/' + req.files[i].name;
        // 使用同步方式重命名一个文件
        fs.renameSync(req.files[i].path, target_path);
        console.log('Successfully renamed a file!');
        titleImgPath = '/images/' + req.files[i].name;
      }
      break;
    }
    if(titleImgPath){
      post.titleImgPath = titleImgPath;
    }
    Post.update(req.body._id, post, function (err){
      if(err){
        console.log(err);
        req.flash('error', '更新文章失败');
        return res.redirect('back');
      }
      res.redirect('/management/p/'+req.body._id);
    });
  });

  app.get('/management/deletePost', function (req, res){
    var postId = req.query._id;
    Post.delete(postId, function (err){
      if(err){
        console.log(err);
        req.flash('error', '删除文章失败!');
        return res.redirect('back');
      }
      res.redirect('/management/posts');
    });
  });

  app.get('/management/p/:_id', checkLogin);
  app.get('/management/p/:_id', function (req, res){
    Post.getOne(req.params._id, true, function (err, post){
      if(err){
        req.flash('error', err);
        return res.redirect('/management/posts');
      }
      req.flash('success', '找到对应文章');
      res.render('post_management', {
        title : post.title,
        user : req.session.user,
        post : post,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      });
    });
  });

  app.get('/logout', checkLogin);
  app.get('/logout', function (req, res){
    req.session.user = null;
    req.flash('success', '登出成功!');
    res.redirect('/login');
  });

  app.get('/p/:_id', function (req, res){
    Post.getOne(req.params._id, true, function (err, post){
      if(err){
        req.flash('error', err);
        return res.redirect('/');
      }
      console.log('找到对应文章');
      req.flash('success', '找到对应文章');
      res.render('article', {
        title : post.title,
        user : req.session.user,
        post : post,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      })
    });
  });

  app.get('/about', function (req, res){
    res.render('about', {
      title : '关于我'
    })
  })

  app.get('/setting/baseInfo', checkLogin);
  app.get('/setting/baseInfo', function (req, res){
    res.render('baseInfo', {
      title : '个人资料',
      user : req.session.user,
      success : req.flash('success').toString(),
      error : req.flash('error').toString()
    });
  });

  app.post('/setting/baseInfo', checkLogin);
  app.post('/setting/baseInfo', function (req, res){
    //目前基本信息修改只涉及到邮箱
    var currentUser = req.session.user,
      email = req.body.email;
    User.update({
      _id : currentUser._id,
      email : email
    }, function (err){
      if(err){
        req.flash('error', '保存基本资料失败!');
        return res.redirect('back');
      }
      currentUser.email = email;
      res.redirect('/setting/baseInfo');
    });
  });

  app.get('/setting/password', checkLogin);
  app.get('/setting/password', function (req, res){
    res.render('password', {
      title : '修改密码',
      user : req.session.user
    });
  });

  app.post('/setting/password', checkLogin);
  app.post('/setting/password', function (req, res){
    var currentUser = req.session.user,
      old_password = req.body.old_password,
      new_password = req.body.new_password,
      confirm_password = req.body.confirm_password,
      md5 = crypto.createHash('md5');
    if(currentUser.password !== md5.update(old_password).digest('hex') ){
      req.flash('error', '用户密码错误!');
      console.log('用户密码错误!');
      return res.redirect('back');
    }
    if(new_password !== confirm_password){
      req.flash('error', '密码输入不一致!');
      return res.redirect('back');
    }
    var new_password_md5 = crypto.createHash('md5').update(new_password).digest('hex');
    User.update({
      _id : currentUser._id,
      password : new_password_md5
    }, function (err){
      if(err){
        req.flash('error', '修改密码失败!');
        console.log('修改密码失败!');
        return res.redirect('back');
      }
      console.log('修改密码成功!');
      currentUser.password = new_password_md5;
      res.redirect('/setting/password');
    });
  });

  app.get('/userList', checkLogin);
  app.get('/userList', function (req, res){
    //获取所有用户
    User.getAll( function (err, users){
      if(err){
        req.flash('error', '获取用户失败!');
        return res.redirect('back');
      }
      res.render('userList',{
        title : '用户管理',
        user : req.session.user,
        users : users,
        success : req.flash('success').toString(),
        error : req.flash('error').toString()
      });
    });
  });

  app.get('/addUser', checkLogin);
  app.get('/addUser', function (req, res){
    res.render('addUser', {
      title : '添加用户',
      user : req.session.user,
      success : req.flash('success').toString(),
      error : req.flash('error').toString()
    });
  });

  app.post('/addUser', checkLogin);
  app.post('/addUser', function (req, res){
    var username = req.body.username,
      password = req.body.password,
      confirm_password = req.body.confirm_password,
      email = req.body.email;
    //判断该用户是否已经存在
    User.get(username, function (err, user){
      if(user){
        req.flash('error', '该用户名已经被使用');
        return res.redirect('back');
      }
      if(password !== confirm_password){
        req.flash('error', '两次输入密码不一致');
        return res.redirect('back');
      }
      var md5 = crypto.createHash('md5'),
        password_md5 = md5.update(password).digest('hex');
      var newUser = new User({
        name : username,
        password : password_md5,
        email : email
      });
      newUser.save(function (err, user){
        if(err){
          req.flash('error', '添加用户失败!');
          return res.redirect('back');
        }
        req.flash('success', '添加用户成功!')
        res.redirect('/userList');
      });
    })
  });

  app.get('/management/deleteUser', checkLogin);
  app.get('/management/deleteUser', function (req, res){
    var currentUser = req.session.user,
      deleteUserId = req.query._id;
    User.isAdmin(currentUser._id, function(err, isAdmin){
      if(isAdmin){
        User.delete(deleteUserId, function(err){
          if(err){
            req.flash('error', '删除用户失败!');
            return res.redirect('back');
          }
          req.flash('success', '删除用户成功!');
          res.redirect('back');
        });
      }else{
        req.flash('error', '您无权删除用户!');
        return res.redirect('back');
      }
    });
  });

  //当无法匹配路径时,调用404页面
  app.use(function (req, res){
    console.log('未找到相应页面');
    res.render('404');
  });

  function checkLogin(req, res, next){
    if(!req.session.user){
      req.flash('error', '未登录');
      return res.redirect('/login');
    }
    next();
  }

  function checkNotLogin(req, res, next){
    if(req.session.user){
      req.flash('error', '已登录');
      return res.redirect('/management');
    }
    next();
  }
}


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

import org.junit.Test;

import static org.junit.Assert.fail;

public class Log4jAdapterTest {

	@Test
	public void testLogEvent() {
		fail("Not yet implemented");
	}

}


text:
TVIConnectOptions *connectOptions = [TVIConnectOptions optionsWithToken:self.accessToken
                                                                  block:^(TVIConnectOptionsBuilder * _Nonnull builder) {
  builder.roomName = @"my-room";
}];

TVIRoom *room = [TwilioVideo connectWithOptions:connectOptions delegate:self];


text:
package org.yaccc.xRPC.transport.netty;

import com.esotericsoftware.reflectasm.ConstructorAccess;
import com.esotericsoftware.reflectasm.MethodAccess;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.yaccc.xRPC.transport.protocol.Request;
import org.yaccc.xRPC.transport.protocol.Response;

import java.net.SocketAddress;

/**
 * Created by zhaodong/yaccc(github.com/yaccc)|xRPC on 16/2/6
 */
public class NettyServerHander extends ChannelHandlerAdapter {
    private static final int STATUS_OK=200;
    private static final int STATUS_FAIL=500;
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(NettyServerHander.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Request request = (Request) msg;
        Response response=new Response();
        try {
            Object result = handle(request);
            response.setResult(result);
            response.setStatus(STATUS_OK);
        } catch (Throwable t) {
            t.printStackTrace();
            response.setStatus(STATUS_FAIL);
            response.setThrowable(t);

        }
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }

    private Object handle(Request req) throws Throwable {
        String className = req.getClassName();
        String methodName = req.getMethodName();
        Class<?>[] parameterTypes = req.getParameterTypes();
        Object[] parameters = req.getParameters();
        //new object
        Class<?> clazz = Class.forName(className);
        ConstructorAccess<?> constructorAccess = ConstructorAccess.get(clazz);
        Object invokeObject = constructorAccess.newInstance();
        //get method access
        MethodAccess methodAccess = MethodAccess.get(clazz);
        Object result = methodAccess.invoke(invokeObject, methodName, parameterTypes, parameters);

        return result;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        super.close(ctx, promise);
    }

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        super.connect(ctx, remoteAddress, localAddress, promise);
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        super.disconnect(ctx, promise);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void read(ChannelHandlerContext ctx) throws Exception {
        super.read(ctx);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        super.write(ctx, msg, promise);
    }
}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(DNSUpdater.Startup))]
namespace DNSUpdater
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
layout: page
title: Sharp 35th Anniversary
date: 2016-05-24
author: Raymond Friedman
tags: weekly links, java
status: published
summary: Maecenas sapien est, tempus ac pellentesque vitae.
banner: images/banner/wedding.jpg
booking:
  startDate: 05/23/2017
  endDate: 05/27/2017
  ctyhocn: DENAPHX
  groupCode: S3A
published: true
---
Duis quis ultrices nunc. Aenean nec velit urna. Suspendisse potenti. Vivamus elementum metus nibh, in ultricies erat varius a. Nam scelerisque vehicula mauris non rutrum. Aliquam porta placerat libero a dictum. Cras a sapien massa.

1 Ut malesuada nibh imperdiet cursus dignissim
1 Duis iaculis quam nec urna vestibulum, nec euismod ante vulputate
1 Aenean eleifend risus nec eros blandit, quis aliquet mi rutrum
1 Duis et dolor fermentum, venenatis magna sodales, dignissim mauris
1 Curabitur aliquam felis ornare nunc elementum lacinia.

Suspendisse ac diam risus. Morbi lacinia, dui vel sagittis laoreet, urna risus elementum dolor, ac sollicitudin enim turpis vitae libero. Cras ac sagittis elit. Aliquam tincidunt vitae urna et pellentesque. Maecenas molestie, erat vitae commodo tincidunt, est ligula vestibulum lectus, tincidunt accumsan lacus erat sit amet sem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Integer maximus felis tellus, quis pulvinar odio molestie in. Vestibulum sodales tellus et ex feugiat, eget tempor ante pellentesque. Aenean mollis eros non nisi eleifend, sed dignissim eros ullamcorper. Sed enim urna, vestibulum a velit vel, gravida venenatis lorem. In eleifend, velit scelerisque condimentum auctor, tortor arcu dictum nulla, et tincidunt tellus velit a erat. Praesent ut quam convallis ante mattis scelerisque. Ut sit amet enim mi. Mauris varius ultrices eleifend.
Nunc ante ante, accumsan ac arcu ut, pretium dictum tellus. Quisque vestibulum sem ac elit placerat, ultrices mattis neque semper. Mauris at molestie lorem. Nam dignissim, lectus eu tempor luctus, enim enim tempus elit, non efficitur nisi sem sed dui. Phasellus euismod massa eu convallis efficitur. Vivamus at tincidunt turpis. Quisque suscipit, ligula a aliquam blandit, ipsum eros consectetur dolor, in elementum urna magna eget quam. Aliquam erat volutpat.


text:
package org.kuali.kra.coi.disclosure;

import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.sys.framework.service.KcServiceLocator;
import org.kuali.kra.coi.CoiDisclosureStatus;
import org.kuali.kra.coi.CoiDispositionStatus;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.util.GlobalVariables;

public class CoiDisclosureAdministratorActionRule {

    private static final String ADMIN_ERRORS = "coiAdminActionErrors";

    public boolean isValidStatus(String disclosureStatus, String dispositionStatus) {
        return isValidStatus(disclosureStatus, convertDispositionStatus(dispositionStatus));
    }

    public boolean isValidStatus(String disclosureStatus, Integer dispositionStatus) {
        boolean isValid = true;
        if (StringUtils.isBlank(disclosureStatus)) {
            GlobalVariables.getMessageMap().putError(ADMIN_ERRORS, KeyConstants.ERROR_COI_DISCLOSURE_STATUS_REQUIRED);
            isValid = false;
        }
        if (dispositionStatus == null) {
            GlobalVariables.getMessageMap().putError(ADMIN_ERRORS, KeyConstants.ERROR_COI_DISPOSITON_STATUS_REQUIRED);
            isValid = false;
        }
        CoiDispositionStatus disposition = KcServiceLocator.getService(BusinessObjectService.class).findBySinglePrimaryKey(CoiDispositionStatus.class, dispositionStatus);
        if (disposition == null) {
            GlobalVariables.getMessageMap().putError(ADMIN_ERRORS, KeyConstants.ERROR_COI_DISPOSITON_STATUS_REQUIRED);
            isValid = false;
        }
        //if the disposition requires disapproval, then the disclosureStatus must be disapproved.
        if (StringUtils.equals(disposition.getCoiDisclosureStatusCode(), CoiDisclosureStatus.DISAPPROVED)
                && !StringUtils.equals(disclosureStatus, CoiDisclosureStatus.DISAPPROVED)) {
            GlobalVariables.getMessageMap().putError(ADMIN_ERRORS, KeyConstants.ERROR_COI_DISCLOSURE_STATUS_INVALID);
            isValid = false;
        }
        return isValid;
    }

    public boolean isValidDispositionStatus(String dispositionStatus) {
        return isValidDispositionStatus(convertDispositionStatus(dispositionStatus));
    }

    public boolean isValidDispositionStatus(Integer dispositionStatus) {
        boolean isValid = true;
        if (dispositionStatus == null) {
            GlobalVariables.getMessageMap().putError(Constants.DISCLOSURE_MANUAL_DISPOSITION_STATUS, KeyConstants.ERROR_COI_DISPOSITON_STATUS_REQUIRED);
            isValid = false;
        }
        return isValid;
    }

    protected Integer convertDispositionStatus(String dispositionStatus) {
        return dispositionStatus != null ? Integer.valueOf(dispositionStatus) : null;
    }

}


text:
var Code = require('code');
var Lab = require('lab');
var Catbox = require('catbox');
var Redis = require('..');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var expect = Code.expect;
var describe = lab.describe;
var it = lab.test;

describe('Redis', function () {

    it('throws an error if not created with new', function (done) {

        var fn = function () {

            var redis = Redis();
        };

        expect(fn).to.throw(Error);
        done();
    });

    it('creates a new connection', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            expect(client.isReady()).to.equal(true);
            done();
        });
    });

    it('closes the connection', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            expect(client.isReady()).to.equal(true);
            client.stop();
            expect(client.isReady()).to.equal(false);
            done();
        });
    });

    it('gets an item after settig it', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            var key = { id: 'x', segment: 'test' };
            client.set(key, '123', 500, function (err) {

                expect(err).to.not.exist();
                client.get(key, function (err, result) {

                    expect(err).to.equal(null);
                    expect(result.item).to.equal('123');
                    done();
                });
            });
        });
    });

    it('fails setting an item circular references', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            var key = { id: 'x', segment: 'test' };
            var value = { a: 1 };
            value.b = value;
            client.set(key, value, 10, function (err) {

                expect(err.message).to.equal('Converting circular structure to JSON');
                done();
            });
        });
    });

    it('ignored starting a connection twice on same event', function (done) {

        var client = new Catbox.Client(Redis);
        var x = 2;
        var start = function () {

            client.start(function (err) {

                expect(client.isReady()).to.equal(true);
                --x;
                if (!x) {
                    done();
                }
            });
        };

        start();
        start();
    });

    it('ignored starting a connection twice chained', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            expect(err).to.not.exist();
            expect(client.isReady()).to.equal(true);

            client.start(function (err) {

                expect(err).to.not.exist();
                expect(client.isReady()).to.equal(true);
                done();
            });
        });
    });

    it('returns not found on get when using null key', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            client.get(null, function (err, result) {

                expect(err).to.equal(null);
                expect(result).to.equal(null);
                done();
            });
        });
    });

    it('returns not found on get when item expired', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            var key = { id: 'x', segment: 'test' };
            client.set(key, 'x', 1, function (err) {

                expect(err).to.not.exist();
                setTimeout(function () {

                    client.get(key, function (err, result) {

                        expect(err).to.equal(null);
                        expect(result).to.equal(null);
                        done();
                    });
                }, 2);
            });
        });
    });

    it('returns error on set when using null key', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            client.set(null, {}, 1000, function (err) {

                expect(err instanceof Error).to.equal(true);
                done();
            });
        });
    });

    it('returns error on get when using invalid key', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            client.get({}, function (err) {

                expect(err instanceof Error).to.equal(true);
                done();
            });
        });
    });

    it('returns error on drop when using invalid key', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            client.drop({}, function (err) {

                expect(err instanceof Error).to.equal(true);
                done();
            });
        });
    });

    it('returns error on set when using invalid key', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            client.set({}, {}, 1000, function (err) {

                expect(err instanceof Error).to.equal(true);
                done();
            });
        });
    });

    it('ignores set when using non-positive ttl value', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            var key = { id: 'x', segment: 'test' };
            client.set(key, 'y', 0, function (err) {

                expect(err).to.not.exist();
                done();
            });
        });
    });

    it('returns error on drop when using null key', function (done) {

        var client = new Catbox.Client(Redis);
        client.start(function (err) {

            client.drop(null, function (err) {

                expect(err instanceof Error).to.equal(true);
                done();
            });
        });
    });

    it('returns error on get when stopped', function (done) {

        var client = new Catbox.Client(Redis);
        client.stop();
        var key = { id: 'x', segment: 'test' };
        client.connection.get(key, function (err, result) {

            expect(err).to.exist();
            expect(result).to.not.exist();
            done();
        });
    });

    it('returns error on set when stopped', function (done) {

        var client = new Catbox.Client(Redis);
        client.stop();
        var key = { id: 'x', segment: 'test' };
        client.connection.set(key, 'y', 1, function (err) {

            expect(err).to.exist();
            done();
        });
    });

    it('returns error on drop when stopped', function (done) {

        var client = new Catbox.Client(Redis);
        client.stop();
        var key = { id: 'x', segment: 'test' };
        client.connection.drop(key, function (err) {

            expect(err).to.exist();
            done();
        });
    });

    it('returns error on missing segment name', function (done) {

        var config = {
            expiresIn: 50000
        };
        var fn = function () {

            var client = new Catbox.Client(Redis);
            var cache = new Catbox.Policy(config, client, '');
        };
        expect(fn).to.throw(Error);
        done();
    });

    it('returns error on bad segment name', function (done) {

        var config = {
            expiresIn: 50000
        };
        var fn = function () {

            var client = new Catbox.Client(Redis);
            var cache = new Catbox.Policy(config, client, 'a\0b');
        };
        expect(fn).to.throw(Error);
        done();
    });

    it('returns error when cache item dropped while stopped', function (done) {

        var client = new Catbox.Client(Redis);
        client.stop();
        client.drop('a', function (err) {

            expect(err).to.exist();
            done();
        });
    });

    describe('#start', function () {

        it('sets client to when the connection succeeds', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.start(function (err) {

                expect(err).to.not.exist();
                expect(redis.client).to.exist();
                done();
            });
        });

        it('reuses the client when a connection is already started', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.start(function (err) {

                expect(err).to.not.exist();
                var client = redis.client;

                redis.start(function () {

                    expect(client).to.equal(redis.client);
                    done();
                });
            });
        });

        it('returns an error when connection fails', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6380
            };

            var redis = new Redis(options);

            redis.start(function (err) {

                expect(err).to.exist();
                expect(err).to.be.instanceOf(Error);
                expect(redis.client).to.not.exist();
                done();
            });
        });

        it('sends auth command when password is provided', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379,
                password: 'wrongpassword'
            };

            var redis = new Redis(options);

            var log = console.log;
            console.log = function (message) {

                expect(message).to.contain('Warning');
                console.log = log;
            };

            redis.start(function (err) {
                done();
            });
        });

        it('sends select command when database is provided', function (done) {
            var options = {
                host: '127.0.0.1',
                port: 6379,
                database: 1
            };

            var redis = new Redis(options);

            redis.start(function () {});

            // redis.client.selected_db gets updated after the callback
            setTimeout(function () {
                expect(redis.client.selected_db).to.equal(1);
                done();
            }, 10);
        });

        it('stops the client on error post connection', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.start(function (err) {

                expect(err).to.not.exist();
                expect(redis.client).to.exist();

                redis.client.emit('error', new Error('injected'));
                expect(redis.client).to.not.exist();
                done();
            });
        });
    });

    describe('#validateSegmentName', function () {

        it('returns an error when the name is empty', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            var result = redis.validateSegmentName('');

            expect(result).to.be.instanceOf(Error);
            expect(result.message).to.equal('Empty string');
            done();
        });

        it('returns an error when the name has a null character', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            var result = redis.validateSegmentName('\0test');

            expect(result).to.be.instanceOf(Error);
            done();
        });

        it('returns null when there aren\'t any errors', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            var result = redis.validateSegmentName('valid');

            expect(result).to.not.be.instanceOf(Error);
            expect(result).to.equal(null);
            done();
        });
    });

    describe('#get', function () {

        it('passes an error to the callback when the connection is closed', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.get('test', function (err) {

                expect(err).to.exist();
                expect(err).to.be.instanceOf(Error);
                expect(err.message).to.equal('Connection not started');
                done();
            });
        });

        it('passes an error to the callback when there is an error returned from getting an item', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);
            redis.client = {
                get: function (item, callback) {

                    callback(new Error());
                }
            };

            redis.get('test', function (err) {

                expect(err).to.exist();
                expect(err).to.be.instanceOf(Error);
                done();
            });
        });

        it('passes an error to the callback when there is an error parsing the result', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);
            redis.client = {
                get: function (item, callback) {

                    callback(null, 'test');
                }
            };

            redis.get('test', function (err) {

                expect(err).to.exist();
                expect(err.message).to.equal('Bad envelope content');
                done();
            });
        });

        it('passes an error to the callback when there is an error with the envelope structure (stored)', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);
            redis.client = {
                get: function (item, callback) {

                    callback(null, '{ "item": "false" }');
                }
            };

            redis.get('test', function (err) {

                expect(err).to.exist();
                expect(err.message).to.equal('Incorrect envelope structure');
                done();
            });
        });

        it('passes an error to the callback when there is an error with the envelope structure (item)', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);
            redis.client = {
                get: function (item, callback) {

                    callback(null, '{ "stored": "123" }');
                }
            };

            redis.get('test', function (err) {

                expect(err).to.exist();
                expect(err.message).to.equal('Incorrect envelope structure');
                done();
            });
        });

        it('is able to retrieve an object thats stored when connection is started', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379,
                partition: 'wwwtest'
            };
            var key = {
                id: 'test',
                segment: 'test'
            };

            var redis = new Redis(options);

            redis.start(function () {

                redis.set(key, 'myvalue', 200, function (err) {

                    expect(err).to.not.exist();
                    redis.get(key, function (err, result) {

                        expect(err).to.not.exist();
                        expect(result.item).to.equal('myvalue');
                        done();
                    });
                });
            });
        });

        it('returns null when unable to find the item', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379,
                partition: 'wwwtest'
            };
            var key = {
                id: 'notfound',
                segment: 'notfound'
            };

            var redis = new Redis(options);

            redis.start(function () {

                redis.get(key, function (err, result) {

                    expect(err).to.not.exist();
                    expect(result).to.not.exist();
                    done();
                });
            });
        });
    });

    describe('#set', function () {

        it('passes an error to the callback when the connection is closed', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.set('test1', 'test1', 3600, function (err) {

                expect(err).to.exist();
                expect(err).to.be.instanceOf(Error);
                expect(err.message).to.equal('Connection not started');
                done();
            });
        });

        it('passes an error to the callback when there is an error returned from setting an item', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);
            redis.client = {
                set: function (key, item, callback) {

                    callback(new Error());
                }
            };

            redis.set('test', 'test', 3600, function (err) {

                expect(err).to.exist();
                expect(err).to.be.instanceOf(Error);
                done();
            });
        });
    });

    describe('#drop', function () {

        it('passes an error to the callback when the connection is closed', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.drop('test2', function (err) {

                expect(err).to.exist();
                expect(err).to.be.instanceOf(Error);
                expect(err.message).to.equal('Connection not started');
                done();
            });
        });

        it('deletes the item from redis', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);
            redis.client = {
                del: function (key, callback) {

                    callback(null, null);
                }
            };

            redis.drop('test', function (err) {

                expect(err).to.not.exist();
                done();
            });
        });
    });

    describe('#stop', function () {

        it('sets the client to null', function (done) {

            var options = {
                host: '127.0.0.1',
                port: 6379
            };

            var redis = new Redis(options);

            redis.start(function () {

                expect(redis.client).to.exist();
                redis.stop();
                expect(redis.client).to.not.exist();
                done();
            });
        });
    });
});


text:
<?php

namespace Krak\Job;

use Krak\Cargo;
use Krak\Mw;
use Krak\AutoArgs;
use Psr\SimpleCache\CacheInterface;
use Psr\Log;

class JobServiceProvider implements Cargo\ServiceProvider
{
    public function register(Cargo\Container $c) {
        $c[Dispatch::class] = function($c) {
            $produce = $c['krak.job.pipeline.produce'];
            return new Dispatch\ProducerDispatch(Mw\compose([$produce]));
        };
        $c[Queue\Doctrine\JobRepository::class] = function($c) {
            return new Queue\Doctrine\JobRepository(
                $c['Doctrine\DBAL\Connection'],
                $c['krak.job.queue.doctrine.table_name']
            );
        };
        $c[Queue\Doctrine\JobMigration::class] = function($c) {
            return new Queue\Doctrine\JobMigration(
                $c['krak.job.queue.doctrine.table_name']
            );
        };
        $c[Queue\Doctrine\DoctrineQueueManager::class] = function($c) {
            return new Queue\Doctrine\DoctrineQueueManager(
                $c[Queue\Doctrine\JobRepository::class]
            );
        };
        $c[Queue\Redis\RedisQueueManager::class] = function($c) {
            return new Queue\Redis\RedisQueueManager($c['Predis\ClientInterface']);
        };
        $c[Queue\Sqs\SqsQueueManager::class] = function($c) {
            return new Queue\Sqs\SqsQueueManager(
                $c['Aws\Sqs\SqsClient'],
                $c['krak.job.queue.sqs.queue_url_map'],
                $c['krak.job.queue.sqs.receive_options']
            );
        };
        $c[Queue\Sync\SyncQueueManager::class] = function($c) {
            return new Queue\Sync\SyncQueueManager($c[Worker::class]);
        };
        $c[Queue\QueueManagerResolver::class] = function($c) {
            return new Queue\QueueManagerResolver($c);
        };
        $c[Queue\QueueManager::class] = function($c) {
            $provider = $c['krak.job.queue_provider'];
            return $c[Queue\QueueManagerResolver::class]->resolveQueueManager($provider);
        };
        $c[ProcessManager\ProcessManager::class] = function($c) {
            return new ProcessManager\SymfonyProcessManager();
        };
        $c[Scheduler::class] = function($c) {
            $loop = $c['krak.job.schedule_loop'];
            return new Scheduler(
                $c[ProcessManager\ProcessManager::class],
                $c[Queue\QueueManagerResolver::class],
                Mw\compose([
                    Mw\guard('No schedulerLoop was able to resolve a response. Please check your configuration.'),
                    $loop
                ]),
                $c->has(CacheInterface::class) ? $c->get(CacheInterface::class) : null
            );
        };
        $c[SchedulerControl::class] = function($c) {
            return new SchedulerControl($c[CacheInterface::class]);
        };
        $c[Worker::class] = function($c) {
            $consume = $c['krak.job.pipeline.consume'];
            return new Worker(Mw\compose([$consume]));
        };
        $c['krak.job.fail_job'] = function($c) {
            return mw\stack([
                FailJob\completeFailJob(),
                FailJob\retryFailJob(),
            ]);
        };
        $c['krak.job.schedule_loop'] = function($c) {
            $fail_job = $c['krak.job.fail_job'];
            return mw\stack([
                ScheduleLoop\queueScheduleLoop(Mw\compose([$fail_job])),
                ScheduleLoop\schedulerScheduleLoop()
            ]);
        };
        $c['krak.job.pipeline.consume'] = function($c) {
            return mw\stack([
                Pipeline\invokeJobConsume($c[AutoArgs\AutoArgs::class], [
                    'objects' => [$c],
                    'container' => $c->toInterop()
                ])
            ])->push(Pipeline\catchExceptionConsume($c['krak.job.debug']), 1);
        };
        $c['krak.job.pipeline.produce'] = function($c) {
            return mw\stack([
                Pipeline\queueProduce($c[Queue\QueueManagerResolver::class], $c->createQueueProviderMap()),
                Pipeline\pipeJobProduce(),
                Pipeline\timestampProduce(),
                Pipeline\classNameProduce(),
                Pipeline\defaultQueueNameProduce($c['krak.job.default_queue_name']),
            ]);
        };
        $c['krak.job.config'] = [
            'queue' => 'jobs',
            'max_jobs' => 10,
            'sleep' => 10,
        ];
        $c['krak.job.debug'] = false;
        $c['krak.job.default_queue_name'] = 'jobs';
        $c['krak.job.queue_provider'] = 'sync';
        $c['krak.job.queue.doctrine.table_name'] = 'krak_jobs';
        $c['krak.job.queue.sqs.queue_url_map'] = [];
        $c['krak.job.queue.sqs.receive_options'] = [];

        if (!isset($c[AutoArgs\AutoArgs::class])) {
            $c[AutoArgs\AutoArgs::class] = function($c) {
                return new AutoArgs\AutoArgs();
            };
        }
        if (!isset($c['dispatch'])) {
            $c->alias(Dispatch::class, 'dispatch');
        }
        if (!isset($c[Log\LoggerInterface::class])) {
            $c[Log\LoggerInterface::class] = function() {
                return new Log\NullLogger();
            };
        }
    }
}


text:
package ch.idsia.agents.controllers.modules;

import ch.idsia.agents.AgentOptions;
import ch.idsia.benchmark.mario.engine.generalization.MarioEntity;
import ch.idsia.benchmark.mario.engine.generalization.Tile;

public class Tiles {

	private MarioEntity mario;

	/**
	 * 2-dimensional array representing the scene terrain+coins.
	 *
	 * Tiles are stored in [row][col] manner.
	 *
	 * Mario is at [marioEgoRow][marioEgoCol].
	 *
	 * The array is {@link #receptiveFieldHeight} x {@link #receptiveFieldWidth} long.
	 */
	public Tile[][] tileField;

	public void reset(AgentOptions options) {
		this.mario = options.mario;
	}

	public Tile getTile(int mapX, int mapY) {
		if (mapY < 0 || mapY >= tileField.length || mapX < 0 || mapX >= tileField[0].length) return Tile.NOTHING;
		return tileField[mapY][mapX];
	}

	public Tile tile(int relMapX, int relMapY) {
		return getTile(mario.egoCol + relMapX, mario.egoRow + relMapY);
	}

	public boolean emptyTile(int relMapX, int relMapY) {
		return tile(relMapX, relMapY) == Tile.NOTHING;
	}

	public boolean anyTile(int relMapX, int relMapY) {
		return !emptyTile(relMapX, relMapY);
	}

	public boolean brick(int relMapX, int relMapY) {
		Tile tile = tile(relMapX, relMapY);
		switch (tile) {
		case BORDER_CANNOT_PASS_THROUGH:
		case BREAKABLE_BRICK:
		case CANNON_MUZZLE:
		case CANNON_TRUNK:
		case FLOWER_POT:
		case FLOWER_POT_OR_CANNON:
		case QUESTION_BRICK:
			return true;
		}
		return false;
	}

}


text:
export default function size({ width, height }) {
  'use strict';

  if (typeof width === 'undefined') {
    return {
      width: this.width(),
      height: this.height()
    }
  }
  else {
    return this.each((i, elem) => {
      $(elem).css({ width, height })
    })
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="exo_media_action_repeat_off_description">Não repetir</string>
  <string name="exo_media_action_repeat_one_description">Repetir uma</string>
  <string name="exo_media_action_repeat_all_description">Repetir tudo</string>
</resources>


text:
import PropTypes from 'prop-types';
import ColorPropType from './ColorPropType';

const ShadowPropTypesIOS = {
  /**
   * Sets the drop shadow color
   * @platform ios
   */
  shadowColor: ColorPropType,
  /**
   * Sets the drop shadow offset
   * @platform ios
   */
  shadowOffset: PropTypes.shape({
    width: PropTypes.number,
    height: PropTypes.number,
  }),
  /**
   * Sets the drop shadow opacity (multiplied by the color's alpha component)
   * @platform ios
   */
  shadowOpacity: PropTypes.number,
  /**
   * Sets the drop shadow blur radius
   * @platform ios
   */
  shadowRadius: PropTypes.number,
};

module.exports = ShadowPropTypesIOS;


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

public class EnergySpawn : MonoBehaviour {
	/** Public GUI Variables **/

	public Transform lowEnergyPrefab;

	public Transform midEnergyPrefab;
	public float midEnergyChance = 0.3f;

	public Transform highEnergyPrefab;
	public float highEnergyChance = 0.01f;

	public float frequency = 1.0f;

	/** Private State **/
	private float elapsed = 0.0f;
	private Vector3 lastSpawnPosition = Vector3.zero;

	/** Lifecycle Methods **/
	void Start() {
		elapsed = 0.0f;
		lastSpawnPosition = transform.position;
	}

	// Update is called once per frame
	void Update () {
		elapsed += Time.deltaTime;

		// only spawn an energy if there isn't one available already
		if (elapsed > frequency) {
			// pull a random value and spawn level based on it
			float randomValue = Random.value;

			if (randomValue < highEnergyChance) {
				spawnHighEnergy();
			} else if (randomValue < midEnergyChance + highEnergyChance) {
				spawnMediumEnergy();
			} else {
				spawnLowEnergy();
			}

			// Clamp lastSpawnPosition
			lastSpawnPosition.x = Mathf.Clamp(lastSpawnPosition.x, transform.position.x - transform.localScale.x * 0.5f,
			                                  transform.position.x + transform.localScale.x * 0.5f);
			elapsed %= frequency;
		}
	}

	/** Spawn Energy Methods **/
	private void spawnHighEnergy() {
		Vector3 position = lastSpawnPosition;
		position.x += (Random.value - 0.5f) * 2.0f * (transform.localScale.x / 2.0f);
		position.y = Random.value * transform.localScale.y + transform.localScale.y / 2.0f;

		position = clampToRegion (position);

		Instantiate (highEnergyPrefab, position, Quaternion.identity);
		lastSpawnPosition = position;
	}

	private void spawnMediumEnergy() {
		Vector3 position = lastSpawnPosition;
		position.x += (Random.value - 0.5f) * 1.0f * (transform.localScale.x / 2.0f);
		position.y = Random.value * transform.localScale.y + transform.localScale.y / 2.0f;

		position = clampToRegion (position);

		Instantiate (midEnergyPrefab, position, Quaternion.identity);
		lastSpawnPosition = position;
	}

	private void spawnLowEnergy() {
		Vector3 position = lastSpawnPosition;
		position.x += (Random.value - 0.5f) * 0.5f * (transform.localScale.x / 2.0f);
		position.y = Random.value * transform.localScale.y + transform.localScale.y / 2.0f;

		position = clampToRegion (position);

		Instantiate (lowEnergyPrefab, position, Quaternion.identity);
		lastSpawnPosition = position;
	}

	/** Helper Methods **/
	private Vector3 clampToRegion(Vector3 position) {
		Vector3 output = Vector3.zero;
		output.x = Mathf.Clamp (position.x, transform.position.x - transform.localScale.x / 2.0f, transform.position.x + transform.localScale.x / 2.0f);
		output.y = Mathf.Clamp (position.y, transform.position.y - transform.localScale.y / 2.0f, transform.position.y + transform.localScale.y / 2.0f);
		output.z = transform.position.z;

		return output;
	}
}


text:
var path = require('path');
var webpack = require('webpack');

var nodeModulesPath = path.join(__dirname, 'node_modules');

module.exports = {
  entry: [
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './src/index.js'
  ],
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js',
    publicPath: '/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  resolve: {
    root: [nodeModulesPath],
    extensions: ['', '.js', '.jsx', 'less']
  },
  resolveLoader: {
    root: nodeModulesPath
  },
  module: {
    loaders: [{
      test: /\.js?$/,
      loaders: ['react-hot', 'babel'],
      include: path.join(__dirname, 'src')
    },{
      test: /\.less$/,
      loader: 'style-loader!css-loader!less-loader'
    }]
  }
};


text:
var falcor = require("./../../../lib/");
var Model = falcor.Model;
var Cache = require('../../data/Cache');
var Expected = require('../../data/expected');
var Rx = require('rx');
var getTestRunner = require('./../../getTestRunner');
var testRunner = require('./../../testRunner');
var noOp = function() {};
var expect = require('chai').expect;
var sinon = require('sinon');
var toValue = function(x) { return {value: x}; };

describe('Cache Only', function() {
    describe('toJSON', function() {
        it('should set a value from falcor.', function(done) {
            var model = new Model({cache: Cache()});
            var value = {hello: 'world'};
            var expected = {
                json: {
                    videos: {
                        1234: {
                            summary: {
                                hello: 'world'
                            }
                        }
                    }
                }
            };
            var next = false;
            model.
                set({path: ['videos', 1234, 'summary'], value: value}).
                toJSON().
                doAction(function(x) {
                    testRunner.compare(expected, x);
                    next = true;
                }, noOp, function() {
                    testRunner.compare(true, next, 'Expect to be onNext at least 1 time.');
                }).
                subscribe(noOp, done, done);
        });
    });
    describe('_toJSONG', function() {
        it('should get a value from falcor.', function(done) {
            var model = new Model({cache: Cache()});
            var value = {hello: 'world'};
            var expected = {
                jsonGraph: {
                    videos: {
                        1234: {
                            summary: {
                                $type: 'atom',
                                $modelCreated: true,
                                $size: 51,
                                value: {
                                    hello: 'world'
                                }
                            }
                        }
                    }
                },
                paths: [['videos', 1234, 'summary']]
            };
            var next = false;
            model.
                set({path: ['videos', 1234, 'summary'], value: value}).
                _toJSONG().
                doAction(function(x) {
                    testRunner.compare(expected, x);
                    next = true;
                }, noOp, function() {
                    testRunner.compare(true, next, 'Expect to be onNext at least 1 time.');
                }).
                subscribe(noOp, done, done);
        });
    });
});


text:
import Ember from 'ember';

import {
  invalidateSession
} from 'aeonvera/tests/helpers/ember-simple-auth';

export default Ember.Test.registerAsyncHelper('logout', function(app) {
  invalidateSession(app);
});


text:
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using WebVRPano.Services;

namespace WebVRPano
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddTransient<IConfigurationService>(r => new ConfigurationService(Configuration));
            services.AddTransient<IPanoService, PanoService>();
            services.AddTransient<IXmlService, XmlService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            Configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables()
                .Build();

            app.UseStaticFiles();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{tinyId?}");
            });
        }
    }
}


text:
$('nav ul#main_nav').on('click','li',function(){
	var $type=$(this).attr('data-title');
	$('nav ul#main_nav li').removeClass('active')
	if ($type=='all') {
		$('nav ul#main_nav li').addClass('active');
		$('div#timeline_container >ul> li').removeClass('hidden');
		$('div#timeline_container >ul> li').removeClass('active');
		$($('div#timeline_container >ul> li')[0]).addClass('active');
	} else {
		$(this).addClass('active');
		$('div#timeline_container >ul> li').addClass('hidden');
		$('div#timeline_container >ul> li.'+$type+'_event').removeClass('hidden');
		$('div#timeline_container >ul> li').removeClass('active');
		$($('div#timeline_container >ul> li.'+$type+'_event')[0]).addClass('active');
	}

});

$(document).on('scroll',function(){
	$('div#instructions_container').fadeOut('fast');
	$('div#info_container').fadeIn('fast');
});
$(document).on('click','div#info_container',function(){
	$('div#instructions_container').fadeIn('fast');
	$('div#info_container').fadeOut('fast');
});

$(document).on('click','li.icon-down-open',function(){
	scrollToNext();
});

$(document).on('click','li.icon-up-open',function(){
	scrollToPrev();
});

$(document).on('keypress',function(e){
	if(e.which==106) {
		scrollToNext();
	} else if(e.which==107) {
		scrollToPrev();
	}
});

$('div#timeline_container').on('click','li', function(){
	showNext($(this));
});

function showNext(li){
	var $itms=$('div#timeline_container li');
	$itms.removeClass('active');
	$(li).addClass('active');
	$('html,body').stop().animate({ scrollTop: $(li).offset().top-$(li).height()}, 500,function(){
		$('html,body').stop();
	});
}

function scrollToNext() {
	var $itms=$('div#timeline_container > ul > li');
	var $current=$itms.index($('div#timeline_container li.active'));

	if ($($itms[$current+1]).length>0 && !$($itms[$current+1]).hasClass('hidden')) {
		$itms.removeClass('active');
		$($itms[$current+1]).addClass('active');
		$('html,body').stop().animate({ scrollTop: $($itms[$current+1]).offset().top-$($itms[$current+1]).height()}, 500);
	} else {
		$('html,body').stop().animate({ scrollTop: $(document).height()}, 500);
	}
}
function scrollToPrev() {
	var $itms=$('div#timeline_container > ul > li');
	var $current=$itms.index($('div#timeline_container li.active'));

	if ($($itms[$current-1]).length>0 && !$($itms[$current-1]).hasClass('hidden')) {
		$itms.removeClass('active');
		$($itms[$current-1]).addClass('active');
		$('html,body').stop().animate({ scrollTop: $($itms[$current-1]).offset().top-$($itms[$current-1]).height()}, 500);
	} else {
		$('html,body').stop().animate({ scrollTop: 0}, 500);
	}
}


text:
Marta APIs made (hopefully) accessible in hubot form.

[![Build Status](https://travis-ci.org/jakswa/hubot-marta.png)](https://travis-ci.org/jakswa/hubot-marta)

## Usage

The most basic syntax is:

```
You> !train for chamblee
Hubot> northbound gold train will arrive at CHAMBLEE STATION in 12 minutes
```

But you'll usually want only trains going a certain direction, or maybe on a certain line. Here's the full accepted syntax:
`!train [headed <dir> ][on <line> ][bound for <dest> ] (for|from) <station>`

Usually you'll only want to mix, at most, two out of the three optional filters. For example, here's two ways to get the next northbound train headed for chamblee:

```
You> !train headed north on gold for chamblee
Hubot> northbound gold train will arrive at CHAMBLEE STATION in 8 minutes
```
will give you the same train as
```
You> !train bound for doraville from chamblee
Hubot> northbound gold train will arrive at CHAMBLEE STATION in 7 minutes
```

## API-related caveats

- A train stopped at its final destination (like doraville or north springs) will not "switch directions" in the API until it leaves. So you'll only see northbound trains for north springs (`!train for north springs`), and you'll only see southbound trains for airport (`!train for airport`). Same for the east/west extremes.
- The API currently doesn't give estimates for trains about to change directions. If a train leaves chamblee, and it's next stop is doraville, there won't be an estimate for when that train turns around and hits chamblee again. Because of this, you'll find certain filters usually yield no results, like `!train headed south for chamblee`. A workaround is to watch the northbound train that is about to switch directions: `!train headed north for doraville`.
- The train API is new, and is bound to change on me. The script is tied to the current API response, which is a list of arrivals:

```json
[{
  DESTINATION: "Airport",
  DIRECTION: "S",
  EVENT_TIME: "3/12/2014 5:40:28 PM",
  LINE: "RED",
  NEXT_ARR: "05:40:37 PM",
  STATION: "WEST END STATION",
  TRAIN_ID: "403506",
  WAITING_SECONDS: "-37",
  WAITING_TIME: "Boarding"
},
...
]
```

## Installation

- Set the `MARTA_API_KEY` environment variable to the API key that marta sent you (apply for one [here](http://www.itsmarta.com/developers/data-sources/marta-rail-realtime-restful-api.aspx))
- Add the package `hubot-marta` as a dependency in your Hubot package.json file.
- Add `hubot-marta` to the list in the `external-scripts.json` file.


text:
#ifdef __cplusplus
#include <cstdio>
#include <cstdlib>
#include <cstring>
#else
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#endif

typedef struct {
    /* options without arguments */
    int help;
    /* options with arguments */
    char *path;
    char *port;
    /* special */
    const char *usage_pattern;
    const char *help_message;
} DocoptArgs;

const char help_message[] =
"Maxeler HTTP Server\n"
"\n"
"Usage:\n"
"  httpServer [--port=PORT] [--path=PATH]\n"
"  httpServer -h | --help\n"
"\n"
"Options:\n"
"  -h --help     Show this screen.\n"
"  --port=PORT   listening port [default: 8080]\n"
"  --path=PATH   hosted files path [default: ./files/]\n"
"";

const char usage_pattern[] =
"Usage:\n"
"  httpServer [--port=PORT] [--path=PATH]\n"
"  httpServer -h | --help";

typedef struct {
    const char *name;
    bool value;
} Command;

typedef struct {
    const char *name;
    char *value;
    char **array;
} Argument;

typedef struct {
    const char *oshort;
    const char *olong;
    bool argcount;
    bool value;
    char *argument;
} Option;

typedef struct {
    int n_commands;
    int n_arguments;
    int n_options;
    Command *commands;
    Argument *arguments;
    Option *options;
} Elements;

/*
 * Tokens object
 */

typedef struct Tokens {
    int argc;
    char **argv;
    int i;
    char *current;
} Tokens;

Tokens tokens_new(int argc, char **argv) {
    Tokens ts = {argc, argv, 0, argv[0]};
    return ts;
}

Tokens* tokens_move(Tokens *ts) {
    if (ts->i < ts->argc) {
        ts->current = ts->argv[++ts->i];
    }
    if (ts->i == ts->argc) {
        ts->current = NULL;
    }
    return ts;
}

/*
 * ARGV parsing functions
 */

int parse_doubledash(Tokens *ts, Elements *elements) {
    //int n_commands = elements->n_commands;
    //int n_arguments = elements->n_arguments;
    //Command *commands = elements->commands;
    //Argument *arguments = elements->arguments;

    // not implemented yet
    // return parsed + [Argument(None, v) for v in tokens]
    return 0;
}

int parse_long(Tokens *ts, Elements *elements) {
    int i;
    int len_prefix;
    int n_options = elements->n_options;
    char *eq = strchr(ts->current, '=');
    Option *option;
    Option *options = elements->options;

    len_prefix = (eq-(ts->current))/sizeof(char);
    for (i=0; i < n_options; i++) {
        option = &options[i];
        if (!strncmp(ts->current, option->olong, len_prefix))
            break;
    }
    if (i == n_options) {
        // TODO '%s is not a unique prefix
        fprintf(stderr, "%s is not recognized\n", ts->current);
        return 1;
    }
    tokens_move(ts);
    if (option->argcount) {
        if (eq == NULL) {
            if (ts->current == NULL) {
                fprintf(stderr, "%s requires argument\n", option->olong);
                return 1;
            }
            option->argument = ts->current;
            tokens_move(ts);
        } else {
            option->argument = eq + 1;
        }
    } else {
        if (eq != NULL) {
            fprintf(stderr, "%s must not have an argument\n", option->olong);
            return 1;
        }
        option->value = true;
    }
    return 0;
}

int parse_shorts(Tokens *ts, Elements *elements) {
    char *raw;
    int i;
    int n_options = elements->n_options;
    Option *option;
    Option *options = elements->options;

    raw = &ts->current[1];
    tokens_move(ts);
    while (raw[0] != '\0') {
        for (i=0; i < n_options; i++) {
            option = &options[i];
            if (option->oshort != NULL && option->oshort[1] == raw[0])
                break;
        }
        if (i == n_options) {
            // TODO -%s is specified ambiguously %d times
            fprintf(stderr, "-%c is not recognized\n", raw[0]);
            return 1;
        }
        raw++;
        if (!option->argcount) {
            option->value = true;
        } else {
            if (raw[0] == '\0') {
                if (ts->current == NULL) {
                    fprintf(stderr, "%s requires argument\n", option->oshort);
                    return 1;
                }
                raw = ts->current;
                tokens_move(ts);
            }
            option->argument = raw;
            break;
        }
    }
    return 0;
}

int parse_argcmd(Tokens *ts, Elements *elements) {
    int i;
    int n_commands = elements->n_commands;
    //int n_arguments = elements->n_arguments;
    Command *command;
    Command *commands = elements->commands;
    //Argument *arguments = elements->arguments;

    for (i=0; i < n_commands; i++) {
        command = &commands[i];
        if (!strcmp(command->name, ts->current)){
            command->value = true;
            tokens_move(ts);
            return 0;
        }
    }
    // not implemented yet, just skip for now
    // parsed.append(Argument(None, tokens.move()))
    /*fprintf(stderr, "! argument '%s' has been ignored\n", ts->current);
    fprintf(stderr, "  '");
    for (i=0; i<ts->argc ; i++)
        fprintf(stderr, "%s ", ts->argv[i]);
    fprintf(stderr, "'\n");*/
    tokens_move(ts);
    return 0;
}

int parse_args(Tokens *ts, Elements *elements) {
    int ret;

    while (ts->current != NULL) {
        if (strcmp(ts->current, "--") == 0) {
            ret = parse_doubledash(ts, elements);
            if (!ret) break;
        } else if (ts->current[0] == '-' && ts->current[1] == '-') {
            ret = parse_long(ts, elements);
        } else if (ts->current[0] == '-' && ts->current[1] != '\0') {
            ret = parse_shorts(ts, elements);
        } else
            ret = parse_argcmd(ts, elements);
        if (ret) return ret;
    }
    return 0;
}

int elems_to_args(Elements *elements, DocoptArgs *args, bool help,
                  const char *version){
    Command *command;
    Argument *argument;
    Option *option;
    int i;

    /* options */
    for (i=0; i < elements->n_options; i++) {
        option = &elements->options[i];
        if (help && option->value && !strcmp(option->olong, "--help")) {
            printf("%s", args->help_message);
            return 1;
        } else if (version && option->value &&
                   !strcmp(option->olong, "--version")) {
            printf("%s\n", version);
            return 1;
        } else if (!strcmp(option->olong, "--help")) {
            args->help = option->value;
        } else if (!strcmp(option->olong, "--path")) {
            if (option->argument)
                args->path = option->argument;
        } else if (!strcmp(option->olong, "--port")) {
            if (option->argument)
                args->port = option->argument;
        }
    }
    /* commands */
    for (i=0; i < elements->n_commands; i++) {
        command = &elements->commands[i];
    }
    /* arguments */
    for (i=0; i < elements->n_arguments; i++) {
        argument = &elements->arguments[i];
    }
    return 0;
}

/*
 * Main docopt function
 */

DocoptArgs docopt(int argc, char *argv[], bool help, const char *version) {
    DocoptArgs args = {
        0, (char*) "./files/", (char*) "8080",
        usage_pattern, help_message
    };
    Tokens ts;
    Command commands[] = {
    };
    Argument arguments[] = {
    };
    Option options[] = {
        {"-h", "--help", 0, 0, NULL},
        {NULL, "--path", 1, 0, NULL},
        {NULL, "--port", 1, 0, NULL}
    };
    Elements elements = {0, 0, 3, commands, arguments, options};

    ts = tokens_new(argc, argv);
    if (parse_args(&ts, &elements))
        exit(EXIT_FAILURE);
    if (elems_to_args(&elements, &args, help, version))
        exit(EXIT_SUCCESS);
    return args;
}


text:
Ext.define('OPF.console.directory.editor.UserEditor', {
    extend: 'OPF.core.component.editor.BaseEditor',

    title: 'USER: [New]',

    infoResourceLookup: 'net.firejack.platform.directory.base-user.user',

    initComponent: function() {
        this.userBasicInfoFieldSet = Ext.create('OPF.console.directory.editor.UserBasicInfoFieldSet');

        this.staticBlocks = [
            this.userBasicInfoFieldSet
        ];

        this.initEditorComponent();
        this.callParent(arguments);
    },

    initEditorComponent: function() {
        if (OPF.isEmpty(this.userInfoFieldSet)) {
            this.userInfoFieldSet = Ext.create('OPF.console.directory.editor.UserInfoFieldSet');
        }
        this.userRoleFieldSet = Ext.create('OPF.console.directory.editor.UserRoleGridFieldSet');

        this.additionalBlocks = [
            this.userInfoFieldSet,
            this.userRoleFieldSet
        ];
    },

    hideEditPanel: function() {
        OPF.console.directory.editor.DirectoryEditor.superclass.hideEditPanel.call(this);
        this.managerLayout.tabPanel.setActiveTab(this.managerLayout.userGridView);
    },

    onAddButton: function() {
        this.saveAs = 'new';

        this.showEditPanel();
    },

    directoryNode: null,    //need to refactored this recursion function

    findParentNodeByType: function(node, type) {
        if (OPF.isNotEmpty(node)) {
            var registryNodeType = OPF.core.utils.RegistryNodeType.findRegistryNodeByType(node.data.type.toLowerCase());
            if (registryNodeType == type) {
                this.directoryNode = node;
                return;
            }
            this.findParentNodeByType(node.parentNode, type);
        }
    },

    onBeforeSetValue: function(jsonData) {
    },

    onAfterSetValue: function(jsonData) {
    },

    showEditPanel: function(registryJsonData) {
        if (this.saveAs == 'update') {
            this.userInfoFieldSet.passwordField.updateMode = true;
            this.userInfoFieldSet.passwordConfirmField.updateMode = true;
            this.title = this.registryNodeType.getTitlePrefix() + ': ' + cutting(registryJsonData.username, 10);
        }

        this.managerLayout.tabPanel.add(this);
        this.managerLayout.tabPanel.doLayout();
        this.managerLayout.tabPanel.setActiveTab(this.id);

        OPF.core.validation.FormInitialisation.hideValidationMessages(this.form);

        var model = this.registryNodeType.createModel(registryJsonData);

        if (OPF.isNotEmpty(this.onBeforeSetValue)) {
            this.onBeforeSetValue(registryJsonData);
        }

        this.form.getForm().loadRecord(model);

        if (OPF.isNotEmpty(this.onAfterSetValue)) {
            this.onAfterSetValue(registryJsonData);
        }

        var options = {};
        if (OPF.isNotEmpty(registryJsonData)) {
            if (OPF.isNotEmpty(this.userRoleFieldSet.userRolesStore)) {
                this.userRoleFieldSet.userRolesStore.loadData(registryJsonData.userRoles);
            } else {
                var i, roles = [];
                if (OPF.isNotEmpty(registryJsonData.userRoles)) {
                    for (i = 0; i < registryJsonData.userRoles.length; i++) {
                        roles.push(registryJsonData.userRoles[i].role);
                    }
                }
                this.userRoleFieldSet.assignedRolesStore.loadData(roles);
                var exceptRolesIds = [];
                for (i = 0; i < roles.length; i++) {
                   exceptRolesIds.push(roles[i].id);
                }
                options = {
                   params: {
                      exceptIds: exceptRolesIds
                   }
                };
            }
        }
        if (OPF.isNotEmpty(this.userRoleFieldSet.availableRolesStore)) {
            this.userRoleFieldSet.availableRolesStore.load(options);
        }

        this.fetchDataFromSelectedNode();

        this.formInitialisation(registryJsonData);
    },

    save: function() {
        this.form.getEl().mask();

        var formData = this.form.getForm().getValues();

        var method = null;
        var url = null;
        if (this.saveAs == 'new') {
            method = 'POST';
            url = this.registryNodeType.generatePostUrl();
        } else if (this.saveAs == 'update') {
            method = 'PUT';
            url = this.registryNodeType.generatePutUrl(formData.id);
            if (isBlank(formData.password)) {
                delete formData.password;
                delete formData.passwordConfirm;
            }
        } else {
            this.form.getEl().unmask();
            this.form.getForm().reset();
            this.hideEditPanel();

            Ext.MessageBox.alert('Failure', 'Unknown operation');
            return false;
        }

        var userRoles;
        if (OPF.isEmpty(this.userRoleFieldSet.assignedRolesStore)) {
            userRoles = getJsonOfStore(this.userRoleFieldSet.userRolesStore);
        } else {
            userRoles = [];
            var roles = getJsonOfStore(this.userRoleFieldSet.assignedRolesStore);
            if (OPF.isNotEmpty(roles)) {
                for (var i = 0; i < roles.length; i++) {
                    var userRole = {
                        role: roles[i]
                    };
                    userRoles.push(userRole);
                }
            }
        }
        formData.userRoles = userRoles;

        delete formData.search;

        delete formData.path;
        delete formData.directory;

        this.saveRequest(formData, url, method);
    },

    onSuccessSaved: function(method, vo) {
    },

    fetchDataFromSelectedNode: function() {
        var parentNode = this.managerLayout.navigationPanel.getSelectedNode();

        this.userBasicInfoFieldSet.pathField.setValue(parentNode.data.lookup);
        this.userBasicInfoFieldSet.registryNodeIdField.setValue(SqGetIdFromTreeEntityId(parentNode.data.id));

        this.findParentNodeByType(parentNode, OPF.core.utils.RegistryNodeType.DIRECTORY);
        if (OPF.isNotEmpty(this.directoryNode)) {
            this.userBasicInfoFieldSet.directoryField.setValue(this.directoryNode.data.text);
        }
    }

});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.springframework.ejb.support.AbstractMessageDrivenBean (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.springframework.ejb.support.AbstractMessageDrivenBean

Packages that use AbstractMessageDrivenBean

org.springframework.ejb.support
Superclasses to make implementing EJBs simpler and less error-prone,
as well as guaranteeing a Spring BeanFactory is available to EJBs.

Uses of AbstractMessageDrivenBean in org.springframework.ejb.support

Subclasses of AbstractMessageDrivenBean in org.springframework.ejb.support

 class
AbstractJmsMessageDrivenBean

          Convenient superclass for JMS MDBs.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2007 The Spring Framework.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Wis. Acad. Sci. Arts Lett. 16(2): 759 (1909)

#### Original name
Cylindrosporium ribis Davis

### Remarks
null


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\EventsCustom */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'event')->dropDownList(\app\models\Events::getListEvents()) ?>

    <?= $form->field($model, 'user_role')->dropDownList(\app\rbac\roles::getRoles()) ?>

    <?= $form->field($model, 'notification_type')->dropDownList(\app\models\Notices::getListTypes()) ?>

        В Шаблоне можно использовать теги,

 #model.title  - содержит объект события.

 #user.  - содержит пользователя совершившего событие

 #recipient.  - содержит пользователя, которому отправляется уведомление

    <?= $form->field($model, 'template_message')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'template_title')->textarea(['rows' => 2]) ?>

    <?= $form->field($model, 'template_link')->textarea(['rows' => 2]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Создать' : 'Обновить', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
 (Lab04Student)
</TITLE>

<META NAME="keywords" CONTENT=" package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Package
      Class
      Tree
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package <Unnamed>

Interface Summary

Library
Defines the interface for a library system that keeps track of media in
 a library.

MatchMaker
Defines an interface for an object that encapsulates a search algorithm.

Class Summary

AnytownLibrary
Represents a library.

AnytownLibraryTest
The test class AnytownLibraryTest.

AuthorMatch
Write a description of class AuthorMatch here.

PartialTitleMatch
Write a description of class PartialTitleMatch here.

TitleMatch
Write a description of class TitleMatch here.

      Package
      Class
      Tree
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
package com.android.androidframework;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;

import com.android.androidframework.actionbar.MainActionBarActivity;
import com.android.androidframework.net.ProgressMessage;
import com.android.androidframework.net.RequestAdapter;
import com.android.androidframework.net.RequestAdapter.RequestContentType;
import com.android.androidframework.net.RequestAdapter.RequestMethod;
import com.android.androidframework.net.ResponseData;
import com.android.androidframework.net.ResponseData.ResultState;

import android.view.View;
import com.xuwei.app.R;
@EActivity(R.layout.activity_main)
public class MainActivity extends MainActionBarActivity {

	@Override
	public void backButtonClick(View v) {

	}

	@Override
	public void titleButtonClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public void rightButtonClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public Boolean showHeadView() {
		// TODO Auto-generated method stub
		return true;
	}

	@Background
	public void bag(){

	}

	@UiThread
	public void uit(){

	}

}


text:
package registry

import (
	"fmt"
	"net/http"
	_ "net/http/pprof"
	"strings"
	"time"
	"io/ioutil"
	"github.com/liuliuzi/stf/pkg/util"
)

type registrar struct{
	name string
}

func NewRegistrar() registrar {
	return registrar{name:"test"}
}

func (r *registrar) AddNode(dstIp string, dstPort string,srcIp string) error{
	path:="/nodes"
	hostname,err:=util.GetHostName()
	if err != nil {
		fmt.Println(err)
		return err
	}
	fmt.Println(hostname)
	nowTime:=time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(nowTime)
	nodeInfo := `{"Id": "`+srcIp+`","Name": "test","HostName": "` + hostname + `","Status": "active","Timestamp": "` + nowTime + `"}`
	fmt.Println(nodeInfo)
	//nodeInfo:=`{"Id": "123","Name": "test","HostName": "ssssss","Status": "active","Timestamp": "20000111"}`
	resp, err := http.Post("http://"+dstIp+":"+dstPort+path,
		"application/json",
		strings.NewReader(nodeInfo))
	if err != nil {
		fmt.Println(err)
		return err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return err
	}

	fmt.Println(string(body))
	return err
}


text:
<ion-view title={{pageTitle}}>
	<ion-content class="dashboard">

Choose Service

COOKING

CLEANING

SPECIALIZED COOKING

SPECIALIZED CLEANING

Instructions

					<textarea class="textarea" rows="8" cols="30" placeholder="Enter the instructions to be passed on to the professional." ng-model = "Dashboard.dashboardDetails.instructions"></textarea>

Choose Cuisine

BREAKFAST

LUNCH

SNACKS

DINNER

Choose Service Area

BEDROOM

LIVING ROOM

DINING ROOM

WASHROOM

Choose Cuisine

BREAKFAST

LUNCH

SNACKS

DINNER

Choose Service Area

BEDROOM

LIVING ROOM

DINING ROOM

WASHROOM

					<button class="button-style waves-effect" ng-click="Dashboard.bookPackage()">ORDER PACKAGE</button>
					<button class="button-style waves-effect no-margin-top" ng-click="Dashboard.bookNow()">BOOK NOW</button>

	</ion-content>

</ion-view>


text:
layout: post
title: Tweets
date: 2021-02-28
summary: These are the tweets for February 28, 2021.
categories:
---