text:
<?php

namespace Podlove\AJAX;

use Podlove\Model\MediaFile;

class FileController
{
    public static function init()
    {
        $actions = [
            'update', 'create',
        ];

        foreach ($actions as $action) {
            add_action('wp_ajax_podlove-file-'.$action, [__CLASS__, str_replace('-', '_', $action)]);
        }
    }

    public static function update()
    {
        $file_id = (int) $_REQUEST['file_id'];

        $file = MediaFile::find_by_id($file_id);

        if (isset($_REQUEST['slug'])) {
            self::simulate_temporary_episode_slug($_REQUEST['slug']);
        }

        $info = $file->determine_file_size();
        $file->save();

        $result = [];
        $result['file_url'] = $file->get_file_url();
        $result['file_id'] = $file_id;
        $result['reachable'] = podlove_is_resolved_and_reachable_http_status($info['http_code']);
        $result['file_size'] = $file->size;
        $result['file_size_human'] = number_format_i18n($file->size);

        if (!$result['reachable']) {
            $info['certinfo'] = print_r($info['certinfo'], true);
            $info['php_open_basedir'] = ini_get('open_basedir');
            $info['php_curl'] = in_array('curl', get_loaded_extensions());
            $info['curl_exec'] = function_exists('curl_exec');

            \Podlove\Log::get()->addError("Can't reach {$file->get_file_url()}", $info);
        } else {
            do_action('podlove_media_file_content_verified', $file->id);
        }

        Ajax::respond_with_json($result);
    }

    public static function create()
    {
        $episode_id = (int) $_REQUEST['episode_id'];
        $episode_asset_id = (int) $_REQUEST['episode_asset_id'];

        if (!$episode_id || !$episode_asset_id) {
            exit();
        }

        if (isset($_REQUEST['slug'])) {
            self::simulate_temporary_episode_slug($_REQUEST['slug']);
        }

        $file = MediaFile::find_or_create_by_episode_id_and_episode_asset_id($episode_id, $episode_asset_id);

        Ajax::respond_with_json([
            'file_id' => $file->id,
            'file_size' => $file->size,
            'file_url' => $file->get_file_url(),
        ]);
    }

    private static function simulate_temporary_episode_slug($slug)
    {
        add_filter('podlove_file_url_template', function ($template) use ($slug) {
            return str_replace('%episode_slug%', \Podlove\prepare_episode_slug_for_url($slug), $template);
        });
    }
}


text:
namespace fst {

template <class Arc, class M = Matcher<Fst<Arc>>,
          class Filter = SequenceComposeFilter<M>,
          class StateTable =
              GenericComposeStateTable<Arc, typename Filter::FilterState>>
struct DifferenceFstOptions
    : public ComposeFstOptions<Arc, M, Filter, StateTable> {
  explicit DifferenceFstOptions(const CacheOptions &opts = CacheOptions(),
                                M *matcher1 = nullptr, M *matcher2 = nullptr,
                                Filter *filter = nullptr,
                                StateTable *state_table = nullptr)
      : ComposeFstOptions<Arc, M, Filter, StateTable>(opts, matcher1, matcher2,
                                                      filter, state_table) {}
};

// Computes the difference between two FSAs. This version is a delayed FST.
// Only strings that are in the first automaton but not in second are retained
// in the result.
//
// The first argument must be an acceptor; the second argument must be an
// unweighted, epsilon-free, deterministic acceptor. One of the arguments must
// be label-sorted.
//
// Complexity: same as ComposeFst.
//
// Caveats: same as ComposeFst.
template <class A>
class DifferenceFst : public ComposeFst<A> {
 public:
  using Arc = A;
  using Weight = typename Arc::Weight;
  using StateId = typename Arc::StateId;

  using ComposeFst<Arc>::CreateBase1;

  // A - B = A ^ B'.
  DifferenceFst(const Fst<Arc> &fst1, const Fst<Arc> &fst2,
                const CacheOptions &opts = CacheOptions())
      : ComposeFst<Arc>(CreateDifferenceImplWithCacheOpts(fst1, fst2, opts)) {
    if (!fst1.Properties(kAcceptor, true)) {
      FSTERROR() << "DifferenceFst: 1st argument not an acceptor";
      GetImpl()->SetProperties(kError, kError);
    }
  }

  template <class Matcher, class Filter, class StateTable>
  DifferenceFst(
      const Fst<Arc> &fst1, const Fst<Arc> &fst2,
      const DifferenceFstOptions<Arc, Matcher, Filter, StateTable> &opts)
      : ComposeFst<Arc>(
            CreateDifferenceImplWithDifferenceOpts(fst1, fst2, opts)) {
    if (!fst1.Properties(kAcceptor, true)) {
      FSTERROR() << "DifferenceFst: 1st argument not an acceptor";
      GetImpl()->SetProperties(kError, kError);
    }
  }

  // See Fst<>::Copy() for doc.
  DifferenceFst(const DifferenceFst<Arc> &fst, bool safe = false)
      : ComposeFst<Arc>(fst, safe) {}

  // Get a copy of this DifferenceFst. See Fst<>::Copy() for further doc.
  DifferenceFst<Arc> *Copy(bool safe = false) const override {
    return new DifferenceFst<Arc>(*this, safe);
  }

 private:
  using Impl = internal::ComposeFstImplBase<Arc>;
  using ImplToFst<Impl>::GetImpl;

