text:
namespace history {

// Version number of the database.
static const int kCurrentVersionNumber = 4;
static const int kCompatibleVersionNumber = 4;

ThumbnailDatabaseQt::ThumbnailDatabaseQt() {
  DLOG(INFO)<<__FUNCTION__;

}

ThumbnailDatabaseQt::~ThumbnailDatabaseQt() {
  DLOG(INFO)<<__FUNCTION__;

}

bool ThumbnailDatabaseQt::Init(const FilePath& db_name) {
  DLOG(INFO)<<__FUNCTION__;
  sql::InitStatus status = OpenDatabase(&db_, db_name);
  if (status != sql::INIT_OK) {
    assert(false);
    return false;
  }

  // Scope initialization in a transaction so we can't be partially initialized.
  sql::Transaction transaction(&db_);
  transaction.Begin();

  // Create the tables.
  if (!initThumbnailTable())  {
    db_.Close();
    assert(false);
    return false;
  }

  // Initialization is complete.
  if (!transaction.Commit()) {
    db_.Close();
    assert(false);
    return false;
  }

  DLOG(INFO)<<__FUNCTION__;
  return true;
}

sql::InitStatus ThumbnailDatabaseQt::OpenDatabase(sql::Connection* db,
                                                const FilePath& db_name) {
  DLOG(INFO)<<__FUNCTION__;
  // Set the exceptional sqlite error handler.
  db->set_error_delegate(GetErrorHandlerForThumbnailDb());

  db->set_page_size(2048);
  db->set_cache_size(32);

  // Run the database in exclusive mode. Nobody else should be accessing the
  // database while we're running, and this will give somewhat improved perf.
  db->set_exclusive_locking();

  if (!db->Open(db_name))
    return sql::INIT_FAILURE;

  return sql::INIT_OK;
}

bool ThumbnailDatabaseQt::initThumbnailTable() {
  DLOG(INFO)<<__FUNCTION__;
  if (!db_.DoesTableExist("rec_thumbnails")) {
    if (!db_.Execute("CREATE TABLE rec_thumbnails ("
	"url LONGVARCHAR PRIMARY KEY,"
        "bookmarked INTEGER DEFAULT 0,"
        "valid INTEGER DEFAULT 0,"
        "data BLOB)"))
      return false;
  }

  return true;
}

bool ThumbnailDatabaseQt::RecreateThumbnailTable() {
  DLOG(INFO)<<__FUNCTION__;
  if (!db_.Execute("DROP TABLE rec_thumbnails"))
    return false;
  return initThumbnailTable();
}

void ThumbnailDatabaseQt::BeginTransaction() {
  DLOG(INFO)<<__FUNCTION__;
  db_.BeginTransaction();
}

void ThumbnailDatabaseQt::CommitTransaction() {
  DLOG(INFO)<<__FUNCTION__;
  db_.CommitTransaction();
}

void ThumbnailDatabaseQt::Vacuum() {
  DLOG(INFO)<<__FUNCTION__;
  DCHECK(db_.transaction_nesting() == 0) <<
      "Can not have a transaction when vacuuming.";
  db_.Execute("VACUUM");
}

bool ThumbnailDatabaseQt::DeleteThumbnail(const std::string url) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "DELETE FROM rec_thumbnails WHERE url = ?"));
  if (!statement)
    return false;

  statement.BindString(0, url);
  return statement.Run();
}

void ThumbnailDatabaseQt::CleanUnusedThumbnails(std::vector<GURL> list_url) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "SELECT url FROM rec_thumbnails WHERE bookmarked=0"));
  if (!statement)
    return;

  int list_count = list_url.size();
  while (statement.Step()) {
    bool found = false;
    std::string url_str = statement.ColumnString(0);
    for(int i=0; i<list_count; i++) {
	if(url_str == list_url[i].spec()) {
	   found = true;
           break;
        }
    }
    if(!found)
      DeleteThumbnail(url_str);
  }
}

int ThumbnailDatabaseQt::ThumbnailsCountExcludeBookmarked() {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "SELECT COUNT(*) FROM rec_thumbnails WHERE bookmarked=0"));
  if (!statement)
    return -1;

  if (!statement.Step())
    return -1;  // don't have this url

  return statement.ColumnInt(0);
}

bool ThumbnailDatabaseQt::HasThisPage(const GURL& url) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "SELECT * FROM rec_thumbnails WHERE url=?"));
  if (!statement)
    return false;

  statement.BindString(0, url.spec());

  if (!statement.Step())
    return false;  // don't have this url

  DLOG(INFO)<<__FUNCTION__<<": "<<true;
  return true;
}

bool ThumbnailDatabaseQt::IsThumbnailValid(const GURL& url) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "SELECT valid FROM rec_thumbnails WHERE url=?"));
  if (!statement)
    return false;

  statement.BindString(0, url.spec());

  if (!statement.Step())
    return false;  // don't have this url

  return statement.ColumnBool(0);
}

// Return false: URL not exist or not bookmarked.
bool ThumbnailDatabaseQt::IsBookmarkedPage(const GURL& url) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "SELECT bookmarked FROM rec_thumbnails WHERE url=?"));
  if (!statement)
    return false;

  statement.BindString(0, url.spec());
  if (!statement.Step())
    return false;  // don't have this url

  return statement.ColumnBool(0);
}

bool ThumbnailDatabaseQt::UpdateBookmarkedColumn(const GURL& url, bool bookmarked) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
	 "UPDATE rec_thumbnails SET bookmarked = ? WHERE url = ?"));
  if (!statement)
    return false;

  statement.BindBool(0, bookmarked);
  statement.BindString(1, url.spec());

  return statement.Run();
}

bool ThumbnailDatabaseQt::SetPageThumbnail(const GURL& url,
					const SkBitmap& thumbnail) {
  DLOG(INFO)<<__FUNCTION__;
  if (!thumbnail.isNull()) {
      sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
	 "UPDATE rec_thumbnails SET data = ?, valid = ? WHERE url = ?"));
      if (!statement)
        return false;

      // We use 90 quality (out of 100) which is pretty high, because
      // we're very sensitive to artifacts for these small sized,
      // highly detailed images.
      std::vector<unsigned char> jpeg_data;
      SkAutoLockPixels thumbnail_lock(thumbnail);
      bool encoded = gfx::JPEGCodec::Encode(
          reinterpret_cast<unsigned char*>(thumbnail.getAddr32(0, 0)),
          gfx::JPEGCodec::FORMAT_SkBitmap, thumbnail.width(),
          thumbnail.height(),
          static_cast<int>(thumbnail.rowBytes()), 90,
          &jpeg_data);

      if (encoded) {
        statement.BindBlob(0, &jpeg_data[0],
                           static_cast<int>(jpeg_data.size()));
	statement.BindBool(1, true);
	statement.BindString(2, url.spec());
        if (!statement.Run()) {
          NOTREACHED() << db_.GetErrorMessage();
          return false;
        }
	return true;
      }
      return false;
  }
}

