text:
/*!
 * \file auto_scheduler/search_task.cc
 * \brief Meta information and hardware parameters for a search task.
 */

#include <dlpack/dlpack.h>
#include <tvm/auto_scheduler/search_task.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/registry.h>
#include <tvm/runtime/threading_backend.h>

#include <utility>

namespace tvm {
namespace auto_scheduler {

TVM_REGISTER_NODE_TYPE(HardwareParamsNode);
TVM_REGISTER_NODE_TYPE(SearchTaskNode);

HardwareParams::HardwareParams(int num_cores, int vector_unit_bytes, int cache_line_bytes,
                               int max_shared_memory_per_block, int max_local_memory_per_block,
                               int max_threads_per_block, int max_vthread_extent, int warp_size) {
  auto node = make_object<HardwareParamsNode>();
  node->num_cores = num_cores;
  node->vector_unit_bytes = vector_unit_bytes;
  node->cache_line_bytes = cache_line_bytes;
  node->max_shared_memory_per_block = max_shared_memory_per_block;
  node->max_local_memory_per_block = max_local_memory_per_block;
  node->max_threads_per_block = max_threads_per_block;
  node->max_vthread_extent = max_vthread_extent;
  node->warp_size = warp_size;
  data_ = std::move(node);
}

HardwareParams HardwareParamsNode::GetDefaultHardwareParams(const Target& target,
                                                            const Target& target_host) {
  // There is no use of target_host so no updates here in the function.
  const auto device_type = target->kind->device_type;
  if (device_type == kDLCPU) {
    return HardwareParams(tvm::runtime::threading::MaxConcurrency(), 64, 64, 0, 0, 0, 0, 0);
  } else if (device_type == kDLCUDA || device_type == kDLROCM) {
    auto dev = Device{static_cast<DLDeviceType>(device_type), 0};
    auto device_name = device_type == kDLCUDA ? "device_api.cuda" : "device_api.rocm";
    auto func = tvm::runtime::Registry::Get(device_name);
    ICHECK(func != nullptr) << "Cannot find CUDA device_api in registry";
    auto device_api = static_cast<tvm::runtime::DeviceAPI*>(((*func)()).operator void*());

    tvm::runtime::TVMRetValue ret;
    device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kMaxSharedMemoryPerBlock, &ret);
    int max_shared_memory_per_block = ret;

    // There is no explicit local memory limition in CUDA runtime,
    // so we can use INT32_MAX to disalbe the check on local_memory.
    int max_local_memory_per_block = INT32_MAX;

    device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kMaxThreadsPerBlock, &ret);
    int max_threads_per_block = ret;

    device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kWarpSize, &ret);
    int warp_size = ret;

    int max_vthread_extent = warp_size / 4;
    return HardwareParams(-1, 16, 64, max_shared_memory_per_block, max_local_memory_per_block,
                          max_threads_per_block, max_vthread_extent, warp_size);
  } else if (device_type == kDLMetal) {
    // Reference: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf
    // This setting looks working for Metal GPUs later than A10
    int max_shared_memory_per_block = 32 * 1024;
    int max_local_memory_per_block = INT32_MAX;  // skip the check on local memory
    int max_threads_per_block = 1024;
    int warp_size = 8;
    int max_vthread_extent = warp_size / 4;
    return HardwareParams(-1, 16, 64, max_shared_memory_per_block, max_local_memory_per_block,
                          max_threads_per_block, max_vthread_extent, warp_size);
  } else if (target->kind->device_type == kDLOpenCL) {
    if (target->GetAttr<String>("device", "") == "mali") {
      // We cannot use device API to get hardware attributes like CUDA,
      // because like Mali target is normally on the remote machine.
      int max_shared_memory_per_block = 32768;
      int max_local_memory_per_block = INT32_MAX;  // skip the check on local memory
      int max_threads_per_block = 256;
      int warp_size = 1;
      int max_vthread_extent = 1;
      return HardwareParams(-1, 16, 64, max_shared_memory_per_block, max_local_memory_per_block,
                            max_threads_per_block, max_vthread_extent, warp_size);
    } else {
      // add other opencl target
      auto dev = Device{static_cast<DLDeviceType>(device_type), 0};
      auto device_name = "device_api.opencl";
      auto func = tvm::runtime::Registry::Get(device_name);
      ICHECK(func != nullptr) << "Cannot find OpenCL device_api in registry";
      auto device_api = static_cast<tvm::runtime::DeviceAPI*>(((*func)()).operator void*());

      tvm::runtime::TVMRetValue ret;
      device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kMaxSharedMemoryPerBlock, &ret);
      int max_shared_memory_per_block = ret;

      int max_local_memory_per_block = INT32_MAX;

      device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kMaxThreadsPerBlock, &ret);
      int max_threads_per_block = ret;

      device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kWarpSize, &ret);
      int warp_size = ret;

      if (warp_size == 1) {
        LOG(WARNING)
            << "Warp size 1 is not recommended for OpenCL devices. Tuning might crash or stuck";
      }

      int max_vthread_extent = std::max(1, warp_size / 4);
      return HardwareParams(-1, 16, 64, max_shared_memory_per_block, max_local_memory_per_block,
                            max_threads_per_block, max_vthread_extent, warp_size);
    }
  } else if (device_type == kDLVulkan) {
    auto dev = Device{static_cast<DLDeviceType>(device_type), 0};
    auto device_name = "device_api.vulkan";
    auto func = tvm::runtime::Registry::Get(device_name);
    ICHECK(func != nullptr) << "Cannot find Vulkan device_api in registry";
    auto device_api = static_cast<tvm::runtime::DeviceAPI*>(((*func)()).operator void*());

    tvm::runtime::TVMRetValue ret;
    device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kMaxSharedMemoryPerBlock, &ret);
    int max_shared_memory_per_block = ret;

    int max_local_memory_per_block = INT32_MAX;

    device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kMaxThreadsPerBlock, &ret);
    int max_threads_per_block = ret;

    device_api->GetAttr(dev, tvm::runtime::DeviceAttrKind::kWarpSize, &ret);
    int warp_size = ret;

    int max_vthread_extent = std::max(1, warp_size / 4);

    return HardwareParams(-1, 16, 64, max_shared_memory_per_block, max_local_memory_per_block,
                          max_threads_per_block, max_vthread_extent, warp_size);
  } else {
    LOG(FATAL) << "No default hardware parameters for target: " << target;
  }
  return HardwareParams();
}

SearchTask::SearchTask(ComputeDAG compute_dag, String workload_key, Target target,
                       Target target_host, Optional<HardwareParams> hardware_params,
                       LayoutRewriteOption layout_rewrite_option, Array<String> task_input_names,
                       String desc) {
  CheckAndUpdateHostConsistency(&target, &target_host);
  auto node = make_object<SearchTaskNode>();
  node->compute_dag = std::move(compute_dag);
  node->workload_key = std::move(workload_key);
  node->desc = std::move(desc);
  node->target = std::move(target);
  node->target_host = std::move(target_host);
  if (hardware_params) {
    node->hardware_params = hardware_params.value();
  } else {
    node->hardware_params =
        HardwareParamsNode::GetDefaultHardwareParams(node->target, node->target_host);
  }
  node->layout_rewrite_option = layout_rewrite_option;
  node->task_input_names = std::move(task_input_names);
  data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("auto_scheduler.HardwareParams")
    .set_body_typed([](int num_cores, int vector_unit_bytes, int cache_line_bytes,
                       int max_shared_memory_per_block, int max_local_memory_per_block,
                       int max_threads_per_block, int max_vthread_extent, int warp_size) {
      return HardwareParams(num_cores, vector_unit_bytes, cache_line_bytes,
                            max_shared_memory_per_block, max_local_memory_per_block,
                            max_threads_per_block, max_vthread_extent, warp_size);
    });

TVM_REGISTER_GLOBAL("auto_scheduler.GetDefaultHardwareParams")
    .set_body_typed([](Target target, Target target_host) {
      return HardwareParamsNode::GetDefaultHardwareParams(target, target_host);
    });

TVM_REGISTER_GLOBAL("auto_scheduler.SearchTask")
    .set_body_typed([](ComputeDAG compute_dag, String workload_key, Target target,
                       Target target_host, Optional<HardwareParams> hardware_params,
                       int layout_rewrite_option, Array<String> task_input_names, String desc) {
      CheckAndUpdateHostConsistency(&target, &target_host);
      return SearchTask(compute_dag, workload_key, target, target_host, hardware_params,
                        LayoutRewriteOption(layout_rewrite_option), task_input_names, desc);
    });

}  // namespace auto_scheduler
}  // namespace tvm


text:
var common = require('../common');
var assert = require('assert');
var http = require('http');

// Simple test of Node's HTTP ServerResponse.statusCode
// ServerResponse.prototype.statusCode

var testsComplete = 0;
var tests = [200, 202, 300, 404, 500];
var testIdx = 0;

var s = http.createServer(function(req, res) {
  var t = tests[testIdx];
  res.writeHead(t, {'Content-Type': 'text/plain'});
  console.log('--\nserver: statusCode after writeHead: ' + res.statusCode);
  assert.equal(res.statusCode, t);
  res.end('hello world\n');
});

s.listen(common.PORT, nextTest);

function nextTest() {
  if (testIdx + 1 === tests.length) {
    return s.close();
  }
  var test = tests[testIdx];

  http.get({ port: common.PROXY_PORT }, function(response) {
    console.log('client: expected status: ' + test);
    console.log('client: statusCode: ' + response.statusCode);
    assert.equal(response.statusCode, test);
    response.on('end', function() {
      testsComplete++;
      testIdx += 1;
      nextTest();
    });
  });
}

process.on('exit', function() {
  assert.equal(4, testsComplete);
});

redpajama_set_name: RedPajamaGithub


text:
import {Command, flags} from '@heroku-cli/command'
import * as Heroku from '@heroku-cli/schema'
import cli from 'cli-ux'

import * as Kolkrabbi from '../../interfaces/kolkrabbi'
import * as git from '../../utils/git'
import {getPipeline} from '../../utils/pipelines'
import {createSourceBlob} from '../../utils/source'
import {displayAndExit} from '../../utils/test-run'
export default class CiRun extends Command {
  static description = 'run tests against current directory'