  static std::shared_ptr<Impl> CreateDifferenceImplWithCacheOpts(
      const Fst<Arc> &fst1, const Fst<Arc> &fst2, const CacheOptions &opts) {
    using RM = RhoMatcher<Matcher<Fst<A>>>;
    ComplementFst<Arc> cfst(fst2);
    ComposeFstOptions<A, RM> copts(
        CacheOptions(), new RM(fst1, MATCH_NONE),
        new RM(cfst, MATCH_INPUT, ComplementFst<Arc>::kRhoLabel));
    return CreateBase1(fst1, cfst, copts);
  }

  template <class Matcher, class Filter, class StateTable>
  static std::shared_ptr<Impl> CreateDifferenceImplWithDifferenceOpts(
      const Fst<Arc> &fst1, const Fst<Arc> &fst2,
      const DifferenceFstOptions<Arc, Matcher, Filter, StateTable> &opts) {
    using RM = RhoMatcher<Matcher>;
    ComplementFst<Arc> cfst(fst2);
    ComposeFstOptions<Arc, RM> copts(opts);
    copts.matcher1 = new RM(fst1, MATCH_NONE, kNoLabel, MATCHER_REWRITE_ALWAYS,
                            opts.matcher1);
    copts.matcher2 = new RM(cfst, MATCH_INPUT, ComplementFst<Arc>::kRhoLabel,
                            MATCHER_REWRITE_ALWAYS, opts.matcher2);
    return CreateBase1(fst1, cfst, copts);
  }
};

// Specialization for DifferenceFst.
template <class Arc>
class StateIterator<DifferenceFst<Arc>>
    : public StateIterator<ComposeFst<Arc>> {
 public:
  explicit StateIterator(const DifferenceFst<Arc> &fst)
      : StateIterator<ComposeFst<Arc>>(fst) {}
};

// Specialization for DifferenceFst.
template <class Arc>
class ArcIterator<DifferenceFst<Arc>> : public ArcIterator<ComposeFst<Arc>> {
 public:
  using StateId = typename Arc::StateId;

  ArcIterator(const DifferenceFst<Arc> &fst, StateId s)
      : ArcIterator<ComposeFst<Arc>>(fst, s) {}
};

using DifferenceOptions = ComposeOptions;

// Useful alias when using StdArc.
using StdDifferenceFst = DifferenceFst<StdArc>;

using DifferenceOptions = ComposeOptions;

// Computes the difference between two FSAs. This version writes the difference
// to an output MutableFst. Only strings that are in the first automaton but not
// in the second are retained in the result.
//
// The first argument must be an acceptor; the second argument must be an
// unweighted, epsilon-free, deterministic acceptor. One of the arguments must
// be label-sorted.
//
// Complexity: same as Compose.
//
// Caveats: same as Compose.
template <class Arc>
void Difference(const Fst<Arc> &ifst1, const Fst<Arc> &ifst2,
                MutableFst<Arc> *ofst,
                const DifferenceOptions &opts = DifferenceOptions()) {
  using M = Matcher<Fst<Arc>>;
  if (opts.filter_type == AUTO_FILTER) {
    CacheOptions nopts;
    nopts.gc_limit = 0;  // Cache only the last state for fastest copy.
    *ofst = DifferenceFst<Arc>(ifst1, ifst2, nopts);
  } else if (opts.filter_type == SEQUENCE_FILTER) {
    DifferenceFstOptions<Arc> dopts;
    dopts.gc_limit = 0;  // Cache only the last state for fastest copy.
    *ofst = DifferenceFst<Arc>(ifst1, ifst2, dopts);
  } else if (opts.filter_type == ALT_SEQUENCE_FILTER) {
    DifferenceFstOptions<Arc, M, AltSequenceComposeFilter<M>> dopts;
    dopts.gc_limit = 0;  // Cache only the last state for fastest copy.
    *ofst = DifferenceFst<Arc>(ifst1, ifst2, dopts);
  } else if (opts.filter_type == MATCH_FILTER) {
    DifferenceFstOptions<Arc, M, MatchComposeFilter<M>> dopts;
    dopts.gc_limit = 0;  // Cache only the last state for fastest copy.
    *ofst = DifferenceFst<Arc>(ifst1, ifst2, dopts);
  }
  if (opts.connect) Connect(ofst);
}

}  // namespace fst

#endif  // FST_DIFFERENCE_H_

redpajama_set_name: RedPajamaGithub


text:
class VolcanoRobot
{
	String status;
	int speed;
	float temperature;

	void checkTemperature()
	{
		if (temperature>660)
		{
			status = "returning home";
			speed = 5;
		}
	}

void showAttributes ()
	{
	System.out.println("Status: " + status);
	System.out.println("Speed: " + speed);
	System.out.println("Temperature: " + temperature);
	}
}


text:
package spinoco.protocol.kafka.codec

import scodec.Codec
import scodec.codecs._
import shapeless.{::, HNil}
import shapeless.tag.@@
import spinoco.protocol.kafka.{Offset, PartitionId, ProtocolVersion, TopicName}
import spinoco.protocol.kafka.Request.FetchRequest
import spinoco.protocol.kafka.Response.{FetchResponse, PartitionFetchResult}
import spinoco.protocol.common.codec._

import scala.concurrent.duration._

/**
  * Created by pach on 27/08/16.
  */
object FetchCodec {

  def requestCodec(version: Int):Codec[FetchRequest] = version match {
    case 0 | 1 | 2 => requestCodecV1_2
    case 3 | _ => requestCodecV3
  }