bool ThumbnailDatabaseQt::InsertNewRow(
    const GURL& url,
    const bool bookmarked) {

  DLOG(INFO)<<__FUNCTION__;

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "INSERT OR REPLACE INTO rec_thumbnails "
      "(url, bookmarked, valid, data) "
      "VALUES (?,?,?,?)"));
  if (!statement)
    return false;

  //char jpeg_data;

  statement.BindString(0, url.spec());
  statement.BindBool(1, bookmarked);
  statement.BindBool(2, false);
  statement.BindNull(3);
  //statement.BindBlob(3, &jpeg_data, 0);

  if (!statement.Run()){
    NOTREACHED() << db_.GetErrorMessage();
    return false;
  }
  return true;
}

bool ThumbnailDatabaseQt::InsertNewRow(
    const GURL& url,
    const bool bookmarked,
    const SkBitmap& thumbnail) {

  DLOG(INFO)<<__FUNCTION__;

  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "INSERT OR REPLACE INTO rec_thumbnails "
      "(url, bookmarked, valid, data) "
      "VALUES (?,?,?,?)"));
  if (!statement)
    return false;

  //char jpeg_data;

  statement.BindString(0, url.spec());
  statement.BindBool(1, bookmarked);
  statement.BindBool(2, false);
  //statement.BindBlob(3, &jpeg_data, 0);
  statement.BindNull(3);

  if (!statement.Run()){
    NOTREACHED() << db_.GetErrorMessage();
    return false;
  }

  return SetPageThumbnail(url, thumbnail);
}

bool ThumbnailDatabaseQt::GetPageThumbnail(const GURL& url,
                                         std::vector<unsigned char>* data) {
  DLOG(INFO)<<__FUNCTION__;
  sql::Statement statement(db_.GetCachedStatement(SQL_FROM_HERE,
      "SELECT data FROM rec_thumbnails WHERE url=?"));
  if (!statement)
    return false;

  statement.BindString(0, url.spec());
  if (!statement.Step())
    return false;  // don't have a thumbnail for this ID

  statement.ColumnBlobAsVector(0, data);
  DLOG(INFO)<<__FUNCTION__<<"got data";
  return true;
}

bool ThumbnailDatabaseQt::RenameAndDropThumbnails(const FilePath& old_db_file,
                                                const FilePath& new_db_file) {
  DLOG(INFO)<<__FUNCTION__;
  return true;
}

}  // namespace history


text:
/*jslint browser:true, indent:2, maxlen:80*/
/*global define, require*/ // Require.JS

define(function (require) {
  'use strict';

  var Q, dfrd;
  Q = require('q');
  dfrd = Q.defer();

  setTimeout(function () {
    dfrd.resolve('q-commonjs');
  }, 0);

  return dfrd.promise;
});

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.runtime.taskmanager;

import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.jobgraph.tasks.TaskOperatorEventGateway;
import org.apache.flink.runtime.jobmaster.JobMasterOperatorEventGateway;
import org.apache.flink.runtime.operators.coordination.CoordinationRequest;
import org.apache.flink.runtime.operators.coordination.CoordinationResponse;
import org.apache.flink.runtime.operators.coordination.OperatorEvent;
import org.apache.flink.util.SerializedValue;

import java.util.concurrent.CompletableFuture;

/** A test / mock implementation of the {@link JobMasterOperatorEventGateway}. */
public class NoOpTaskOperatorEventGateway implements TaskOperatorEventGateway {

    @Override
    public void sendOperatorEventToCoordinator(
            OperatorID operatorID, SerializedValue<OperatorEvent> event) {}

    @Override
    public CompletableFuture<CoordinationResponse> sendRequestToCoordinator(
            OperatorID operator, SerializedValue<CoordinationRequest> request) {
        return CompletableFuture.completedFuture(null);
    }
}