  static examples = [
    `$ heroku ci:run --app murmuring-headland-14719
`,
  ]

  static flags = {
    app: flags.string({char: 'a', description: 'app name'}),
    pipeline: flags.pipeline({required: false}),
  }

  async run() {
    const {flags} = this.parse(CiRun)
    const pipeline = await getPipeline(flags, this)
    const commit = await git.readCommit('HEAD')

    cli.action.start('Preparing source')
    const sourceBlobUrl = await createSourceBlob(commit.ref, this)
    cli.action.stop()

    cli.action.start('Starting test run')
    const {body: pipelineRepository} = await this.heroku.get<Kolkrabbi.KolkrabbiApiPipelineRepositories>(`https://kolkrabbi.heroku.com/pipelines/${pipeline.id}/repository`)
    const organization = pipelineRepository.organization && pipelineRepository.organization.name
    const {body: testRun} = await this.heroku.post<Heroku.TestRun>('/test-runs', {body: {
      commit_branch: commit.branch,
      commit_message: commit.message,
      commit_sha: commit.ref,
      pipeline: pipeline.id,
      organization,
      source_blob_url: sourceBlobUrl,
    },
    })
    cli.action.stop()

    await displayAndExit(pipeline, testRun.number!, this)
  }
}


text:
package com.amazonaws.services.config.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PutRemediationConfigurationsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Returns a list of failed remediation batch objects.
     *

     */
    private com.amazonaws.internal.SdkInternalList<FailedRemediationBatch> failedBatches;

    /**
     *

     * Returns a list of failed remediation batch objects.
     *

     *
     * @return Returns a list of failed remediation batch objects.
     */

    public java.util.List<FailedRemediationBatch> getFailedBatches() {
        if (failedBatches == null) {
            failedBatches = new com.amazonaws.internal.SdkInternalList<FailedRemediationBatch>();
        }
        return failedBatches;
    }

    /**
     *

     * Returns a list of failed remediation batch objects.
     *

     *
     * @param failedBatches
     *        Returns a list of failed remediation batch objects.
     */

    public void setFailedBatches(java.util.Collection<FailedRemediationBatch> failedBatches) {
        if (failedBatches == null) {
            this.failedBatches = null;
            return;
        }

        this.failedBatches = new com.amazonaws.internal.SdkInternalList<FailedRemediationBatch>(failedBatches);
    }

    /**
     *

     * Returns a list of failed remediation batch objects.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setFailedBatches(java.util.Collection)} or {@link #withFailedBatches(java.util.Collection)} if you want
     * to override the existing values.
     *

     *
     * @param failedBatches
     *        Returns a list of failed remediation batch objects.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutRemediationConfigurationsResult withFailedBatches(FailedRemediationBatch... failedBatches) {
        if (this.failedBatches == null) {
            setFailedBatches(new com.amazonaws.internal.SdkInternalList<FailedRemediationBatch>(failedBatches.length));
        }
        for (FailedRemediationBatch ele : failedBatches) {
            this.failedBatches.add(ele);
        }
        return this;
    }

    /**
     *

     * Returns a list of failed remediation batch objects.
     *

     *
     * @param failedBatches
     *        Returns a list of failed remediation batch objects.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutRemediationConfigurationsResult withFailedBatches(java.util.Collection<FailedRemediationBatch> failedBatches) {
        setFailedBatches(failedBatches);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getFailedBatches() != null)
            sb.append("FailedBatches: ").append(getFailedBatches());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PutRemediationConfigurationsResult == false)
            return false;
        PutRemediationConfigurationsResult other = (PutRemediationConfigurationsResult) obj;
        if (other.getFailedBatches() == null ^ this.getFailedBatches() == null)
            return false;
        if (other.getFailedBatches() != null && other.getFailedBatches().equals(this.getFailedBatches()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getFailedBatches() == null) ? 0 : getFailedBatches().hashCode());
        return hashCode;
    }

    @Override
    public PutRemediationConfigurationsResult clone() {
        try {
            return (PutRemediationConfigurationsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package org.bouncycastle.cms;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.bouncycastle.asn1.kisa.KISAObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.ntt.NTTObjectIdentifiers;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.sec.SECObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;

public class CMSAlgorithm
{
    public static final ASN1ObjectIdentifier  DES_CBC         = OIWObjectIdentifiers.desCBC;
    public static final ASN1ObjectIdentifier  DES_EDE3_CBC    = PKCSObjectIdentifiers.des_EDE3_CBC;
    public static final ASN1ObjectIdentifier  RC2_CBC         = PKCSObjectIdentifiers.RC2_CBC;
    public static final ASN1ObjectIdentifier  IDEA_CBC        = new ASN1ObjectIdentifier("1.3.6.1.4.1.188.7.1.1.2");
    public static final ASN1ObjectIdentifier  CAST5_CBC       = new ASN1ObjectIdentifier("1.2.840.113533.7.66.10");

    public static final ASN1ObjectIdentifier  AES128_CBC      = NISTObjectIdentifiers.id_aes128_CBC;
    public static final ASN1ObjectIdentifier  AES192_CBC      = NISTObjectIdentifiers.id_aes192_CBC;
    public static final ASN1ObjectIdentifier  AES256_CBC      = NISTObjectIdentifiers.id_aes256_CBC;
    public static final ASN1ObjectIdentifier  AES128_CCM      = NISTObjectIdentifiers.id_aes128_CCM;
    public static final ASN1ObjectIdentifier  AES192_CCM      = NISTObjectIdentifiers.id_aes192_CCM;
    public static final ASN1ObjectIdentifier  AES256_CCM      = NISTObjectIdentifiers.id_aes256_CCM;
    public static final ASN1ObjectIdentifier  AES128_GCM      = NISTObjectIdentifiers.id_aes128_GCM;
    public static final ASN1ObjectIdentifier  AES192_GCM      = NISTObjectIdentifiers.id_aes192_GCM;
    public static final ASN1ObjectIdentifier  AES256_GCM      = NISTObjectIdentifiers.id_aes256_GCM;

    public static final ASN1ObjectIdentifier  CAMELLIA128_CBC = NTTObjectIdentifiers.id_camellia128_cbc;
    public static final ASN1ObjectIdentifier  CAMELLIA192_CBC = NTTObjectIdentifiers.id_camellia192_cbc;
    public static final ASN1ObjectIdentifier  CAMELLIA256_CBC = NTTObjectIdentifiers.id_camellia256_cbc;
    public static final ASN1ObjectIdentifier  SEED_CBC        = KISAObjectIdentifiers.id_seedCBC;

    public static final ASN1ObjectIdentifier  DES_EDE3_WRAP   = PKCSObjectIdentifiers.id_alg_CMS3DESwrap;
    public static final ASN1ObjectIdentifier  AES128_WRAP     = NISTObjectIdentifiers.id_aes128_wrap;
    public static final ASN1ObjectIdentifier  AES192_WRAP     = NISTObjectIdentifiers.id_aes192_wrap;
    public static final ASN1ObjectIdentifier  AES256_WRAP     = NISTObjectIdentifiers.id_aes256_wrap;
    public static final ASN1ObjectIdentifier  CAMELLIA128_WRAP = NTTObjectIdentifiers.id_camellia128_wrap;
    public static final ASN1ObjectIdentifier  CAMELLIA192_WRAP = NTTObjectIdentifiers.id_camellia192_wrap;
    public static final ASN1ObjectIdentifier  CAMELLIA256_WRAP = NTTObjectIdentifiers.id_camellia256_wrap;
    public static final ASN1ObjectIdentifier  SEED_WRAP       = KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap;

    public static final ASN1ObjectIdentifier  ECDH_SHA1KDF    = X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme;
    public static final ASN1ObjectIdentifier  ECCDH_SHA1KDF    = X9ObjectIdentifiers.dhSinglePass_cofactorDH_sha1kdf_scheme;
    public static final ASN1ObjectIdentifier  ECMQV_SHA1KDF   = X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme;

    public static final ASN1ObjectIdentifier  ECDH_SHA224KDF    = SECObjectIdentifiers.dhSinglePass_stdDH_sha224kdf_scheme;
    public static final ASN1ObjectIdentifier  ECCDH_SHA224KDF    = SECObjectIdentifiers.dhSinglePass_cofactorDH_sha224kdf_scheme;
    public static final ASN1ObjectIdentifier  ECMQV_SHA224KDF   = SECObjectIdentifiers.mqvSinglePass_sha224kdf_scheme;

    public static final ASN1ObjectIdentifier  ECDH_SHA256KDF    = SECObjectIdentifiers.dhSinglePass_stdDH_sha256kdf_scheme;
    public static final ASN1ObjectIdentifier  ECCDH_SHA256KDF    = SECObjectIdentifiers.dhSinglePass_cofactorDH_sha256kdf_scheme;
    public static final ASN1ObjectIdentifier  ECMQV_SHA256KDF   = SECObjectIdentifiers.mqvSinglePass_sha256kdf_scheme;

    public static final ASN1ObjectIdentifier  ECDH_SHA384KDF    = SECObjectIdentifiers.dhSinglePass_stdDH_sha384kdf_scheme;
    public static final ASN1ObjectIdentifier  ECCDH_SHA384KDF    = SECObjectIdentifiers.dhSinglePass_cofactorDH_sha384kdf_scheme;
    public static final ASN1ObjectIdentifier  ECMQV_SHA384KDF   = SECObjectIdentifiers.mqvSinglePass_sha384kdf_scheme;

    public static final ASN1ObjectIdentifier  ECDH_SHA512KDF    = SECObjectIdentifiers.dhSinglePass_stdDH_sha512kdf_scheme;
    public static final ASN1ObjectIdentifier  ECCDH_SHA512KDF    = SECObjectIdentifiers.dhSinglePass_cofactorDH_sha512kdf_scheme;
    public static final ASN1ObjectIdentifier  ECMQV_SHA512KDF   = SECObjectIdentifiers.mqvSinglePass_sha512kdf_scheme;

    public static final ASN1ObjectIdentifier  SHA1 = OIWObjectIdentifiers.idSHA1;
    public static final ASN1ObjectIdentifier  SHA224 = NISTObjectIdentifiers.id_sha224;
    public static final ASN1ObjectIdentifier  SHA256 = NISTObjectIdentifiers.id_sha256;
    public static final ASN1ObjectIdentifier  SHA384 = NISTObjectIdentifiers.id_sha384;
    public static final ASN1ObjectIdentifier  SHA512 = NISTObjectIdentifiers.id_sha512;
    public static final ASN1ObjectIdentifier  MD5 = PKCSObjectIdentifiers.md5;
    public static final ASN1ObjectIdentifier  GOST3411 = CryptoProObjectIdentifiers.gostR3411;
    public static final ASN1ObjectIdentifier  RIPEMD128 = TeleTrusTObjectIdentifiers.ripemd128;
    public static final ASN1ObjectIdentifier  RIPEMD160 = TeleTrusTObjectIdentifiers.ripemd160;
    public static final ASN1ObjectIdentifier  RIPEMD256 = TeleTrusTObjectIdentifiers.ripemd256;

}


text:
{% extends 'base_AdminLTE.html' %}

{% block title %}Docklet | History{% endblock %}

{% block panel_title %}History of
{{ vnode_name }}
{% endblock %}

{% block panel_list %}

      Home

      History

      History of Vnode

{% endblock %}

{% block css_src %}
<link href="/static/dist/css/flotconfig.css" rel="stylesheet">
{% endblock %}

{% block content %}

History

         <button type="button" class="btn btn-box-tool" data-widget="collapse">
         </button>
         <button type="button" class="btn btn-box-tool" data-widget="remove"></button>

                        History ID
                        Action
                        Running Time
                        Cpu Time
                        Billing
                        Action Time

                      {% for record in history %}

                      {{ record['id'] }}
                      {{ record['action'] }}
                      {{ record['runningtime'] }} seconds
                      {{ record['cputime'] }} seconds
                      {{ record['billing'] }} beans
                      {{ record['actionTime'] }}

                      {% endfor %}

{% endblock %}

{% block script_src %}

{% endblock %}


text:
use std::ptr;
use std::sync::Arc;
use ash::vk;
use ash::version::DeviceV1_0;
use smallvec::SmallVec;

use command::{CommandBuffer, SubpassCommandBuffer};
use hal::pool;
use {Backend, RawDevice};

pub struct RawCommandPool {
    pub(crate) raw: vk::CommandPool,
    pub(crate) device: Arc<RawDevice>,
}

impl pool::RawCommandPool<Backend> for RawCommandPool {
    fn reset(&mut self) {
        unsafe {
            self.device.0.fp_v1_0().reset_command_pool(
                self.device.0.handle(),
                self.raw,
                vk::CommandPoolResetFlags::empty()
            );
        }
    }

    fn allocate(&mut self, num: usize) -> Vec<CommandBuffer> {
        let info = vk::CommandBufferAllocateInfo {
            s_type: vk::StructureType::CommandBufferAllocateInfo,
            p_next: ptr::null(),
            command_pool: self.raw,
            level: vk::CommandBufferLevel::Primary,
            command_buffer_count: num as u32,
        };

        let device = &self.device;
        let cbufs_raw = unsafe {
            device.0.allocate_command_buffers(&info)
        }.expect("Error on command buffer allocation");

        cbufs_raw
            .into_iter()
            .map(|buffer| {
                CommandBuffer {
                    raw: buffer,
                    device: device.clone(),
                }
            }).collect()
    }

    unsafe fn free(&mut self, cbufs: Vec<CommandBuffer>) {
        let buffers: SmallVec<[vk::CommandBuffer; 16]> =
            cbufs.into_iter()
                 .map(|buffer| buffer.raw)
                 .collect();
        self.device.0.free_command_buffers(self.raw, &buffers);
    }
}

pub struct SubpassCommandPool {
    _pool: vk::CommandPool,
    _command_buffers: Vec<SubpassCommandBuffer>,
    _next_buffer: usize,
    _device: Arc<RawDevice>,
}

impl pool::SubpassCommandPool<Backend> for SubpassCommandPool { }


text:
package prompt

import (
	"syscall"
)

const (
	tcgets  = syscall.TIOCGETA
	tcsets  = syscall.TIOCSETA
	tcsetsf = syscall.TIOCSETAF
)


text:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;

public class CountWorkingDays {

    public static void main(String[] args) throws ParseException {
        Scanner scanner = new Scanner(System.in);

        SimpleDateFormat parser = new SimpleDateFormat("dd-M-yyyy");
        Date startDate = parser.parse(scanner.nextLine());
        Date endDate = parser.parse(scanner.nextLine());

        SimpleDateFormat parser2 = new SimpleDateFormat("dd-M");

        Date[] holidays = new Date[11];
        holidays[0] = parser2.parse("01-01");
        holidays[1] = parser2.parse("03-03");
        holidays[2] = parser2.parse("01-05");
        holidays[3] = parser2.parse("06-05");
        holidays[4] = parser2.parse("24-05");
        holidays[5] = parser2.parse("06-09");
        holidays[6] = parser2.parse("22-09");
        holidays[7] = parser2.parse("01-10");
        holidays[8] = parser2.parse("24-12");
        holidays[9] = parser2.parse("25-12");
        holidays[10] = parser2.parse("26-12");

        int workingDays = 0;

        for(Date date = startDate; date.before(addDays(endDate, 1)); date = addDays(date, 1)){

            boolean isHoliday = false;

            for (Date holiday : holidays) {
                holiday = setHoliday(date, holiday);
                if(date.compareTo(holiday) == 0){
                    isHoliday = true;
                    break;
                }
            }

            if(!isHoliday){
                if(!isWeekend(date) && !isHoliday){
                    workingDays++;
                }
            }
        }
        System.out.println(workingDays);
    }

    private static Date setHoliday(Date date, Date holiday) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(holiday);

        int year = cal1.get(Calendar.YEAR);
        int month = cal2.get(Calendar.MONTH);
        int day = cal2.get(Calendar.DATE);

        cal2.set(year, month,day);

        return cal2.getTime();

    }

    private static boolean isWeekend(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayOfWeek == 7 || dayOfWeek == 1){
            return true;
        } else {
            return false;
        }
    }

    public static Date addDays(Date date, int days){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }
}


text:
Given(/^I touch the add marker CTA$/) do
  find("#marker-cta").click
end

Given(/^I click on the map$/) do
  page.find("#map").click # Write code here that turns the phrase above into concrete actions
end

Then(/^I should see "([^"]*)" when it loads$/) do |arg1|
  wait_for_ajax
  wait_until { page.has_content?(arg1)}
  if page.respond_to? :should
    page.should have_content(arg1)
  else
    assert page.has_content?(arg1)
  end
end

def wait_until
  require "timeout"
  Timeout.timeout(Capybara.default_max_wait_time) do
    sleep(0.1) until value = yield
    value
  end
end

def wait_for_ajax
  Timeout.timeout(Capybara.default_max_wait_time) do
    loop until finished_all_ajax_requests?
  end
end

def finished_all_ajax_requests?
    page.evaluate_script('jQuery.active').zero?
end


text:
/*
 * @author Kayla
 * @date 11/13/2015
 */
