text:
// Copyright 2018-present Barefoot Networks, Inc.
// SPDX-License-Identifier: Apache-2.0

#include "stratum/hal/lib/bmv2/bmv2_switch.h"

#include <algorithm>
#include <map>
#include <set>
#include <vector>

#include "absl/memory/memory.h"
#include "absl/synchronization/mutex.h"
#include "stratum/glue/gtl/map_util.h"
#include "stratum/glue/integral_types.h"
#include "stratum/glue/logging.h"
#include "stratum/glue/status/status_macros.h"
#include "stratum/hal/lib/pi/pi_node.h"
#include "stratum/lib/constants.h"
#include "stratum/lib/macros.h"

namespace stratum {
namespace hal {
namespace bmv2 {

using ::stratum::hal::pi::PINode;

Bmv2Switch::Bmv2Switch(PhalInterface* phal_interface,
                       Bmv2ChassisManager* bmv2_chassis_manager,
                       const std::map<uint64, PINode*>& node_id_to_pi_node)
    : phal_interface_(ABSL_DIE_IF_NULL(phal_interface)),
      bmv2_chassis_manager_(ABSL_DIE_IF_NULL(bmv2_chassis_manager)),
      node_id_to_pi_node_(node_id_to_pi_node) {}

Bmv2Switch::~Bmv2Switch() {}

::util::Status Bmv2Switch::PushChassisConfig(const ChassisConfig& config) {
  absl::WriterMutexLock l(&chassis_lock);
  std::set<uint64> known_node_ids;
  std::set<uint64> new_node_ids;
  for (auto& node : node_id_to_pi_node_) known_node_ids.insert(node.first);
  for (auto& node : config.nodes()) new_node_ids.insert(node.id());
  if (known_node_ids != new_node_ids) {
    return MAKE_ERROR(ERR_INVALID_PARAM)
           << "The Bmv2Switch expects constant node ids";
  }
  RETURN_IF_ERROR(phal_interface_->PushChassisConfig(config));
  RETURN_IF_ERROR(bmv2_chassis_manager_->PushChassisConfig(config));
  for (auto& node : node_id_to_pi_node_) {
    // Sets the node_id for the PINode the first time, does not do anything in
    // subsequent calls (the node_id is constant).
    RETURN_IF_ERROR(node.second->PushChassisConfig(config, node.first));
  }
  return ::util::OkStatus();
}

::util::Status Bmv2Switch::VerifyChassisConfig(const ChassisConfig& config) {
  absl::ReaderMutexLock l(&chassis_lock);
  ::util::Status status = ::util::OkStatus();
  APPEND_STATUS_IF_ERROR(status, phal_interface_->VerifyChassisConfig(config));
  APPEND_STATUS_IF_ERROR(status,
                         bmv2_chassis_manager_->VerifyChassisConfig(config));
  for (auto& node : node_id_to_pi_node_) {
    APPEND_STATUS_IF_ERROR(status,
                           node.second->PushChassisConfig(config, node.first));
  }
  return status;
}

::util::Status Bmv2Switch::PushForwardingPipelineConfig(
    uint64 node_id, const ::p4::v1::ForwardingPipelineConfig& config) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  RETURN_IF_ERROR(pi_node->PushForwardingPipelineConfig(config));

  LOG(INFO) << "P4-based forwarding pipeline config pushed successfully to "
            << "node with ID " << node_id << ".";

  return ::util::OkStatus();
}

::util::Status Bmv2Switch::SaveForwardingPipelineConfig(
    uint64 node_id, const ::p4::v1::ForwardingPipelineConfig& config) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  RETURN_IF_ERROR(pi_node->SaveForwardingPipelineConfig(config));

  LOG(INFO) << "P4-based forwarding pipeline config saved successfully to "
            << "node with ID " << node_id << ".";

  return ::util::OkStatus();
}

::util::Status Bmv2Switch::CommitForwardingPipelineConfig(uint64 node_id) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  RETURN_IF_ERROR(pi_node->CommitForwardingPipelineConfig());

  LOG(INFO) << "P4-based forwarding pipeline config committed successfully to "
            << "node with ID " << node_id << ".";

  return ::util::OkStatus();
}

::util::Status Bmv2Switch::VerifyForwardingPipelineConfig(
    uint64 node_id, const ::p4::v1::ForwardingPipelineConfig& config) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  return pi_node->VerifyForwardingPipelineConfig(config);
}

::util::Status Bmv2Switch::Shutdown() {
  ::util::Status status = ::util::OkStatus();
  APPEND_STATUS_IF_ERROR(status, bmv2_chassis_manager_->Shutdown());
  return status;
}

::util::Status Bmv2Switch::Freeze() { return ::util::OkStatus(); }

::util::Status Bmv2Switch::Unfreeze() { return ::util::OkStatus(); }

::util::Status Bmv2Switch::WriteForwardingEntries(
    const ::p4::v1::WriteRequest& req, std::vector<::util::Status>* results) {
  if (!req.updates_size()) return ::util::OkStatus();  // nothing to do.
  RET_CHECK(req.device_id()) << "No device_id in WriteRequest.";
  RET_CHECK(results != nullptr)
      << "Need to provide non-null results pointer for non-empty updates.";

  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(req.device_id()));
  return pi_node->WriteForwardingEntries(req, results);
}

::util::Status Bmv2Switch::ReadForwardingEntries(
    const ::p4::v1::ReadRequest& req,
    WriterInterface<::p4::v1::ReadResponse>* writer,
    std::vector<::util::Status>* details) {
  RET_CHECK(req.device_id()) << "No device_id in ReadRequest.";
  RET_CHECK(writer) << "Channel writer must be non-null.";
  RET_CHECK(details) << "Details pointer must be non-null.";

  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(req.device_id()));
  return pi_node->ReadForwardingEntries(req, writer, details);
}

::util::Status Bmv2Switch::RegisterStreamMessageResponseWriter(
    uint64 node_id,
    std::shared_ptr<WriterInterface<::p4::v1::StreamMessageResponse>> writer) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  return pi_node->RegisterStreamMessageResponseWriter(writer);
}

::util::Status Bmv2Switch::UnregisterStreamMessageResponseWriter(
    uint64 node_id) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  return pi_node->UnregisterStreamMessageResponseWriter();
}

::util::Status Bmv2Switch::HandleStreamMessageRequest(
    uint64 node_id, const ::p4::v1::StreamMessageRequest& request) {
  ASSIGN_OR_RETURN(auto* pi_node, GetPINodeFromNodeId(node_id));
  return pi_node->HandleStreamMessageRequest(request);
}

::util::Status Bmv2Switch::RegisterEventNotifyWriter(
    std::shared_ptr<WriterInterface<GnmiEventPtr>> writer) {
  return bmv2_chassis_manager_->RegisterEventNotifyWriter(writer);
}

::util::Status Bmv2Switch::UnregisterEventNotifyWriter() {
  return bmv2_chassis_manager_->UnregisterEventNotifyWriter();
}

::util::Status Bmv2Switch::RetrieveValue(uint64 /*node_id*/,
                                         const DataRequest& request,
                                         WriterInterface<DataResponse>* writer,
                                         std::vector<::util::Status>* details) {
  absl::ReaderMutexLock l(&chassis_lock);
  for (const auto& req : request.requests()) {
    ::util::StatusOr<DataResponse> resp;
    switch (req.request_case()) {
      case DataRequest::Request::kOperStatus:
      case DataRequest::Request::kAdminStatus:
      case DataRequest::Request::kMacAddress:
      case DataRequest::Request::kPortSpeed:
      case DataRequest::Request::kNegotiatedPortSpeed:
      case DataRequest::Request::kLacpRouterMac:
      case DataRequest::Request::kPortCounters:
      case DataRequest::Request::kHealthIndicator:
      case DataRequest::Request::kForwardingViability:
      case DataRequest::Request::kAutonegStatus:
      case DataRequest::Request::kSdnPortId:
        resp = bmv2_chassis_manager_->GetPortData(req);
        break;
      default:
        resp =
            MAKE_ERROR(ERR_UNIMPLEMENTED)
            << "DataRequest field "
            << req.descriptor()->FindFieldByNumber(req.request_case())->name()
            << " is not supported yet!";
        break;
    }
    if (resp.ok()) {
      // If everything is OK send it to the caller.
      writer->Write(resp.ValueOrDie());
    }
    if (details) details->push_back(resp.status());
  }
  return ::util::OkStatus();
}

::util::Status Bmv2Switch::SetValue(uint64 node_id, const SetRequest& request,
                                    std::vector<::util::Status>* details) {
  VLOG(1) << "Bmv2Switch::SetValue\n";
  LOG(INFO) << "Bmv2Switch::SetValue is not implemented yet, but changes will "
            << "be peformed when ChassisConfig is pushed again.";
  // TODO(antonin)
  return ::util::OkStatus();
}

::util::StatusOr<std::vector<std::string>> Bmv2Switch::VerifyState() {
  return std::vector<std::string>();
}

std::unique_ptr<Bmv2Switch> Bmv2Switch::CreateInstance(
    PhalInterface* phal_interface, Bmv2ChassisManager* bmv2_chassis_manager,
    const std::map<uint64, PINode*>& node_id_to_pi_node) {
  return absl::WrapUnique(
      new Bmv2Switch(phal_interface, bmv2_chassis_manager, node_id_to_pi_node));
}

::util::StatusOr<PINode*> Bmv2Switch::GetPINodeFromNodeId(
    uint64 node_id) const {
  PINode* pi_node = gtl::FindPtrOrNull(node_id_to_pi_node_, node_id);
  if (pi_node == nullptr) {
    return MAKE_ERROR(ERR_ENTRY_NOT_FOUND)
           << "Node with ID " << node_id
           << " is unknown or no config has been pushed to it yet.";
  }
  return pi_node;
}

}  // namespace bmv2
}  // namespace hal
}  // namespace stratum


text:
package com.clark.app;

import com.baidu.javalite.DBConnection;
import com.baidu.javalite.DBHelper;
import com.baidu.javalite.Database;
import com.baidu.javalite.PrepareStmt;
import com.baidu.javalite.SqliteException;
import com.baidu.javalite.Transaction;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by clark on 14-9-22.
 */
public class DBOwner {
    public static void main(String[] args) {
        try {
            doMain(args);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private static void doMain(String[] args) throws ParseException, IOException {
        CommandLineParser parser = new BasicParser();
        Options options = new Options();
        options.addOption("cfg", true, "指定配置文件");
        options.addOption("db", true, "数据库文件名称");
        CommandLine cli = parser.parse(options, args);

        String filePath = cli.getOptionValue("cfg", "crash-owner.txt");
        File cfgFile = new File(filePath);
        if (!cfgFile.isFile()) {
            System.err.println("找不到配置文件 " + cfgFile.getAbsolutePath());
            System.exit(1);
        }

        String dbPath = cli.getOptionValue("db", "a.db");
        File dbFile = new File(dbPath);
        if (!dbFile.isFile()) {
            System.err.println("找不到数据库文件 " + dbFile.getAbsolutePath());
            System.exit(1);
        }

        DBConnection conn = new Database(dbPath).open();
//        conn.setUpdateHook(new MyUpdateHook());

        System.out.println("数据库文件打开成功!");
        try {
            if (!Utils.isTableExist(conn, "owner")) {
                createUserTable(conn);
            }

            FileInputStream cfgInput = new FileInputStream(cfgFile);
            BufferedReader reader = new BufferedReader(new InputStreamReader(cfgInput, "UTF-8"));
            String line;

            Transaction transaction = conn.newTransaction();
            PrepareStmt stmt = conn.prepare("insert or ignore into owner (flag, team, name) values (?, ?, ?);");

            try {
                transaction.begin();
                System.out.println("删除旧数据!");
                conn.exec("delete from owner;");

                System.out.println("开始导入数据!");

                // 输入第一条
                stmt.bindText(1, "系统");
                stmt.bindInt(2, 0);
                stmt.bindText(3, "系统");
                stmt.step();
                stmt.reset();

                // 输入第二条
                stmt.bindText(1, "基线");
                stmt.bindInt(2, 1);
                stmt.bindText(3, "未知");
                stmt.step();
                stmt.reset();

                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.length() == 0) {
                        continue;
                    }

                    final String[] contents = line.split(" ");
                    stmt.bindText(1, contents[0]);
                    stmt.bindInt(2, getTeamId(contents[1]));
                    stmt.bindText(3, contents[2]);

                    stmt.step();
                    stmt.reset();
                }
                transaction.commit();
                System.out.println("数据导入成功!");
            } catch (SqliteException e) {
                transaction.rollback();
                System.err.println("数据库出现错误,回滚!");
                e.printStackTrace();
            } finally {
                DBHelper.closeQuietly(stmt);
                if (cfgInput != null) {
                    cfgInput.close();
                }
            }
        } finally {
            DBHelper.closeQuietly(conn);
        }
    }