text:
This blog is based on HuxBlog Boilerplate.
If you want to know more about this blog, you can visit [huxpro.github.io repo](https://github.com/Huxpro/huxpro.github.io).


text:
analysis home page

        <button type='button' class='btn btn-info {{show_diff}}' (click)="FC_ShowModal(1)">Diff</button>
        <button type='button' class='btn btn-info {{show_diff_new_id}}' (click)="FC_ShowModal(2)">Diff (new ID only)</button>
        <button type='button' class='btn btn-info {{show_protocol_identify}}' (click)="FC_ShowModal(3)">协议识别</button>
        <button type='button' class='btn btn-info {{show_find_action_frame}}' (click)="FC_ShowModal(4)">Find action frame</button>
        <button type='button' class='btn btn-info {{show_detect_change_for_ECU}}' (click)="FC_ShowModal(5)">Detect changes for ECU</button>
        <button type='button' class='btn btn-info {{show_singal_data_change_trend}}' (click)="FC_ShowModal(6)">单ID数据变化走势</button>

        kongde xiashi

    <analysis-diff></analysis-diff>

    <protocol-identify></protocol-identify>

    <find-actionframe></find-actionframe>

    <detectchange-for-ECU></detectchange-for-ECU>


text:
using Umbraco.Cms.Core.Configuration.Models;

namespace Umbraco.Extensions;

/// <summary>
/// Extension methods for a connection string.
/// </summary>
public static class ConnectionStringExtensions
{
    /// <summary>
    /// Determines whether the connection string is configured (set to a non-empty value).
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    /// <returns>
    ///   <c>true</c> if the connection string is configured; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsConnectionStringConfigured(this ConnectionStrings connectionString)
        => connectionString != null &&
        !string.IsNullOrWhiteSpace(connectionString.ConnectionString) &&
        !string.IsNullOrWhiteSpace(connectionString.ProviderName);
}


text:
package com.thoughtworks.go.config.registry;

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.PackageMaterialConfig;
import com.thoughtworks.go.config.materials.PluggableSCMMaterialConfig;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig;
import com.thoughtworks.go.config.materials.git.GitMaterialConfig;
import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig;
import com.thoughtworks.go.config.materials.perforce.P4MaterialConfig;
import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig;
import com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig;
import com.thoughtworks.go.config.pluggabletask.PluggableTask;
import com.thoughtworks.go.domain.BuildOutputMatcher;
import com.thoughtworks.go.domain.OutputMatcher;
import com.thoughtworks.go.domain.Task;
import com.thoughtworks.go.domain.config.Admin;
import com.thoughtworks.go.domain.materials.MaterialConfig;
import com.thoughtworks.go.plugins.presentation.BuiltinTaskViewModelFactory;
import com.thoughtworks.go.plugins.presentation.PluggableTaskViewModelFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ConfigElementImplementationRegistrar {
    private ConfigElementImplementationRegistry registry;

    @Autowired
    public ConfigElementImplementationRegistrar(ConfigElementImplementationRegistry registry) {
        this.registry = registry;
    }

    public void initialize() {
        registerBuiltinTasks();
        registerBuiltinMaterials();
        registerBuiltinUserTypes();
        registerBuiltinConsoleOutputMatchers();
        registerBuiltinArtifactTypes();
        registerRoleTypes();
    }

    private void registerRoleTypes() {
        registry.registerImplementer(Role.class, RoleConfig.class, PluginRoleConfig.class);
    }

    private void registerBuiltinTasks() {
        registry.registerImplementer(Task.class, AntTask.class, NantTask.class, ExecTask.class, RakeTask.class, FetchTask.class, PluggableTask.class, FetchPluggableArtifactTask.class);
        registry.registerView(AntTask.class, new BuiltinTaskViewModelFactory("ant"));
        registry.registerView(NantTask.class, new BuiltinTaskViewModelFactory("nant"));
        registry.registerView(ExecTask.class, new BuiltinTaskViewModelFactory("exec"));
        registry.registerView(RakeTask.class, new BuiltinTaskViewModelFactory("rake"));
        registry.registerView(FetchTask.class, new BuiltinTaskViewModelFactory("fetch"));
        registry.registerView(FetchPluggableArtifactTask.class, new BuiltinTaskViewModelFactory("fetch_pluggable_artifact"));
        registry.registerView(PluggableTask.class, new PluggableTaskViewModelFactory());
    }

    private void registerBuiltinArtifactTypes() {
        registry.registerImplementer(Artifact.class, TestArtifactConfig.class, ArtifactConfig.class, PluggableArtifactConfig.class);
    }

    private void registerBuiltinConsoleOutputMatchers() {
        registry.registerImplementer(OutputMatcher.class, BuildOutputMatcher.class);
    }

    private void registerBuiltinUserTypes() {
        registry.registerImplementer(Admin.class, AdminUser.class, AdminRole.class);
    }

    private void registerBuiltinMaterials() {
        registry.registerImplementer(MaterialConfig.class, SvnMaterialConfig.class, HgMaterialConfig.class, GitMaterialConfig.class, DependencyMaterialConfig.class, P4MaterialConfig.class,
                TfsMaterialConfig.class, PackageMaterialConfig.class, PluggableSCMMaterialConfig.class);
    }
}


text:
using FluentAssertions;
using NUnit.Framework;
using OutlookMatters.Core.Mattermost.v1.Interface;

namespace Test.OutlookMatters.Core.Mattermost.v1.Interface
{
    [TestFixture]
    public class MattermostExceptionTest
    {
        [Test]
        public void Message_ReturnsErrorMessage()
        {
            var error = new Error();
            error.message = "error message";
            var classUnderTest = new MattermostException(error);

            var message = classUnderTest.Message;

            message.Should().Be(error.message);
        }

        [Test]
        public void Details_ReturnsDetailedError()
        {
            var error = new Error();
            error.detailed_error = "detailed error";
            var classUnderTest = new MattermostException(error);

            var details = classUnderTest.Details;

            details.Should().Be(error.detailed_error);
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Greathouse & Ames, Mycologia 37(1): 145 (1945)

#### Original name
Chaetomium dolichotrichum L.M. Ames, 1945

### Remarks
null


text:
package com.facebook.buck.worker;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.TestProjectFilesystems;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.Ansi;
import com.facebook.buck.util.Console;
import com.facebook.buck.util.DefaultProcessExecutor;
import com.facebook.buck.util.FakeProcessExecutor;
import com.facebook.buck.util.ProcessExecutorParams;
import com.facebook.buck.util.Verbosity;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;

public class WorkerProcessTest {

  @Rule public TemporaryPaths temporaryPaths = new TemporaryPaths();

  private ProcessExecutorParams createDummyParams() {
    return ProcessExecutorParams.builder().setCommand(ImmutableList.of()).build();
  }

  @Test
  public void testSubmitAndWaitForJob() throws IOException {
    ProjectFilesystem filesystem = new FakeProjectFilesystem();
    Path tmpPath = Files.createTempDirectory("tmp").toAbsolutePath().normalize();
    Path argsPath = Paths.get(tmpPath.toString(), "0.args");
    Path stdoutPath = Paths.get(tmpPath.toString(), "0.out");
    Path stderrPath = Paths.get(tmpPath.toString(), "0.err");
    Path workerStdErr = Paths.get(tmpPath.toString(), "stderr");
    String jobArgs = "my job args";
    int exitCode = 0;

    Optional<String> stdout = Optional.of("my stdout");
    Optional<String> stderr = Optional.of("my stderr");

    try (DefaultWorkerProcess process =
        new DefaultWorkerProcess(
            new FakeProcessExecutor(), createDummyParams(), filesystem, workerStdErr, tmpPath)) {
      process.setProtocol(
          new FakeWorkerProcessProtocol.FakeCommandSender() {
            @Override
            public int receiveCommandResponse(int messageId) throws IOException {
              // simulate the external tool and write the stdout and stderr files
              filesystem.writeContentsToPath(
                  stdout.orElseThrow(IllegalStateException::new), stdoutPath);
              filesystem.writeContentsToPath(
                  stderr.orElseThrow(IllegalStateException::new), stderrPath);
              return super.receiveCommandResponse(messageId);
            }
          });

      WorkerJobResult expectedResult = WorkerJobResult.of(exitCode, stdout, stderr);
      assertThat(process.submitAndWaitForJob(jobArgs), equalTo(expectedResult));
      assertThat(
          filesystem.readFileIfItExists(argsPath).orElseThrow(IllegalStateException::new),
          equalTo(jobArgs));
    }
  }

  @Test
  public void testClose() {
    FakeWorkerProcessProtocol.FakeCommandSender protocol =
        new FakeWorkerProcessProtocol.FakeCommandSender();

    try (DefaultWorkerProcess process =
        new DefaultWorkerProcess(
            new FakeProcessExecutor(),
            createDummyParams(),
            new FakeProjectFilesystem(),
            Paths.get("stderr"),
            Paths.get("tmp").toAbsolutePath().normalize())) {
      process.setProtocol(protocol);

      assertFalse(protocol.isClosed());
      process.close();
      assertTrue(protocol.isClosed());
    }
  }

  @Test(timeout = 20 * 1000)
  public void testDoesNotBlockOnLargeStderr() throws IOException {
    ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "worker_process", temporaryPaths);
    workspace.setUp();
    ProjectFilesystem projectFilesystem =
        TestProjectFilesystems.createProjectFilesystem(workspace.getDestPath());
    Console console = new Console(Verbosity.ALL, System.out, System.err, Ansi.withoutTty());
    String script;
    if (Platform.detect() == Platform.WINDOWS) {
      script = workspace.getDestPath().resolve("script.bat").toString();
    } else {
      script = "./script.py";
    }
    try (DefaultWorkerProcess workerProcess =
        new DefaultWorkerProcess(
            new DefaultProcessExecutor(console),
            ProcessExecutorParams.builder()
                .setCommand(ImmutableList.of(script))
                .setDirectory(workspace.getDestPath())
                .build(),
            projectFilesystem,
            temporaryPaths.newFile("stderr").getPath(),
            temporaryPaths.newFolder().getPath())) {
      workerProcess.ensureLaunchAndHandshake();
      fail("Handshake should have failed");
    } catch (HumanReadableException e) {
      // Check that all of the process's stderr was reported.
      assertThat(e.getMessage().length(), is(greaterThan(1024 * 1024)));
    }
  }
}


text:
<?php
/*
 * Custom routing Router to Dealer
 * @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
 */

//  We have two workers, here we copy the code, normally these would
//  run on different boxes...
function worker_a()
{
    $context = new ZMQContext();
    $worker = $context->getSocket(ZMQ::SOCKET_DEALER);
    $worker->setSockOpt(ZMQ::SOCKOPT_IDENTITY, "A");
    $worker->connect("ipc://routing.ipc");

    $total = 0;
    while (true) {
        //  We receive one part, with the workload
        $request = $worker->recv();
        if ($request == 'END') {
            printf ("A received: %d%s", $total, PHP_EOL);
            break;
        }
        $total++;
    }
}

function worker_b()
{
    $context = new ZMQContext();
    $worker = $context->getSocket(ZMQ::SOCKET_DEALER);
    $worker->setSockOpt(ZMQ::SOCKOPT_IDENTITY, "B");
    $worker->connect("ipc://routing.ipc");

    $total = 0;
    while (true) {
        //  We receive one part, with the workload
        $request = $worker->recv();
        if ($request == 'END') {
            printf ("B received: %d%s", $total, PHP_EOL);
            break;
        }
        $total++;
    }
}

$pid = pcntl_fork();
if ($pid == 0) { worker_a(); exit(); }
$pid = pcntl_fork();
if ($pid == 0) { worker_b(); exit(); }

$context = new ZMQContext();
$client = new ZMQSocket($context, ZMQ::SOCKET_ROUTER);
$client->bind("ipc://routing.ipc");

//  Wait for threads to stabilize
sleep(1);

//  Send 10 tasks scattered to A twice as often as B
for ($task_nbr = 0; $task_nbr != 10; $task_nbr++) {
    //  Send two message parts, first the address...
    if (mt_rand(0, 2) > 0) {
        $client->send("A", ZMQ::MODE_SNDMORE);
    } else {
        $client->send("B", ZMQ::MODE_SNDMORE);
    }
    //  And then the workload
    $client->send("This is the workload");
}

$client->send("A", ZMQ::MODE_SNDMORE);
$client->send("END");

$client->send("B", ZMQ::MODE_SNDMORE);
$client->send("END");

sleep (1);              //  Give 0MQ/2.0.x time to flush output


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@ag-grid-community/core");
var gridSerializer_1 = require("./gridSerializer");
var LINE_SEPARATOR = '\r\n';
var CsvSerializingSession = /** @class */ (function (_super) {
    __extends(CsvSerializingSession, _super);
    function CsvSerializingSession(config) {
        var _this = _super.call(this, config) || this;
        _this.isFirstLine = true;
        _this.result = '';
        var suppressQuotes = config.suppressQuotes, columnSeparator = config.columnSeparator;
        _this.suppressQuotes = suppressQuotes;
        _this.columnSeparator = columnSeparator;
        return _this;
    }
    CsvSerializingSession.prototype.addCustomContent = function (content) {
        var _this = this;
        if (!content) {
            return;
        }
        if (typeof content === 'string') {
            // we used to require the customFooter to be prefixed with a newline but no longer do,
            // so only add the newline if the user has not supplied one
            if (!/^\s*\n/.test(content)) {
                this.beginNewLine();
            }
            // replace whatever newlines are supplied with the style we're using
            content = content.replace(/\r?\n/g, LINE_SEPARATOR);
            this.result += content;
        }
        else {
            content.forEach(function (row) {
                _this.beginNewLine();
                row.forEach(function (cell, index) {
                    if (index !== 0) {
                        _this.result += _this.columnSeparator;
                    }
                    _this.result += _this.putInQuotes(cell.data.value || '');
                    if (cell.mergeAcross) {
                        _this.appendEmptyCells(cell.mergeAcross);
                    }
                });
            });
        }
    };
    CsvSerializingSession.prototype.onNewHeaderGroupingRow = function () {
        this.beginNewLine();
        return {
            onColumn: this.onNewHeaderGroupingRowColumn.bind(this)
        };
    };
    CsvSerializingSession.prototype.onNewHeaderGroupingRowColumn = function (header, index, span) {
        if (index != 0) {
            this.result += this.columnSeparator;
        }
        this.result += this.putInQuotes(header);
        this.appendEmptyCells(span);
    };
    CsvSerializingSession.prototype.appendEmptyCells = function (count) {
        for (var i = 1; i <= count; i++) {
            this.result += this.columnSeparator + this.putInQuotes("");
        }
    };
    CsvSerializingSession.prototype.onNewHeaderRow = function () {
        this.beginNewLine();
        return {
            onColumn: this.onNewHeaderRowColumn.bind(this)
        };
    };
    CsvSerializingSession.prototype.onNewHeaderRowColumn = function (column, index, node) {
        if (index != 0) {
            this.result += this.columnSeparator;
        }
        this.result += this.putInQuotes(this.extractHeaderValue(column));
    };
    CsvSerializingSession.prototype.onNewBodyRow = function () {
        this.beginNewLine();
        return {
            onColumn: this.onNewBodyRowColumn.bind(this)
        };
    };
    CsvSerializingSession.prototype.onNewBodyRowColumn = function (column, index, node) {
        if (index != 0) {
            this.result += this.columnSeparator;
        }
        this.result += this.putInQuotes(this.extractRowCellValue(column, index, core_1.Constants.EXPORT_TYPE_CSV, node));
    };
    CsvSerializingSession.prototype.putInQuotes = function (value) {
        if (this.suppressQuotes) {
            return value;
        }
        if (value === null || value === undefined) {
            return '""';
        }
        var stringValue;
        if (typeof value === 'string') {
            stringValue = value;
        }
        else if (typeof value.toString === 'function') {
            stringValue = value.toString();
        }
        else {
            console.warn('unknown value type during csv conversion');
            stringValue = '';
        }
        // replace each " with "" (ie two sets of double quotes is how to do double quotes in csv)
        var valueEscaped = stringValue.replace(/"/g, "\"\"");
        return '"' + valueEscaped + '"';
    };
    CsvSerializingSession.prototype.parse = function () {
        return this.result;
    };
    CsvSerializingSession.prototype.beginNewLine = function () {
        if (!this.isFirstLine) {
            this.result += LINE_SEPARATOR;
        }
        this.isFirstLine = false;
    };
    return CsvSerializingSession;
}(gridSerializer_1.BaseGridSerializingSession));
exports.CsvSerializingSession = CsvSerializingSession;
var BaseCreator = /** @class */ (function () {
    function BaseCreator() {
    }
    BaseCreator.prototype.setBeans = function (beans) {
        this.beans = beans;
    };
    BaseCreator.prototype.export = function (userParams) {
        if (this.isExportSuppressed()) {
            console.warn("ag-grid: Export cancelled. Export is not allowed as per your configuration.");
            return '';
        }
        var _a = this.getMergedParamsAndData(userParams), mergedParams = _a.mergedParams, data = _a.data;
        var fileNamePresent = mergedParams && mergedParams.fileName && mergedParams.fileName.length !== 0;
        var fileName = fileNamePresent ? mergedParams.fileName : this.getDefaultFileName();
        if (fileName.indexOf(".") === -1) {
            fileName = fileName + "." + this.getDefaultFileExtension();
        }
        this.beans.downloader.download(fileName, this.packageFile(data));
        return data;
    };
    BaseCreator.prototype.getData = function (params) {
        return this.getMergedParamsAndData(params).data;
    };
    BaseCreator.prototype.getMergedParamsAndData = function (userParams) {
        var mergedParams = this.mergeDefaultParams(userParams);
        var data = this.beans.gridSerializer.serialize(this.createSerializingSession(mergedParams), mergedParams);
        return { mergedParams: mergedParams, data: data };
    };
    BaseCreator.prototype.mergeDefaultParams = function (userParams) {
        var baseParams = this.beans.gridOptionsWrapper.getDefaultExportParams();
        var params = {};
        core_1._.assign(params, baseParams);
        core_1._.assign(params, userParams);
        return params;
    };
    BaseCreator.prototype.packageFile = function (data) {
        return new Blob(["\ufeff", data], {
            type: window.navigator.msSaveOrOpenBlob ? this.getMimeType() : 'octet/stream'
        });
    };
    return BaseCreator;
}());
exports.BaseCreator = BaseCreator;
var CsvCreator = /** @class */ (function (_super) {
    __extends(CsvCreator, _super);
    function CsvCreator() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CsvCreator.prototype.postConstruct = function () {
        this.setBeans({
            downloader: this.downloader,
            gridSerializer: this.gridSerializer,
            gridOptionsWrapper: this.gridOptionsWrapper
        });
    };
    CsvCreator.prototype.exportDataAsCsv = function (params) {
        return this.export(params);
    };
    CsvCreator.prototype.getDataAsCsv = function (params) {
        return this.getData(params);
    };
    CsvCreator.prototype.getMimeType = function () {
        return 'text/csv;charset=utf-8;';
    };
    CsvCreator.prototype.getDefaultFileName = function () {
        return 'export.csv';
    };
    CsvCreator.prototype.getDefaultFileExtension = function () {
        return 'csv';
    };
    CsvCreator.prototype.createSerializingSession = function (params) {
        var _a = this, columnController = _a.columnController, valueService = _a.valueService, gridOptionsWrapper = _a.gridOptionsWrapper;
        var processCellCallback = params.processCellCallback, processHeaderCallback = params.processHeaderCallback, processGroupHeaderCallback = params.processGroupHeaderCallback, processRowGroupCallback = params.processRowGroupCallback, suppressQuotes = params.suppressQuotes, columnSeparator = params.columnSeparator;
        return new CsvSerializingSession({
            columnController: columnController,
            valueService: valueService,
            gridOptionsWrapper: gridOptionsWrapper,
            processCellCallback: processCellCallback || undefined,
            processHeaderCallback: processHeaderCallback || undefined,
            processGroupHeaderCallback: processGroupHeaderCallback || undefined,
            processRowGroupCallback: processRowGroupCallback || undefined,
            suppressQuotes: suppressQuotes || false,
            columnSeparator: columnSeparator || ','
        });
    };
    CsvCreator.prototype.isExportSuppressed = function () {
        return this.gridOptionsWrapper.isSuppressCsvExport();
    };
    __decorate([
        core_1.Autowired('columnController')
    ], CsvCreator.prototype, "columnController", void 0);
    __decorate([
        core_1.Autowired('valueService')
    ], CsvCreator.prototype, "valueService", void 0);
    __decorate([
        core_1.Autowired('downloader')
    ], CsvCreator.prototype, "downloader", void 0);
    __decorate([
        core_1.Autowired('gridSerializer')
    ], CsvCreator.prototype, "gridSerializer", void 0);
    __decorate([
        core_1.Autowired('gridOptionsWrapper')
    ], CsvCreator.prototype, "gridOptionsWrapper", void 0);
    __decorate([
        core_1.PostConstruct
    ], CsvCreator.prototype, "postConstruct", null);
    CsvCreator = __decorate([
        core_1.Bean('csvCreator')
    ], CsvCreator);
    return CsvCreator;
}(BaseCreator));
exports.CsvCreator = CsvCreator;
//# sourceMappingURL=csvCreator.js.map


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.resourcemanager.rediscache.samples;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.management.AzureEnvironment;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.redis.models.DayOfWeek;
import com.azure.resourcemanager.redis.models.RebootType;
import com.azure.resourcemanager.redis.models.RedisAccessKeys;
import com.azure.resourcemanager.redis.models.RedisCache;
import com.azure.resourcemanager.redis.models.RedisCachePremium;
import com.azure.resourcemanager.redis.models.RedisKeyType;
import com.azure.core.management.Region;
import com.azure.resourcemanager.resources.fluentcore.model.Creatable;
import com.azure.resourcemanager.resources.fluentcore.model.CreatedResources;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.samples.Utils;

/**
 * Azure Redis sample for managing Redis Cache:
 *  - Create a Redis Cache and print out hostname.
 *  - Get access keys.
 *  - Regenerate access keys.
 *  - Create another 2 Redis Caches with Premium Sku.
 *  - List all Redis Caches in a resource group – for each cache with Premium Sku:
 *     - set Redis patch schedule to Monday at 5 am.
 *     - update shard count.
 *     - enable non-SSL port.
 *     - modify max memory policy and reserved settings.
 *     - restart it.
 *  - Clean up all resources.
 */

public final class ManageRedisCache {

    /**
     * Main function which runs the actual sample.
     * @param azureResourceManager instance of the azure client
     * @return true if sample runs successfully
     */
    public static boolean runSample(AzureResourceManager azureResourceManager) {
        final String redisCacheName1 = Utils.randomResourceName(azureResourceManager, "rc1", 20);
        final String redisCacheName2 = Utils.randomResourceName(azureResourceManager, "rc2", 20);
        final String redisCacheName3 = Utils.randomResourceName(azureResourceManager, "rc3", 20);
        final String rgName = Utils.randomResourceName(azureResourceManager, "rgRCMC", 20);
        try {
            // ============================================================
            // Define a redis cache

            System.out.println("Creating a Redis Cache");

            Creatable<RedisCache> redisCache1Definition = azureResourceManager.redisCaches().define(redisCacheName1)
                    .withRegion(Region.US_CENTRAL)
                    .withNewResourceGroup(rgName)
                    .withBasicSku();

            // ============================================================
            // Define two more Redis caches

            Creatable<RedisCache> redisCache2Definition = azureResourceManager.redisCaches().define(redisCacheName2)
                    .withRegion(Region.US_CENTRAL)
                    .withNewResourceGroup(rgName)
                    .withPremiumSku()
                    .withShardCount(3);

            Creatable<RedisCache> redisCache3Definition = azureResourceManager.redisCaches().define(redisCacheName3)
                    .withRegion(Region.US_CENTRAL)
                    .withNewResourceGroup(rgName)
                    .withPremiumSku(2)
                    .withShardCount(3);

            // ============================================================
            // Create all the caches in parallel to save time

            System.out.println("Creating three Redis Caches in parallel... (this will take several minutes)");

            @SuppressWarnings("unchecked")
            CreatedResources<RedisCache> createdCaches = azureResourceManager.redisCaches().create(
                    redisCache1Definition,
                    redisCache2Definition,
                    redisCache3Definition);

            System.out.println("Created Redis caches:");
            RedisCache redisCache1 = createdCaches.get(redisCache1Definition.key());

            for (RedisCache redisCache : createdCaches.values()) {
                Utils.print(redisCache);
                System.out.println();
            }

            // ============================================================
            // Get | regenerate Redis Cache access keys

            System.out.println("Getting the first Redis cache's access keys");
            RedisAccessKeys redisAccessKeys = redisCache1.keys();
            Utils.print(redisAccessKeys);

            System.out.println("Regenerating secondary Redis cache access key");
            redisAccessKeys = redisCache1.regenerateKey(RedisKeyType.SECONDARY);
            Utils.print(redisAccessKeys);

            // ============================================================
            // List Redis Caches inside the resource group

            System.out.println("Listing Redis Caches");

            PagedIterable<RedisCache> caches = azureResourceManager.redisCaches().listByResourceGroup(rgName);

            // Walk through all the caches
            for (RedisCache redis : caches) {
                // If the instance of the Redis Cache is Premium Sku
                if (redis.isPremium()) {
                    RedisCachePremium premium = redis.asPremium();

                    // Update each Premium Sku Redis Cache instance
                    System.out.println("Updating Premium Redis Cache");
                    premium.update()
                            .withPatchSchedule(DayOfWeek.MONDAY, 5)
                            .withShardCount(4)
                            .withNonSslPort()
                            .withRedisConfiguration("maxmemory-policy", "allkeys-random")
                            .withRedisConfiguration("maxmemory-reserved", "20")
                            .apply();

                    System.out.println("Updated Redis Cache:");
                    Utils.print(premium);

                    // Restart Redis Cache
                    System.out.println("Restarting updated Redis Cache");
                    premium.forceReboot(RebootType.ALL_NODES, 1);

                    System.out.println("Redis Cache restart scheduled");
                }
            }

            // ============================================================
            // Delete a Redis Cache

            System.out.println("Deleting a Redis Cache  - " + redisCache1.name());

            azureResourceManager.redisCaches().deleteById(redisCache1.id());

            System.out.println("Deleted Redis Cache");
            return true;
        } finally {
            if (azureResourceManager.resourceGroups().getByName(rgName) != null) {
                System.out.println("Deleting Resource Group: " + rgName);
                azureResourceManager.resourceGroups().deleteByName(rgName);
                System.out.println("Deleted Resource Group: " + rgName);
            } else {
                System.out.println("Did not create any resources in Azure. No clean up is necessary");
            }
        }
    }

    /**
     * Main entry point.
     * @param args the parameters
     */
    public static void main(String[] args) {
        try {
            //=============================================================
            // Authenticate

            final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
            final TokenCredential credential = new DefaultAzureCredentialBuilder()
                .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                .build();

            AzureResourceManager azureResourceManager = AzureResourceManager
                .configure()
                .withLogLevel(HttpLogDetailLevel.BASIC)
                .authenticate(credential, profile)
                .withDefaultSubscription();

            // Print selected subscription
            System.out.println("Selected subscription: " + azureResourceManager.subscriptionId());

            runSample(azureResourceManager);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    private ManageRedisCache() {
    }
}


text:
package ymdError

import "fmt"

const unknownErrorMsg = `83vdgt8r`

func PanicToErrMsgAndStack(f func()) (errMsg string, stack Stack) {
	defer func() {
		ei := recover()
		if ei == nil {
			return
		}
		errMsg = fmt.Sprint(ei)
		if errMsg == `` {
			errMsg = unknownErrorMsg
		}
		stack = getAllStack(4)
	}()
	f()
	return
}

func PanicIfError(err error) {
	if err != nil {
		panic(err)
	}
}


text:
module Fiona

  class Settings
    def initialize(&block)
      @state = :initializing
      @defaults = {}

      yield(self)

      merge_settings
      @state = :initialized
    end

    def default(key, value, scope = nil)
      raise 'You must set defaults when initializing' unless @state == :initializing
      raise 'You must provide a key' if key.nil?
      raise 'Key must be a symbol' unless key.is_a?(Symbol)
      raise 'You must provide a scope' if scope.nil? && @defaults[key]
      raise 'You can not change a scope' if @defaults[key] && scope
      raise 'Scope must be :public or :private' if scope && ![:public, :private].include?(scope)

      setting = @defaults[key] ||= {}
      setting[:value] = value
      setting[:scope] = scope if scope

      return true
    end

    def all_settings
      return @merged.clone
    end

    def public_settings
      return settings_for_scope(:public)
    end

    def private_settings
      return settings_for_scope(:private)
    end

    def settings_for_scope(scope)
      return @merged.select { |k, v| v[:scope] == scope }
    end

    def reload
      return merge_settings
    end

    def method_missing(m, *args, &block)
      m = m.to_sym

      if @merged.include?(m)
        return @merged[m][:value]
      else
        raise 'Unknown key'
      end
    end

    private

    def merge_settings
      @merged = {}

      @defaults.each do |k, v|
        @merged[k] = { :value => v[:value], :scope => v[:scope] }

        if (template = Fiona::SettingTemplate.find_by_key("setting_#{k}"))
          @merged[k][:value] = template.value
        end
      end

      return all_settings
    end
  end

end


text:
package watodo.model.task;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

//@@author A0119505J
public class StatusTest {

    private static final String NOT_COMPLETED_MESSAGE = "(Task is incomplete)";
    private static final String COMPLETED_MESSAGE = "(Task is completed)";
    private static final String UNDEFINED_STATUS_MESSAGE = "An internal error has occured. Status not readable.";

    @Test
    public void isStatusLevel() {
        // invalid status cases
        Status testCase3 = new Status(2);
        assertTrue(testCase3.toString().equals(UNDEFINED_STATUS_MESSAGE));

        // valid status cases
        Status testCase1 = new Status(0);
        Status testCase2 = new Status(1);
        assertTrue(testCase1.toString().equals(NOT_COMPLETED_MESSAGE));
        assertTrue(testCase2.toString().equals(COMPLETED_MESSAGE));
        assertTrue(testCase1.isValidTransaction(1));
    }
}


text:
'''
The Splunk Software Development Kit for Solutions.
'''

from . import (
    acl,
    api_documenter,
    compression,
    conf_manager,
    credentials,
    file_monitor,
    hec_config,
    ip_math,
    log,
    metadata,
    net_utils,
    orphan_process_monitor,
    pattern,
    server_info,
    splunk_rest_client,
    splunkenv,
    time_parser,
    timer_queue,
    user_access,
    utils,
)

__all__ = ['acl',
           'api_documenter',
           'compression',
           'conf_manager',
           'credentials',
           'file_monitor',
           'hec_config',
           'ip_math',
           'log',
           'metadata',
           'net_utils',
           'orphan_process_monitor',
           'pattern',
           'server_info',
           'splunk_rest_client',
           'splunkenv',
           'time_parser',
           'timer_queue',
           'user_access',
           'utils']

__version__ = '1.0.17-dev.194'


text:
import React, { Component } from 'react';
import './Provide.css';

class Provide extends Component {
    render() {
        return (

Vous avez des solutions ?

Proposez-les pour ...

Gagner en visibilité

Organiser des évènements (conférence, réunion de travail, etc.)

Utiliser des outils de communication (forum, wiki, sondages, mailing-list, etc.)

Partager ces outils avec les autres solutions afin d'être complémentaires

Rester synchronisé avec Facebook, Meetup, DemocracyOS, Communecter, etc.

        );
    }
}

export default Provide;


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "ads_images".
 *
 * @property integer $id
 * @property integer $ad_id
 * @property string $path
 * @property integer $weight
 * @property integer $status
 *
 * @property Ad $ad
 */
class AdImage extends \yii\db\ActiveRecord
{
    const IMAGES_PATH = '/uploads/images/ads/';
    const IMAGE_SERVER_PATH = 'http://localhost/qway/web';

        /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'ads_images';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ad_id', 'path'], 'required'],
            [['ad_id', 'weight', 'status'], 'integer'],
            [['path'], 'string', 'max' => 256],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'ad_id' => 'Ad ID',
            'path' => 'Path',
            'weight' => 'Weight',
            'status' => 'Status',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAd()
    {
        return $this->hasOne(Ad::className(), ['id' => 'ad_id']);
    }
}


text:
package com.opengamma.analytics.financial.timeseries.util;

import org.apache.commons.lang.Validate;

import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.timeseries.date.DateDoubleTimeSeries;
import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries;

/**
 * Calculates a one-day percentage change series from a series of absolute changes.
 */
public class TimeSeriesPercentageChangeOperator extends Function1D<DateDoubleTimeSeries<?>, DateDoubleTimeSeries<?>> {

  @Override
  public DateDoubleTimeSeries<?> evaluate(final DateDoubleTimeSeries<?> ts) {
    Validate.notNull(ts, "time series");
    Validate.isTrue(ts.size() > 1, "time series length must be > 1");
    final int[] times = ts.timesArrayFast();
    final double[] values = ts.valuesArrayFast();
    final int n = times.length;
    final int[] resultTimes = new int[n - 1];
    final double[] percentageChanges = new double[n - 1];
    for (int i = 1; i < n; i++) {
      resultTimes[i - 1] = times[i];
      percentageChanges[i - 1] = (values[i] - values[i - 1]) / values[i - 1];
    }
    return ImmutableLocalDateDoubleTimeSeries.of(resultTimes, percentageChanges);
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="EmptyCollection">
        <attr name="message" format="string" />
        <attr name="name" format="string" />
        <attr name="icon" format="reference" />
    </declare-styleable>
</resources>


text:
#import "MCTComponentFramework.h"
#import "MCTGetServiceActionInfoRH.h"
#import "MCTIntent.h"

#define PICKLE_ACTION_KEY @"action"

@implementation MCTGetServiceActionInfoRH

+ (MCTGetServiceActionInfoRH *)responseHandlerWithHash:(NSString *)emailHash andAction:(NSString *)action
{
    MCTGetServiceActionInfoRH *rh = [[MCTGetServiceActionInfoRH alloc] init];
    rh.hashOrEmail = emailHash;
    rh.action = action;
    return rh;
}

- (void)handleError:(NSString *)error
{
    T_BIZZ();
    LOG(@"Error response for GetServiceActionInfo request: %@", error);
    MCTIntent *intent = [MCTIntent intentWithAction:kINTENT_SERVICE_ACTION_RETRIEVED];
    [intent setBool:NO forKey:@"success"];
    [intent setString:self.hashOrEmail forKey:@"hash"];
    [intent setString:self.action forKey:@"action"];
    [[MCTComponentFramework intentFramework] broadcastIntent:intent];
}

- (void)handleResult:(MCT_com_mobicage_to_service_GetServiceActionInfoResponseTO *)result
{
    T_BIZZ();
    LOG(@"Result received for GetServiceActionInfo request");
    MCTIntent *intent = [MCTIntent intentWithAction:kINTENT_SERVICE_ACTION_RETRIEVED];
    [intent setString:self.hashOrEmail forKey:@"hash"];
    [intent setString:self.action forKey:@"action"];
    [intent setLong:MCTFriendTypeService forKey:@"type"];

    [intent setString:result.avatar forKey:@"avatar"];
    [intent setString:result.name forKey:@"name"];
    [intent setString:result.email forKey:@"email"];
    if (![MCTUtils isEmptyOrWhitespaceString:result.descriptionX])
        [intent setString:result.descriptionX forKey:@"description"];
    if (![MCTUtils isEmptyOrWhitespaceString:result.descriptionBranding])
        [intent setString:result.descriptionBranding forKey:@"descriptionBranding"];
    if (![MCTUtils isEmptyOrWhitespaceString:result.actionDescription])
        [intent setString:result.actionDescription forKey:@"actionDescription"];
    if (![MCTUtils isEmptyOrWhitespaceString:result.qualifiedIdentifier])
        [intent setString:result.qualifiedIdentifier forKey:@"qualifiedIdentifier"];
    if (![MCTUtils isEmptyOrWhitespaceString:result.staticFlow])
        [intent setString:result.staticFlow forKey:@"staticFlow"];
    if (![MCTUtils isEmptyOrWhitespaceString:result.staticFlowHash])
        [intent setString:result.staticFlowHash forKey:@"staticFlowHash"];

    if (result.error) {
        [intent setBool:NO forKey:@"success"];
        [intent setString:result.error.message forKey:@"errorMessage"];
        [intent setString:result.error.title forKey:@"errorTitle"];
        [intent setString:result.error.action forKey:@"errorAction"];
        [intent setString:result.error.caption forKey:@"errorCaption"];
    } else {
        [intent setBool:YES forKey:@"success"];
    }

    [[MCTComponentFramework intentFramework] broadcastIntent:intent];

    for (NSString *staticFlowBranding in result.staticFlowBrandings) {
        [[MCTComponentFramework brandingMgr] queueGenericBranding:staticFlowBranding];
    }
}

- (id)initWithCoder:(NSCoder *)coder forClassVersion:(int)classVersion
{
    T_BACKLOG();
    if (self = [super initWithCoder:coder forClassVersion:classVersion]) {
        self.action = [coder decodeObjectForKey:PICKLE_ACTION_KEY];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
    T_BACKLOG();
    [super encodeWithCoder:coder];
    [coder encodeObject:self.action forKey:PICKLE_ACTION_KEY];
}

@end


text:
require 'fiber'

require_relative "thread_attr_accessor/version"
require_relative 'core_ext/thread/parent_thread'
require_relative 'core_ext/fiber/parent_fiber'
require_relative 'core_ext/fiber/storage'

# `extend` this module on your class/module to get per-thread class attribute
# accessors. Example:
#
# class MyClass
#   extend ThreadAttrAccessor
#
#   thread_attr_accessor :setting
# end
#
# MyClass.setting = :original
#
# threads = [
#   Thread.new { MyClass.setting = :foo; puts MyClass.setting },
#   Thread.new { MyClass.setting = :bar; puts MyClass.setting },
# ]
#
# threads.each(&:join)
# MyClass.setting == :original # true
module ThreadAttrAccessor
  def self.thread_accessor_key(base, name)
    "#{base.name}.#{name}"
  end

  class FiberStorage
    attr_reader :fiber, :thread
    def initialize(fiber = Fiber.current, thread = Thread.current)
      @fiber  = fiber
      @thread = thread
    end

    def [](key)
      fiber.fiber_variable_get(key)
    end

    def []=(key, value)
      fiber.fiber_variable_set(key, value)
      if fiber.parent_fiber.nil?
        thread.thread_variable_set(key, value)
      end

      value
    end

    def has_key?(key)
      fiber.fiber_variable?(key)
    end
  end

  class ThreadStorage
    attr_reader :thread
    def initialize(thread)
      @thread = thread
    end

    def [](key)
      thread.thread_variable_get(key)
    end

    def []=(key, value)
      thread.thread_variable_set(key, value)
    end

    def has_key?(key)
      !!thread.thread_variable_get(key)
    end
  end

  def self.search_in_ancestor_threads(key)
    fiber  = Fiber.current
    thread = Thread.current

    until fiber.nil?
      storage = FiberStorage.new(fiber, thread)

      if storage.has_key?(key)
        return storage[key]
      else
        fiber = fiber.parent_fiber
      end
    end

    until thread.nil?
      storage = ThreadStorage.new(thread)

      if storage.has_key?(key)
        return storage[key]
      else
        thread = thread.parent_thread
      end
    end

    nil
  end

  def self.extended(base)
    mod = Module.new

    unless base.const_defined?(:ThreadAttributeAccessors, false)
      base.const_set(:ThreadAttributeAccessors, mod)
      base.extend(mod)
    end
  end

  def thread_attr_writer(*names, private: false, **opts)
    mod = const_get(:ThreadAttributeAccessors)

    names.each do |name|
      thread_key = ThreadAttrAccessor.thread_accessor_key(self, name)

      mod.send(:define_method, "#{name}=") do |value|
        FiberStorage.new[thread_key] = value
        value
      end

      if private
        mod.send :private, "#{name}="
      end
    end
  end

  def thread_attr_reader(*names, default: nil, inherit: false, private: false, **opts)
    if default && inherit
      get_default = ->(thread_key) {
        ThreadAttrAccessor.search_in_ancestor_threads(thread_key) ||
        default.call
      }
    elsif inherit
      get_default = ThreadAttrAccessor.method(:search_in_ancestor_threads)
    elsif default
      get_default = ->(*) { default.call }
    end

    if get_default
      get_value = ->(thread_key) {
        storage = FiberStorage.new
        storage[thread_key] ||= get_default.call(thread_key)
      }
    else
      get_value = ->(thread_key) {
        FiberStorage.new[thread_key]
      }
    end

    mod = const_get(:ThreadAttributeAccessors)

    names.each do |name|
      thread_key = ThreadAttrAccessor.thread_accessor_key(self, name)

      mod.send(:define_method, name) do
        get_value.call(thread_key)
      end

      if private
        mod.send :private, name
      end
    end
  end

  def thread_attr_accessor(*names, private: false, **opts)
    private_reader = private.to_s == "reader" || private == true
    private_writer = private.to_s == "writer" || private == true

    thread_attr_reader(*names, private: private_reader, **opts)
    thread_attr_writer(*names, private: private_writer, **opts)
  end
end


text:
module HtmlMockup::Release::Processors
  class Mockup < Base

    attr_accessor :project

    def initialize(options={})
      @options = {
        :env => {},
        :match => ["**/*.{html,md,html.erb}"],
        :skip => [/\Astylesheets/, /\Ajavascripts/]
      }

      @options.update(options) if options
    end

    def call(release, options={})
      self.project = release.project

      options = {}.update(@options).update(options)

      options[:env].update("MOCKUP_PROJECT" => project)

      release.log(self, "Processing mockup files")

      release.log(self, "  Matching: #{options[:match].inspect}", true)
      release.log(self, "  Skiping : #{options[:skip].inspect}", true)
      release.log(self, "  Env     : #{options[:env].inspect}", true)
      release.log(self, "  Files   :", true)

      release.get_files(options[:match], options[:skip]).each do |file_path|
        release.log(self, "    Extract: #{file_path}", true)
        self.run_on_file!(file_path, options[:env])
      end
    end

    def run_on_file!(file_path, env = {})
      template = HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path)

      # Clean up source file
      FileUtils.rm(file_path)

      # Write out new file
      File.open(self.target_path(file_path, template),"w"){|f| f.write(template.render(env.dup)) }
    end

    # Runs the extractor on a single file and return processed source.
    def extract_source_from_file(file_path, env = {})
      HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path).render(env.dup)
    end

    protected

    def target_path(path, template)
      # 1. If we have a double extension we rip of the template it's own extension and be done with it
      parts = File.basename(path.to_s).split(".")
      dir = Pathname.new(File.dirname(path.to_s))

      # 2. Try to figure out the extension based on the template's mime-type
      mime_types = {
        "text/html" => "html",
        "text/css"  => "css",
        "application/javascript" => "js",
        "text/xml" => "xml",
        "application/xml" => "xml",
        "text/csv" => "csv",
        "application/json" => "json"
      }
      extension = mime_types[template.template.class.default_mime_type]

      # Always return .html directly as it will cause too much trouble otherwise
      if parts.last == "html"
        return path
      end

      if parts.size > 2
        # Strip extension
        dir + parts[0..-2].join(".")
      else
        return path if extension.nil?

        if parts.size > 1
          # Strip extension and replace with extension
          dir + (parts[0..-2] << extension).join(".")
        else
          # Let's just add the extension
          dir + (parts << extension).join(".")
        end
      end
    end

  end
end