  val requestCodecV1_2: Codec[FetchRequest] = {
    (
      ("ReplicaId"          | kafkaBrokerId ) ::
        ("MaxWaitTime"        | durationIntMs(int32)) ::
        ("MinBytes"           | int32) ::
        ("Topics"             | impl.topics)
      ).xmap(
      { case replicaId :: maxWaitTime :: minBytes :: topics :: HNil =>
        FetchRequest(replicaId, maxWaitTime, minBytes, None, topics)
      }
      , rq => rq.replica :: rq.maxWaitTime :: rq.minBytes :: rq.topics :: HNil
    )
  }

  val requestCodecV3: Codec[FetchRequest] = {
    (
      ("ReplicaId"          | kafkaBrokerId ) ::
        ("MaxWaitTime"        | durationIntMs(int32)) ::
        ("MinBytes"           | int32) ::
        ("MaxBytes"           | int32) ::
        ("Topics"             | impl.topics)
      ).xmap(
      { case replicaId :: maxWaitTime :: minBytes :: maxBytes :: topics :: HNil =>
        FetchRequest(replicaId, maxWaitTime, minBytes, Some(maxBytes), topics)
      }
      , rq => rq.replica :: rq.maxWaitTime :: rq.minBytes :: rq.maxBytes.getOrElse(Int.MaxValue) :: rq.topics :: HNil
    )
  }

  def responseCodec(version:ProtocolVersion.Value):Codec[FetchResponse] = {
    version match {
      case ProtocolVersion.Kafka_0_8 =>
        "FetchResponse V0" | impl.fetchResponse.xmap(FetchResponse(_,None), _.data)

      case ProtocolVersion.Kafka_0_10 |
           ProtocolVersion.Kafka_0_10_1 |
           ProtocolVersion.Kafka_0_10_2 |
           ProtocolVersion.Kafka_0_9 =>
        (
          ("ThrottleTime"     | durationIntMs(int32) ) ~
          ("data"             | impl.fetchResponse)
        ).xmap(
          { case (time, resp) => FetchResponse(resp,Some(time))}
          , resp => resp.throttleTime.getOrElse(0.millis) -> resp.data
        )
    }
  }

  object impl {

    val requestPartitionFetch : Codec[(Int @@ PartitionId, Long @@ Offset, Int)] = {
      import shapeless.syntax.std.tuple._
      (
        ("Partition"    | kafkaPartitionId) ::
        ("FetchOffset"  | kafkaOffset) ::
        ("MaxBytes"     | int32)
      ).xmap(_.tupled, _.productElements)
    }

    val topics: Codec[Vector[(String @@ TopicName, Vector[(Int @@ PartitionId, Long @@ Offset, Int)])]] = {
      kafkaArray(
        ("TopicName"    | kafkaTopicName ) ~
        ("Partitions"   | kafkaArray(impl.requestPartitionFetch))
      )

    }

    val partitionFetchResult: Codec[Vector[PartitionFetchResult]] = {
      kafkaArray(
        (
          ("Partition"            | kafkaPartitionId) ::
          ("ErrorCode"            | kafkaError) ::
          ("HighwaterMarkOffset"  | kafkaOffset) ::
          ("MessageSetSize"       | variableSizeBytes(int32 , MessageSetCodec.messageSetCodec))
        ).xmap(
          { case partitionId :: error :: offset :: messageSet :: HNil =>
            PartitionFetchResult(partitionId,error,offset,messageSet)
          }
          , r => r.partitionId :: r.error :: r.highWMOffset :: r.messages :: HNil
        )
      )
    }

    val fetchResponse : Codec[Vector[(String @@ TopicName, Vector[PartitionFetchResult])]] = {
      kafkaArray(
        ("TopicName"      | kafkaTopicName ) ~
        ("Partitions"     | partitionFetchResult)
      )
    }

  }

}


text:
package com.haogrgr.netty.chapter2_3;

import org.springframework.core.io.ClassPathResource;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EchoServer {

	private final int port = 9999;

	public static void main(String[] args) throws Exception {
		ClassPathResource res = new ClassPathResource("/app.properties");
		System.out.println(res.getFile().getAbsolutePath());
		System.out.println(Files.toString(res.getFile(), Charsets.UTF_8));

		EchoServer server = new EchoServer();
		server.start();
	}

	public void start() throws Exception {
		EchoServerHandler hander = new EchoServerHandler();
		NioEventLoopGroup group = new NioEventLoopGroup();

		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(group);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.localAddress(port);
			bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(hander);
				}
			});

			ChannelFuture future = bootstrap.bind().sync();
			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();
		}

	}
}


text:
<?php
namespace backend\module\rbac\service;

use Yii;
use yii\db\Transaction;
use yii\helpers\Url;
use yii\helpers\Json;
use common\lib\helpers\ArrayHelper;
use backend\models\OperationLog;
use yii\data\ActiveDataProvider;
use yii\web\ForbiddenHttpException;
use yii\web\ServerErrorHttpException;
use backend\module\rbac\models\AuthMenu;
use backend\module\rbac\models\AuthItem;
use backend\service\LogService;
/**
 *
 * @author Yong
 *
 */