var AttackHandler = Java.type('org.virtue.game.entity.combat.impl.AttackHandler');
var AttackInfo = Java.type('org.virtue.game.entity.combat.AttackInfo');
var AttackEvent = Java.type('org.virtue.game.entity.combat.AttackEvent');
var SwitchAttack = Java.type('org.virtue.game.entity.combat.impl.combo.SwitchAttack');
var SwitchAttackEvent = Java.type('org.virtue.game.entity.combat.impl.combo.SwitchAttackEvent');
var MeleeAttackHandler = Java.extend(Java.type('org.virtue.game.entity.combat.impl.melee.MeleeAttackHandler'));
var CombatStyle = Java.type('org.virtue.game.entity.combat.CombatStyle');
var AbstractNPC = Java.type('org.virtue.game.entity.npc.AbstractNPC');
var Projectile = Java.type('org.virtue.game.world.region.zone.Projectile');

var MELEE = new MeleeAttackHandler(500, 1000) {
	getAttackInfo: function(entity, lock) {
		return AttackInfo.create(entity, new AnimationBlock(16204), null, Java.super(MELEE).impact(entity, lock, CombatStyle.MELEE, null, null));
	}
};

var RANGE = new MeleeAttackHandler(750, 1000) {
	getAttackInfo: function(entity, lock) {
		var info = AttackInfo.create(entity, new AnimationBlock(16202), new SpotAnimationBlock(1, 2994),
						Java.super(RANGE).impact(entity, lock, CombatStyle.RANGE, new SpotAnimationBlock(2, 3000), null));
		info.setEvent(function(e, l) {
		});
		return info;
	}
};

var MAGIC = new MeleeAttackHandler(750, 1000) {
	getAttackInfo: function(entity, lock) {
		var info = AttackInfo.create(entity, new AnimationBlock(16195), new SpotAnimationBlock(1, 2995),
						Java.super(MAGIC).impact(entity, lock, CombatStyle.MAGIC, null, new Projectile(2984, 35, 72, 16, 58, 32)));
		info.setEvent(function(e, l) {
		});
		return info;
	}
};

var Jad = Java.extend(AbstractNPC);

var TzTokJad = function(id, tile) {

	var attackHandler = new SwitchAttackEvent(
						new SwitchAttack(CombatStyle.MELEE, MELEE),
						new SwitchAttack(CombatStyle.RANGE, RANGE),
						new SwitchAttack(CombatStyle.MAGIC, MAGIC));

	return new Jad(id, tile) {

		newInstance : function(id, tile) {
			return TzTokJad(id, tile);
		},

		getNextAttack : function(lock) {
			return attackHandler;
		},

		getIds : function() {
			return [2745];
		},
	}

};

var listen = function(scriptManager) {
	TzTokJad(2745, null).register();
};