    private static int getTeamId(String content) {
        if ("基线".equals(content)) {
            return 1;
        } else if ("组件".equals(content)) {
            return 2;
        } else if ("导航".equals(content)) {
            return 3;
        } else if ("步行导航".equals(content)) {
            return 4;
        } else if ("第三方".equals(content)) {
            return 5;
        }
        return 0;
    }

    private static void createUserTable(DBConnection connection) throws SqliteException {
        System.out.println("没有 owner 数据库表,需要创建!");
        connection.exec("CREATE TABLE owner (" +
                "id INTEGER PRIMARY KEY," +
                "name TEXT," +                      // 名字
                "team INTEGER," +                   // 团队  1:基线;2:组件;3:导航;4:步行导航;5:第三方
                "flag TEXT UNIQUE);");              // 标记
        System.out.println("数据库表 owner 创建完毕!");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.gbaldera.yts.loaders;

import android.content.Context;

import com.gbaldera.yts.enumerations.YtsMovieGenre;
import com.gbaldera.yts.enumerations.YtsMovieOrder;
import com.gbaldera.yts.enumerations.YtsMovieQuality;
import com.gbaldera.yts.enumerations.YtsMovieSort;
import com.gbaldera.yts.helpers.ServicesHelper;
import com.gbaldera.yts.models.YtsMovie;
import com.gbaldera.yts.models.YtsMovieList;
import com.github.underscore._;
import com.jakewharton.trakt.entities.Movie;
import com.jakewharton.trakt.enumerations.Extended2;

import java.util.List;

public class PopularMoviesLoader extends BaseMoviesLoader<List<Movie>> {

    public PopularMoviesLoader(Context context) {
        super(context);
    }

    @Override
    protected List<Movie> getMoviesFromTrakt(List<String> imbIds) {
        return ServicesHelper.getTrakt(getContext())
                .movieService().summaries(_.join(imbIds, ","), Extended2.FULL);
    }

    @Override
    protected List<YtsMovie> getMoviesFromYts() {
        YtsMovieList ytsMovieList = ServicesHelper.getYtsService(getContext()).
                list(30, 1, YtsMovieQuality.ALL, 0, null, YtsMovieGenre.ALL,
                        YtsMovieSort.DOWNLOADED, YtsMovieOrder.DESC);
        return ytsMovieList.MovieList;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <properties>
    <hadoop.version>0.18.3</hadoop.version>
  </properties>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-core</artifactId>
  <name>Hadoop Core (MapReduce) Library ${hadoop.version}</name>
  <packaging>jar</packaging>
  <version>${hadoop.version}</version>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-antrun-plugin</artifactId>
        <executions>
          <execution>
            <id>copyFiles</id>
            <phase>package</phase>
            <configuration>
              <tasks>
                <copy file="hadoop-0.18.3-core.jar"
                      tofile="target/hadoop-core-0.18.3.jar"
                      overwrite="true" verbose="true" failonerror="true"/>
              </tasks>
            </configuration>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
import { Component } from '@angular/core';

import { HomePage } from '../home/home';
import { ClientsPage } from '../clients/clients';
import { SalesPage } from '../sales/sales';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = HomePage;
  tab2Root: any = ClientsPage;
  tab3Root: any = SalesPage;

  constructor() {

  }
}


text:
using Midi.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Midi
{
    /// <summary>
    /// Creates a message from a MIDI data stream.
    /// </summary>
    public class MidiMessageBuilder
    {
        /// <summary>
        /// Attempts to create a MIDI message from the MIDI data available.
        /// </summary>
        /// <param name="data">The raw MIDI data.</param>
        /// <param name="message">The generated MIDI message which you can cast to the required type.</param>
        /// <returns>True if the message type was recognised, otherwise false.</returns>
        public static bool TryBuild(byte[] data, out MidiMessage message)
        {
            message = null;

            switch((MidiCommand) data[0])
            {
                case MidiCommand.SystemExclusiveStart:
                    return TryBuildSystemExclusive(data,1,out message);
            }

            return message != null;
        }

        /// <summary>
        /// Attempts to create a MIDI message from the MIDI data available.
        /// </summary>
        /// <param name="data">The raw MIDI data.</param>
        /// <param name="dataOffset">The data offset.</param>
        /// <param name="message">The generated MIDI message which you can cast to the required type.</param>
        /// <returns>
        /// True if the message type was recognised, otherwise false.
        /// </returns>
        public static bool TryBuildSystemExclusive(byte[] data,int dataOffset, out MidiMessage message)
        {
            message = null;

            switch ((MidiManufacturerId) data[dataOffset])
            {
                case MidiManufacturerId.UniversalRealTime:
                    message = new MidiShowControl.MscMessage();
                    break;
            }

            if(message != null)
                message.ReadData(new MidiBinaryReader(new MemoryStream(data)));

            return message != null;
        }
    }
}


text:
module Graphene
  module Views
    class Base
      include Renderable

      attr_reader :dataset
      attr_reader :axis
      attr_accessor :name

      def initialize
        @axis = :y
        @name = "Dataset"
      end

      def axis=(value)
        raise ArgumentError, "axis must be either :y or :y2" unless [:y, :y2].include?(value)
        @axis = value
      end

      def push_watermark(watermark, type, comparitor)
        watermark
      end

      def preferred_width;  nil; end
      def preferred_height; nil; end
    end
  end
end


text:
package ldif_test

import (
	"bytes"
	"testing"

	"github.com/go-ldap/ldap/v3"
	"github.com/go-ldap/ldif"
)

var personLDIF = `dn: uid=someone,ou=people,dc=example,dc=org
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
uid: someone
cn: Someone
mail: someone@example.org

`

var ouLDIF = `dn: ou=people,dc=example,dc=org
objectClass: top
objectClass: organizationalUnit
ou: people

`

var entries = []*ldap.Entry{
	{
		DN: "ou=people,dc=example,dc=org",
		Attributes: []*ldap.EntryAttribute{
			{
				Name: "objectClass",
				Values: []string{
					"top",
					"organizationalUnit",
				},
			},
			{
				Name:   "ou",
				Values: []string{"people"},
			},
		},
	},
	{
		DN: "uid=someone,ou=people,dc=example,dc=org",
		Attributes: []*ldap.EntryAttribute{
			{
				Name: "objectClass",
				Values: []string{
					"top",
					"person",
					"organizationalPerson",
					"inetOrgPerson",
				},
			},
			{
				Name:   "uid",
				Values: []string{"someone"},
			},
			{
				Name:   "cn",
				Values: []string{"Someone"},
			},
			{
				Name:   "mail",
				Values: []string{"someone@example.org"},
			},
		},
	},
}

func TestMarshalSingleEntry(t *testing.T) {
	l := &ldif.LDIF{
		Entries: []*ldif.Entry{
			{Entry: entries[1]},
		},
	}
	res, err := ldif.Marshal(l)
	if err != nil {
		t.Errorf("Failed to marshal entry: %s", err)
	}
	if res != personLDIF {
		t.Errorf("unexpected result: >>%s<<\n", res)
	}
}

func TestMarshalEntries(t *testing.T) {
	l := &ldif.LDIF{
		Entries: []*ldif.Entry{
			{Entry: entries[0]},
			{Entry: entries[1]},
		},
	}
	res, err := ldif.Marshal(l)
	if err != nil {
		t.Errorf("Failed to marshal entry: %s", err)
	}
	if res != ouLDIF+personLDIF {
		t.Errorf("unexpected result: >>%s<<\n", res)
	}
}

func TestMarshalB64(t *testing.T) {
	entryLDIF := `dn: ou=people,dc=example,dc=org
objectClass: top
objectClass: organizationalUnit
ou: people
description:: VGhlIFBlw7ZwbGUgw5ZyZ2FuaXphdGlvbg==

`
	entry := &ldap.Entry{
		DN: "ou=people,dc=example,dc=org",
		Attributes: []*ldap.EntryAttribute{
			{
				Name: "objectClass",
				Values: []string{
					"top",
					"organizationalUnit",
				},
			},
			{
				Name:   "ou",
				Values: []string{"people"},
			},
			{
				Name:   "description",
				Values: []string{"The Peöple Örganization"},
			},
		},
	}
	l := &ldif.LDIF{
		Entries: []*ldif.Entry{
			{Entry: entry},
		},
	}
	res, err := ldif.Marshal(l)
	if err != nil {
		t.Errorf("Failed to marshal entry: %s", err)
	}
	if res != entryLDIF {
		t.Errorf("unexpected result: >>%s<<\n", res)
	}
}

func TestMarshalMod(t *testing.T) {
	modLDIF := `dn: uid=someone,ou=people,dc=example,dc=org
changetype: modify
replace: sn
sn: One
-
add: givenName
givenName: Some
-
delete: mail
-
delete: telephoneNumber
telephoneNumber: 123 456 789 - 0
-

`
	mod := ldap.NewModifyRequest("uid=someone,ou=people,dc=example,dc=org", []ldap.Control{})
	mod.Replace("sn", []string{"One"})
	mod.Add("givenName", []string{"Some"})
	mod.Delete("mail", []string{})
	mod.Delete("telephoneNumber", []string{"123 456 789 - 0"})
	l := &ldif.LDIF{
		Entries: []*ldif.Entry{
			{Modify: mod},
		},
	}
	res, err := ldif.Marshal(l)
	if err != nil {
		t.Errorf("Failed to marshal entry: %s", err)
	}
	if res != modLDIF {
		t.Errorf("unexpected result: >>%s<<", res)
	}
}

func TestMarshalAdd(t *testing.T) {
	addLDIF := `dn: uid=someone,ou=people,dc=example,dc=org
changetype: add
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
uid: someone
cn: Someone
mail: someone@example.org

`
	add := ldap.NewAddRequest("uid=someone,ou=people,dc=example,dc=org", []ldap.Control{})
	for _, a := range entries[1].Attributes {
		add.Attribute(a.Name, a.Values)
	}
	l := &ldif.LDIF{
		Entries: []*ldif.Entry{
			{Add: add},
		},
	}
	res, err := ldif.Marshal(l)
	if err != nil {
		t.Errorf("Failed to marshal entry: %s", err)
	}
	if res != addLDIF {
		t.Errorf("unexpected result: >>%s<<", res)
	}
}

func TestMarshalDel(t *testing.T) {
	delLDIF := `dn: uid=someone,ou=people,dc=example,dc=org
changetype: delete

`
	del := ldap.NewDelRequest("uid=someone,ou=people,dc=example,dc=org", nil)
	l := &ldif.LDIF{
		Entries: []*ldif.Entry{
			{Del: del},
		},
	}
	res, err := ldif.Marshal(l)
	if err != nil {
		t.Errorf("Failed to marshal entry: %s", err)
	}
	if res != delLDIF {
		t.Errorf("unexpected result: >>%s<<", res)
	}
}

func TestDump(t *testing.T) {
	delLDIF := `dn: uid=someone,ou=people,dc=example,dc=org
changetype: delete

`
	del := ldap.NewDelRequest("uid=someone,ou=people,dc=example,dc=org", nil)
	buf := bytes.NewBuffer(nil)
	err := ldif.Dump(buf, 0, del)
	if err != nil {
		t.Errorf("Failed to dump entry: %s", err)
	}
	res := buf.String()
	if res != delLDIF {
		t.Errorf("unexpected result: >>%s<<", res)
	}
}


text:
<?php

declare(strict_types=1);

namespace App\Entity\Migration;

use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20201109203951 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add unique constraint for analytics.';
    }

    public function preUp(Schema $schema): void
    {
        $analytics = $this->connection->fetchAllAssociative('SELECT id, station_id, type, moment FROM analytics ORDER BY id ASC');
        $rows = [];

        foreach ($analytics as $row) {
            $rowKey = ($row['station_id'] ?? 'all') . '_' . $row['type'] . '_' . $row['moment'];

            if (isset($rows[$rowKey])) {
                $this->connection->delete('analytics', [
                    'id' => $row['id'],
                ], [
                    'id' => ParameterType::INTEGER,
                ]);
            } else {
                $rows[$rowKey] = $row['id'];
            }
        }
    }

    public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->addSql('CREATE UNIQUE INDEX stats_unique_idx ON analytics (station_id, type, moment)');
    }