class MenuService extends BaseService
{
   /**
    * 菜单列表
    * @param AuthMenu $model
    * @param bool $filter
    * @return \yii\data\ActiveDataProvider[]
    */
   public static function index(AuthMenu $model, bool $filter)
   {
       $return = [];
       $query = $model::find();
       $dataProvider = new ActiveDataProvider([
           'query' => $query,
           'sort' => [
               'defaultOrder' => [
                   'level' => SORT_ASC,
                   'pid' => SORT_ASC,
                   'sort' => SORT_ASC,
                   'created_at' => SORT_DESC,
               ]
           ],
       ]);

       if ($filter) {
           $query->filterWhere([
               'id' => $model->id,
               'pid' => $model->pid,
               'created_at' => $model->created_at,
               'level' => $model->level,
           ]);
           $query->andFilterWhere(['like', 'name', $model->name])
               ->andFilterWhere(['like', 'uri', $model->uri]);
       }

       $allMenu = AuthMenu::getAllMenu(); //全部菜单
       $pidList = ArrayHelper::arArrayColumn($dataProvider->getModels(), 'pid', true);
       $return['dataProvider'] = $dataProvider;
       $return['preLevelMenuList'] = AuthMenu::getByIds($pidList);//当前页的菜单的上级菜单列表
       $return['levelCnameList'] = self::getLevelCName(1111); //菜单级别名称列表
       //选择框选项菜单列表
       $return['menuList'] = [
           '一级菜单' => array_column($allMenu[0], 'name', 'id'),
           '二级级菜单' => array_column($allMenu[1], 'name', 'id'),
           '三级级菜单' => array_column($allMenu[2], 'name', 'id'),
       ];
       return $return;
   }

   /**
    * 获取详情显示所需要数据
    * @param AuthMenu $model
    * @return string[]|mixed[]|\backend\module\rbac\logic\string[][]
    */
   public static function view(AuthMenu $model)
   {
       return [
           'pMenuName' => self::getPMenuName($model),
           'levelCnameList' => self::getLevelCName(1111),
       ];
   }

   /**
    * 获取更新所需要数据
    * @param AuthMenu $model
    * @return string[]|mixed[]|\backend\module\rbac\logic\string[][]
    */
   public static function getUpdateNData(AuthMenu $model)
   {
       return [
           'pMenuName' => self::getPMenuName($model),
           'levelCnameList' => self::getLevelCName(1111),
           'preLevelMenu' => self::getPlevelMenuList($model),
       ];
   }

   /**
    * 获取父菜单名字 (view对应数据方法)
    * @param AuthMenu $model
    * @return string|mixed
    */
   public static function getPMenuName(AuthMenu $model)
   {
       $pMenu = AuthMenu::getByid($model->pid);
       return $pMenu['name'] ?? '';
   }

   /**
    * 获取当前菜单上级菜单列表
    * @param AuthMenu $model
    */
   public static function getPlevelMenuList(AuthMenu $model)
   {
       return array_column(AuthMenu::getLevelMenu($model->level-1), 'name', 'id');
   }

   /**
    * 保存菜单数据
    * @param AuthMenu $model
    * @param string $runValidation
    * @param mix $attributeNames
    * @throws Exception
    * @return boolean
    */
   public static function saveMenu(AuthMenu $model, $runValidation = true, $attributeNames = null)
   {
       $model->updated_at = time();
       $connection = Yii::$app->getDb();
       $auth = Yii::$app->getAuthManager();
       $transaction = $connection->beginTransaction(Transaction::READ_COMMITTED);
       try {
           //当前操作类型
           $type = $model->isNewRecord ? OperationLog::CREATE : OperationLog::UPDATE ;
           $oldUri = $model->isNewRecord ? '' : $model->oldAttributes['uri'];
           $oldLevel = $model->isNewRecord ? $model->level : $model->oldAttributes['level'];
           if ($model->id >0 && $model->id == $model->pid) {
               $model->addError('pid', '不可以将自己修改为父级菜单');
               throw new ServerErrorHttpException;
           }//禁止修改含有子级菜单的菜单的菜单级别
           elseif (!$model->isNewRecord  && $oldLevel != $model->level && !empty(AuthMenu::getByPid($model->id))) {
               $model->addError('level', '含有子级菜单的不可以修改菜单级别');
               throw new ServerErrorHttpException;
           }//三四级菜单添加修改
           elseif (($model->isNewRecord || $oldLevel >= 3) && $model->level >= 3) {
               if($model->uri === 'null'){
                   $model->addError('uri', '路由不能为null');
                   throw new ServerErrorHttpException;
               }
               if ($model->isNewRecord) {
                   $newMenu = $auth->createPermission($model->uri);
                   $newMenu->description = $model->name;
                   $auth->add($newMenu);
               } else {
                   if($oldUri !== $model->uri && $model->uri !== 'null'){
                       $connection->createCommand()->update('{{%auth_item}}', [
                          'name' => $model->uri, 'updated_at' => time(), 'description' => $model->name
                       ], ['name' => $oldUri])->execute();
                   }
               }
           }//一二级菜单转换三四级菜单
           elseif (!$model->isNewRecord && $oldLevel < 3 &&  $model->level >= 3 ) {
               $newMenu = $auth->createPermission($model->uri);
               $newMenu->description = $model->name;
               $auth->add($newMenu);
           }//三四级转换一二级
           elseif (!$model->isNewRecord && $oldLevel >= 3 && $model->level<3) {
               $model->pid = $model->level==1? 0 : $model->pid;
               $model->uri = 'null';
               if(!$model->save($runValidation, $attributeNames)){
                   throw new ServerErrorHttpException;
               }
               $permission = $auth->createPermission($oldUri);
               if (!$auth->remove($permission)) {
                   throw new ServerErrorHttpException;
               }
           }//一二级菜单添加修改
           else {
               $model->uri = 'null';
               $model->pid = $model->level == 1 ? 0 : $model->pid;
           }//保存菜单
           if (!$model->save($runValidation, $attributeNames)) {
               throw new ServerErrorHttpException;
           }
           //保存系统操作日志
           LogService::saveOperationLog($type, __METHOD__, Json::encode($model));
           $transaction->commit();
           //重置缓存
           AuthMenu::updateMenuCache($model, $type === OperationLog::CREATE, $oldLevel);
           return true;
       } catch (\Exception $e) {
           $transaction->rollBack();
           if (stripos($e->getMessage(), 'duplicate') !== false) {
               $model->addError('uri', '该路由已经存在');
           }
           return false;
       }
   }