text:
[![Our Facebook Page](http://leoraw.com/zib/wp-content/uploads/2010/08/like_fb.gif)](https://www.facebook.com/nusfunbot)

## Who will benefit from our project?

:large_orange_diamond:Nus Students and maybe others.

## Define what is the problem you are solving?
Thousands of basic requests are sent to nus teachers and offices everyday though some of the info can certainly be found on the nus website. This creates a wastage of time and effort of the teachers and offices even when the same question is repeated by different student. Hence, using NLP and modern messaging platform, this bot we are creating will be able to answer these requests and automatically respond to the sender saving time for offices and teacher to respond to more personal questions.

## Define user stories
Users want to know whether CS3217 is available next sem and the procedure to apply for it. Usually, users will go on IVLE or NUSmods to find out which might take a lot of time or even email the professors. Instead of doing this, users will just message the bot and all the info will be sent to user. Simple and fast. Definitely better than google.
Our implemented features so far:
- [x] exam date
- [x] class location
- [x] module cors bidding stats
- [x] module description
- [x] professor's email address
- [x] location
- [x] bidding rounds alert
- [x] can tell you a random joke
- [ ] ~~recognize song~~
- [ ] etc :shipit:

## Does your proposed features make for a good Minimum Viable Product (MVP)?
At first, for our MVP, we will just create a facebook bot that is able to handle requests about modules. Further info and database will be needed to scale the project but it provides a good environment to test the users' experience and get their feedbacks.

*Update 1*: Basic requests about modules, classes, and location in NUS have been handled. Our next improved MVP will be able to search for teachers' info (eg. modules taught and email), and maybe bidding queries

*Update 2*: Bot is online with an online mongodb database.
          Requests about modules: classes, exam, description, cors history, lectures are handled.
          Requests about location inside and outside NUS are handled.
          Requests about professors' details and emails are handled.
          Reminder for CORS bidding is integrated.

## How you plan to achieve the end product through the remaining sprints:
We have the echo bot and the AI engine. Next step should be to connect them with nusmods api to get the modules database.

*Update 1*: Module database has been retrieved from nusmods and basic modules queries have been handle. By the next milestone, hopefully we can finish the MVP

*Update 2*: We are thinking of a new way of doing confessions. Users will be able to anonymously message any fb account through our bot. They can also broadcast the message to anyone who subscribed to our bot
## Draft out a clear plan for satisfying the Orbital requirements in terms of time contributed for the remaining sprints.
After finishing the MVP, we will test our bot with students from NUS. Only then we'll know what to do to perfect our product.

*Update*: We have already launch our test with the nus students. Bugs are identified and fixed everyday and we are intensively working on new features. I think we are on a ~~good~~ very good track:heavy_exclamation_mark:


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('cameras', '0002_auto_20151202_1520'),
    ]

    operations = [
        migrations.AlterField(
            model_name='camera',
            name='network',
            field=models.OneToOneField(null=True, blank=True, to='apps.NetworkInfo'),
        ),
    ]


text:
package com.hazelcast.quorum.lock;

import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.ILock;
import com.hazelcast.quorum.BaseQuorumListenerTest;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.concurrent.CountDownLatch;

@RunWith(HazelcastSerialClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class LockQuorumListenerTest extends BaseQuorumListenerTest {

    @Test
    public void testQuorumFailureEventFiredWhenNodeCountBelowThreshold() {
        CountDownLatch quorumNotPresent = new CountDownLatch(1);
        String lockName = randomString();
        Config config = addQuorum(new Config(), lockName, quorumListener(null, quorumNotPresent));
        HazelcastInstance instance = createHazelcastInstance(config);
        ILock q = instance.getLock(lockName);
        try {
            q.lock();
        } catch (Exception expected) {
            expected.printStackTrace();
        }
        assertOpenEventually(quorumNotPresent, 15);
    }

    @Override
    protected void addQuorumConfig(Config config, String distributedObjectName, String quorumName) {
        config.getLockConfig(distributedObjectName).setQuorumName(quorumName);
    }
}


text:
using Boxing.Contracts.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Boxing.Contracts.Requests.Users
{
    public class GetUserRequest : IRequest<UserDto>
    {
        public string Username { get; set; }
    }
}


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

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.client.JobExecutionException;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.execution.librarycache.BlobLibraryCacheManager;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.highavailability.RunningJobsRegistry;
import org.apache.flink.runtime.highavailability.RunningJobsRegistry.JobSchedulingStatus;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobmanager.OnCompletionActions;
import org.apache.flink.runtime.leaderelection.LeaderContender;
import org.apache.flink.runtime.leaderelection.LeaderElectionService;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.metrics.groups.JobManagerMetricGroup;
import org.apache.flink.runtime.metrics.util.MetricUtils;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.RpcService;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;

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

import javax.annotation.Nullable;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * The runner for the job manager. It deals with job level leader election and make underlying job manager
 * properly reacted.
 */
public class JobManagerRunner implements LeaderContender, OnCompletionActions, FatalErrorHandler {

	private static final Logger log = LoggerFactory.getLogger(JobManagerRunner.class);

	// ------------------------------------------------------------------------

	/** Lock to ensure that this runner can deal with leader election event and job completion notifies simultaneously. */
	private final Object lock = new Object();

	/** The job graph needs to run. */
	private final JobGraph jobGraph;

	/** The listener to notify once the job completes - either successfully or unsuccessfully. */
	private final OnCompletionActions toNotifyOnComplete;

	/** The handler to call in case of fatal (unrecoverable) errors. */
	private final FatalErrorHandler errorHandler;

	/** Used to check whether a job needs to be run. */
	private final RunningJobsRegistry runningJobsRegistry;

	/** Leader election for this job. */
	private final LeaderElectionService leaderElectionService;

	private final JobManagerServices jobManagerServices;

	private final JobMaster jobManager;

	private final JobManagerMetricGroup jobManagerMetricGroup;

	private final Time timeout;

	/** flag marking the runner as shut down. */
	private volatile boolean shutdown;

	// ------------------------------------------------------------------------

	/**
	 * Exceptions that occur while creating the JobManager or JobManagerRunner are directly
	 * thrown and not reported to the given {@code FatalErrorHandler}.
	 *
	 *
This JobManagerRunner assumes that it owns the given {@code JobManagerServices}.
	 * It will shut them down on error and on calls to {@link #shutdown()}.
	 *
	 * @throws Exception Thrown if the runner cannot be set up, because either one of the
	 *                   required services could not be started, ot the Job could not be initialized.
	 */
	public JobManagerRunner(
			final ResourceID resourceId,
			final JobGraph jobGraph,
			final Configuration configuration,
			final RpcService rpcService,
			final HighAvailabilityServices haServices,
			final HeartbeatServices heartbeatServices,
			final JobManagerServices jobManagerServices,
			final MetricRegistry metricRegistry,
			final OnCompletionActions toNotifyOnComplete,
			final FatalErrorHandler errorHandler,
			@Nullable final String restAddress) throws Exception {

		JobManagerMetricGroup jobManagerMetrics = null;

		// make sure we cleanly shut down out JobManager services if initialization fails
		try {
			this.jobGraph = checkNotNull(jobGraph);
			this.toNotifyOnComplete = checkNotNull(toNotifyOnComplete);
			this.errorHandler = checkNotNull(errorHandler);
			this.jobManagerServices = checkNotNull(jobManagerServices);

			checkArgument(jobGraph.getNumberOfVertices() > 0, "The given job is empty");

			final String hostAddress = rpcService.getAddress().isEmpty() ? "localhost" : rpcService.getAddress();
			jobManagerMetrics = MetricUtils.instantiateJobManagerMetricGroup(metricRegistry, hostAddress);
			this.jobManagerMetricGroup = jobManagerMetrics;

			// libraries and class loader first
			final BlobLibraryCacheManager libraryCacheManager = jobManagerServices.libraryCacheManager;
			try {
				libraryCacheManager.registerJob(
						jobGraph.getJobID(), jobGraph.getUserJarBlobKeys(), jobGraph.getClasspaths());
			} catch (IOException e) {
				throw new Exception("Cannot set up the user code libraries: " + e.getMessage(), e);
			}

			final ClassLoader userCodeLoader = libraryCacheManager.getClassLoader(jobGraph.getJobID());
			if (userCodeLoader == null) {
				throw new Exception("The user code class loader could not be initialized.");
			}

			// high availability services next
			this.runningJobsRegistry = haServices.getRunningJobsRegistry();
			this.leaderElectionService = haServices.getJobManagerLeaderElectionService(jobGraph.getJobID());

			// now start the JobManager
			this.jobManager = new JobMaster(
				rpcService,
				resourceId,
				jobGraph,
				configuration,
				haServices,
				heartbeatServices,
				jobManagerServices.executorService,
				jobManagerServices.blobServer,
				jobManagerServices.libraryCacheManager,
				jobManagerServices.restartStrategyFactory,
				jobManagerServices.rpcAskTimeout,
				jobManagerMetrics,
				this,
				this,
				userCodeLoader,
				restAddress,
				metricRegistry.getMetricQueryServicePath());

			this.timeout = jobManagerServices.rpcAskTimeout;
		}
		catch (Throwable t) {
			// clean up everything
			if (jobManagerMetrics != null) {
				jobManagerMetrics.close();
			}

			throw new JobExecutionException(jobGraph.getJobID(), "Could not set up JobManager", t);
		}
	}

	//----------------------------------------------------------------------------------------------
	// Getter
	//----------------------------------------------------------------------------------------------

	public JobMasterGateway getJobManagerGateway() {
		return jobManager.getSelfGateway(JobMasterGateway.class);
	}

	//----------------------------------------------------------------------------------------------
	// Lifecycle management
	//----------------------------------------------------------------------------------------------

	public void start() throws Exception {
		try {
			leaderElectionService.start(this);
		}
		catch (Exception e) {
			log.error("Could not start the JobManager because the leader election service did not start.", e);
			throw new Exception("Could not start the leader election service.", e);
		}
	}

	public void shutdown() throws Exception {
		shutdownInternally().get();
	}

	private CompletableFuture<Void> shutdownInternally() {
		synchronized (lock) {
			shutdown = true;

			jobManager.shutDown();

			return jobManager.getTerminationFuture()
				.thenAccept(
					ignored -> {
						Throwable exception = null;
						try {
							leaderElectionService.stop();
						} catch (Throwable t) {
							exception = ExceptionUtils.firstOrSuppressed(t, exception);
						}

						// make all registered metrics go away
						try {
							jobManagerMetricGroup.close();
						} catch (Throwable t) {
							exception = ExceptionUtils.firstOrSuppressed(t, exception);
						}

						if (exception != null) {
							throw new CompletionException(new FlinkException("Could not properly shut down the JobManagerRunner.", exception));
						}
					});
		}
	}

	//----------------------------------------------------------------------------------------------
	// Result and error handling methods
	//----------------------------------------------------------------------------------------------

	/**
	 * Job completion notification triggered by JobManager.
	 */
	@Override
	public void jobFinished(JobExecutionResult result) {
		try {
			unregisterJobFromHighAvailability();
			shutdownInternally();
		}
		finally {
			if (toNotifyOnComplete != null) {
				toNotifyOnComplete.jobFinished(result);
			}
		}
	}

	/**
	 * Job completion notification triggered by JobManager.
	 */
	@Override
	public void jobFailed(Throwable cause) {
		try {
			unregisterJobFromHighAvailability();
			shutdownInternally();
		}
		finally {
			if (toNotifyOnComplete != null) {
				toNotifyOnComplete.jobFailed(cause);
			}
		}
	}

	/**
	 * Job completion notification triggered by self.
	 */
	@Override
	public void jobFinishedByOther() {
		try {
			shutdownInternally();
		}
		finally {
			if (toNotifyOnComplete != null) {
				toNotifyOnComplete.jobFinishedByOther();
			}
		}
	}

	/**
	 * Job completion notification triggered by JobManager or self.
	 */
	@Override
	public void onFatalError(Throwable exception) {
		// we log first to make sure an explaining message goes into the log
		// we even guard the log statement here to increase chances that the error handler
		// gets the notification on hard critical situations like out-of-memory errors
		try {
			log.error("JobManager runner encountered a fatal error.", exception);
		} catch (Throwable ignored) {}

		// in any case, notify our handler, so it can react fast
		try {
			if (errorHandler != null) {
				errorHandler.onFatalError(exception);
			}
		}
		finally {
			// the shutdown may not even needed any more, if the fatal error
			// handler kills the process. that is fine, a process kill cleans up better than anything.
			shutdownInternally();
		}
	}

	/**
	 * Marks this runner's job as not running. Other JobManager will not recover the job
	 * after this call.
	 *
	 *
This method never throws an exception.
	 */
	private void unregisterJobFromHighAvailability() {
		try {
			runningJobsRegistry.setJobFinished(jobGraph.getJobID());
		}
		catch (Throwable t) {
			log.error("Could not un-register from high-availability services job {} ({})." +
					"Other JobManager's may attempt to recover it and re-execute it.",
					jobGraph.getName(), jobGraph.getJobID(), t);
		}
	}

	//----------------------------------------------------------------------------------------------
	// Leadership methods
	//----------------------------------------------------------------------------------------------

	@Override
	public void grantLeadership(final UUID leaderSessionID) {
		synchronized (lock) {
			if (shutdown) {
				log.info("JobManagerRunner already shutdown.");
				return;
			}

			log.info("JobManager runner for job {} ({}) was granted leadership with session id {} at {}.",
				jobGraph.getName(), jobGraph.getJobID(), leaderSessionID, getAddress());

			// The operation may be blocking, but since this runner is idle before it been granted the leadership,
			// it's okay that job manager wait for the operation complete
			leaderElectionService.confirmLeaderSessionID(leaderSessionID);

			final JobSchedulingStatus schedulingStatus;
			try {
				schedulingStatus = runningJobsRegistry.getJobSchedulingStatus(jobGraph.getJobID());
			}
			catch (Throwable t) {
				log.error("Could not access status (running/finished) of job {}. ", jobGraph.getJobID(), t);
				onFatalError(t);
				return;
			}

			if (schedulingStatus == JobSchedulingStatus.DONE) {
				log.info("Granted leader ship but job {} has been finished. ", jobGraph.getJobID());
				jobFinishedByOther();
				return;
			}

			// Double check the leadership after we confirm that, there is a small chance that multiple
			// job managers schedule the same job after if they try to recover at the same time.
			// This will eventually be noticed, but can not be ruled out from the beginning.
			if (leaderElectionService.hasLeadership()) {
				try {
					// Now set the running status is after getting leader ship and
					// set finished status after job in terminated status.
					// So if finding the job is running, it means someone has already run the job, need recover.
					if (schedulingStatus == JobSchedulingStatus.PENDING) {
						runningJobsRegistry.setJobRunning(jobGraph.getJobID());
					}

					CompletableFuture<Acknowledge> startingFuture = jobManager.start(new JobMasterId(leaderSessionID), timeout);

					startingFuture.whenCompleteAsync(
						(Acknowledge ack, Throwable throwable) -> {
							if (throwable != null) {
								onFatalError(new Exception("Could not start the job manager.", throwable));
							}
						},
						jobManagerServices.executorService);
				} catch (Exception e) {
					onFatalError(new Exception("Could not start the job manager.", e));
				}
			}
		}
	}

	@Override
	public void revokeLeadership() {
		synchronized (lock) {
			if (shutdown) {
				log.info("JobManagerRunner already shutdown.");
				return;
			}

			log.info("JobManager for job {} ({}) was revoked leadership at {}.",
				jobGraph.getName(), jobGraph.getJobID(), getAddress());

			CompletableFuture<Acknowledge>  suspendFuture = jobManager.suspend(new Exception("JobManager is no longer the leader."), timeout);

			suspendFuture.whenCompleteAsync(
				(Acknowledge ack, Throwable throwable) -> {
					if (throwable != null) {
						onFatalError(new Exception("Could not start the job manager.", throwable));
					}
				},
				jobManagerServices.executorService);
		}
	}

	@Override
	public String getAddress() {
		return jobManager.getAddress();
	}

	@Override
	public void handleError(Exception exception) {
		log.error("Leader Election Service encountered a fatal error.", exception);
		onFatalError(exception);
	}

	//----------------------------------------------------------------------------------------------
	// Testing
	//----------------------------------------------------------------------------------------------

	@VisibleForTesting
	boolean isShutdown() {
		return shutdown;
	}
}


text:
from contextlib import contextmanager
from tfmesos.scheduler import Job, TFMesosScheduler

__VERSION__ = '0.0.9'

@contextmanager
def cluster(jobs, **kw):
    if isinstance(jobs, dict):
        jobs = [Job(**jobs)]

    if isinstance(jobs, Job):
        jobs = [jobs]

    jobs = [job if isinstance(job, Job) else Job(**job)
            for job in jobs]
    s = TFMesosScheduler(jobs, **kw)
    try:
        s.start()
        yield s
    finally:
        s.stop()


text:
from kcbo.statistical_tests.utils import StatisticalTest, statistic
from kcbo.utils import output_templates

import numpy as np
from tabulate import tabulate
from itertools import combinations

class LognormalMedianComparison(StatisticalTest):

    TYPE = 'Lognormal Median Comparison Test'

    def __init__(self, *args, **kwargs):
        super(type(self), self).__init__(*args, **kwargs)

    def initialize_test(self, dataframe, groups=None, groupcol='group', valuecol='value', samples=100000, **kwargs):
        df = dataframe
        df = df[df[valuecol] > 0]

        if not groups:
            groups = df[groupcol].unique()

        pooled = df[valuecol]

        self.pooled = pooled
        self.groups = groups
        self.groupcol = groupcol
        self.valuecol = valuecol
        self.df = df
        self.samples = samples

        self.keys = list(combinations(groups, 2))
        self.median_distributions = {}
        self.mean_distributions = {}

    def run_model(self, *args, **kwargs):

        groups = kwargs.get('groups', self.groups)

        m, v = (self.pooled.mean(), self.pooled.var())

        compute_mu = lambda m, v: np.log(m ** 2 / np.sqrt(v + m ** 2))
        compute_var = lambda m, v: np.log(v * 1. / m ** 2 + 1)

        pooled_mean = compute_mu(m, v)
        pooled_variance = compute_var(m, v)
        pooled_tau = 1. / 1000000

        mc_samples = self.samples

        tau = 1. / pooled_variance
        for group in groups:
            g = self.df[self.df[self.groupcol] == group][self.valuecol]
            n = g.shape[0]

            # MC Simulation to generate distribution
            mean_data = np.random.normal(
                loc=(pooled_tau * pooled_mean + tau * np.log(g).mean() * n) /
                (pooled_tau + n * tau),
                scale= np.sqrt(1. / (pooled_tau + n * tau)),
                size=mc_samples
            )

            median_data = np.exp(mean_data)

            self.median_distributions[group] = median_data
            self.mean_distributions[group] = mean_data

    @statistic('median', individual=True, is_distribution=True, is_estimate=True)
    def group_median_distribution(self, group):
        return self.median_distributions.get(group, [])

    @statistic('mu', individual=True, is_distribution=True, is_estimate=True)
    def group_mean_distribution(self, group):
        return self.mean_distributions.get(group, [])

    @statistic('diff_medians', is_distribution=True, pairwise=True, is_estimate=True)
    def diff_medians(self, groups):
        group1, group2 = groups
        return self.median_distributions[group2] - self.median_distributions[group1]

    @statistic('p_diff_medians', pairwise=True, is_estimate=True)
    def p_diff_medians(self, groups):
        return (self.diff_medians(groups) > 0).mean()

    def summary(self, *args, **kwargs):
        summary_data = self.compute_statistic(
            keys=list(self.keys).extend(self.groups))
        return self.generate_text_description(summary_data), summary_data

    def generate_text_description(self, summary_data):
        group_summary_header = [
            'Group', 'Median', '95% CI Lower', '95% CI Upper', 'Mu', '95% CI Lower', '95% CI Upper']
        group_summary_table_data = [
            [
                group,
                summary_data[group]['estimate median'],
                summary_data[group]['95_CI median'][0],
                summary_data[group]['95_CI median'][1],
                summary_data[group]['estimate mu'],
                summary_data[group]['95_CI mu'][0],
                summary_data[group]['95_CI mu'][1]
            ]
            for group in self.groups]

        group_summary_table = tabulate(
            group_summary_table_data, group_summary_header, tablefmt="pipe")

        comparisons_header = [
            "Hypothesis", "Difference of Medians", "P.Value", "95% CI Lower", "95% CI Upper"]
        comparisons_data = [
            [
                "{} < {}".format(*pair),
                self.diff_medians(pair).mean(),
                summary_data[pair]['p_diff_medians'],
                summary_data[pair]['95_CI diff_medians'][0],
                summary_data[pair]['95_CI diff_medians'][1],
            ] for pair in self.keys
        ]

        comparison_summary_table = tabulate(
            comparisons_data, comparisons_header, tablefmt="pipe")

        description = output_templates['groups with comparison'].format(
            title=self.TYPE,
            groups_header="Groups:",
            groups_string=", ".join(self.groups),
            groups_summary=group_summary_table,
            comparison_summary=comparison_summary_table,
        )

        return description

def lognormal_comparison_test(dataframe, groups=None, groupcol='group', valuecol='value', **kwargs):
    """Lognormal Median Comparison

    Given a dataframe of the form:

    |Group  |Observed Value|
    |-------|--------------|
    |<group>|       <float>|
    ...

    Compute estimates of the difference of medians between groups.

    Note: This test assumes that input comes from distributions with the same variance.

    Inputs:
    dataframe -- Pandas dataframe of form above
    groups -- (optional) list of groups to look at. Excluded looks at all groups
    groupcol -- string for indexing dataframe column for groups
    valuecol -- string for indexing dataframe column for values of observations

    Returns:
    (description, raw_data)
    description: table describing output data
    raw_data: dictionary of output data

    """

    results = LognormalMedianComparison(
        dataframe, groups=None, groupcol='group', valuecol='value', **kwargs)
    return results.summary()


text:
package rayo.ui.editors.html;

import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;

import rayo.core.RayoFile;
import rayo.ui.editors.AbstractTextEditor;

public class CssEditor extends AbstractTextEditor {
	private static final long serialVersionUID = 1L;

	public CssEditor(RayoFile file) {
		super(file);
	}

	@Override
	protected void initTextArea(RSyntaxTextArea textArea) {
		textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_CSS);
		textArea.setCodeFoldingEnabled(true);
		textArea.setMarkOccurrences(true);
		textArea.setUseFocusableTips(true);
	}
}


text:
using parquet::LogicalType;
using parquet::Repetition;
using parquet::Type;
using parquet::schema::GroupNode;
using parquet::schema::PrimitiveNode;

constexpr int FIXED_LENGTH = 10;

static std::shared_ptr<GroupNode> SetupSchema() {
  parquet::schema::NodeVector fields;
  // Create a primitive node named 'boolean_field' with type:BOOLEAN,
  // repetition:REQUIRED
  fields.push_back(PrimitiveNode::Make("boolean_field", Repetition::REQUIRED,
                                       Type::BOOLEAN, LogicalType::NONE));

  // Create a primitive node named 'int32_field' with type:INT32, repetition:REQUIRED,
  // logical type:TIME_MILLIS
  fields.push_back(PrimitiveNode::Make("int32_field", Repetition::REQUIRED, Type::INT32,
                                       LogicalType::TIME_MILLIS));

  // Create a primitive node named 'int64_field' with type:INT64, repetition:REPEATED
  fields.push_back(PrimitiveNode::Make("int64_field", Repetition::REPEATED, Type::INT64,
                                       LogicalType::NONE));

  fields.push_back(PrimitiveNode::Make("int96_field", Repetition::REQUIRED, Type::INT96,
                                       LogicalType::NONE));

  fields.push_back(PrimitiveNode::Make("float_field", Repetition::REQUIRED, Type::FLOAT,
                                       LogicalType::NONE));

  fields.push_back(PrimitiveNode::Make("double_field", Repetition::REQUIRED, Type::DOUBLE,
                                       LogicalType::NONE));

  // Create a primitive node named 'ba_field' with type:BYTE_ARRAY, repetition:OPTIONAL
  fields.push_back(PrimitiveNode::Make("ba_field", Repetition::OPTIONAL, Type::BYTE_ARRAY,
                                       LogicalType::NONE));

  // Create a primitive node named 'flba_field' with type:FIXED_LEN_BYTE_ARRAY,
  // repetition:REQUIRED, field_length = FIXED_LENGTH
  fields.push_back(PrimitiveNode::Make("flba_field", Repetition::REQUIRED,
                                       Type::FIXED_LEN_BYTE_ARRAY, LogicalType::NONE,
                                       FIXED_LENGTH));

  // Create a GroupNode named 'schema' using the primitive nodes defined above
  // This GroupNode is the root node of the schema tree
  return std::static_pointer_cast<GroupNode>(
      GroupNode::Make("schema", Repetition::REQUIRED, fields));
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('catalog', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='product',
            name='name',
            field=models.CharField(max_length=255),
        ),
        migrations.AlterField(
            model_name='product',
            name='price',
            field=models.FloatField(blank=True, null=True),
        ),
    ]


text:
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using PeanutButter.TestUtils.AspNetCore.Fakes;

// ReSharper disable ClassNeverInstantiated.Global

namespace PeanutButter.TestUtils.AspNetCore.Builders;

/// <summary>
/// Constructs an ActionExecutingContext
/// </summary>
public class ActionExecutingContextBuilder
    : Builder<ActionExecutingContextBuilder, ActionExecutingContext>
{
    private ActionContext _actionContext;
    private IList<IFilterMetadata> _filterMetadata;
    private IDictionary<string, object> _actionArguments;
    private object _controller;
    private HttpContext _httpContext;
    private RouteData _routeData;
    private ActionDescriptor _actionDescriptor;

    /// <inheritdoc />
    public ActionExecutingContextBuilder()
    {
        WithPreCursor(() => _actionContext = GenerateDefaultActionContext())
            .WithPreCursor(() => _filterMetadata = new List<IFilterMetadata>())
            .WithPreCursor(() => _actionArguments = new Dictionary<string, object>())
            .WithPreCursor(() => _controller = null)
            .WithPreCursor(() => _httpContext = null)
            .WithPreCursor(() => _routeData = null)
            .WithPreCursor(() => _actionDescriptor = null);
    }

    /// <summary>
    /// Sets an action argument on the ActionExecutingContext
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public ActionExecutingContextBuilder WithActionArgument(
        string key,
        object value
    )
    {
        return With(
            o => o.ActionArguments[key] = value
        );
    }

    /// <summary>
    /// Sets the "action" route parameter
    /// </summary>
    /// <param name="action"></param>
    /// <returns></returns>
    public ActionExecutingContextBuilder WithAction(
        string action
    )
    {
        return WithRouteValue("action", action);
    }

    /// <summary>
    /// Sets a value on the associated route data
    /// </summary>
    /// <param name="key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public ActionExecutingContextBuilder WithRouteValue(
        string key,
        string value
    )
    {
        return With(o => o.RouteData.Values[key] = value);
    }

    /// <summary>
    /// Sets the controller for the ActionExecutingContext
    /// </summary>
    /// <param name="controller"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public ActionExecutingContextBuilder WithController<T>(
        T controller
    ) where T : ControllerBase
    {
        return With(
            o =>
            {
                var fake = o.As<FakeActionExecutingContext>();
                fake.SetController(controller);
            }
        );
    }

    /// <summary>
    /// Sets an header on the HttpContext.Request of the ActionExecutingContext
    /// </summary>
    /// <param name="header"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public ActionExecutingContextBuilder WithHeader(
        string header,
        string value
    )
    {
        return With(
            o => o.HttpContext.Request.Headers[header] = value
        );
    }

    /// <summary>
    /// Adds filter metadata to the ActionExecutingContext
    /// </summary>
    /// <param name="metadata"></param>
    /// <returns></returns>
    public ActionExecutingContextBuilder WithFilterMetadata(
        IFilterMetadata metadata
    )
    {
        return With(
            o => o.Filters.Add(metadata)
        );
    }

    /// <summary>
    /// Constructs the fake ActionExecutingContext
    /// </summary>
    /// <returns></returns>
    /// <exception cref="MissingConstructorRequirementException{ActionExecutingContext}"></exception>
    protected override ActionExecutingContext ConstructEntity()
    {
        return new FakeActionExecutingContext(
            _actionContext ?? throw Missing(nameof(_actionContext)),
            _filterMetadata ?? throw Missing(nameof(_filterMetadata)),
            _actionArguments ?? throw Missing(nameof(_actionArguments)),
            _controller // could be set later
        );

        MissingConstructorRequirementException<ActionExecutingContext> Missing(string ctx)
        {
            return new MissingConstructorRequirementException<ActionExecutingContext>(ctx);
        }
    }

    private ActionContext GenerateDefaultActionContext()
    {
        return new ActionContext(
            _httpContext ?? HttpContextBuilder.BuildDefault(),
            _routeData ?? new RouteData(),
            _actionDescriptor ?? new ActionDescriptor()
        );
    }
}