    public function down(Schema $schema): void
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->addSql('DROP INDEX stats_unique_idx ON analytics');
    }
}


text:
class Friendsrequest < ApplicationRecord
  belongs_to :user
  belongs_to :friend, class_name: "User"

  def accept_request
      Friendship.create(user_id: recipient_id, friend_id: sender_id)
      Friendrequest.find(id).update_attributes(status: 1)
  end
end


text:
{% load sitetracker %}

            {% for site in fleet.sites.all %}

                {% if user in site and site in pending_sites %}

                {% elif user in site %}

                {% else %}

                {% endif %}
                 {{site.timestamp|date:"H:i"}} {{site.site_type.shortname}}

            {% empty %}
            No sites yet!
            {% endfor %}


text:
namespace_ens_begin
void CGLProgramWithUnifos::passUnifoValue1f(string unifoName,GLfloat v){
    glUniform1f(m_unifoMap[unifoName],v);
}
void CGLProgramWithUnifos::passUnifoValue1i(string unifoName,GLint v){
    glUniform1i(m_unifoMap[unifoName],v);
}
void CGLProgramWithUnifos::passUnifoValueMatrixNfv(string unifoName,const GLfloat *array,int arrayLen){
    assert(arrayLen==4||arrayLen==9||arrayLen==16);
    switch (arrayLen) {
        case 4:
        glUniformMatrix2fv(m_unifoMap[unifoName],1,GL_FALSE,array);
        break;
        case 9:
        glUniformMatrix3fv(m_unifoMap[unifoName],1,GL_FALSE,array);
        break;
        case 16:
        glUniformMatrix4fv(m_unifoMap[unifoName],1,GL_FALSE,array);
        break;
        default:
        assert(false);
        break;
    }

}
void CGLProgramWithUnifos::passUnifoValueNfv(string unifoName,const GLfloat*array,int arrayLen){
    assert(arrayLen>=1&&arrayLen<=4);
    switch (arrayLen) {
        case 1:
        glUniform1fv(m_unifoMap[unifoName],1,array);
        break;
        case 2:
        glUniform2fv(m_unifoMap[unifoName],1,array);
        break;
        case 3:
        glUniform3fv(m_unifoMap[unifoName],1,array);
        break;
        case 4:
        glUniform4fv(m_unifoMap[unifoName],1,array);
        break;
        default:
        assert(false);
        break;
    }

}
void CGLProgramWithUnifos::passUnifoValueNfvN(string unifoName,const GLfloat*array,int arrayLen,int arrayCount){
    assert(arrayLen>=1&&arrayLen<=4);
    switch (arrayLen) {
        case 1:
            glUniform1fv(m_unifoMap[unifoName],arrayCount,array);
            break;
        case 2:
            glUniform2fv(m_unifoMap[unifoName],arrayCount,array);
            break;
        case 3:
            glUniform3fv(m_unifoMap[unifoName],arrayCount,array);
            break;
        case 4:
            glUniform4fv(m_unifoMap[unifoName],arrayCount,array);
            break;
        default:
            assert(false);
            break;
    }

}
void CGLProgramWithUnifos::passUnifoValueNiv(string unifoName,const GLint*array,int arrayLen){
    assert(arrayLen>=1&&arrayLen<=4);
    switch (arrayLen) {
        case 1:
        glUniform1iv(m_unifoMap[unifoName],1,array);
        break;
        case 2:
        glUniform2iv(m_unifoMap[unifoName],1,array);
        break;
        case 3:
        glUniform3iv(m_unifoMap[unifoName],1,array);
        break;
        case 4:
        glUniform4iv(m_unifoMap[unifoName],1,array);
        break;
        default:
        assert(false);
        break;
    }

}
void CGLProgramWithUnifos::passUnifoValueMatrixNfv(string unifoName,const vector<GLfloat>&valueList){
    passUnifoValueMatrixNfv(unifoName, &valueList.front(), (int)valueList.size());
}
void CGLProgramWithUnifos::passUnifoValueNfv(string unifoName,const vector<GLfloat>&valueList){
    passUnifoValueNfv(unifoName, &valueList.front(), (int)valueList.size());
}
void CGLProgramWithUnifos::passUnifoValueNiv(string unifoName,const vector<GLint>&valueList){
    passUnifoValueNiv(unifoName, &valueList.front(), (int)valueList.size());
}
namespace_ens_end


text:
from __future__ import annotations
from .typecheck import *

from .import core

import os
import hashlib

VERSION_NUMBER = 0

def file_name_for_project_name(project_name: str):
	hash = hashlib.sha224(project_name.encode('utf-8')).hexdigest()
	file_name = os.path.join(core.current_package(), "data/{}.json".format(hash))
	return file_name

def load(project_name: str) -> Any:
	file_name = file_name_for_project_name(project_name)
	try:
		with open(file_name, 'r') as file:
			contents = file.read() or "{}"

		json = core.json_decode(contents)
		if json.get("_version") == VERSION_NUMBER:
			return json

	except FileNotFoundError:
		pass
	return {}

def save(project_name: str, data: Any):
	file_name = file_name_for_project_name(project_name)
	with open(file_name, 'w') as file:
		data['_version'] = VERSION_NUMBER
		data['_project_name'] = project_name
		file.write(core.json_encode(data, pretty=True))


text:
package de.hpi.bpmn2_0.model.connector;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import de.hpi.bpmn2_0.model.FlowElement;
import de.hpi.bpmn2_0.transformation.Visitor;
import de.hpi.diagram.SignavioUUID;

/**
 *
Java class for tDataInputAssociation complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="tDataInputAssociation">
 *   <complexContent>
 *     <extension base="{http://www.omg.org/bpmn20}tDataAssociation">
 *       <sequence>
 *         <element name="sourceRef" type="{http://www.w3.org/2001/XMLSchema}IDREF" maxOccurs="unbounded"/>
 *         <element name="targetRef" type="{http://www.w3.org/2001/XMLSchema}IDREF"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tDataInputAssociation")
public class DataInputAssociation
    extends DataAssociation
{

	/**
	 * Default constructor
	 */
	public DataInputAssociation() {
		super();
	}

	/**
	 * Constructor creates an data input association base on a data association.
	 * @param dataAssociation
	 */
	public DataInputAssociation(DataAssociation dataAssociation) {
		this.id = SignavioUUID.generate();
		this.assignment = dataAssociation.getAssignment();
		this.documentation = dataAssociation.getDocumentation();
		this.transformation = dataAssociation.getTransformation();
		this.process = dataAssociation.getProcess();
	}

	public void acceptVisitor(Visitor v){
		v.visitDataInputAssociation(this);
	}

	public FlowElement getTargetRef() {
		if(parent != null) {
			return parent;
		}

		return super.getTargetRef();
	}
}


text:
<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
    <channel>
        <title>Git - Category - Welcome to Thai's Home</title>
        <link>https://hpthai7.github.io/categories/git/</link>
        <description>Git - Category - Welcome to Thai's Home</description>
        <generator>Hugo -- gohugo.io</generator><language>en</language><managingEditor>th3ho@yahoo.com (Thai Ho)</managingEditor>
            <webMaster>th3ho@yahoo.com (Thai Ho)</webMaster><copyright>This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.</copyright><lastBuildDate>Fri, 01 May 2020 00:00:00 +0000</lastBuildDate><atom:link href="https://hpthai7.github.io/categories/git/" rel="self" type="application/rss+xml" /><item>
    <title>Git Cheat Sheets</title>
    <link>https://hpthai7.github.io/git-cheat-sheet/</link>
    <pubDate>Fri, 01 May 2020 00:00:00 +0000</pubDate>
    <author>Author</author>
    <guid>https://hpthai7.github.io/git-cheat-sheet/</guid>
    <description><![CDATA[GitLab Gitlab CI-CD Reference Pay attention that the correct file for gitlab ci-cd pipeline .gitlab-ci.yml ends with .yml, not .yaml.
Choose which executor for gitlab runner Increase concurrent jobs Jobs are executed by Runners. Multiple jobs in the same stage are executed in parallel, if there are enough concurrent runners.
The limit of concurrent jobs are tunable in config.toml.
Job image vs docker executor In the definition of jobs, the image keyword is the name of the Docker image the Docker executor will run to perform the CI tasks.]]></description>
</item></channel>
</rss>


text:
@interface HotbrevListViewController : UITableViewController

@property (nonatomic, retain) NSMutableArray *hotdrinks;

@property (nonatomic, strong) NSString *str6;

@end


text:
package org.axonframework.queryhandling;

import org.axonframework.messaging.responsetypes.ResponseType;

import java.util.Map;
import javax.annotation.Nonnull;

/**
 * Message type that carries a Subscription Query: a request for information. Besides a payload, Subscription Query
 * Messages also carry the expected response type and update type. The response type is the type of result expected by
 * the caller. The update type is type of incremental updates.
 * <p>
 * Handlers should only answer a query if they can respond with the appropriate response type and update type.
 *
 * @param <Q> the type of payload
 * @param <I> the type of initial response
 * @param <U> the type of incremental responses
 * @author Allard Buijze
 * @since 3.3
 */
public interface SubscriptionQueryMessage<Q, I, U> extends QueryMessage<Q, I> {

    /**
     * Returns the type of incremental responses.
     *
     * @return the type of incremental responses
     */
    ResponseType<U> getUpdateResponseType();

    /**
     * Returns a copy of this SubscriptionQueryMessage with the given {@code metaData}. The payload remains unchanged.
     *
     * @param metaData The new MetaData for the SubscriptionQueryMessage
     * @return a copy of this message with the given MetaData
     */
    @Override
    SubscriptionQueryMessage<Q, I, U> withMetaData(@Nonnull Map<String, ?> metaData);

    /**
     * Returns a copy of this SubscriptionQueryMessage with its MetaData merged with given {@code metaData}. The payload
     * remains unchanged.
     *
     * @param additionalMetaData The MetaData to merge into the SubscriptionQueryMessage
     * @return a copy of this message with the given additional MetaData
     */
    @Override
    SubscriptionQueryMessage<Q, I, U> andMetaData(@Nonnull Map<String, ?> additionalMetaData);
}


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 org.apache.karaf.subsystem.commands;

import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.osgi.service.subsystem.Subsystem;

@Command(scope = "subsystem", name = "start", description = "Start the specified subsystems")
@Service
public class StartAction extends SubsystemSupport implements Action {

    @Argument(description = "Subsystem names or ids")
    @Completion(SubsystemCompleter.class)
    String id;