   /**
    * 检查菜单级别是否大于1
    * @param  AuthMenu $model
    * @return boolean
    */
   public static function isLevelMoreThanOne(AuthMenu $model)
   {
       return $model->level > 1;
   }

   /**
    * 检查菜单级别是否大于2
    * @param AuthMenu $model
    * @return boolean
    */
   public static function isLevelMoreThanTwo(AuthMenu $model)
   {
       $model->uri = strtolower($model->uri);
       return $model->level > 2;
   }

   /**
    * 删除一个菜单
    * @param AuthMenu $model
    * @throws ForbiddenHttpException
    * @return number|\yii\db\false
    */
   public static function delete(AuthMenu $model)
   {
       if($model->isNewRecord){
           throw new ForbiddenHttpException('禁止空模型调删除接口');
       } elseif (AuthMenu::getByPid($model->id)) {
           throw new ForbiddenHttpException('禁止删除含有子级菜单的菜单');
       } elseif (AuthItem::findOne(['name' => $model->uri])->delete()) {
           AuthMenu::updateMenuCache($model, false, 1, true);
           LogService::saveOperationLog(OperationLog::DELETE, __METHOD__, Json::encode($model));
           return true;
       }
   }

   /**
    * 批量删除菜单
    * @param array $idList
    * @return string
    */
   public static function bulkDelete(array $idList)
   {
       $idList = array_unique(array_map('intval', $idList));
       $hasCHildIdList = AuthMenu::getByPids($idList, ['pid']);
       $noCHildIdList = array_diff($idList, $hasCHildIdList);
       if (empty($noCHildIdList)) {
           $msg = '选择数据均不能删除';
       } else {
           $nameList = $uriList = [];
           $menus = AuthMenu::findAll(['id' => $noCHildIdList]);
           foreach ($menus as $menu) {
               if ($menu->level >= 3) {
                   $nameList[] = $menu->uri;
               }
               $uriList[] = $menu->uri;
           }
           $num = AuthItem::deleteAll(['name' => $nameList, 'type' => AuthItem::MENU]);
           $num += AuthMenu::deleteAll(['id' => $noCHildIdList]);
           if ($num) {
               AuthMenu::bulkDelMenuCache($menus);
               $msg = '成功删除ID为'.implode(',', $noCHildIdList).',uri值为' . implode(',', $uriList) . '的'.$num.'条数据';
               LogService::saveOperationLog(OperationLog::DELETE, __METHOD__, $msg);
           } else {
               \Yii::$app->getResponse()->setStatusCode(500);
               $msg = '系统异常';
           }
       }
       return $msg;
   }

   /**
    * 获取某一级菜单名称或者菜单名称列表
    * @param int $level
    * @return string[]|string
    */
   public static function getLevelCName(int $level)
   {
       $levelList = [
           1 => '导航栏',
           2 => '二级菜单',
           3 => '三级菜单',
           4 => '按钮操作',
       ];
       return $levelList[$level] ?? $levelList;
   }

   /**
    * 获取菜单列表
    * @return array
    */
   public static function getMenuNav()
   {
       $return = [];
       $user = Yii::$app->getUser();
       list ($level1, $level2, $level3) = AuthMenu::getAllMenu();
       foreach ($level3 as $v) {
           if (!$user->can($v['uri']) || $v['uri'] === 'debug/default/view') {
               continue;
           }
           $items = [];
           $items['id'] = $v['id'];
           $items['text'] = $v['name'];
           $items['href'] = Url::to([ '/' . $v['uri']]);
           $level2[$v['pid']]['items'][] = $items ;
       }
       foreach ($level2 as $v) {
           if (empty($v['items'])) {
               continue;
           }
           $menu = [];
           $menu['collapsed'] = true;
           $menu['text'] = $v['name'];
           $menu['items'] = $v['items'];
           $level1[$v['pid']]['menu'][] = $menu;
       }
       foreach ($level1 as $v) {
           if (empty($v['menu'])) {
               continue;
           }
           $return[] = $v;
       }
       return $return;
   }

}