text:
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import org.junit.Before;
import org.junit.Test;

import solution_attempts.CorrectTransactionWithCalendar;
import solution_attempts.CorrectTransactionWithDate;

public class CompareToCaseTest extends TestBase {

	@Before
	public void setUp() {
		test = new CompareToCase();
	}

	@Test
	public void successWithCalendar() {
		assertTestSucceeds(CorrectTransactionWithCalendar.class);
	}

	@Test
	public void successWithDate() {
		assertTestSucceeds(CorrectTransactionWithDate.class);
	}

	@Test
	public void cannotInstantiate() {
		assertTestFails(Transaction.class, ObjectAccessor.CANNOT_INSTANTIATE);
	}

	static class TooManyInterfaces implements Comparable<TooManyInterfaces>, Cloneable {
		public TooManyInterfaces(BigDecimal amount, Calendar date, String description) {}
		@Override public int compareTo(TooManyInterfaces o) { return 0; }
	}
	@Test
	public void tooManyInterfaec() {
		assertTestFails(TooManyInterfaces.class, CompareToCase.TOO_MANY_INTERFACES);
	}

	static class ImplementsSomethingElse implements Cloneable {
		public ImplementsSomethingElse(BigDecimal amount, Calendar date, String description) {}
	}
	@Test
	public void implementsSomethingElse() {
		assertTestFails(ImplementsSomethingElse.class, CompareToCase.DOES_NOT_IMPLEMENT_INTERFACE);
	}