    @Override
    public Object execute() throws Exception {
        for (Subsystem ss : getSubsystems(id)) {
            ss.start();
        }
        return null;
    }

}


text:
typedef enum _DataSource
{
    SOURCE_FTDI,
    SOURCE_FILE,
} DataSource;

typedef struct _Options
{
    long baudRate;
    char rawFilename[255];
    char textFilename[255];
    char sourceFilename[255];
    DataSource dataSource;
} Options;

Options options =
{
    38400,
    "out.bin",
    "out.txt",
    "",
    SOURCE_FTDI
};
FILE* source;
FT_HANDLE ft_handle;

BOOL WINAPI exitHandler(DWORD signal);

bool FtdiInit(unsigned long baudRate);
bool SourceFileOpen( char* sourceFilename);

bool DataSourceInit(Options* options);
bool DataSourceGetNext(uint8_t* data, Options* options);
void DataSourceExit(Options* options);

int main(int argc, char** argv)
{

    int option_index = 0;

    while (( option_index = getopt(argc, argv, "u:g")) != -1){

    switch (option_index)
    {
        case 'b':
            options.baudRate = atol(optarg);
            break;
        case 'r':
            strncpy(options.rawFilename, optarg, 255);
            break;
        case 't':
            strncpy(options.textFilename, optarg, 255);
            break;
        case 's':
            strncpy(options.sourceFilename, optarg, 255);
            options.dataSource = SOURCE_FILE;
            break;
        default:
            fprintf(stderr, "Invalid option '%c'\n", option_index);
            return 1;
        } //end block for switch
    }  //end block for while

    if (!SetConsoleCtrlHandler(exitHandler, TRUE)) {
        fprintf(stderr, "\nERROR: Could not set exit handler");
        return 1;
    }

    if (!ConsoleExpansion_Init(options.rawFilename, options.textFilename, "XT2PS2 Console Host"))
    {
        return 1;
    }

    bool initSuccess = DataSourceInit(&options);

    if (!initSuccess)
    {
        return 1;
    }

    ConsoleExpansion_RegisterExpander(CON_SRC_TEST, testConsoleHandler, testSourceText);
    ConsoleExpansion_RegisterExpander(CON_SRC_XTH_XCVR, xthXcvrConsoleHandler, xthXcvrSourceText);
    ConsoleExpansion_RegisterExpander(CON_SRC_XTH_KBD, xthKbdConsoleHandler, xthKbdSourceText);
    ConsoleExpansion_RegisterExpander(CON_SRC_PS2D_KBD, ps2dKbdConsoleHandler, ps2dKbdSourceText);
    ConsoleExpansion_RegisterExpander(CON_SRC_PS2D_XCVR, ps2dXcvrConsoleHandler, ps2dXcvrSourceText);
    ConsoleExpansion_RegisterExpander(CON_SRC_XT2PS2, xt2Ps2ConsoleHandler, xt2Ps2SourceText);
    ConsoleExpansion_RegisterExpander(CON_SRC_KEYMAP, keymapConsoleHandler, keymapSourceText);

    while (1)
    {
        uint8_t data;
        if (DataSourceGetNext(&data, &options))
        {
            ConsoleExpansion_ProcessData(data);
        }

    }

    ConsoleExpansion_Exit();

    return 0;
}

bool FtdiInit(unsigned long baudRate)
{
    LONG comPortNumber;
    FT_STATUS ft_status;

    ft_status = FT_Open(0,&ft_handle);

    if (ft_status != FT_OK)
    {
        fprintf(stderr, "No FTDI serial port detected");
        return false;
    }

    ft_status = FT_GetComPortNumber(ft_handle, &comPortNumber);

    FT_SetBaudRate(ft_handle, baudRate);

    FT_SetDataCharacteristics(ft_handle,       // Handle of the chip(FT232)
                              FT_BITS_8,       // No of Data bits = 8
                              FT_STOP_BITS_1,  // No of Stop Bits = 1
                              FT_PARITY_NONE   // Parity = NONE
                              );

    FT_SetFlowControl(ft_handle, FT_FLOW_NONE, 0, 0);

    FT_Purge(ft_handle, FT_PURGE_RX | FT_PURGE_TX);

    printf("Connected to FTDI serial converter on COM%ld\n", comPortNumber);
    printf("Ready..\n");
    printf("\n");

    return true;
}

bool SourceFileOpen( char* sourceFilename)
{
    source = fopen(sourceFilename, "r");
    if (source == NULL)
    {
        fprintf(stderr, "Unable to open file to read source data: %s", sourceFilename);
        return false;
    }

    return true;
}

bool FtdiRead(uint8_t* data)
{
    DWORD bytesToRead;
    unsigned char byteRead;
    DWORD bytesRead;

    FT_STATUS ft_status;

    ft_status = FT_GetQueueStatus(ft_handle, &bytesToRead);
    if (ft_status == FT_OK && bytesToRead > 0)
    {
        ft_status = FT_Read(ft_handle, &byteRead, 1, &bytesRead );
        if (ft_status != FT_OK)
        {
            fprintf(stderr, "Failure reading from FTDI");
            return false;
        }
        else
        {
            *data = byteRead;
        }
    }
    else
    {
        return false;
    }

    return true;
}

bool SourceFileRead(uint8_t* data)
{
    size_t bytesRead;

    bytesRead = fread(&data, 1, 1, source);

    if (bytesRead < 1)
    {
        fprintf(stderr, "Failure reading from source file");
        return false;
    }

    return data;
}

bool DataSourceInit(Options* options)
{
    bool result = false;

    switch (options->dataSource)
    {
        case SOURCE_FTDI:
            result = FtdiInit(options->baudRate);
            break;
        case SOURCE_FILE:
            result = SourceFileOpen(options->sourceFilename);
            break;
    }
    return result;
}

bool DataSourceGetNext(uint8_t* data, Options* options)
{
    bool result;
    switch (options->dataSource)
    {
        case SOURCE_FTDI:
            result = FtdiRead(data);
            break;
        case SOURCE_FILE:
            result = SourceFileRead(data);
            break;
    }

    return result;
}

void DataSourceExit(Options* options)
{
    switch (options->dataSource)
    {
        case SOURCE_FTDI:
            FT_Close(ft_handle);
            break;
        case SOURCE_FILE:
            fclose(source);
            break;
    }

}

BOOL WINAPI exitHandler(DWORD signal)
{
    ConsoleExpansion_Exit();
    DataSourceExit(&options);

    printf("\n");
    printf("Exiting...\n");

    return FALSE;
}


text:
/* -*- c++ -*- (enables emacs c++ mode) */
/*===========================================================================

 Copyright (C) 2002-2012 Yves Renard

 This file is a part of GETFEM++

 Getfem++  is  free software;  you  can  redistribute  it  and/or modify it
 under  the  terms  of the  GNU  Lesser General Public License as published
 by  the  Free Software Foundation;  either version 3 of the License,  or
 (at your option) any later version along with the GCC Runtime Library
 Exception either version 3.1 or (at your option) any later version.
 This program  is  distributed  in  the  hope  that it will be useful,  but
 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 or  FITNESS  FOR  A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 License and GCC Runtime Library Exception for more details.
 You  should  have received a copy of the GNU Lesser General Public License
 along  with  this program;  if not, write to the Free Software Foundation,
 Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA.

 As a special exception, you  may use  this file  as it is a part of a free
 software  library  without  restriction.  Specifically,  if   other  files
 instantiate  templates  or  use macros or inline functions from this file,
 or  you compile this  file  and  link  it  with other files  to produce an
 executable, this file  does  not  by itself cause the resulting executable
 to be covered  by the GNU Lesser General Public License.  This   exception
 does not  however  invalidate  any  other  reasons why the executable file
 might be covered by the GNU Lesser General Public License.

===========================================================================*/

/**@file gmm_solver_constrained_cg.h
   @author  Yves Renard <Yves.Renard@insa-lyon.fr>
   @date October 13, 2002.
   @brief Constrained conjugate gradient. */
//  preconditionning does not work

#ifndef GMM_SOLVER_CCG_H__
#define GMM_SOLVER_CCG_H__

#include "gmm_kernel.h"
#include "gmm_iter.h"

namespace gmm {

  template <typename CMatrix, typename CINVMatrix, typename Matps,
	    typename VectorX>
  void pseudo_inverse(const CMatrix &C, CINVMatrix &CINV,
		      const Matps& /* PS */, VectorX&) {
    // compute the pseudo inverse of the non-square matrix C such
    // CINV = inv(C * trans(C)) * C.
    // based on a conjugate gradient method.

    // optimisable : copie de la ligne, precalcul de C * trans(C).

    typedef VectorX TmpVec;
    typedef typename linalg_traits<VectorX>::value_type value_type;

    size_type nr = mat_nrows(C), nc = mat_ncols(C);

    TmpVec d(nr), e(nr), l(nc), p(nr), q(nr), r(nr);
    value_type rho, rho_1, alpha;
    clear(d);
    clear(CINV);

    for (size_type i = 0; i < nr; ++i) {
      d[i] = 1.0; rho = 1.0;
      clear(e);
      copy(d, r);
      copy(d, p);

      while (rho >= 1E-38) { /* conjugate gradient to compute e             */
	                     /* which is the i nd row of inv(C * trans(C))  */
	mult(gmm::transposed(C), p, l);
	mult(C, l, q);
	alpha = rho / vect_sp(p, q);
	add(scaled(p, alpha), e);
	add(scaled(q, -alpha), r);
	rho_1 = rho;
	rho = vect_sp(r, r);
	add(r, scaled(p, rho / rho_1), p);
      }

      mult(transposed(C), e, l); /* l is the i nd row of CINV     */
      // cout << "l = " << l << endl;
      clean(l, 1E-15);
      copy(l, mat_row(CINV, i));

      d[i] = 0.0;
    }
  }

  /** Compute the minimum of @f$ 1/2((Ax).x) - bx @f$ under the contraint @f$ Cx <= f @f$ */
  template < typename Matrix,  typename CMatrix, typename Matps,
	     typename VectorX, typename VectorB, typename VectorF,
	     typename Preconditioner >
  void constrained_cg(const Matrix& A, const CMatrix& C, VectorX& x,
		      const VectorB& b, const VectorF& f,const Matps& PS,
		      const Preconditioner& M, iteration &iter) {
    typedef typename temporary_dense_vector<VectorX>::vector_type TmpVec;
    typedef typename temporary_vector<CMatrix>::vector_type TmpCVec;
    typedef row_matrix<TmpCVec> TmpCmat;

    typedef typename linalg_traits<VectorX>::value_type value_type;
    value_type rho = 1.0, rho_1, lambda, gamma;
    TmpVec p(vect_size(x)), q(vect_size(x)), q2(vect_size(x)),
      r(vect_size(x)), old_z(vect_size(x)), z(vect_size(x)),
      memox(vect_size(x));
    std::vector<bool> satured(mat_nrows(C));
    clear(p);
    iter.set_rhsnorm(sqrt(vect_sp(PS, b, b)));
    if (iter.get_rhsnorm() == 0.0) iter.set_rhsnorm(1.0);

    TmpCmat CINV(mat_nrows(C), mat_ncols(C));
    pseudo_inverse(C, CINV, PS, x);

    while(true) {
      // computation of residu
      copy(z, old_z);
      copy(x, memox);
      mult(A, scaled(x, -1.0), b, r);
      mult(M, r, z); // preconditionner not coherent
      bool transition = false;
      for (size_type i = 0; i < mat_nrows(C); ++i) {
	value_type al = vect_sp(mat_row(C, i), x) - f[i];
	if (al >= -1.0E-15) {
	  if (!satured[i]) { satured[i] = true; transition = true; }
	  value_type bb = vect_sp(mat_row(CINV, i), z);
	  if (bb > 0.0) add(scaled(mat_row(C, i), -bb), z);
	}
	else
	  satured[i] = false;
      }

      // descent direction
      rho_1 = rho; rho = vect_sp(PS, r, z); // ...

      if (iter.finished(rho)) break;

      if (iter.get_noisy() > 0 && transition) std::cout << "transition\n";
      if (transition || iter.first()) gamma = 0.0;
      else gamma = std::max(0.0, (rho - vect_sp(PS, old_z, z) ) / rho_1);
      // std::cout << "gamma = " << gamma << endl;
      // itl::add(r, itl::scaled(p, gamma), p);
      add(z, scaled(p, gamma), p); // ...

      ++iter;
      // one dimensionnal optimization
      mult(A, p, q);
      lambda = rho / vect_sp(PS, q, p);
      for (size_type i = 0; i < mat_nrows(C); ++i)
	if (!satured[i]) {
	  value_type bb = vect_sp(mat_row(C, i), p) - f[i];
	  if (bb > 0.0)
	    lambda = std::min(lambda, (f[i]-vect_sp(mat_row(C, i), x)) / bb);
	}
      add(x, scaled(p, lambda), x);
      add(memox, scaled(x, -1.0), memox);

    }
  }

}