text:
An example application for making an executable jar file out of a ruby gem using the [warbler](https://github.com/jruby/warbler) gem.

## Creating your own

Create a new gem

```bash
$ bundle new my_gem_name
$ cd my_gem_name
```

## Create a bin/my_gem_name file to run as the "public static void main(String[] args)"

Create the bin dir and add your file inside

```bash
$ mkdir bin
(add your file to the bin folder)
```

## Edit the my_gem_name.gemspec and add your executable file (if not already done)

## Use the example [config/warble.rb] in this repo as a template for your jar

## Create your jar

```bash
$ warble
```

## Run your jar

Here is an example of running this jar created by this repo

```bash
$ java -jar simple_ruby_jar.jar
Hello World Java 1.6.0_65!
```


text:
from buildbot.www.hooks.github import GitHubEventHandler
from dateutil.parser import parse as dateparse
from twisted.internet import defer
from twisted.python import log
import logging, json

class JuliaGithubListener(GitHubEventHandler):
    def handle_create(self, payload, event):
        if 'ref_type' not in payload:
            payload = json.loads(payload['payload'][0])

        if payload['ref_type'] != 'tag':
            return [], 'git'

        change = {
            'author': payload['sender']['login'],
            'repository': payload['repository']['clone_url'],
            'project': payload['repository']['full_name'],
            'branch': payload['ref'],
            'comments': 'tag-creation commit',
            'category': 'tag',
        }

        # Do some magic here
        return [change], 'git'

    # In addition to all the other events, we parse release events as well
    # (for things like LLVM.jl, Cxx.jl, etc...)
    def handle_release(self, payload, event):
        if 'release' not in payload:
            payload = json.loads(payload['payload'][0])

        change = {
            'author': payload['release']['author']['login'],
            'repository': payload['repository']['clone_url'],
            'project': payload['repository']['full_name'],
            'revision': payload['release']['tag_name'],
            'when_timestamp': dateparse(payload['release']['published_at']),
            'revlink': payload['release']['html_url'],
            'category': 'release',
            'comments': payload['release']['body'],
            'branch': payload['release']['tag_name'],
        }

        # Do some magic here
        return [change], 'git'

    # We override handle_pull_request to use merge commits instead of branch tip sha's
    # This requires a single changed line of code, highlighted below:
    @defer.inlineCallbacks
    def handle_pull_request(self, payload, event):
        changes = []
        number = payload['number']
        refname = 'refs/pull/{}/{}'.format(number, self.pullrequest_ref)
        basename = payload['pull_request']['base']['ref']
        commits = payload['pull_request']['commits']
        title = payload['pull_request']['title']
        comments = payload['pull_request']['body']
        repo_full_name = payload['repository']['full_name']
        head_sha = payload['pull_request']['head']['sha']

        log.msg('Processing GitHub PR #{}'.format(number),
                logLevel=logging.DEBUG)

        head_msg = yield self._get_commit_msg(repo_full_name, head_sha)
        if self._has_skip(head_msg):
            log.msg("GitHub PR #{}, Ignoring: "
                    "head commit message contains skip pattern".format(number))
            return ([], 'git')

        action = payload.get('action')
        if action not in ('opened', 'reopened', 'synchronize'):
            log.msg("GitHub PR #{} {}, ignoring".format(number, action))
            return (changes, 'git')

        properties = self.extractProperties(payload['pull_request'])
        properties.update({'event': event})
        properties.update({'basename': basename})

        # Prefer the merge commit sha, if we can find it
        #revision = payload['pull_request']['merge_commit_sha']
        #if revision is None:
        # REVERTED FOR NOW, it was randomly failing, and also broke status reporting
        revision = payload['pull_request']['head']['sha']
        change = {
            'revision': revision,
            'when_timestamp': dateparse(payload['pull_request']['created_at']),
            'branch': refname,
            'revlink': payload['pull_request']['_links']['html']['href'],
            'repository': payload['repository']['html_url'],
            'project': payload['pull_request']['base']['repo']['full_name'],
            'category': 'pull',
            # TODO: Get author name based on login id using txgithub module
            'author': payload['sender']['login'],
            'comments': 'GitHub Pull Request #{0} ({1} commit{2})\n{3}\n{4}'.format(
                number, commits, 's' if commits != 1 else '', title, comments),
            'properties': properties,
        }

        if callable(self._codebase):
            change['codebase'] = self._codebase(payload)
        elif self._codebase is not None:
            change['codebase'] = self._codebase

        changes.append(change)

        log.msg("Received {} changes from GitHub PR #{}".format(
            len(changes), number))
        return (changes, 'git')


text:
module Spree
  class AddOnMallPrice < ActiveRecord::Base
    belongs_to :variant, class_name: 'Spree::Variant', :foreign_key => :variant_id
    belongs_to :add_on_mall, class_name: 'Spree::AddOnMall', :foreign_key => :add_on_mall_id
    validates_uniqueness_of :add_on_mall_id, :scope => :variant_id
    validates_uniqueness_of :amount, :scope => [:add_on_mall_id, :variant_id], allow_nil: true
    validates_uniqueness_of :currency, :scope => [:add_on_mall_id, :variant_id], allow_nil: true
  end
end


text:
void naiboard_eeprom_readcounter(void);
uint8_t naiboard_eeprom_readstatusbyte(void);
void naiboard_eeprom_writestatusbyte(uint8_t statusbyte);
void naiboard_eeprom_init(void);

#endif


text:
angular.module('errandRunner')
  .factory('Payment', function($http) {
    return {
      addPayment: function(Pay) {
        return $http.post('/api/payment', { cardHolder: Pay.cardHolder, amount: Pay.amount,
          itemId: Pay.itemId });
      },
      getProgress: function(_id) {
        return $http.get('/api/payment', _id);
      }
    };
  });


text:
using System.Reflection;

namespace Whathecode.System.Reflection.Extensions
{
	public static partial class Extensions
	{
		/// <summary>
		///   Returns whether the event is static or not.
		/// </summary>
		/// <param name = "source">The event to verify whether it is static or not.</param>
		/// <returns>True when the event is static; false otherwise.</returns>
		public static bool IsStatic( this EventInfo source )
		{
			// When an event is static, both the add and remove method are static.
			return source.AddMethod.IsStatic;
		}
	}
}


text:
body{
	margin: 0;
	padding: 0;
}

section{
	background: #DFDFDF;
	margin: 10px auto;
	padding: 10px;
	width: 80%;
}

h1{
	border-bottom: 1px solid #FFFFFF;
	color: #4682B4;
	padding-bottom: 20px;
	text-align: center;
}

.types {
	margin: auto;
	overflow: hidden;
}

.nth-of-type, .nth-child{
	float: left;
	margin: 10px 10px;
	width: 45%;
}

.UI {
	clear: both;
	margin: 10px auto;
	width: 60%;
}

form{
	margin: 40px auto;
	color: steelblue;
	width: 370px;
}

li.nth-of-type-li, div.nth-of-type-div{
	border: 1px solid #000000;
	font-family: Arial;
	font-size: 0.8em;
	list-style-type: none;
	margin: 5px;
	padding: 5px 10px;
}

li.nth-child-li{
	border: 1px solid #dddddd;
	list-style-type: none;
	margin: 2px 50px 2px 0;
	padding: 5px 10px;
}

input[type="email"], input[type="text"], textarea{
	display: block;
	margin-bottom: 20px;
	width: 100%;
	border: 2px solid steelblue;
	padding: 5px;
}

input[type="radio"]{
	margin: 0 12px 20px;
}

input[type="submit"]{
	background: steelblue;
	border: 2px solid white;
	color: #FFFFFF;
	cursor: pointer;
	height: 50px;
	margin: 10px 0;
	width: 330px;
}

/*--PSEUDO CLASE ESTRUCTURAL :nth-of-type(posición)--

Determinamos el tipo de elemento a seleccionar
Si lo hicieramos con li:nth-child(5), no funcionaría porque en este caso el quinto elemento es un DIV

Con la pseudo-clase :nth-of-type() omitimos los demás elementos dentro del mismo padre que no sean del tipo
que lo definamos

También tenemos el :nth-last-of-type()

Otros pseudo-clases estructurales de tipo:

- :first-of-type
- :last-of-type
- :only-of-type*/

li.nth-of-type-li:nth-last-of-type(2n+1){
	background: blue ;
	color: white;
	font-size: 2em;
}

div.nth-of-type-div:nth-last-of-type(2n){
	background: orange;
	color: white;
	font-size: 2em;
}

/*-- Diferencia entre :only-of-type y :only-child

En el ejemplo de abajo si utilizaramos la pseudo-clase :only-child, no haria nada, puesto que strong no el único
"hijo" del elemento tiene p. En cambio con only-of-type, especificamos que de todos los elementos "hijo" que pueda
tener p, solo se aplique la regla a los que son strong */

p strong:only-of-type{
	color: red;
	font-size: 2em;
}

/*--PSEUDO CLASES ESTRUCTURALES :nth-child(posición) y :nth-last-child(posición)

La posición se puede establecer mediante:

1.- Valor númerico
2.- Even: elementos pares / odd: elementos impares
3.- Formulas matemáticas: 2n+4
	- Siempre en ese orden. 4+2n no funcionará
	- 2n+4: Empezando en el elemento 4 y añadiendo 2 elementos hasta que se acabe la lista en este caso
	- La formula matemática para restar valores: -2n+6, empieza en la sexta posición desde el principio y va restando 2

:nth-list-child(posición): establece el punto de partida empezando desde el final:

1.- :nth-last-child(4): cuarto elemento desde el final
2.- :nth-last-child(2n+6): sexto elemento desde el final y sumandole 2.Al ser last, la dirección en la que se lee la lista cambia. En este caso
	los elementos seleccionados serán el 5, el 3 y el 1
3.- :nth-last-child(-2n+6): sexto elemento desde el final y restandole 2.Al ser last, la dirección en la que se lee la lista cambia. En este caso
	los elementos seleccionados serán el 5, el 7 y el 9 */

li.nth-child-li:nth-last-child(-2n+4){
	background: red;
	color: white;
}

li.nth-child-li:nth-last-child(even){
	background: green;
	color: white;
}

/*------------- Estilos Pseudo Clases UI ------------*/

input[type="email"]:enabled{ /*selecciona los elementos que tienen un estado positivo, es decir
,están activos. Por defecto todos los elementos están activos, menos los checkbox, radio...*/
	background: yellow;
	color: green;
}

:disabled{ /*selecciona los elementos que tienen un estado negativo es decir
,están desactivados. Hay que inidcar implicitamente en el documento qué elementos están disabled*/
	background: #666;
	color: white;
	cursor: no-drop;
}

input[type="radio"]:checked + label{selecciona los elementos del formulario que están checkeados
	font-weight: bold;
	color: black;
	padding: 3px;
	border: 1px solid steelblue;
}

input[type="submit"]:hover{
	background: white;
	color: steelblue;
	border: 2px solid steelblue;
}


text:
package com.orctom.laputa.utils;

public abstract class Booleans {

  public static boolean isBooleam(String value) {
    return value != null &&
        (value.equalsIgnoreCase("true") ||
            value.equalsIgnoreCase("t") ||
            value.equalsIgnoreCase("1") ||
            value.equalsIgnoreCase("enabled") ||
            value.equalsIgnoreCase("y") ||
            value.equalsIgnoreCase("yes") ||
            value.equalsIgnoreCase("on"));
  }
}


text:
"""Export and import material meshes."""

import bpy
import nose.tools

from pyffi.formats.nif import NifFormat

from test import SingleNif
from test.geometry.trishape import gen_geometry
from test.geometry.trishape.test_geometry import TestBaseGeometry
from test.property.material.gen_material import Material

class TestMaterialProperty(SingleNif):
    n_name = 'property/material/base_material'
    b_name = 'Cube'

    def b_create_objects(self):
        b_obj = TestBaseGeometry().b_create_base_geometry()
        b_obj.name = self.b_name
        self.b_create_material_block(b_obj)

    def b_create_material_block(self, b_obj):
        b_mat = bpy.data.materials.new(name='Material')
        b_mat.specular_intensity = 0 # disable NiSpecularProperty
        b_obj.data.materials.append(b_mat)
        bpy.ops.object.shade_smooth()
        self.b_create_material_property(b_mat)
        return b_obj

    def b_create_material_property(self, b_mat):
        # TODO_3.0 - See above
        b_mat.ambient = 1.0
        b_mat.diffuse_color = (1.0,1.0,1.0)
        b_mat.diffuse_intensity = 1.0

    def b_check_data(self):
        b_obj = bpy.data.objects[self.b_name]
        TestBaseGeometry().b_check_geom_obj(b_obj)
        self.b_check_material_block(b_obj)

    def b_check_material_block(self, b_obj):
        b_mesh = b_obj.data
        b_mat = b_mesh.materials[0]
        nose.tools.assert_equal(len(b_mesh.materials), 1)
        self.b_check_material_property(b_mat)

    def b_check_material_property(self, b_mat):
        nose.tools.assert_equal(b_mat.ambient, 1.0)
        nose.tools.assert_equal(b_mat.diffuse_color[0], 1.0)
        nose.tools.assert_equal(b_mat.diffuse_color[1], 1.0)
        nose.tools.assert_equal(b_mat.diffuse_color[2], 1.0)

    def n_create_data(self):
        data = gen_geometry.n_create_data()
        data = Material().n_create(data)
        return data

    def n_check_data(self, n_data):
        TestBaseGeometry().n_check_data(n_data)
        self.n_check_material_block(n_data)

    def n_check_material_block(self, n_data):
        n_geom = n_data.roots[0].children[0]
        nose.tools.assert_equal(n_geom.num_properties, 1)
        self.n_check_material_property(n_geom.properties[0])

    '''
    TODO_3.0 - per version checking????
        self.n_check_flags(n_data.header())

    def n_check_flags(self, n_header):
        pass
        if(self.n_header.version == 'MORROWIND'):
            nose.tools.assert_equal(n_geom.properties[0].flags == 1)
    '''

    def n_check_material_property(self, n_mat_prop):
        nose.tools.assert_is_instance(n_mat_prop, NifFormat.NiMaterialProperty)
        # TODO - Refer to header - can be ignored for now, defaults.
        nose.tools.assert_equal((n_mat_prop.ambient_color.r,
                                 n_mat_prop.ambient_color.g,
                                 n_mat_prop.ambient_color.b), (1.0,1.0,1.0))

        nose.tools.assert_equal((n_mat_prop.diffuse_color.r,
                                 n_mat_prop.diffuse_color.g,
                                 n_mat_prop.diffuse_color.b), (1.0,1.0,1.0))

'''
class TestAmbientMaterial(TestMaterialProperty):
    n_name = "property/material/base_material"

    def b_create_object(self):
        b_obj = TestBaseGeometry.b_create_object(self)
        b_mat = b_obj.data.materials[0]

        #diffuse settings
        b_mat.niftools.ambient_color = (0.0,1.0,0.0)#TODO_3.0 - update func-> World ambient
        return b_obj

    def b_check_data(self, b_obj):
        b_mesh = b_obj.data
        b_mat = b_mesh.materials[0]
        self.b_check_ambient_property(b_mat)

    def b_check_ambient_property(self, b_mat)
        nose.tools.assert_equal(b_mat.niftools.ambient_color, (0.0,1.0,0.0))

    def n_check_data(self, n_data):
        n_geom = n_data.roots[0].children[0]
        self.n_check_material_property(n_geom.properties[0])

    def n_check_material_property(self, n_mat_prop):
        nose.tools.assert_is_instance(n_mat_prop, NifFormat.NiMaterialProperty)
        nose.tools.assert_equal(n_mat_prop.ambient_color, (0.0,1.0,0.0))

class TestDiffuseMaterial(TestMaterialProperty):
    n_name = "property/material/base_material"

    def b_create_object(self):
        b_obj = TestBaseGeometry.b_create_object(self)
        b_mat = b_obj.data.materials[0]

        #diffuse settings
        b_mat.niftools.diffuse_color = (0.0,1.0,0.0)#TODO_3.0 - update func-> World ambient
        return b_obj

    def b_check_data(self, b_obj):
        b_mesh = b_obj.data
        b_mat = b_mesh.materials[0]
        self.b_check_diffuse_property(b_mat)

    def b_check_diffuse_property(self, b_mat)
        nose.tools.assert_equal(b_mat.niftools.diffuse_color, (0.0,1.0,0.0))
        nose.tools.assert_equal(b_mat.diffuse_intensity, 1.0)

    def n_check_data(self, n_data):
        n_geom = n_data.roots[0].children[0]
        self.n_check_material_property(n_geom.properties[0])

    def n_check_material_property(self, n_mat_prop):
        nose.tools.assert_is_instance(n_mat_prop, NifFormat.NiMaterialProperty)
        nose.tools.assert_equal(n_mat_prop.diffuse_color, (0.0,1.0,0.0))

'''