	static class DoesNotImplementInterface {
		public DoesNotImplementInterface(BigDecimal amount, Calendar date, String description) {}
	}
	@Test
	public void implementsInterface() {
		assertTestFails(DoesNotImplementInterface.class, CompareToCase.DOES_NOT_IMPLEMENT_INTERFACE);
	}

	static class WrongGenericParameter implements Comparable<String> {
		public WrongGenericParameter(BigDecimal amount, Calendar date, String description) {}
		@Override public int compareTo(String o) { return 0; }
	}
	@Test
	public void wrongGenericParameter() {
		assertTestFails(WrongGenericParameter.class, CompareToCase.WRONG_GENERIC_PARAMETER);
	}

	@SuppressWarnings("rawtypes")
	static class NoGenericParameter implements Comparable {
		public NoGenericParameter(BigDecimal amount, Calendar date, String description) {}
		@Override
		public int compareTo(Object o) {
			return 0;
		}
	}
	@Test
	public void noGenericParameter() {
		assertTestFails(NoGenericParameter.class, CompareToCase.WRONG_GENERIC_PARAMETER);
	}

	static class NoOrder implements Comparable<NoOrder> {
		public NoOrder(BigDecimal amount, Date date, String description) {}

		@Override
		public int compareTo(NoOrder o) {
			return 0;
		}
	}
	@Test
	public void noOrder() {
		assertTestFails(NoOrder.class, CompareToCase.WRONG_ORDER);
	}