#endif //  GMM_SOLVER_CCG_H__


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Controller users, module users

class Users extends MX_Controller {

	function __construct()
	{

		parent::__construct();
        $this->load->model('users_model');
		//$this->load->model("user_model");
        $this->load->library('form_validation');

		$this->load->helper("general");

	}

	public function login()
	{
		$this->index();
	}

	public function user_list()
	{

		$users = $this->users_model->get_all();

        $data = array(
            'users_data' => $users
        );

		$data["title"]	  	  = "User - User list";
		$data["header_title"] = "User";
		$data["content"]	  = "users/users_list";
		$data["template"] 	  = "users/template";

		$this->load->view("index",$data);

	}

	public function index()
	{

		$data["title"] = "Login";

		$this->load->view("login",$data);

	}

	public function register()
	{
		$data["title"] = "Register";
		$this->load->view("register",$data);
	}

	function load_jabatan()
	{
		$is_ajax = $this->input->is_ajax_request();
		if(!$is_ajax)
		{
			show_404();
			exit;
		}

		$this->load->model("master/json_ajax");

		$role = $this->input->post("role");

		if($role == "division")
		{
			$this->json_ajax->select_division();
		}
		else
		{
			$this->json_ajax->select_department();
		}

	}

	public function read($id)
    {
        $row = $this->users_model->detail_users_row($id);

        if ($row) {

            $data = array(
				'id' => $row["id"],
				'name' => $row["name"],
				'email' => $row["email"],
				'role' => $row["role"],
				'kode' => $row["kode"],
				'photo' => $row["photo"],
				'password' => $row["password"],
				'created_at' => $row["created_at"],
				'updated_at' => $row["updated_at"],
			);

			$data["title"] 		  = "User Detail";
			$data["header_title"] = "User Detail";
			$data["template"] 	  = "users/template";
			$data["content"] 	  = "users/users_read";

            $this->load->view('index', $data);

        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('users'));
        }
	}

    public function create_action()
    {
		$name  = $this->input->post('name',TRUE);
		$email = $this->input->post('email',TRUE);
		$role = $this->input->post('role',TRUE);
		$password = $this->input->post('password',TRUE);
		$agreement = $this->input->post("agreement",TRUE);

		$a = explode("@",$email);
		$username = $a[0];

		if($role == "department")
		{
			$kode = $this->input->post("department",TRUE);
			$this->form_validation->set_rules("department","Department","required");
		}
		else
		{
			$kode = $this->input->post("division",TRUE);
			$this->form_validation->set_rules("division","Division","required");
		}

		$photo =  $_FILES["photo"];

        $this->_rules();

		//check_email
		$check_email = $this->users_model->check_email($email);

        if ($this->form_validation->run() == FALSE || !empty($check_email) || $agreement == FALSE) {

			$email_err = "";
			if(!empty($check_email))
			{
				$email_err .= "
 Email has been used
";
			}
			if($agreement == FALSE)
			{
				$email_err .= "
 You must accept the agreement
";
			}

			$error = notif_error(validation_errors().$email_err);
			$this->session->set_flashdata('message',$error);
			redirect(site_url("users/register"));

        } else {

			$new_name = "";
			if(!empty($_FILES))
			{
				$pathinfo = pathinfo($photo["name"]);
				$new_name = $username.".".$pathinfo["extension"];

				if(move_uploaded_file($photo["tmp_name"],"resources/upload/$new_name"))
				{
					echo "success upload";
				}
			}

            $data = array(
				'name' => $name,
				'email' => $email,
				'role' => $role,
				'kode' => $kode,
				'photo' => $new_name,
				'password' =>  password_hash($password,PASSWORD_BCRYPT),
				'created_at' => date("Y-m-d H:i:s"),
				//'updated_at' => date("d-m-Y H:i:s"),
			);

            $this->users_model->insert($data);
            $this->session->set_flashdata('message', notif_success('Create Record Success'));
            redirect(site_url('users/login'));
        }
    }

    public function update($id)
    {
        $row = $this->users_model->detail_users_row($id);

        if ($row) {
            $data = array(

					'button' => 'Update',
					'action' => site_url('users/update_action'),
					'id' 	 => set_value('id', $row["id"]),
					'name'   => set_value('name', $row["name"]),
					'email'  => set_value('email', $row["email"]),
					'role'   => set_value('role', $row["role"]),
					'kode'   => set_value('kode', $row["kode"]),
					'photo'  => set_value('photo', $row["photo"]),

			);

			$data["title"] 		  = "User Detail";
			$data["header_title"] = "User Detail";
			$data["template"] 	  = "users/template";
			$data["content"] 	  = "users/users_form";

            $this->load->view('index', $data);
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('users'));
        }
    }

    public function update_action()
    {
					$name  = $this->input->post('name',TRUE);
					$email = $this->input->post('email',TRUE);
					$role  = $this->input->post('role',TRUE);
					$username = $this->session->userdata("username");
					$password = $this->input->post("password",TRUE);
					$new_pass = $this->input->post("new_pass",TRUE);
					$repeat_pass = $this->input->post("repeat_pass",TRUE);
					$id = $this->input->post("id",TRUE);

					if($role == "department")
					{
						$kode = $this->input->post("department",TRUE);
					}
					else
					{
						$kode = $this->input->post("division",TRUE);
					}

					$password =  $this->input->post("password",TRUE);
					$photo = $_FILES["photo"];

					$this->form_validation->set_error_delimiters('
', '
');

					$this->form_validation->set_rules('name', 'name', 'trim|required');
					$this->form_validation->set_rules('email', 'email', 'trim|required');
					//$this->form_validation->set_rules('role', 'role', 'trim|required');

					$update_password = "no";
					$check_pass = $this->users_model->check_password($username,$password);
					if(!empty($password) && !empty($check_pass))
					{
						$update_password = "yes";
						$this->form_validation->set_rules("new_pass","New Password","required|matches[repeat_pass]");

					}

			        //$this->_rules();
					//check_email
					$check_email = $this->users_model->check_email($email);
					$check_email2 = $this->users_model->check_email2($email,$check_email["email"]);

					if ($this->form_validation->run() == FALSE || !empty($check_email2)) {

						$email_err = "";
						if(!empty($check_email))
						{
							$email_err = "
 Email has been used
";
						}

						$error_text = validation_errors()." ".$email_err;

						$result["status"] = "error";
						$result["message"] = notif_error($error_text);
			            // $this->update($this->input->post('id', TRUE));

			        } else {

						$photo = $_FILES["photo"];
						if(!empty($photo))
						{
							$update_photo = "yes";
							$pathinfo = pathinfo($photo["name"]);
							$new_name = $username.".".$pathinfo["extension"];

							if(move_uploaded_file($photo["tmp_name"],"resources/upload/$new_name"))
							{
								echo "success upload";
							}
						}
						else
						{
							$update_photo = "no";
							$photo["name"] = "";
						}

						$data = array(
						  	  'name' => $name,
							  'email' => $email
							  //'role' => $role,
							  //'kode' => $kode
						);

						if($update_photo == "yes")
						{
							$this->users_model->update_photo( $username,$photo["name"]);
						}

						if($update_password == "yes")
						{
							$this->users_model->update_password($username,$new_pass);
						}

			            $this->users_model->update($this->input->post('id', TRUE), $data);

			            $result["status"] = "success";
						$result["message"] = notif_success("You successfully updated this user");
			        }

					//echo json_encode($result);
					 $this->session->set_flashdata('message', $result["message"]);
					 redirect(site_url("users/update/$id"));
    }

    public function delete($id)
    {
        $row = $this->Users_model->get_by_id($id);

        if ($row) {
            $this->Users_model->delete($id);
            $this->session->set_flashdata('message', 'Delete Record Success');
            redirect(site_url('users'));
        } else {
            $this->session->set_flashdata('message', 'Record Not Found');
            redirect(site_url('users'));
        }
    }

    public function _rules()
    {
		$this->form_validation->set_error_delimiters('
', '
');

		$this->form_validation->set_rules('name', 'name', 'trim|required');
		$this->form_validation->set_rules('email', 'email', 'trim|required');
		$this->form_validation->set_rules('role', 'role', 'trim|required');
		//$this->form_validation->set_rules('kode', 'kode', 'trim|required');
		//$this->form_validation->set_rules('photo', 'photo', 'trim|required');
		$this->form_validation->set_rules('password', 'password', 'trim|required');
		//$this->form_validation->set_rules('created_at', 'created at', 'trim|required');
		//$this->form_validation->set_rules('updated_at', 'updated at', 'trim|required');
		$this->form_validation->set_value("agreement","Agreement","required");

		$this->form_validation->set_rules('id', 'id', 'trim');
		$this->form_validation->set_error_delimiters('', '');
    }

	function __destruct()
	{

	}
}

/* End of file users.php */
/* Location: ./application/modules/users/controllers/users.php */


text:
/*
 * Authors: Thomas Hellström <thomas-at-tungstengraphics-dot-com>
 */

#include <linux/export.h>
#include "drmP.h"

#if defined(CONFIG_X86)
static void
drm_clflush_page(struct page *page)
{
	uint8_t *page_virtual;
	unsigned int i;

	if (unlikely(page == NULL))
		return;

	page_virtual = kmap_atomic(page, KM_USER0);
	for (i = 0; i < PAGE_SIZE; i += boot_cpu_data.x86_clflush_size)
		clflush(page_virtual + i);
	kunmap_atomic(page_virtual, KM_USER0);
}

static void drm_cache_flush_clflush(struct page *pages[],
				    unsigned long num_pages)
{
	unsigned long i;

	mb();
	for (i = 0; i < num_pages; i++)
		drm_clflush_page(*pages++);
	mb();
}

static void
drm_clflush_ipi_handler(void *null)
{
	wbinvd();
}
#endif

void
drm_clflush_pages(struct page *pages[], unsigned long num_pages)
{

#if defined(CONFIG_X86)
	if (cpu_has_clflush) {
		drm_cache_flush_clflush(pages, num_pages);
		return;
	}

	if (on_each_cpu(drm_clflush_ipi_handler, NULL, 1) != 0)
		printk(KERN_ERR "Timed out waiting for cache flush.\n");

#elif defined(__powerpc__)
	unsigned long i;
	for (i = 0; i < num_pages; i++) {
		struct page *page = pages[i];
		void *page_virtual;

		if (unlikely(page == NULL))
			continue;

		page_virtual = kmap_atomic(page, KM_USER0);
		flush_dcache_range((unsigned long)page_virtual,
				   (unsigned long)page_virtual + PAGE_SIZE);
		kunmap_atomic(page_virtual, KM_USER0);
	}
#else
	printk(KERN_ERR "Architecture has no drm_cache.c support\n");
	WARN_ON_ONCE(1);
#endif
}
EXPORT_SYMBOL(drm_clflush_pages);


text:
package org.diirt.graphene;

import java.awt.Color;
import org.diirt.util.stats.Ranges;
import org.junit.Test;

/**
 *
 * @author carcassi
 */
public class GraphAreaDataTest {

    @Test
    public void linearGraphRange() throws Exception {
        GraphBuffer graphBuffer = new GraphBuffer(300, 200);
        GraphAreaData data = new GraphAreaData();
        data.setGraphArea(5, 194, 294, 5);
        data.setGraphPadding(0, 0, 0, 0);
        data.setGraphBuffer(graphBuffer);
        data.setLabelMargin(5, 5);
        data.setRanges(Ranges.range(-5, 5), ValueScales.linearScale(), Ranges.range(-10, 10), ValueScales.linearScale());
        graphBuffer.drawBackground(Color.WHITE);
        data.prepareLabels(FontUtil.getLiberationSansRegular(), Color.BLACK);
        data.prepareGraphArea(true, Color.GRAY);
        data.drawGraphArea();

        ImageAssert.compareImages("graphAreaData.linearGraphRange", graphBuffer.getImage());
    }
}


text:
// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "concurrency/fifo_enforcer.hpp"

#include "errors.hpp"
#include <boost/variant.hpp>

#include "arch/timing.hpp"
#include "concurrency/auto_drainer.hpp"
#include "concurrency/fifo_enforcer_queue.hpp"
#include "concurrency/wait_any.hpp"
#include "unittest/unittest_utils.hpp"
#include "unittest/gtest.hpp"

namespace unittest {

class test_shared_variable_t {
public:
    explicit test_shared_variable_t(int initial) : variable(initial) { }
    void spawn_read(int expected_value) {
        coro_t::spawn_sometime(std::bind(
            &test_shared_variable_t::attempt_read, this,
            expected_value,
            source.enter_read(),
            auto_drainer_t::lock_t(&auto_drainer)));
    }
    void spawn_write(int expected_value, int new_value) {
        coro_t::spawn_sometime(std::bind(
            &test_shared_variable_t::attempt_write, this,
            expected_value, new_value,
            source.enter_write(),
            auto_drainer_t::lock_t(&auto_drainer)));
    }
private:
    void attempt_read(int expected_value, fifo_enforcer_read_token_t token, auto_drainer_t::lock_t) {
        if (rng.randint(2) == 0) {
            nap(rng.randint(10));
        }
        fifo_enforcer_sink_t::exit_read_t exit(&sink, token);
        exit.wait_lazily_unordered();
        EXPECT_EQ(expected_value, variable);
    }
    void attempt_write(int expected_value, int new_value, fifo_enforcer_write_token_t token, auto_drainer_t::lock_t) {
        if (rng.randint(2) == 0) {
            nap(rng.randint(10));
        }
        fifo_enforcer_sink_t::exit_write_t exit(&sink, token);
        exit.wait_lazily_unordered();
        EXPECT_EQ(expected_value, variable);
        variable = new_value;
    }
    fifo_enforcer_source_t source;
    fifo_enforcer_sink_t sink;
    int variable;
    rng_t rng;
    auto_drainer_t auto_drainer;
};

TPTEST(FIFOEnforcer, FIFOEnforcer) {
    rng_t rng;
    int var1 = rng.randint(10000);
    test_shared_variable_t var2(var1);
    for (int i = 0; i < 1000; i++) {
        if (rng.randint(4) == 0) {
            int new_value = rng.randint(10000);
            var2.spawn_write(var1, new_value);
            var1 = new_value;
        } else {
            var2.spawn_read(var1);
        }
    }
}

TPTEST(FIFOEnforcer, StateTransfer) {
    fifo_enforcer_source_t source;
    UNUSED fifo_enforcer_write_token_t tok = source.enter_write();
    fifo_enforcer_sink_t sink(source.get_state());
    fifo_enforcer_write_token_t tok2 = source.enter_write();
    {
        try {
            signal_timer_t interruptor;
            interruptor.start(1000);
            fifo_enforcer_sink_t::exit_write_t fifo_exit(&sink, tok2);
            wait_interruptible(&fifo_exit, &interruptor);
        } catch (const interrupted_exc_t &) {
            ADD_FAILURE() << "Got stuck trying to exit FIFO";
        }
    }
}

/* This tests that dummy entries to fifo enforcers, that is entries which we
 * construct and then destroy (as we are doing with source.new_write_token()
 * and exit_write_t, don't trip up the fifo_enforce's destructors. */
TPTEST(FIFOEnforcer, DummyEntry) {
    fifo_enforcer_source_t source;
    fifo_enforcer_sink_t sink;

    source.enter_write();

    fifo_enforcer_sink_t::exit_write_t(&sink, source.enter_write());
}

TPTEST(FIFOEnforcer, QueueEquivalence) {
    fifo_enforcer_source_t source;
    fifo_enforcer_sink_t sink;
    fifo_enforcer_queue_t<boost::variant<fifo_enforcer_read_token_t, fifo_enforcer_write_token_t> > queue;

    int total_inserted = 0;
    for (int i = 0; i < 1000; i++) {
        for (int j = 0; j < 50; j++) {
            fifo_enforcer_read_token_t t = source.enter_read();
            queue.push(t, t);
            total_inserted++;
        }
        fifo_enforcer_write_token_t t = source.enter_write();
        queue.push(t, t);
        total_inserted++;
    }
    while(queue.control.get()) {
        boost::variant<fifo_enforcer_read_token_t, fifo_enforcer_write_token_t>  token = queue.produce_next_value();
        if (fifo_enforcer_read_token_t *read_token = boost::get<fifo_enforcer_read_token_t>(&token)) {
            fifo_enforcer_sink_t::exit_read_t er(&sink, *read_token);
            EXPECT_TRUE(er.is_pulsed());
            queue.finish_read(*read_token);
        } else if (fifo_enforcer_write_token_t *write_token = boost::get<fifo_enforcer_write_token_t>(&token)) {
            fifo_enforcer_sink_t::exit_write_t ew(&sink, *write_token);
            EXPECT_TRUE(ew.is_pulsed());
            queue.finish_write(*write_token);
        }
        total_inserted--;
    }

    EXPECT_EQ(total_inserted, 0);
}

}   /* namespace unittest */


text:
package org.apache.storm.blobstore;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.storm.generated.AccessControl;
import org.apache.storm.generated.AuthorizationException;
import org.apache.storm.generated.KeyAlreadyExistsException;
import org.apache.storm.generated.KeyNotFoundException;
import org.apache.storm.generated.ReadableBlobMeta;
import org.apache.storm.generated.SettableBlobMeta;
import org.apache.storm.utils.NimbusClient;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class ClientBlobStoreTest {

    private ClientBlobStore client;

    @Before
    public void setUp() throws Exception {

        client = new TestClientBlobStore();
        Map<String, Object> conf = new HashMap<>();
        client.prepare(conf);

    }

    @After
    public void tearDown() throws Exception {
        client = null;
    }

    @Test(expected = AuthorizationException.class)
    public void testDuplicateACLsForCreate() throws Exception {
        SettableBlobMeta meta = new SettableBlobMeta();
        AccessControl submitterAcl = BlobStoreAclHandler.parseAccessControl("u:tester:rwa");
        meta.add_to_acl(submitterAcl);
        AccessControl duplicateAcl = BlobStoreAclHandler.parseAccessControl("u:tester:r--");
        meta.add_to_acl(duplicateAcl);
        String testKey = "testDuplicateACLsBlobKey";
        client.createBlob(testKey, meta);
    }

    @Test
    public void testGoodACLsForCreate() throws Exception {
        SettableBlobMeta meta = new SettableBlobMeta();
        AccessControl submitterAcl = BlobStoreAclHandler.parseAccessControl("u:tester:rwa");
        meta.add_to_acl(submitterAcl);
        String testKey = "testBlobKey";
        client.createBlob(testKey, meta);
        validatedBlobAcls(testKey);
    }

    @Test(expected = AuthorizationException.class)
    public void testDuplicateACLsForSetBlobMeta() throws Exception {
        String testKey = "testDuplicateACLsBlobKey";
        SettableBlobMeta meta = new SettableBlobMeta();
        createTestBlob(testKey, meta);
        AccessControl duplicateAcl = BlobStoreAclHandler.parseAccessControl("u:tester:r--");
        meta.add_to_acl(duplicateAcl);
        client.setBlobMeta(testKey, meta);
    }

    @Test
    public void testGoodACLsForSetBlobMeta() throws Exception {
        String testKey = "testBlobKey";
        SettableBlobMeta meta = new SettableBlobMeta();
        createTestBlob(testKey, meta);
        meta.add_to_acl(BlobStoreAclHandler.parseAccessControl("u:nextuser:r--"));
        client.setBlobMeta(testKey, meta);
        validatedBlobAcls(testKey);
    }

    @Test
    public void testBloblStoreKeyWithUnicodesValidation() throws Exception {
        BlobStore.validateKey("msg-kafka-unicodewriter䶵-11-1483434711-stormconf.ser");
        BlobStore.validateKey("msg-kafka-ascii-11-148343436363-stormconf.ser");
    }

    private void createTestBlob(String testKey, SettableBlobMeta meta) throws AuthorizationException, KeyAlreadyExistsException {
        AccessControl submitterAcl = BlobStoreAclHandler.parseAccessControl("u:tester:rwa");
        meta.add_to_acl(submitterAcl);
        client.createBlob(testKey, meta);
    }

    private void validatedBlobAcls(String testKey) throws KeyNotFoundException, AuthorizationException {
        ReadableBlobMeta blobMeta = client.getBlobMeta(testKey);
        Assert.assertNotNull("The blob" + testKey + "does not have any readable blobMeta.", blobMeta);
        SettableBlobMeta settableBlob = blobMeta.get_settable();
        Assert.assertNotNull("The blob" + testKey + "does not have any settable blobMeta.", settableBlob);
    }

    public class TestClientBlobStore extends ClientBlobStore {

        private Map<String, SettableBlobMeta> allBlobs;

        @Override
        public void prepare(Map<String, Object> conf) {
            this.conf = conf;
            allBlobs = new HashMap<String, SettableBlobMeta>();
        }

        @Override
        protected AtomicOutputStream createBlobToExtend(String key, SettableBlobMeta meta) throws AuthorizationException,
            KeyAlreadyExistsException {
            allBlobs.put(key, meta);
            return null;
        }

        @Override
        public AtomicOutputStream updateBlob(String key) throws AuthorizationException, KeyNotFoundException {
            return null;
        }

        @Override
        public ReadableBlobMeta getBlobMeta(String key) throws AuthorizationException, KeyNotFoundException {
            ReadableBlobMeta reableMeta = null;
            if (allBlobs.containsKey(key)) {
                reableMeta = new ReadableBlobMeta();
                reableMeta.set_settable(allBlobs.get(key));
            }
            return reableMeta;
        }

        @Override
        public boolean isRemoteBlobExists(String blobKey) throws AuthorizationException {
            return allBlobs.containsKey(blobKey);
        }

        @Override
        protected void setBlobMetaToExtend(String key, SettableBlobMeta meta) throws AuthorizationException, KeyNotFoundException {
        }

        @Override
        public void deleteBlob(String key) throws AuthorizationException, KeyNotFoundException {
        }

        @Override
        public InputStreamWithMeta getBlob(String key) throws AuthorizationException, KeyNotFoundException {
            return null;
        }

        @Override
        public Iterator<String> listKeys() {
            return null;
        }

        @Override
        public void shutdown() {
        }

        @Override
        public void close() {
        }

        @Override
        public int getBlobReplication(String key) {
            return -1;
        }

        @Override
        public int updateBlobReplication(String key, int replication) {
            return -1;
        }

        @Override
        public boolean setClient(Map<String, Object> conf, NimbusClient client) {
            return false;
        }

        @Override
        public void createStateInZookeeper(String key) {
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Athlete',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('strava_id', models.IntegerField(unique=True)),
                ('strava_token', models.CharField(unique=True, max_length=50)),
            ],
        ),
    ]


text:
nodegetter
==========

This is a TV show bittorrent manager written in Node.JS.

TODO:
==========
* Integrate with SQLite.
* Outline config file.
* Integrate with bittorrent client.
* Define regex rules to identify Show, Season, Episode, Quality, et al.


text:
package com.ansorgit.plugins.bash.lang.psi.impl.shell;

import com.ansorgit.plugins.bash.lang.lexer.BashTokenTypes;
import com.ansorgit.plugins.bash.lang.parser.BashElementTypes;
import com.ansorgit.plugins.bash.lang.psi.api.shell.BashCase;
import com.ansorgit.plugins.bash.lang.psi.impl.BashKeywordDefaultImpl;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;

import java.util.Collection;

/**
 * Implements the Bash Case construct.
 * <br>
 * @author jansorg
 */
public class BashCaseImpl extends BashKeywordDefaultImpl implements BashCase {
    public BashCaseImpl() {
        super(BashElementTypes.CASE_COMMAND);
    }

    public PsiElement keywordElement() {
        return findPsiChildByType(BashTokenTypes.CASE_KEYWORD);
    }

    public Collection<? extends PsiElement> patternList() {
        return PsiTreeUtil.findChildrenOfType(this, BashCasePatternListElementImpl.class);
    }

    @Override
    public boolean isCommandGroup() {
        return false;
    }
}


text:
package aqa.parser;

/**
 * This class IGNORES requests to write output.  It does nothing!
 *
 * It is unwise to use this class in production unless you are certain that the
 * program contains no OUTPUT or INSPECT statements - as they won't have any
 * effect.
 *
 * It is useful in testing.
 *
 * @author martinhart
 */
public class NullOutputWriter implements OutputWriter {

    @Override
    public void output(String message) {
        // do nothing
    }

}


text:
/**
*	@desc: auto counter editor
*	@returns: dhtmlxGrid cell editor object
*	@type: public
*/
function eXcell_cntr(cell){
	this.cell = cell;
    this.grid = this.cell.parentNode.grid;
	if (!this.grid._ex_cntr_ready && !this._realfake){
		this.grid._ex_cntr_ready=true;
		if (this.grid._h2)
			this.grid.attachEvent("onOpenEn",function(id){
				this.resetCounter(cell._cellIndex);
			});
		var fix_cnt = function(){
			var that=this;
			window.setTimeout(function(){
				if (!that.resetCounter) return;
				if (that._fake && !that._realfake && cell._cellIndex<that._fake._cCount)
					that._fake.resetCounter(cell._cellIndex);
				else
				    that.resetCounter(cell._cellIndex);
			},1);
			return true;
		};

		this.grid.attachEvent("onBeforeSorting", fix_cnt);
		this.grid.attachEvent("onFilterEnd", fix_cnt);
	}

	this.edit = function(){}
	this.getValue = function(){
		return this.cell.innerHTML;
	}
	this.setValue = function(val){
		this.cell.style.paddingRight = "2px";
		var cell=this.cell;

		window.setTimeout(function(){
			if (!cell.parentNode) return;
			var val=cell.parentNode.rowIndex;
			if (cell.parentNode.grid.currentPage || val<0 || cell.parentNode.grid._srnd) val=cell.parentNode.grid.rowsBuffer._dhx_find(cell.parentNode)+1;
			if (val<=0) return;
			cell.innerHTML = val;
			if (cell.parentNode.grid._fake && cell._cellIndex<cell.parentNode.grid._fake._cCount && cell.parentNode.grid._fake.rowsAr[cell.parentNode.idd]) cell.parentNode.grid._fake.cells(cell.parentNode.idd,cell._cellIndex).setCValue(val);
			cell=null;
		},100);
	}
}
dhtmlXGridObject.prototype.resetCounter=function(ind){
	if (this._fake && !this._realfake && ind < this._fake._cCount) this._fake.resetCounter(ind,this.currentPage);
	var i=arguments[0]||0;
	if (this.currentPage)
		i=(this.currentPage-1)*this.rowsBufferOutSize;
	for (i=0; i<this.rowsBuffer.length; i++)
		if (this.rowsBuffer[i] && this.rowsBuffer[i].tagName == "TR" && this.rowsAr[this.rowsBuffer[i].idd])
			this.rowsAr[this.rowsBuffer[i].idd].childNodes[ind].innerHTML=i+1;
}
eXcell_cntr.prototype = new eXcell;
//(c)dhtmlx ltd. www.dhtmlx.com


text:
import store from 'kolibri.coreVue.vuex.store';
import { PageNames } from '../constants';
import pages from '../views/reports/allReportsPages';
import {
  generateExerciseDetailHandler,
  exerciseRootRedirectHandler,
} from '../modules/exerciseDetail/handlers';
import { generateExamReportDetailHandler } from '../modules/examReportDetail/handlers';
import {
  generateQuestionDetailHandler,
  questionRootRedirectHandler,
} from '../modules/questionDetail/handlers';
import { generateQuestionListHandler } from '../modules/questionList/handlers';
import { generateResourceHandler } from '../modules/resourceDetail/handlers';
import LessonEditDetailsPage from '../views/plan/LessonEditDetailsPage';
import QuizEditDetailsPage from '../views/plan/QuizEditDetailsPage';

const ACTIVITY = '/activity';
const CLASS = '/:classId/reports';
const GROUPS = '/groups';
const GROUP = '/groups/:groupId';
const LEARNERS = '/learners';
const LEARNER = '/learners/:learnerId';
const LESSONS = '/lessons';
const LESSON = '/lessons/:lessonId';
const QUIZZES = '/quizzes';
const QUIZ = '/quizzes/:quizId';
const QUESTIONS = '/questions';
const QUESTION = '/questions/:questionId';
const TRY = '/try/:tryIndex';
const INTERACTION = '/interactions/:interactionIndex';
const EXERCISE = '/exercises/:exerciseId';
const RESOURCES = '/resources';
const RESOURCE = '/resources/:resourceId';

function path(...args) {
  return args.join('');
}

function defaultHandler() {
  store.dispatch('notLoading');
}

export default [
  {
    name: PageNames.REPORTS_PAGE,
    path: path(CLASS),
    redirect: { name: 'ReportsLessonListPage' },
  },
  {
    path: path(CLASS, GROUP, ACTIVITY),
    component: pages.ReportsGroupActivityPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['activityLabel', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LEARNERS),
    component: pages.ReportsGroupLearnerListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['membersLabel', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUPS),
    component: pages.ReportsGroupListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['groupsLabel', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, LEARNER),
    component: pages.ReportsGroupReportLessonLearnerPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['learnersLabel', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, EXERCISE, LEARNERS),
    component: pages.ReportsGroupReportLessonExerciseLearnerListPage,
    handler: generateResourceHandler(['exerciseId']),
    meta: {
      titleParts: ['learnersLabel', 'EXERCISE_NAME', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, EXERCISE, LEARNER),
    name: PageNames.REPORTS_GROUP_REPORT_LESSON_EXERCISE_LEARNER_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return exerciseRootRedirectHandler(
        params,
        pages.ReportsGroupReportLessonExerciseLearnerPage.name,
        next
      );
    },
    meta: {
      titleParts: ['LEARNER_NAME', 'EXERCISE_NAME', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, EXERCISE, LEARNER, TRY, QUESTION, INTERACTION),
    component: pages.ReportsGroupReportLessonExerciseLearnerPage,
    handler: generateExerciseDetailHandler(['groupId', 'learnerId', 'lessonId', 'exerciseId']),
    meta: {
      // Leaves out attempt and interaction
      titleParts: ['LEARNER_NAME', 'EXERCISE_NAME', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },

  {
    path: path(CLASS, GROUP, LESSON, EXERCISE, QUESTIONS),
    component: pages.ReportsGroupReportLessonExerciseQuestionListPage,
    handler: generateQuestionListHandler(['groupId', 'lessonId', 'exerciseId']),
    meta: {
      titleParts: ['questionsLabel', 'EXERCISE_NAME', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, EXERCISE, QUESTION),
    name: PageNames.REPORTS_GROUP_REPORT_LESSON_EXERCISE_QUESTION_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return questionRootRedirectHandler(
        params,
        pages.ReportsGroupReportLessonExerciseQuestionPage.name,
        next
      );
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, EXERCISE, QUESTION, LEARNER, INTERACTION),
    component: pages.ReportsGroupReportLessonExerciseQuestionPage,
    handler: generateQuestionDetailHandler(['groupId', 'lessonId', 'exerciseId', 'questionId']),
    meta: {
      // Leaves out info on question
      titleParts: ['questionLabel', 'EXERCISE_NAME', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, RESOURCES),
    component: pages.ReportsGroupReportLessonPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['LESSON_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, LEARNERS),
    component: pages.ReportsGroupReportLessonLearnerListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, LESSON, RESOURCE, LEARNERS),
    component: pages.ReportsGroupReportLessonResourceLearnerListPage,
    handler: generateResourceHandler(['resourceId']),
    meta: {
      titleParts: ['learnersLabel', 'RESOURCE_NAME', 'LESSON_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, '/reports'),
    component: pages.ReportsGroupReportPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['reportsLabel', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, QUIZ, LEARNERS),
    component: pages.ReportsGroupReportQuizLearnerListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['learnersLabel', 'QUIZ_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, QUIZ, LEARNER),
    name: PageNames.REPORTS_GROUP_REPORT_QUIZ_LEARNER_PAGE_ROOT,
    redirect: to => {
      const { params } = to;
      return {
        name: pages.ReportsGroupReportQuizLearnerPage.name,
        params: {
          ...params,
          questionId: 0,
          interactionIndex: 0,
          tryIndex: 0,
        },
      };
    },
  },
  {
    path: path(CLASS, GROUP, QUIZ, LEARNER, TRY, QUESTION, INTERACTION),
    component: pages.ReportsGroupReportQuizLearnerPage,
    handler: generateExamReportDetailHandler(['groupId', 'learnerId', 'quizId']),
    meta: {
      titleParts: ['LEARNER_NAME', 'QUIZ_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, QUIZ, QUESTIONS),
    component: pages.ReportsGroupReportQuizQuestionListPage,
    handler: generateQuestionListHandler(['groupId', 'quizId']),
    meta: {
      titleParts: ['questionsLabel', 'QUIZ_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, GROUP, QUIZ, QUESTION),
    name: PageNames.REPORTS_GROUP_REPORT_QUIZ_QUESTION_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return questionRootRedirectHandler(
        params,
        pages.ReportsGroupReportQuizQuestionPage.name,
        next
      );
    },
  },
  {
    path: path(CLASS, GROUP, QUIZ, QUESTION, LEARNER, INTERACTION),
    component: pages.ReportsGroupReportQuizQuestionPage,
    handler: generateQuestionDetailHandler(['groupId', 'quizId', 'questionId']),
    meta: {
      titleParts: ['questionsLabel', 'QUIZ_NAME', 'GROUP_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, ACTIVITY, EXERCISE),
    name: PageNames.REPORTS_LEARNER_ACTIVITY_EXERCISE_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return exerciseRootRedirectHandler(
        params,
        pages.ReportsLearnerActivityExercisePage.name,
        next
      );
    },
    meta: {
      titleParts: ['EXERCISE_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, ACTIVITY, EXERCISE, QUESTION, INTERACTION),
    component: pages.ReportsLearnerActivityExercisePage,
    handler: generateExerciseDetailHandler(['learnerId', 'exerciseId']),
    meta: {
      titleParts: ['EXERCISE_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, ACTIVITY),
    component: pages.ReportsLearnerActivityPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['activityLabel', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNERS),
    component: pages.ReportsLearnerListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['learnersLabel', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, LESSON, EXERCISE),
    name: PageNames.REPORTS_LEARNER_REPORT_LESSON_EXERCISE_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return exerciseRootRedirectHandler(
        params,
        pages.ReportsLearnerReportLessonExercisePage.name,
        next
      );
    },
    meta: {
      titleParts: ['EXERCISE_NAME', 'LESSON_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, LESSON, EXERCISE, TRY, QUESTION, INTERACTION),
    component: pages.ReportsLearnerReportLessonExercisePage,
    handler: generateExerciseDetailHandler(['learnerId', 'lessonId', 'exerciseId']),
    meta: {
      titleParts: ['EXERCISE_NAME', 'LESSON_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, LESSON),
    component: pages.ReportsLearnerReportLessonPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['LESSON_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, '/reports'),
    component: pages.ReportsLearnerReportPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['reportsLabel', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LEARNER, QUIZ),
    name: PageNames.REPORTS_LEARNER_REPORT_QUIZ_PAGE_ROOT,
    redirect: to => {
      const { params } = to;
      return {
        name: pages.ReportsLearnerReportQuizPage.name,
        params: {
          ...params,
          questionId: 0,
          interactionIndex: 0,
        },
      };
    },
  },
  {
    path: path(CLASS, LEARNER, QUIZ, TRY, QUESTION, INTERACTION),
    component: pages.ReportsLearnerReportQuizPage,
    handler: generateExamReportDetailHandler(['learnerId', 'quizId']),
    meta: {
      titleParts: ['QUIZ_NAME', 'LEARNER_NAME', 'CLASS_NAME'],
    },
  },
  {
    name: 'LessonReportEditDetailsPage',
    path: path(CLASS, LESSON, '/edit'),
    component: LessonEditDetailsPage,
    props: {
      showResourcesTable: true,
    },
    handler: defaultHandler,
  },
  {
    path: path(CLASS, LESSON, EXERCISE, LEARNERS),
    component: pages.ReportsLessonExerciseLearnerListPage,
    handler: generateResourceHandler(['exerciseId']),
    meta: {
      titleParts: ['learnersLabel', 'EXERCISE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, EXERCISE, LEARNER),
    name: PageNames.REPORTS_LESSON_EXERCISE_LEARNER_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params, query } = to;
      return exerciseRootRedirectHandler(
        params,
        pages.ReportsLessonExerciseLearnerPage.name,
        next,
        query
      );
    },
    meta: {
      titleParts: ['LEARNER_NAME', 'EXERCISE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },

  {
    path: path(CLASS, LESSON, EXERCISE, LEARNER, TRY, QUESTION, INTERACTION),
    component: pages.ReportsLessonExerciseLearnerPage,
    handler: generateExerciseDetailHandler(['learnerId', 'lessonId', 'exerciseId']),
    meta: {
      titleParts: ['LEARNER_NAME', 'EXERCISE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, EXERCISE, QUESTIONS),
    component: pages.ReportsLessonExerciseQuestionListPage,
    handler: generateQuestionListHandler(['lessonId', 'exerciseId']),
    meta: {
      titleParts: ['questionsLabel', 'EXERCISE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },

  {
    path: path(CLASS, LESSON, EXERCISE, QUESTION),
    name: PageNames.REPORTS_LESSON_EXERCISE_QUESTION_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return questionRootRedirectHandler(
        params,
        pages.ReportsLessonExerciseQuestionPage.name,
        next
      );
    },
  },
  {
    path: path(CLASS, LESSON, EXERCISE, QUESTION, LEARNER, INTERACTION),
    component: pages.ReportsLessonExerciseQuestionPage,
    handler: generateQuestionDetailHandler(['lessonId', 'exerciseId', 'questionId']),
    meta: {
      // No info on question
      titleParts: ['EXERCISE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, LEARNER, EXERCISE),
    name: PageNames.REPORTS_LESSON_LEARNER_EXERCISE_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return exerciseRootRedirectHandler(params, pages.ReportsLessonLearnerExercisePage.name, next);
    },
    meta: {
      titleParts: ['EXERCISE_NAME', 'LEARNER_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, LEARNER, EXERCISE, TRY, QUESTION, INTERACTION),
    component: pages.ReportsLessonLearnerExercisePage,
    handler: generateExerciseDetailHandler(['learnerId', 'lessonId', 'exerciseId']),
    meta: {
      // Leaves out attempt and interaction numbers
      titleParts: ['LEARNER_NAME', 'EXERCISE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, LEARNERS),
    component: pages.ReportsLessonLearnerListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['learnersLabel', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, LEARNER),
    component: pages.ReportsLessonLearnerPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['LEARNER_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSONS),
    component: pages.ReportsLessonListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['lessonsLabel', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, '/manager'),
    component: pages.ReportsLessonManagerPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['manageResourcesAction', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, RESOURCES),
    component: pages.ReportsLessonReportPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['reportLabel', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, LESSON, RESOURCE, LEARNERS),
    component: pages.ReportsLessonResourceLearnerListPage,
    handler: generateResourceHandler(['resourceId']),
    meta: {
      titleParts: ['RESOURCE_NAME', 'LESSON_NAME', 'CLASS_NAME'],
    },
  },
  {
    name: 'QuizReportEditDetailsPage',
    path: path(CLASS, QUIZ, '/edit'),
    component: QuizEditDetailsPage,
    handler: defaultHandler,
  },
  {
    path: path(CLASS, QUIZ, LEARNERS),
    component: pages.ReportsQuizLearnerListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['learnersLabel', 'QUIZ_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, QUIZ, LEARNER),
    name: PageNames.REPORTS_QUIZ_LEARNER_PAGE_ROOT,
    redirect: to => {
      const { params } = to;
      return {
        name: pages.ReportsQuizLearnerPage.name,
        params: {
          ...params,
          questionId: 0,
          tryIndex: 0,
          interactionIndex: 0,
        },
      };
    },
  },
  {
    path: path(CLASS, QUIZ, LEARNER, TRY, QUESTION, INTERACTION),
    component: pages.ReportsQuizLearnerPage,
    handler: generateExamReportDetailHandler(['learnerId', 'quizId']),
    meta: {
      // Leaves out question and interaction numbers
      titleParts: ['LEARNER_NAME', 'QUIZ_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, QUIZZES),
    component: pages.ReportsQuizListPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['quizzesLabel', 'CLASS_NAME'],
    },
  },
  {
    name: pages.ReportsQuizPreviewPage.name,
    path: path(CLASS, QUIZ, '/preview'),
    component: pages.ReportsQuizPreviewPage,
    handler: defaultHandler,
    meta: {
      titleParts: ['previewLabel', 'QUIZ_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, QUIZ, QUESTIONS),
    component: pages.ReportsQuizQuestionListPage,
    handler: generateQuestionListHandler(['quizId']),
    meta: {
      titleParts: ['questionsLabel', 'QUIZ_NAME', 'CLASS_NAME'],
    },
  },
  {
    path: path(CLASS, QUIZ, QUESTION),
    name: PageNames.REPORTS_QUIZ_QUESTION_PAGE_ROOT,
    beforeEnter: (to, from, next) => {
      const { params } = to;
      return questionRootRedirectHandler(params, pages.ReportsQuizQuestionPage.name, next);
    },
  },
  {
    path: path(CLASS, QUIZ, QUESTION, LEARNER, INTERACTION),
    component: pages.ReportsQuizQuestionPage,
    handler: generateQuestionDetailHandler(['quizId', 'questionId']),
    meta: {
      // TODO Leaves out details about the question
      titleParts: ['QUIZ_NAME', 'CLASS_NAME'],
    },
  },
];


text:
challenges
==========

My code from programming challenges.  Also see [fp](https://github.com/reprah/fp).


text:
/**
 project:* batreh-aspnet-make
 type: buile tool
 company: Borna Mehr Fann.
 treadmark: Barteh
 Licence: MIT
    description: nodejs library tool for build and bundle asp.net and
    modern js libraqries like angularjs.
    auther: Ahad Rafat Talebi.
site: www.barteh.ir
 */
var fs = require('fs');
var extra = require('fs-extra');
var glob = require('glob');
var path=require('path');

exports.make = function (dirs,tmp) {
    var fonts = glob.sync(tmp + '/**/*.ttf');
    fonts = fonts.concat(glob.sync(tmp + '/**/*.woff'));
    fonts = fonts.concat(glob.sync(tmp + '/**/*.eot'));

    for (var i = 0; i < fonts.length;i++)
        extra.copySync(fonts[i], dirs.fonts+'/'+path.basename(fonts[i]));
}


text:
package org.kaazing.mina.core.future;

import org.apache.mina.core.future.DefaultWriteFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;

/**
 * A default implementation of {@link WriteFuture}.
 */
public class DefaultWriteFutureEx extends DefaultIoFutureEx implements WriteFutureEx {
    /**
     * Returns a new {@link DefaultWriteFuture} which is already marked as 'written'.
     */
    public static WriteFutureEx newWrittenFuture(IoSession session) {
        DefaultWriteFutureEx unwrittenFuture = new DefaultWriteFutureEx(session);
        unwrittenFuture.setWritten();
        return unwrittenFuture;
    }

    /**
     * Returns a new {@link DefaultWriteFuture} which is already marked as 'not written'.
     */
    public static WriteFutureEx newNotWrittenFuture(IoSession session, Throwable cause) {
        DefaultWriteFutureEx unwrittenFuture = new DefaultWriteFutureEx(session);
        unwrittenFuture.setException(cause);
        return unwrittenFuture;
    }

    /**
     * Creates a new instance.
     */
    public DefaultWriteFutureEx(IoSession session) {
        super(session);
    }

    // "reset" constructor
    protected DefaultWriteFutureEx() {
        super(null);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isWritten() {
        if (isDone()) {
            Object v = getValue();
            if (v instanceof Boolean) {
                return (Boolean) v;
            }
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Throwable getException() {
        if (isDone()) {
            Object v = getValue();
            if (v instanceof Throwable) {
                return (Throwable) v;
            }
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setWritten() {
        setValue(Boolean.TRUE);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setException(Throwable exception) {
        if (exception == null) {
            throw new NullPointerException("exception");
        }

        setValue(exception);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public WriteFutureEx await() throws InterruptedException {
        return (WriteFutureEx) super.await();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public WriteFutureEx awaitUninterruptibly() {
        return (WriteFutureEx) super.awaitUninterruptibly();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public WriteFutureEx addListener(IoFutureListener<?> listener) {
        return (WriteFutureEx) super.addListener(listener);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public WriteFutureEx removeListener(IoFutureListener<?> listener) {
        return (WriteFutureEx) super.removeListener(listener);
    }
}


text:
package org.ovirt.engine.ui.common.widget.renderer;

import java.util.Iterator;
import java.util.Set;

import org.ovirt.engine.core.common.businessentities.gluster.TransportType;
import org.ovirt.engine.ui.uicompat.EnumTranslator;
import org.ovirt.engine.ui.uicompat.Translator;

import com.google.gwt.text.shared.AbstractRenderer;

public class VolumeTransportTypeRenderer extends AbstractRenderer<Set<TransportType>> {

    public VolumeTransportTypeRenderer() {

    }

    @Override
    public String render(Set<TransportType> transportTypes) {
        Translator transportTypeTranslator = EnumTranslator.create(TransportType.class);
        StringBuilder transportTypesBuilder = new StringBuilder();
        Iterator<TransportType> iterator = transportTypes.iterator();
        while (iterator.hasNext()) {
            TransportType transportType = iterator.next();
            if (transportTypeTranslator.containsKey(transportType)) {
                transportTypesBuilder.append(transportTypeTranslator.get(transportType));
            }
            else {
                transportTypesBuilder.append(transportType.toString());
            }

            if (iterator.hasNext()) {
                transportTypesBuilder.append(", "); //$NON-NLS-1$
            }
        }
        return transportTypesBuilder.toString();
    }

}