	static class AscendingOrderWithCalendar implements Comparable<AscendingOrderWithCalendar> {
		private final Calendar date;
		public AscendingOrderWithCalendar(BigDecimal amount, Calendar date, String description) { this.date = date; }

		@Override
		public int compareTo(AscendingOrderWithCalendar o) {
			return date.compareTo(o.date);
		}
	}
	@Test
	public void orderingWithCalendar() {
		assertTestFails(AscendingOrderWithDate.class, CompareToCase.WRONG_ORDER);
	}

	static class AscendingOrderWithDate implements Comparable<AscendingOrderWithDate> {
		private final Date date;
		public AscendingOrderWithDate(BigDecimal amount, Date date, String description) { this.date = date; }

		@Override
		public int compareTo(AscendingOrderWithDate o) {
			return date.compareTo(o.date);
		}
	}
	@Test
	public void orderingWithDate() {
		assertTestFails(AscendingOrderWithDate.class, CompareToCase.WRONG_ORDER);
	}

	static class InconsistentWithEqualsOnlyAmount implements Comparable<InconsistentWithEqualsOnlyAmount> {
		private final BigDecimal amount;
		private final Calendar date;
		private final String description;
		public InconsistentWithEqualsOnlyAmount(BigDecimal amount, Calendar date, String description)
				{ this.amount = amount; this.date = date; this.description = description; }

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof InconsistentWithEqualsOnlyAmount)) {
				return false;
			}
			InconsistentWithEqualsOnlyAmount other = (InconsistentWithEqualsOnlyAmount)obj;
			return amount.equals(other.amount) && date.equals(other.date) && description.equals(other.description);
		}

		@Override
		public int compareTo(InconsistentWithEqualsOnlyAmount obj) {
			int dateDiff = obj.date.compareTo(date);
			if (dateDiff != 0) {
				return dateDiff;
			}
			return description.compareTo(obj.description);
		}
	}
	@Test
	public void inconsistentWithEqualsOnlyAmount() {
		assertTestFails(InconsistentWithEqualsOnlyAmount.class, CompareToCase.CONSISTENT_WITH_EQUALS);
	}

	static class InconsistentWithEqualsOnlyDescription implements Comparable<InconsistentWithEqualsOnlyDescription> {
		private final BigDecimal amount;
		private final Calendar date;
		private final String description;
		public InconsistentWithEqualsOnlyDescription(BigDecimal amount, Calendar date, String description)
				{ this.amount = amount; this.date = date; this.description = description; }

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof InconsistentWithEqualsOnlyDescription)) {
				return false;
			}
			InconsistentWithEqualsOnlyDescription other = (InconsistentWithEqualsOnlyDescription)obj;
			return amount.equals(other.amount) && date.equals(other.date) && description.equals(other.description);
		}

		@Override
		public int compareTo(InconsistentWithEqualsOnlyDescription obj) {
			int dateDiff = obj.date.compareTo(date);
			if (dateDiff != 0) {
				return dateDiff;
			}
			return description.compareTo(obj.description);
		}
	}
	@Test
	public void inconsistentWithEqualsOnlyDescription() {
		assertTestFails(InconsistentWithEqualsOnlyDescription.class, CompareToCase.CONSISTENT_WITH_EQUALS);
	}

	static class InconsistentWithEqualsAllFields implements Comparable<InconsistentWithEqualsAllFields> {
		private final BigDecimal amount;
		private final Calendar date;
		private final String description;
		public InconsistentWithEqualsAllFields(BigDecimal amount, Calendar date, String description)
				{ this.amount = amount; this.date = date; this.description = description; }

		@Override
		public boolean equals(Object obj) {
			if (!(obj instanceof InconsistentWithEqualsAllFields)) {
				return false;
			}
			InconsistentWithEqualsAllFields other = (InconsistentWithEqualsAllFields)obj;
			return amount.equals(other.amount) && date.equals(other.date) && description.equals(other.description);
		}

		@Override
		public int compareTo(InconsistentWithEqualsAllFields obj) {
			return obj.date.compareTo(date);
		}
	}
	@Test
	public void inconsistentWithEqualsAllFields() {
		assertTestFails(InconsistentWithEqualsAllFields.class, CompareToCase.CONSISTENT_WITH_EQUALS);
	}
}


text:
<?php

/**
 * Myads setup plugin
 *
 * @package myads
 * @version 2.1
 * @author  Roffun
 * @copyright Copyright(c) 2014 http://olro.net/blog/blog-internet/myads-plugin-cotonti
 * @license BSD
 */

defined('COT_CODE') or die('Wrong URL.');


text:
$(document).ready(function () {
  var displaylimit = 3;
  var screenname = "@myt_team";
  var showdirecttweets = false;
  var showretweets = true;
  var showtweetlinks = true;
  var showprofilepic = true;

  var headerHTML = '';
  var loadingHTML = '';
  loadingHTML += '

';

  $('#twitter-feed').html(headerHTML + loadingHTML);

    $.getJSON('get-tweets.php',
        function(feeds) {
        var feedHTML = '';
        var displayCounter = 1;
        for (var i=0; i<feeds.length; i++) {
        var tweetscreenname = feeds[i].user.name;
        var tweetusername = feeds[i].user.screen_name;
        var profileimage = feeds[i].user.profile_image_url_https;
        var status = feeds[i].text;
        var isaretweet = false;
        var isdirect = false;
        var tweetid = feeds[i].id_str;

        //If the tweet has been retweeted, get the profile pic of the tweeter
        if(typeof feeds[i].retweeted_status != 'undefined'){
           profileimage = feeds[i].retweeted_status.user.profile_image_url_https;
           tweetscreenname = feeds[i].retweeted_status.user.name;
           tweetusername = feeds[i].retweeted_status.user.screen_name;
           tweetid = feeds[i].retweeted_status.id_str
           isaretweet = true;
         };

         //Check to see if the tweet is a direct message
         if (feeds[i].text.substr(0,1) == "@") {
           isdirect = true;
         }

        //console.log(feeds[i]);

         if (((showretweets == true) || ((isaretweet == false) && (showretweets == false))) && ((showdirecttweets == true) || ((showdirecttweets == false) && (isdirect == false)))) {
          if ((feeds[i].text.length > 1) && (displayCounter <= displaylimit)) {
            if (showtweetlinks == true) {
              status = addlinks(status);
            }

            if (displayCounter == 1) {
              feedHTML += headerHTML;
            }

            feedHTML += '
';
            feedHTML += '
'+screenname+' '+status+'
';
            feedHTML += ''+relative_time(feeds[i].created_at)+'';
            feedHTML += '
';
            displayCounter++;
          }
         }
            }

            $('#twitter-feed').html(feedHTML);
    });

    //Function modified from Stack Overflow
    function addlinks(data) {
        //Add link to all http:// links within tweets
        data = data.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return ''+url+'';
        });

        //Add link to @usernames used within tweets
        data = data.replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return ''+reply.charAt(0)+reply.substring(1)+'';
        });
        return data;
    }

    function relative_time(time_value) {
      var values = time_value.split(" ");
      time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      delta = delta + (relative_to.getTimezoneOffset() * 60);

      if (delta < 60) {
        return 'less than a minute ago';
      } else if(delta < 120) {
        return 'about a minute ago';
      } else if(delta < (60*60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
      } else if(delta < (120*60)) {
        return 'about an hour ago';
      } else if(delta < (24*60*60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
      } else if(delta < (48*60*60)) {
        return '1 day ago';
      } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
      }
    }

});


text:
/*
 * File: app/store/storeProveedor.js
 *
 * This file was generated by Sencha Architect version 4.1.2.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Ext JS 5.1.x library, under independent license.
 * License of Sencha Architect does not include license for Ext JS 5.1.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('hwtProPedidoVentas.store.storeProveedor', {
    extend: 'Ext.data.Store',

    requires: [
        'hwtProPedidoVentas.model.modProveedor'
    ],

    constructor: function(cfg) {
        var me = this;
        cfg = cfg || {};
        me.callParent([Ext.apply({
            storeId: 'storeProveedor',
            model: 'hwtProPedidoVentas.model.modProveedor'
        }, cfg)]);
    }
});


text:
if [ "$#" -ne 1 ]; then
    echo "Invalid parameters."
    exit 1
fi

main() {

    local filename=$1
    echo "Deleting $filename"

    rm -f $filename

    echo 'Zipping mimetype'
    zip -0 -X $filename mimetype

    echo 'Zipping epub content'
    zip -9 -r $filename META-INF/ OEBPS/
}
main $1


text:
require 'mail/fields'

# encoding: utf-8
module Mail
  # Provides a single class to call to create a new structured or unstructured
  # field.  Works out per RFC what field of field it is being given and returns
  # the correct field of class back on new.
  #
  # ===Per RFC 2822
  #
  #  2.2. Header Fields
  #
  #     Header fields are lines composed of a field name, followed by a colon
  #     (":"), followed by a field body, and terminated by CRLF.  A field
  #     name MUST be composed of printable US-ASCII characters (i.e.,
  #     characters that have values between 33 and 126, inclusive), except
  #     colon.  A field body may be composed of any US-ASCII characters,
  #     except for CR and LF.  However, a field body may contain CRLF when
  #     used in header "folding" and  "unfolding" as described in section
  #     2.2.3.  All field bodies MUST conform to the syntax described in
  #     sections 3 and 4 of this standard.
  #
  class Field

    include Patterns
    include Comparable

    STRUCTURED_FIELDS = %w[ bcc cc content-description content-disposition
                            content-id content-location content-transfer-encoding
                            content-type date from in-reply-to keywords message-id
                            mime-version received references reply-to
                            resent-bcc resent-cc resent-date resent-from
                            resent-message-id resent-sender resent-to
                            return-path sender to ]

    KNOWN_FIELDS = STRUCTURED_FIELDS + ['comments', 'subject']

    FIELDS_MAP = {
      "to" => ToField,
      "cc" => CcField,
      "bcc" => BccField,
      "message-id" => MessageIdField,
      "in-reply-to" => InReplyToField,
      "references" => ReferencesField,
      "subject" => SubjectField,
      "comments" => CommentsField,
      "keywords" => KeywordsField,
      "date" => DateField,
      "from" => FromField,
      "sender" => SenderField,
      "reply-to" => ReplyToField,
      "resent-date" => ResentDateField,
      "resent-from" => ResentFromField,
      "resent-sender" =>  ResentSenderField,
      "resent-to" => ResentToField,
      "resent-cc" => ResentCcField,
      "resent-bcc" => ResentBccField,
      "resent-message-id" => ResentMessageIdField,
      "return-path" => ReturnPathField,
      "received" => ReceivedField,
      "mime-version" => MimeVersionField,
      "content-transfer-encoding" => ContentTransferEncodingField,
      "content-description" => ContentDescriptionField,
      "content-disposition" => ContentDispositionField,
      "content-type" => ContentTypeField,
      "content-id" => ContentIdField,
      "content-location" => ContentLocationField,
    }

    # Generic Field Exception
    class FieldError < StandardError
    end

    # Raised when a parsing error has occurred (ie, a StructuredField has tried
    # to parse a field that is invalid or improperly written)
    class ParseError < FieldError #:nodoc:
      attr_accessor :element, :value, :reason

      def initialize(element, value, reason)
        @element = element
        @value = value
        @reason = reason
        super("#{element} can not parse |#{value}|\nReason was: #{reason}")
      end
    end

    # Raised when attempting to set a structured field's contents to an invalid syntax
    class SyntaxError < FieldError #:nodoc:
    end

    # Accepts a string:
    #
    #  Field.new("field-name: field data")
    #
    # Or name, value pair:
    #
    #  Field.new("field-name", "value")
    #
    # Or a name by itself:
    #
    #  Field.new("field-name")
    #
    # Note, does not want a terminating carriage return.  Returns
    # self appropriately parsed.  If value is not a string, then
    # it will be passed through as is, for example, content-type
    # field can accept an array with the type and a hash of
    # parameters:
    #
    #  Field.new('content-type', ['text', 'plain', {:charset => 'UTF-8'}])
    def initialize(name, value = nil, charset = 'utf-8')
      case
      when name =~ /:/                  # Field.new("field-name: field data")
        charset = value unless value.blank?
        name, value = split(name)
        create_field(name, value, charset)
      when name !~ /:/ && value.blank?  # Field.new("field-name")
        create_field(name, nil, charset)
      else                              # Field.new("field-name", "value")
        create_field(name, value, charset)
      end
      return self
    end

    def field=(value)
      @field = value
    end

    def field
      @field
    end

    def name
      field.name
    end

    def value
      field.value
    end

    def value=(val)
      create_field(name, val, charset)
    end

    def to_s
      field.to_s
    end

    def update(name, value)
      create_field(name, value, charset)
    end

    def same( other )
      match_to_s(other.name, field.name)
    end

    alias_method :==, :same

    def <=>( other )
      self.field_order_id <=> other.field_order_id
    end

    def field_order_id
      @field_order_id ||= (FIELD_ORDER_LOOKUP[self.name.to_s.downcase] || 100)
    end

    def method_missing(name, *args, &block)
      field.send(name, *args, &block)
    end

    FIELD_ORDER = %w[ return-path received
                      resent-date resent-from resent-sender resent-to
                      resent-cc resent-bcc resent-message-id
                      date from sender reply-to to cc bcc
                      message-id in-reply-to references
                      subject comments keywords
                      mime-version content-type content-transfer-encoding
                      content-location content-disposition content-description ]

    FIELD_ORDER_LOOKUP = Hash[FIELD_ORDER.each_with_index.to_a]

    private

    def split(raw_field)
      match_data = raw_field.mb_chars.match(FIELD_SPLIT)
      [match_data[1].to_s.mb_chars.strip, match_data[2].to_s.mb_chars.strip]
    rescue
      STDERR.puts "WARNING: Could not parse (and so ignoring) '#{raw_field}'"
    end

    def create_field(name, value, charset)
      begin
        self.field = new_field(name, value, charset)
      rescue Mail::Field::ParseError => e
        self.field = Mail::UnstructuredField.new(name, value)
        self.field.errors << [name, value, e]
        self.field
      end
    end

    def new_field(name, value, charset)
      lower_case_name = name.to_s.downcase
      if field_klass = FIELDS_MAP[lower_case_name]
        field_klass.new(value, charset)
      else
        OptionalField.new(name, value, charset)
      end
    end

  end

end


text:
ViewServiceProvider
===================

[![Build Status](https://travis-ci.org/gigablah/silex-view.png?branch=master)](https://travis-ci.org/gigablah/silex-view) [![Coverage Status](https://coveralls.io/repos/gigablah/silex-view/badge.png)](https://coveralls.io/r/gigablah/silex-view)

The ViewServiceProvider gives engine-agnostic templating capabilities to your [Silex][1] application.

Installation
------------

Use [Composer][2] to install the gigablah/silex-view library by adding it to your `composer.json`. You'll also need a rendering engine, such as [Mustache][3].

```json
{
    "require": {
        "silex/silex": "~1.0",
        "mustache/mustache": "~2.4",
        "gigablah/silex-view": "~0.0.1"
    }
}
```

Usage
-----

Just register the service provider and optionally pass in some defaults.

```php
$app->register(new Gigablah\Silex\View\ViewServiceProvider(), array(
    'view.globals' => array('foo' => 'bar'),
    'view.default_engine' => 'mustache'
));
```

The provider registers the `ArrayToViewListener` which intercepts the output from your controllers and wraps it with a `View` object. For it to work, you have to return an array of data from your controller function.

Views
-----

Normally you do not need to instantiate any view entities on your own; the listener will convert your controller output. If you wish to do it manually, the syntax is as follows:

```php
$view = $app['view']->create($template = '/path/to/template', $context = array('foo' => 'bar'));
```

Views can be rendered by calling the `render()` function, or casting to string:

```php
$output = $view->render();
$output = (string) $view;
```

Again, you should not need to render your views manually since they will be handled by the `Response` object.

View Context
------------

The view entity is simply an instance of `ArrayObject`, so you can use regular array notation to set the context, along with convenience functions like `with()`:

```php
$view['foo'] = 'bar';
$view->with(array('foo' => 'bar'));
```

To insert into the global context, use `share()`:

```php
$view->share(array('foo' => 'bar'));
```

You can initialize the global context by overriding `view.globals`.

Resolving Templates
-------------------

How does the listener know which template to use? By default it reads the `_route` attribute from the request entity in lowercase, and appends the extension based on the value of `view.default_engine`. Some examples:

```php
$app->get('/foobar', function () {}); // get_foobar.mustache
$app->get('/', function () {}); // get_.mustache
$app->match('/', function () {}); // _.mustache
```

Since you probably want more descriptive template names, you can use named routes:

```php
$app->match('/', function () {})->bind('home'); // home.mustache
```

You can also set the `_template` attribute in the request, or as part of the controller output:

```php
$app->get('/foo', function (Symfony\Component\HttpFoundation\Request $request) {
    $request->attributes->set('_template', 'foo.html');
});

$app->get('/bar', function () {
    return array('_template' => 'bar.html');
});
```

If you need custom logic for generating template paths, you can create your own class that implements `TemplateResolverInterface` and override `view.template_resolver`.

Engines
-------

This library does not handle any actual view rendering; that task is delegated to the templating library of your choice. Currently adapters are provided for:

* [Mustache][3]
* [Smarty][4]
* [Twig][5]
* [Aura.View][6]
* [Plates][7]
* Raw PHP
* Token replacement using strtr()

There is a special `DelegatingEngine` which acts as a registry for multiple different engines, selecting the appropriate one based on the template file extension. Since Aura.View, Plates and Raw PHP all use the same default file extension (.php), you will need to manually configure the extension mapping as follows:

```php
$app->register(new Gigablah\Silex\View\ViewServiceProvider(), array(
    'view.default_engine' => 'php',
    'view.engines' => array(
        'php' => 'view.engine.plates'
    )
));
```

Composite Views
---------------

Views can be nested inside another:

```php
$view->nest($app['view']->create('foobar.html'), 'section');
```

For a single view, it is equivalent to:

```php
$view['section'] = $app['view']->create('foobar.html');
```

However, the difference lies in nesting multiple views in the same location. Doing this will place the child views adjacent to each other rather than overwriting:

```php
$view->nest($app['view']->create('foobar.html'), 'section');
$view->nest($app['view']->create('foobar.html'), 'section'); // foobar.html is now repeated twice
```

What's more, you can mix and match different engines:

```php
$mustacheView = $app['view']->create('foo.mustache');
$smartyView = $app['view']->create('bar.tpl')->nest($mustacheView, 'section');
```

Nested views will inherit the context of their parent views.

Exception Handling
------------------

All rendering exceptions are captured and stored in a shared `ExceptionBag`.

To access the last thrown exception, or return all of them:

```php
$exception = $app['view']->getExceptionBag()->pop();
$exceptions = $app['view']->getExceptionBag()->all();
```

More Examples
-------------

You can view a code sample of various usage scenarios in the [demo application][8].

License
-------

Released under the MIT license. See the LICENSE file for details.

[1]: http://silex.sensiolabs.org
[2]: http://getcomposer.org
[3]: http://mustache.github.io
[4]: http://www.smarty.net
[5]: http://twig.sensiolabs.org
[6]: http://github.com/auraphp/Aura.View
[7]: http://platesphp.com
[8]: http://github.com/gigablah/silex-view/blob/master/demo/app.php


text:
* patches
    * Removing unused dependency on express