text:
package org.jcodec.containers.mp4;

import static org.jcodec.common.IOUtils.readFileToByteArray;
import static org.jcodec.common.NIOUtils.readableFileChannel;
import static org.jcodec.common.NIOUtils.rwFileChannel;
import static org.jcodec.common.NIOUtils.writableFileChannel;
import static org.jcodec.common.model.ColorSpace.RGB;
import static org.jcodec.containers.mp4.TrackType.SOUND;
import static org.jcodec.containers.mp4.TrackType.VIDEO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

import javax.imageio.ImageIO;

import org.jcodec.codecs.prores.ProresDecoder;
import org.jcodec.codecs.wav.WavHeader;
import org.jcodec.codecs.wav.WavHeader.FmtChunk;
import org.jcodec.common.FileChannelWrapper;
import org.jcodec.common.NIOUtils;
import org.jcodec.common.SeekableByteChannel;
import org.jcodec.common.model.Packet;
import org.jcodec.common.model.Picture;
import org.jcodec.containers.mp4.MP4Util.Atom;
import org.jcodec.containers.mp4.boxes.AudioSampleEntry;
import org.jcodec.containers.mp4.boxes.EndianBox.Endian;
import org.jcodec.containers.mp4.boxes.MovieBox;
import org.jcodec.containers.mp4.boxes.VideoSampleEntry;
import org.jcodec.containers.mp4.demuxer.AbstractMP4DemuxerTrack;
import org.jcodec.containers.mp4.demuxer.MP4Demuxer;
import org.jcodec.containers.mp4.muxer.FramesMP4MuxerTrack;
import org.jcodec.containers.mp4.muxer.MP4Muxer;
import org.jcodec.containers.mp4.muxer.PCMMP4MuxerTrack;
import org.jcodec.scale.Yuv422pToRgb;
import org.junit.Assert;

public class TestDemuxer {

    private static void testAll(File src, File base) throws Exception {
        MP4Demuxer demuxer = new MP4Demuxer(readableFileChannel(src));
        AbstractMP4DemuxerTrack vt = demuxer.getVideoTrack();
        ProresDecoder decoder = new ProresDecoder();

        long duration = vt.getDuration().getNum();
        long frameCount = vt.getFrameCount();

        for (int t = 0;; t++) {
            randomPts(vt, decoder, duration, new Yuv422pToRgb(2, 0), base);
            // randomFrame(vt, decoder, frameCount, transform, dest);
        }
    }

    private static void randomPts(AbstractMP4DemuxerTrack vt, ProresDecoder decoder, long duration, Yuv422pToRgb transform,
            File base) throws IOException {

        long pts = (long) (Math.random() * duration);
        vt.seek(pts);
        for (int i = 0; i < 10; i++) {
            Packet frames = vt.nextFrame();
            Picture pic = decoder.decodeFrame(frames.getData(), allocBuffer(vt));
            Picture dest = Picture.create(pic.getWidth(), pic.getHeight(), RGB);
            transform.transform(pic, dest);

//            ImageIO.write(AWTUtil.toBufferedImage(dest), "jpg", new File(base, "pts_" + pts + "_" + i + ".jpg"));
        }
    }

    private static int[][] allocBuffer(AbstractMP4DemuxerTrack vt) {
        VideoSampleEntry vse = (VideoSampleEntry) vt.getSampleEntries()[0];
        int size = (int) ((11 * vse.getWidth() * vse.getHeight()) / 10);
        return new int[][] { new int[size], new int[size], new int[size] };
    }

    private static void randomFrame(AbstractMP4DemuxerTrack vt, ProresDecoder decoder, long frameCount, Yuv422pToRgb transform,
            File base) throws IOException {
        long frame = (long) (Math.random() * frameCount);
        System.out.println(frame);
        vt.gotoFrame((int) frame);
        for (int i = 0; i < 10; i++) {
            Packet frames = vt.nextFrame();
            Picture pic = decoder.decodeFrame(frames.getData(), allocBuffer(vt));
            Picture dest = Picture.create(pic.getWidth(), pic.getHeight(), RGB);

            transform.transform(pic, dest);
//            ImageIO.write(AWTUtil.toBufferedImage(dest), "jpg", new File(base, "frm_" + frame + "_" + i + ".jpg"));
        }
    }

    private static void testAudio(File src, File wavFile) throws Exception {
        MP4Demuxer demuxer = new MP4Demuxer(readableFileChannel(src));
        AbstractMP4DemuxerTrack demuxerTrack = demuxer.getAudioTracks().get(0);

        FileChannelWrapper fos = NIOUtils.writableFileChannel(wavFile);

        AudioSampleEntry se = (AudioSampleEntry) demuxerTrack.getSampleEntries()[0];

        WavHeader wav = new WavHeader("RIFF", 40, "WAVE", new FmtChunk((short) 1, (short) se.getChannelCount(),
                (int) se.getSampleRate(), (int) se.getSampleRate() * se.getBytesPerFrame(),
                (short) se.getBytesPerFrame(), (short) ((se.getBytesPerFrame() / se.getChannelCount()) << 3)), 44,
                se.getBytesPerFrame() * demuxerTrack.getFrameCount());
        wav.write(fos);

        while (true) {
            Packet packet = demuxerTrack.nextFrame();
            fos.write(packet.getData());
        }
    }

    private static void testProres(File base) throws Exception {
        ProresDecoder decoder = new ProresDecoder();
        for (int i = 1;; i++) {
            System.out.println(i);
            ByteBuffer buffer = NIOUtils.fetchFrom(new File(base, String.format("frame%08d.raw", i)));

            int sz = 1920 * 1080 * 2;
            decoder.decodeFrame(buffer, new int[][] { new int[sz], new int[sz], new int[sz] });
        }
    }

    private static void testVideo(File src, File base) throws IOException, FileNotFoundException {
        int startFn = 7572;
        MP4Demuxer demuxer = new MP4Demuxer(readableFileChannel(src));
        AbstractMP4DemuxerTrack vt = demuxer.getVideoTrack();
        vt.gotoFrame(startFn);
        for (int i = 0;; i++) {
            byte[] expected = readFileToByteArray(new File(base, String.format("frame%08d.raw", i + startFn
                    + 1)));
            Packet pkt = vt.nextFrame();
            Assert.assertArrayEquals(expected, NIOUtils.toArray(pkt.getData()));
            System.out.print(".");
            if ((i % 100) == 0)
                System.out.println();
        }
    }

    private static void testAudioMuxer(File wav, File out) throws IOException {
        WavHeader header = WavHeader.read(wav);
        RandomAccessFile in = new RandomAccessFile(wav, "r");
        in.seek(header.dataOffset);
        FileChannel ch = in.getChannel();
        MP4Muxer muxer = new MP4Muxer(writableFileChannel(out));
        PCMMP4MuxerTrack track = muxer.addPCMTrack(48000, 1, 3,
                MP4Muxer.audioSampleEntry("in24", 1, 3, 1, 48000, Endian.LITTLE_ENDIAN));

        ByteBuffer buffer = ByteBuffer.allocate(3 * 24000);
        while (ch.read(buffer) != -1) {
            track.addSamples(buffer);
        }
        muxer.writeHeader();
    }

    private static void testRemux(File src, File dst) throws Exception {
        MP4Muxer muxer = new MP4Muxer(writableFileChannel(dst));

        MP4Demuxer demuxer1 = new MP4Demuxer(readableFileChannel(src));
        AbstractMP4DemuxerTrack vt1 = demuxer1.getVideoTrack();

        FramesMP4MuxerTrack outTrack = muxer.addTrack(VIDEO, (int) vt1.getTimescale());
        outTrack.addSampleEntry(vt1.getSampleEntries()[0]);
        for (int i = 0; i < vt1.getFrameCount(); i++) {
            outTrack.addFrame((MP4Packet)vt1.nextFrame());
        }

        muxer.writeHeader();
    }

    private static void storeMdat(File src, File dst) throws Exception {
        List<Atom> rootAtoms = MP4Util.getRootAtoms(readableFileChannel(src));
        long mdatOff = -1, mdatSize = 0;
        for (Atom atom : rootAtoms) {
            if ("mdat".equals(atom.getHeader().getFourcc())) {
                mdatOff = atom.getOffset();
                mdatOff += atom.getHeader().headerSize();
                mdatSize = atom.getHeader().getBodySize();
            }
        }
        if (mdatOff == -1) {
            System.out.println("no mdat");
            return;
        }

        InputStream in = new BufferedInputStream(new FileInputStream(src));
        in.skip(mdatOff);
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dst));

        for (int i = 0; i < mdatSize; i++) {
            out.write(in.read());
        }
    }

    private static void narrowDown(File src, File dst) throws Exception {
        SeekableByteChannel rw = rwFileChannel(dst);
        SeekableByteChannel inp = readableFileChannel(src);
        List<Atom> rootAtoms = MP4Util.getRootAtoms(inp);
        for (Atom atom : rootAtoms) {
            if ("moov".equals(atom.getHeader().getFourcc())) {
                MovieBox box = (MovieBox) atom.parseBox(inp);
                MP4Util.writeMovie(rw, box);
            } else {
                atom.copy(inp, rw);
            }
        }
        inp.close();
        rw.close();
    }
}


text:
#include <memory>
#include <string>
#include <vector>

#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/service/computation_placer.h"
#include "tensorflow/compiler/xla/service/hlo_input_output_alias_config.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xrt/xrt.pb.h"
#include "tensorflow/compiler/xrt/xrt_compilation_cache.h"
#include "tensorflow/compiler/xrt/xrt_device.h"
#include "tensorflow/compiler/xrt/xrt_memory_manager.h"
#include "tensorflow/compiler/xrt/xrt_state.h"
#include "tensorflow/compiler/xrt/xrt_util.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/gtl/cleanup.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/stream_executor/stream_executor.h"
#include "tensorflow/stream_executor/stream_executor_internal.h"

namespace tensorflow {

namespace {

struct InputBuffers {
  std::vector<RefPtr<XRTTupleAllocation>> input_tuples;
  std::vector<xla::ShapedBuffer> input_allocations;
  std::vector<xla::ShapedBuffer*> input_pointers;
};

uint32 InitialRandomSeed() {
  // Support plumbing the TF seed through to XLA is being worked on.
  // If a user wants deterministic behavior, their best option
  // is to start with a known checkpoint. This also handles issues when
  // multiple random calls can be invoked in any order by TF executor.
  // Another option is to use stateless random ops. They have much cleaner
  // semantics.
  // If a user really wants to set a deterministic seed for XLA-based
  // devices, this is the place to do it.
  std::random_device rd;
  // Make the starting value odd.
  return rd() | 1;
}

uint32 GetXLARandomSeed() {
  // We initialize counter with an odd number and increment it by two
  // everytime. This ensures that it will never be zero, even
  // after an overflow. When seeded with zero, some XLA backends
  // can return all zeros instead of random numbers.
  static std::atomic<uint32> counter(InitialRandomSeed());
  return counter.fetch_add(2);
}

xla::StatusOr<InputBuffers> GetInputBuffers(
    XRTMemoryManager::WorkingSet* working_set, xla::Backend* backend,
    const std::vector<InputCoords>& input_coords, bool release_inputs) {
  InputBuffers input_buffers;
  input_buffers.input_tuples.reserve(input_coords.size());
  input_buffers.input_allocations.reserve(input_coords.size());
  input_buffers.input_pointers.reserve(input_coords.size());
  for (size_t i = 0; i < input_coords.size(); ++i) {
    TF_RETURN_IF_ERROR(
        working_set->LookupAndPin(backend, input_coords[i].handle));
    auto tuple = working_set->PinnedTuples().back();
    input_buffers.input_tuples.emplace_back(tuple);
    if (release_inputs) {
      // We are holding a reference to the tuple, so we can safely delete it
      // from the resource manager here.
      TF_RETURN_IF_ERROR(
          working_set->MemoryManager()->Release(input_coords[i].handle));
      VLOG(2) << "Released allocation handle " << input_coords[i].handle;
    }
    if (input_coords[i].index.empty()) {
      TF_ASSIGN_OR_RETURN(xla::ShapedBuffer shaped_buffer,
                          tuple->ToShapedBuffer());
      input_buffers.input_allocations.emplace_back(std::move(shaped_buffer));
    } else {
      TF_ASSIGN_OR_RETURN(xla::ShapedBuffer shaped_buffer,
                          tuple->ToShapedBuffer());
      TF_ASSIGN_OR_RETURN(xla::ShapedBuffer sub_shaped_buffer,
                          shaped_buffer.SubShapedBuffer(input_coords[i].index));
      input_buffers.input_allocations.emplace_back(
          std::move(sub_shaped_buffer));
    }
  }
  for (size_t i = 0; i < input_buffers.input_allocations.size(); ++i) {
    input_buffers.input_pointers.push_back(&input_buffers.input_allocations[i]);
  }
  return std::move(input_buffers);
}

xla::StatusOr<InputBuffers> GetChainedOpInputs(
    const xrt::XRTChainedExecuteOp& op,
    absl::Span<const RefPtr<XRTTupleAllocation>> op_inputs) {
  InputBuffers input_buffers;
  input_buffers.input_tuples.reserve(op.inputs_size());
  input_buffers.input_allocations.reserve(op.inputs_size());
  input_buffers.input_pointers.reserve(op.inputs_size());
  for (int i = 0; i < op.inputs_size(); ++i) {
    auto& input = op.inputs(i);
    input_buffers.input_tuples.emplace_back(op_inputs[i]);
    // Thanks to the greatness of proto3, there is no way to query for
    // explicitly set fields, so the default for output_index (zero) means no
    // sub-index. As consequence, the real index is output_index - 1.
    if (input.output_index() == 0) {
      TF_ASSIGN_OR_RETURN(xla::ShapedBuffer shaped_buffer,
                          input_buffers.input_tuples.back()->ToShapedBuffer());
      input_buffers.input_allocations.emplace_back(std::move(shaped_buffer));
    } else {
      TF_ASSIGN_OR_RETURN(xla::ShapedBuffer shaped_buffer,
                          input_buffers.input_tuples.back()->ToShapedBuffer());
      TF_ASSIGN_OR_RETURN(
          xla::ShapedBuffer sub_shaped_buffer,
          shaped_buffer.SubShapedBuffer({input.output_index() - 1}));
      input_buffers.input_allocations.emplace_back(
          std::move(sub_shaped_buffer));
    }
  }
  for (size_t i = 0; i < input_buffers.input_allocations.size(); ++i) {
    input_buffers.input_pointers.push_back(&input_buffers.input_allocations[i]);
  }
  return std::move(input_buffers);
}

xla::StatusOr<RefPtr<XRTTupleAllocation>> RunExecutable(
    OpKernelContext* context, XRTGenericDeviceAccessor::ScopedRef* device_ref,
    xla::LocalExecutable* executable, const InputBuffers& input_buffers,
    se::Stream* stream, int rng_seed) {
  VLOG(2) << "Executing computation.";
  xla::ExecutableRunOptions run_options;
  run_options.set_stream(stream);
  run_options.set_allocator(device_ref->backend()->memory_allocator());
  run_options.set_intra_op_thread_pool(&context->eigen_cpu_device());
  run_options.set_rng_seed(rng_seed);

  Env* env = Env::Default();
  auto start_time = env->NowMicros();
  TF_ASSIGN_OR_RETURN(
      xla::ScopedShapedBuffer run_result,
      executable->Run(input_buffers.input_pointers, run_options));
  auto elapsed = env->NowMicros() - start_time;
  VLOG(2) << "Elapsed time: " << elapsed << "us";

  auto shaped_buffer = run_result.release();
  XRTTupleAllocation* output_tuple;
  TF_RETURN_IF_ERROR(XRTTupleAllocation::CreateFromBuffer(
      shaped_buffer, device_ref->backend(), device_ref->device_ordinal(),
      &output_tuple));
  RefPtr<XRTTupleAllocation> output_tuple_ptr(output_tuple);

  // The ScopedShapedBuffer returned by the executable Run() API, in case of
  // input/output buffer aliasing, might have holes in it, which need to be
  // filled using the proper input tuples buffers which are the source of
  // aliasing.
  const xla::HloInputOutputAliasConfig& input_output_alias =
      executable->executable()->module().input_output_alias_config();
  auto alias_function =
      [&](const xla::ShapeIndex& output_index,
          const xla::HloInputOutputAliasConfig::Alias& alias) -> Status {
    TF_RET_CHECK(alias.parameter_number < input_buffers.input_tuples.size());
    return alias.kind == xla::HloInputOutputAliasConfig::AliasKind::kUserAlias
               ? output_tuple->AliasBufferFrom(
                     *input_buffers.input_tuples[alias.parameter_number],
                     alias.parameter_index, output_index)
               : Status::OK();
  };
  TF_RETURN_IF_ERROR(input_output_alias.ForEachAliasWithStatus(alias_function));

  return std::move(output_tuple_ptr);
}

xla::StatusOr<RefPtr<XRTTupleAllocation>> ExecuteComputation(
    OpKernelContext* context, XRTMemoryManager* memory_manager,
    XRTGenericDeviceAccessor::ScopedRef* device_ref,
    xla::LocalExecutable* executable, const InputBuffers& input_buffers,
    se::Stream* stream, int rng_seed) {
  auto runfn = [&]() {
    return RunExecutable(context, device_ref, executable, input_buffers, stream,
                         rng_seed);
  };

  // We pass zero as requested_free_size as there is no simple way to get the
  // peak heap size. Upon zero, the Run() API will try to free chunks of device
  // memory, until either the runfn can run, or we run out of freeable memory.
  return memory_manager->Run<RefPtr<XRTTupleAllocation>>(
      runfn, device_ref->backend(), device_ref->device_ordinal(),
      /*requested_free_size=*/0);
}

xla::StatusOr<RefPtr<XRTTupleAllocation>> ExecuteComputation(
    OpKernelContext* context, const RefPtr<XRTMemoryManager>& memory_manager,
    XRTGenericDeviceAccessor::ScopedRef* device_ref,
    xla::LocalExecutable* executable,
    const std::vector<InputCoords>& input_coords, bool release_inputs,
    se::Stream* stream, int rng_seed) {
  XRTMemoryManager::WorkingSet working_set(memory_manager);
  TF_ASSIGN_OR_RETURN(InputBuffers input_buffers,
                      GetInputBuffers(&working_set, device_ref->backend(),
                                      input_coords, release_inputs));
  return ExecuteComputation(context, memory_manager.get(), device_ref,
                            executable, input_buffers, stream, rng_seed);
}

// XRTExecuteOp

class XRTExecuteOp : public AsyncOpKernel {
 public:
  explicit XRTExecuteOp(OpKernelConstruction* context);
  ~XRTExecuteOp() override;

  void ComputeAsync(OpKernelContext* context, DoneCallback done) override;

 private:
  Status DoWork(OpKernelContext* context);
};

XRTExecuteOp::XRTExecuteOp(OpKernelConstruction* context)
    : AsyncOpKernel(context) {}

void XRTExecuteOp::ComputeAsync(OpKernelContext* context, DoneCallback done) {
  // Schedule onto the default queue, for unbounded concurrency. See b/73520706
  Env::Default()->SchedClosure([this, context, done]() {
    OP_REQUIRES_OK_ASYNC(context, DoWork(context), done);
    done();
  });
}

Status XRTExecuteOp::DoWork(OpKernelContext* context) {
  VLOG(1) << "XRTExecuteOp::Compute";
  ResourceMgr* rm;
  TF_RETURN_IF_ERROR(
      XRTGenericDeviceAccessor::GetResourceManager(context, &rm));

  const Tensor& execution_input = context->input(0);
  TF_RET_CHECK(TensorShapeUtils::IsScalar(execution_input.shape()));
  int64 compilation_handle = execution_input.scalar<int64>()();

  const Tensor& execution_config = context->input(1);
  TF_RET_CHECK(TensorShapeUtils::IsScalar(execution_config.shape()));
  xrt::XRTExecutionConfig config_proto;
  TF_RET_CHECK(
      config_proto.ParseFromString(execution_config.scalar<tstring>()()));

  int core_index_in_replica = config_proto.core_index_in_replica();
  TF_RET_CHECK(core_index_in_replica == 0);
  bool release_inputs = config_proto.release_input_handles();
  bool release_compilation = config_proto.release_compilation_handle();

  TF_ASSIGN_OR_RETURN(
      auto cache, GetOrCreateCompilationCache(rm, /*max_number_of_entries=*/0));
  // We are guaranteed that the underlying device object won't be deleted out
  // from under us, while the ScopedRef is live.
  class XRTGenericDeviceAccessor::ScopedRef device_ref;
  TF_RETURN_IF_ERROR(
      XRTGenericDeviceAccessor::InitScopedRef(context, &device_ref));

  int rng_seed = config_proto.rng_seed();
  if (rng_seed == 0) {
    rng_seed = GetXLARandomSeed();
  }

  se::Stream* stream = context->op_device_context()
                           ? context->op_device_context()->stream()
                           : nullptr;
  RefPtr<XRTMemoryManager> memory_manager = XRTMemoryManager::Get(rm);
  TF_ASSIGN_OR_RETURN(std::vector<InputCoords> input_coords,
                      GetComputationInputs(context, "input_handles"));

  std::unique_ptr<XRTCompilationCacheEntryRef> entry;
  TF_RETURN_IF_ERROR(cache->Lookup(compilation_handle, &entry));
  xla::LocalExecutable* executable = entry->get().get_executable();
  if (release_compilation) {
    // Process-wide cache of XLA executables.
    TF_RETURN_IF_ERROR(cache->Release(compilation_handle));
    VLOG(2) << "Released compilation handle " << compilation_handle;
  }

  TF_ASSIGN_OR_RETURN(
      RefPtr<XRTTupleAllocation> output_tuple,
      ExecuteComputation(context, memory_manager, &device_ref, executable,
                         input_coords, release_inputs, stream, rng_seed));

  return CreateExecuteOutput(context, memory_manager.get(),
                             std::move(output_tuple),
                             config_proto.return_exploded_tuple());
}

XRTExecuteOp::~XRTExecuteOp() = default;

class XRTExecuteChainedOp : public AsyncOpKernel {
 public:
  explicit XRTExecuteChainedOp(OpKernelConstruction* context);
  ~XRTExecuteChainedOp() override;

  void ComputeAsync(OpKernelContext* context, DoneCallback done) override;

 private:
  Status DoWork(OpKernelContext* context);
};

XRTExecuteChainedOp::XRTExecuteChainedOp(OpKernelConstruction* context)
    : AsyncOpKernel(context) {}

void XRTExecuteChainedOp::ComputeAsync(OpKernelContext* context,
                                       DoneCallback done) {
  // Schedule onto the default queue, for unbounded concurrency. See b/73520706
  Env::Default()->SchedClosure([this, context, done]() {
    OP_REQUIRES_OK_ASYNC(context, DoWork(context), done);
    done();
  });
}

Status XRTExecuteChainedOp::DoWork(OpKernelContext* context) {
  VLOG(1) << "XRTExecuteChainedOp::Compute";
  ResourceMgr* rm;
  TF_RETURN_IF_ERROR(
      XRTGenericDeviceAccessor::GetResourceManager(context, &rm));

  const Tensor& execution_plan = context->input(0);
  TF_RET_CHECK(TensorShapeUtils::IsScalar(execution_plan.shape()));
  xrt::XRTChainedExecutePlan plan;
  TF_RET_CHECK(plan.ParseFromString(execution_plan.scalar<tstring>()()));

  const Tensor& execution_config = context->input(1);
  TF_RET_CHECK(TensorShapeUtils::IsScalar(execution_config.shape()));
  xrt::XRTChainedExecuteConfig config;
  TF_RET_CHECK(config.ParseFromString(execution_config.scalar<tstring>()()));

  TF_ASSIGN_OR_RETURN(
      auto cache, GetOrCreateCompilationCache(rm, /*max_number_of_entries=*/0));
  // We are guaranteed that the underlying device object won't be deleted out
  // from under us, while the ScopedRef is live.
  class XRTGenericDeviceAccessor::ScopedRef device_ref;
  TF_RETURN_IF_ERROR(
      XRTGenericDeviceAccessor::InitScopedRef(context, &device_ref));

  int rng_seed = config.rng_seed();
  if (rng_seed == 0) {
    rng_seed = GetXLARandomSeed();
  }

  se::Stream* stream = context->op_device_context()
                           ? context->op_device_context()->stream()
                           : nullptr;
  RefPtr<XRTMemoryManager> memory_manager = XRTMemoryManager::Get(rm);
  auto execute_op = [&](const xrt::XRTChainedExecuteOp& op,
                        absl::Span<const RefPtr<XRTTupleAllocation>> op_inputs)
      -> xla::StatusOr<RefPtr<XRTTupleAllocation>> {
    TF_ASSIGN_OR_RETURN(InputBuffers input_buffers,
                        GetChainedOpInputs(op, op_inputs));

    std::unique_ptr<XRTCompilationCacheEntryRef> entry;
    TF_RETURN_IF_ERROR(cache->Lookup(op.computation_handle(), &entry));
    xla::LocalExecutable* executable = entry->get().get_executable();

    return ExecuteComputation(context, memory_manager.get(), &device_ref,
                              executable, input_buffers, stream, rng_seed);
  };

  return ExecuteChained(context, memory_manager, device_ref.backend(),
                        device_ref.device_ordinal(), plan, config, execute_op);
}

XRTExecuteChainedOp::~XRTExecuteChainedOp() = default;

}  // namespace

REGISTER_KERNEL_BUILDER(Name("XRTExecute")
                            .Device(DEVICE_XLA_CPU)
                            .HostMemory("computation_handle")
                            .HostMemory("execution_config")
                            .HostMemory("input_handles")
                            .HostMemory("output_handle"),
                        XRTExecuteOp);

REGISTER_KERNEL_BUILDER(Name("XRTExecute")
                            .Device(DEVICE_XLA_GPU)
                            .HostMemory("computation_handle")
                            .HostMemory("execution_config")
                            .HostMemory("input_handles")
                            .HostMemory("output_handle"),
                        XRTExecuteOp);

REGISTER_KERNEL_BUILDER(Name("XRTExecuteChained")
                            .Device(DEVICE_XLA_CPU)
                            .HostMemory("execution_plan")
                            .HostMemory("execution_config")
                            .HostMemory("output_handle"),
                        XRTExecuteChainedOp);

REGISTER_KERNEL_BUILDER(Name("XRTExecuteChained")
                            .Device(DEVICE_XLA_GPU)
                            .HostMemory("execution_plan")
                            .HostMemory("execution_config")
                            .HostMemory("output_handle"),
                        XRTExecuteChainedOp);

}  // namespace tensorflow

redpajama_set_name: RedPajamaGithub


text:
({
	runBackfill : function (component) {
		var runBatchAction = component.get("c.executeEthnicityRaceBatch");
		runBatchAction.setCallback(this, function(response) {
	        if(response.getState() === "SUCCESS") {

			    var backfillStatusMsg = component.find("ethnicRaceMsg");
			    $A.util.toggleClass(backfillStatusMsg, "slds-hide");

	        } else if(response.getState() === "ERROR") {
	        	this.displayError(response);
		    }
		});
		$A.enqueueAction(runBatchAction);
	},
	runCleanUp : function (component) {
		var runBatchAction = component.get("c.executePreferredEmailCleanUpBatch");
		runBatchAction.setCallback(this, function(response) {
	        if(response.getState() === "SUCCESS") {

			    var statusMsg = component.find("cleanUpMsg");
			    $A.util.toggleClass(statusMsg, "slds-hide");

	        } else if(response.getState() === "ERROR") {
	        	this.displayError(response);
		    }
		});
		$A.enqueueAction(runBatchAction);
	}
})


text:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;

namespace DanMuJi.Bilibili
{
    public class DanMuPa
    {
        public enum MessageType
        {
            Live, Preparing,Danmu,Gift,Welcome,Dammy
        }

        private Option option;

        public DanMuPa():this(new Option { ShowGift = true, ShowDanmu = false, ShowSystem = false })
        {

        }
        public DanMuPa(Option option)
        {
            this.option = option;
        }

        public string ParsePackage(Byte[] data)
        {
            var header = new Byte[12];
            Array.Copy(data, 0, header, 0, 0x0C);
            var cmd = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(header, 0x04));
            switch (cmd)
            {
                case 0x08:
                    return "Has connected into room...";
                case 0x05:
                    var text = Encoding.UTF8.GetString(data, 0x0C, data.Length - 0x0C);
                    var type = ParseMessage(text);
                    if (type == MessageType.Gift  || type == MessageType.Danmu)
                    {
                        return text;
                    }
                    else
                    {
                        return string.Empty;
                    }

                case 0x03:
                    var online = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data, 0x0C));
                    return $"online: {online}";
                default:
                    return string.Empty;
            }

        }

        private MessageType ParseMessage(string message)
        {
            var json = JObject.Parse(message);
            if (json["cmd"] != null)
            {
                switch (json.Value<string>("cmd"))
                {
                    case "SEND_GIFT":
                        return MessageType.Gift;
                    case "DANMU_MSG":
                        return MessageType.Danmu;
                    default:
                        return MessageType.Dammy;
                }
            }
            else
            {
                return MessageType.Dammy;
            }
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>at.irian.ankor.path (Ankor - Project 0.1 API)</title>
<meta name="date" content="2014-02-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

at.irian.ankor.path

Interfaces

PathSyntax


text:
/**
 * Purpose: Convert a decimal number to binary or a binary number
 * to its decimal equivalent.
 * @author Julian D. Quitian
 */

import java.util.Scanner;

 public class BinaryDecimalConverter{
   /**
    * Use {@code Scanner} to accept user input. Allows only {@code userInput} that
    * meets both {@code conditionOne} and {@code conditionTwo}, which stipulate
    * that only one of the given options is entered.
    *
    * @param conditionOne for {@code userInput} to be accepted.
    * @param conditionTwo for {@code userInput} to be accepted.
    * @return userInput once it meets requirements.
    */
   public static int getIntSelection(String conditionOne, String conditionTwo){
     Scanner in = new Scanner(System.in);
     int userInput;
     //Limits user input to desired values.
     do{
       System.out.print(conditionOne);
       while(!in.hasNextInt()){
         System.out.print(conditionTwo);
         in.next();
       }
       userInput = in.nextInt();
     }while(userInput <= 0 || userInput > 3);
     return userInput;
   }
   /**
    *
    */
   public static int binaryInputToDecimal(){
     int decimal;
     String binaryString = getBinary();
     decimal = Integer.parseInt(binaryString, 2);
     System.out.println(binaryString + " in binary equals " + decimal + " in decimal");
     return decimal;
   }
   /**
    *
    */
   public static String getBinary(){
     Scanner in = new Scanner(System.in);
     boolean restartLoop;
     String input;
     System.out.println("Please print binary to be converted");
     input = in.next();
     do{
       restartLoop = false;
       for(int i = 0; i < input.length(); i++){
         String temp = input.substring(i,i+1);
         if(!temp.equals("0") && !temp.equals("1")){
           restartLoop = true;
         }
       }
       if(restartLoop){
         System.out.println(input + " is not a binary, try again: ");
         input = in.next();
       }
     }while(restartLoop);
     return input;
   }
   public static void main(String[] args) {
     int userSelection;
     System.out.println("Welcome to Binary-Decimal Converter!");
     userSelection = getIntSelection("Enter [1] for Binary to Decimal, [2] for Decimal to Binary, "
                    + "or [3] to Exit: ", "[1] Binary-Decimal, [2] Decimal-Binary, [3] Exit: ");
     while(userSelection != 3){
       if(userSelection == 1){
         binaryInputToDecimal();
       }
         userSelection = getIntSelection("Enter [1] for Binary to Decimal, [2] for Decimal to Binary, "
          + "or [3] to Exit: ", "[1] Binary-Decimal, [2] Decimal-Binary, [3] Exit: ");
     }
   }
 }


text:
package eu.atos.sla.datamodel.bean;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import eu.atos.sla.datamodel.IService;

/**
 * A POJO object storing a provider's info.
 *
 */
@Entity
@Table(name = "provider")
@NamedQueries({
        @NamedQuery(name = Service.QUERY_FIND_ALL, query = "SELECT p FROM Service p"),
        @NamedQuery(name = Service.QUERY_FIND_BY_UUID, query = "SELECT p FROM Service p where p.uuid = :uuid"),
        @NamedQuery(name = Service.QUERY_FIND_BY_NAME, query = "SELECT p FROM Service p where p.name = :name") })
public class Service implements IService, Serializable {

    public final static String QUERY_FIND_ALL = "Service.findAll";
    public final static String QUERY_FIND_BY_UUID = "Service.getByUuid";
    public final static String QUERY_FIND_BY_NAME = "Service.getByName";

    private static final long serialVersionUID = -6655604906240872609L;

    Long id;
    String uuid;
    String name;

    public Service() {
    }

    public Service(Long id, String uuid, String name) {
        this.id = id;
        this.uuid = uuid;
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "uuid", unique = true)
    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
FIND_LIBRARY (PCRE2_LIBRARIES NAMES pcre2 pcre2-8)
FIND_PATH (PCRE2_INCLUDE_DIRS pcre2.h)
IF (PCRE2_LIBRARIES AND PCRE2_INCLUDE_DIRS)
  MESSAGE (STATUS "")
  MESSAGE (STATUS "PCRE2 Setup:")
  MESSAGE (STATUS "------------")
  MESSAGE (STATUS "     LIBRARIES: ${PCRE2_LIBRARIES}")
  MESSAGE (STATUS "  INCLUDE_DIRS: ${PCRE2_INCLUDE_DIRS}")
  SET (PCRE2_FOUND TRUE CACHE BOOL "Found PCRE2 libraries" FORCE)
  GET_FILENAME_COMPONENT(PCRE2_DIRECTORY "${PCRE2_LIBRARIES}" DIRECTORY CACHE)
  IF ("${CMAKE_HOST_SYSTEM}" MATCHES ".*Windows.*")
    SET (PCRE2_RUNTIME_DIRECTORY "${PCRE2_DIRECTORY}/../bin")
  ELSE ()
    SET (PCRE2_RUNTIME_DIRECTORY "${PCRE2_DIRECTORY}")
  ENDIF ()
else()
  MESSAGE(STATUS "")
  MESSAGE(STATUS "PCRE2 Setup: buit-in")
  SET(PCRE2_FOUND FALSE CACHE BOOL "Found PCRE2 libraries" FORCE)
endif()


text:
namespace Microsoft.Azure.Management.Sql
{
    using Azure;
    using Management;
    using Rest;
    using Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// ServersOperations operations.
    /// </summary>
    public partial interface IServersOperations
    {
        /// <summary>
        /// Creates or updates a firewall rule.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='firewallRuleName'>
        /// The name of the firewall rule.
        /// </param>
        /// <param name='parameters'>
        /// The required parameters for creating or updating a firewall rule.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ServerFirewallRule>> CreateOrUpdateFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, ServerFirewallRule parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes a firewall rule.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='firewallRuleName'>
        /// The name of the firewall rule.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a firewall rule.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='firewallRuleName'>
        /// The name of the firewall rule.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ServerFirewallRule>> GetFirewallRuleWithHttpMessagesAsync(string resourceGroupName, string serverName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Returns a list of firewall rules.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IEnumerable<ServerFirewallRule>>> ListFirewallRulesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Imports a bacpac into a new database.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='parameters'>
        /// The required parameters for importing a Bacpac into a database.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ImportExportOperationResponse>> ImportDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, ImportRequestParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Returns a list of servers.
        /// </summary>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IEnumerable<Server>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Creates or updates a new server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='parameters'>
        /// The required parameters for creating or updating a server.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<Server>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, Server parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes a SQL server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a server.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<Server>> GetByResourceGroupWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Returns a list of servers in a resource group.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IEnumerable<Server>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Returns server usages.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IEnumerable<ServerMetric>>> ListUsagesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a database service objective.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='serviceObjectiveName'>
        /// The name of the service objective to retrieve.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ServiceObjective>> GetServiceObjectiveWithHttpMessagesAsync(string resourceGroupName, string serverName, string serviceObjectiveName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Returns database service objectives.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IEnumerable<ServiceObjective>>> ListServiceObjectivesWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Imports a bacpac into a new database.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The name of the resource group that contains the resource. You can
        /// obtain this value from the Azure Resource Manager API or the
        /// portal.
        /// </param>
        /// <param name='serverName'>
        /// The name of the server.
        /// </param>
        /// <param name='parameters'>
        /// The required parameters for importing a Bacpac into a database.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<ImportExportOperationResponse>> BeginImportDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, ImportRequestParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
<?php
namespace PhpMigration\Changes\v5dot6;

/**
 * @author Yuchen Wang <phobosw@gmail.com>
 *
 * Code is compliant with PSR-1 and PSR-2 standards
 * http://www.php-fig.org/psr/psr-1/
 * http://www.php-fig.org/psr/psr-2/
 */

use PhpMigration\Changes\AbstractChangeTest;
use PhpMigration\Utils\TestHelper;

class IncompMiscTest extends AbstractChangeTest
{
    public function testJson()
    {
        $this->assertHasSpot('json_decode();');
    }

    public function testGmp()
    {
        $table = TestHelper::fetchProperty($this->change, 'gmpTable');
        foreach ($table as $name => $dummy) {
            $this->assertHasSpot($name.'();');
        }
    }

    public function testMcrypt()
    {
        $table = TestHelper::fetchProperty($this->change, 'mcryptTable');
        foreach ($table as $name => $dummy) {
            $this->assertHasSpot($name.'();');
        }
    }
}


text:
layout: default
title: Contact
permalink: /contact/
---

   Reach me via email

   And find me on these networks:

   / LinkedIn /
   Twitter /
    Github   /

   / GitLab /
    Stack Overflow /

   <object type="image/svg+xml" data="../css/mountainssoftgreenorange.svg">
   <mountains here>
   </object>


text:
Showtime is a lightweight framework for easily creating stunning tours around your web app.
It comes with a built in chain so its really easy to mix your tours with custom functionality.

**Demo:** http://apps.tweecode.com/custom/showtime/
### Usage
Download showtime.js and include it in your html.
```html
<script src="showtime.js"></script>
<button onclick="tour.start()" style="position: relative; z-index: 10000;">Take a tour</button>
<div class="element">Lorem ipsum</div>
<script>
var tour = new Showtime()
    .show({
        element: document.querySelector('.element'),
        title: 'hey I have a title.',
        content: '<p>This is the tooltip content</p>',
        placement: 'right',
        buttons: [
            {
                label: 'Quit',
                click: function () {
                    tour.quit()
                }
            },
            {
                label: 'Next',
                click: function () {
                    tour.next()
                }
            }
        ]
    })
    .call(function () {
        alert('This was a short tour');
    });
</script>
```
From this point you can chain as many show, modal and call functions you like to the showtime chain.
Sometimes you end up with a lot of repetitions. so to make your code pretty you can define global defaults for the chain like in the example below.

Example code
```javascript
var tour = new Showtime({
    //these options will become default for all .show functions chained on this instance
    padding: 10,
    removeOnOuterClick: true,
    focusClick: function () {
        tour.next();
    },
    buttons: [
        {
            label: 'Quit',
            click: function () {
                tour.quit()
            }
        },
        {
            label: 'Next',
            click: function () {
                tour.next()
            }
        }
    ]
})
.show({
    element: '.leftMenu',
    title: 'hey I have a title again.',
    placement: 'right',
    content: '<p>This is a ball</p>',
    dimentions: {
        height: 400 // We can override the dementions of the focuspoint. top, left, height, width
    },
    focusClick: function () { // Hijack the event for the selected element to do whatever you want
        tour.next();
    },
    buttons: [
        {
            label: 'quit',
            click: function () {
                tour.quit()
            }
        },
        {
            label: 'next',
            click: function () {
                tour.next()
            }
        }
    ]
})
.modal({
    title: 'Modal title',
    message: 'this can contain <strong>HTML</strong>'
})
.call(function () {
    console.log('foobar');
})
.show({
    element: '.topMenu',
    placement: 'top',
    content: '<p>Lorem ipsum</p>'
})
.show({
    element: '.filterButtons',
    placement: 'bottom',
    content: '<p>Lorem ipsum</p>',
    focusClick: function () {
        alert('Thats all folks');
    },
});
```
### Showtime functions
tour.show([options])
tour.call([function])
tour.modal([options])

### Controls
```javascript
// start the tour
tour.start();
// Run the next function in the chain
tour.next();
// Run the previous function in the chain
tour.previous();
// End the tour
tour.quit();
```

### Show Options
- element //type, class, id, element object, jquery object
- padding //integer, value in px
- buttons //array of objects with label and click
- focusClick //function
- dimentions //object width, height, top, left
- placement //top, left, right, bottom
- removeOnOuterClick
- autoplay //not really tested with call functions
- autoplayDelay

### Modal Options
- title
- message
- withBackdrop
- size //normal large small
- onClose
- onOpen

### TODO
- add keyboard shortcuts
- custom template option for Modal
- create themes


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="shr_product_grid_spacing">16dp</dimen>
    <dimen name="shr_product_grid_spacing_small">4dp</dimen>
    <dimen name="shr_product_card_image_height">108dp</dimen>

    <dimen name="shr_product_grid_reveal_height">200dp</dimen>

    <!-- Dimens for staggered asymmetric grid layout cards-->
    <dimen name="shr_staggered_product_grid_spacing_large">30dp</dimen>
    <dimen name="shr_staggered_product_grid_spacing_small">26dp</dimen>
    <dimen name="shr_staggered_product_grid_margin_top_first">72dp</dimen>
    <dimen name="shr_staggered_product_grid_margin_top_second">56dp</dimen>
    <dimen name="shr_staggered_product_grid_margin_top_third">152dp</dimen>
    <dimen name="shr_staggered_product_grid_card_width_portrait">165dp</dimen>
    <dimen name="shr_staggered_product_grid_card_height_portrait">247dp</dimen>
    <dimen name="shr_staggered_product_grid_card_width_landscape">188dp</dimen>
    <dimen name="shr_staggered_product_grid_card_height_landscape">140dp</dimen>
</resources>


text:
package de.plushnikov.intellij.plugin;

import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiMethodCallExpression;
import com.intellij.testFramework.LightCodeInsightTestCase;
import org.jetbrains.annotations.NonNls;

import java.util.List;

/**
 * Based on logic from com.intellij.codeInsight.ExceptionCheckingTest
 */
public class SneakyThrowsTest extends LightCodeInsightTestCase {

  public void testCatchAllException() throws Exception {
    PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows void foo() {  throwsMyException(); }");
    List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
    assertTrue(exceptions.isEmpty());
  }

  public void testCatchSpecificException() throws Exception {
    PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows(MyException.class) void foo() {  throwsMyException(); }");
    List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
    assertTrue(exceptions.isEmpty());
  }

  public void testCatchGeneralException() throws Exception {
    PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows(Exception.class) void foo() {  throwsMyException(); }");
    List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
    assertTrue(exceptions.isEmpty());
  }

  public void testNotCatchException() throws Exception {
    PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows(SomeException.class) void foo() {  throwsMyException(); }");
    List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
    assertEquals(1, exceptions.size());
    assertEquals("Test.MyException", exceptions.get(0).getCanonicalText());
  }

  @Override
  protected Sdk getProjectJDK() {
    return JavaSdk.getInstance().createJdk("java 1.7", "lib/mockJDK-1.7", false);
  }

  private static PsiMethodCallExpression createCall(@NonNls final String body) throws Exception {
    final PsiFile file = createFile("test.java", "class Test { " + body +
      "void throwsMyException() throws MyException {}" +
      "void throwsSomeException() throws SomeException {}" +
      "static class MyException extends Exception {}" +
      "static class SomeException extends Exception {}" +
      "static class Exception {}" +
      "}");
    PsiMethodCallExpression methodCall = findMethodCall(file);
    assertNotNull(methodCall);
    return methodCall;
  }

  private static PsiMethodCallExpression findMethodCall(PsiElement element) {
    if (element instanceof PsiMethodCallExpression) {
      return (PsiMethodCallExpression) element;
    }

    for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
      final PsiMethodCallExpression call = findMethodCall(child);
      if (call != null) {
        return call;
      }
    }

    return null;
  }
}


text:
require File.join(File.dirname(__FILE__), 'spec_helper')
require 'selenium-webdriver'

describe "Slideshows" do
  it "should be able to be read on mobile devices" do
    url = "/articles/1521247-biggest-signs-that-dwight-howard-will-remain-with-la-lakers-long-term"
    @driver.goto url
    @driver.title.should include("Bleacher Report")

    @wait = Selenium::WebDriver::Wait.new(:timeout => 30) # seconds

    #################################
    #     content       #
    #################################
    @driver.find_element(:class, 'border-box').should_not be_nil
    @driver.find_element(:class, 'article-title').should_not be_nil
    container = @driver.find_element(:id, 'article-container')
    container.should_not be_nil
    @driver.find_element(:class, 'article-body').should_not be_nil

    # ~ Comment icon loads text field and closes:
    # comments-count comments-count-bottom js-open-comments
    #@driver.find_element(:xpath, '//*[@id="article-container"]/section[1]/div/span').click
    #@driver.find_element(:class, 'comments-textarea').should_not be_nil
    #@driver.find_element(:class, 'close-comments').click
    #@driver.find_element(:xpath, '//*[@id="article-container"]/section[1]/div/span').should_not be_nil

    # ~~ Click Comment Button
    sleep 20
    comment_button = @wait.until { @driver.find_elements(:xpath => '//*[@id="article-container"]/section[1]/div/div[2]/div[1]') }
    comment_button[0].click()
    #@driver.execute_script("arguments[0].click();", comment_button)
    #@driver.action.move_to(comment_button[0],20,20).click.perform

    # ~~ Check Comment Box Came Up and Close
    #ßcomment_box = @wait.until { @driver.find_element(:class => "comment-textarea") }

    # ~~ Swipe to next article
    article = @driver.find_element(:xpath => '//*[@id="article-container"]/section[2]/div/div[3]')
    @driver.action.drag_and_drop_by(article, -200, 0).perform
    sleep(10)

    # ~~ Check Slide Number
    slide_indicator = @driver.find_element(:xpath => '//*[@id="article-container"]/section[2]/div/header/hgroup/h3/span')
    slide_indicator.text.should == "(Slide 2 of 7)"

    #################################
    #     Legacy Code:       #
    #################################
    #Content
#    @driver.find_element(:id, "article-header").should_not be_nil
#    @driver.find_element(:css => '#article-container > div:nth-of-type(1) > div:nth-of-type(2) > div:nth-of-type(2) > div:nth-of-type(1) > img:nth-of-type(1)')
#    @driver.find_element(:css => '#article-container > div:nth-of-type(1) > div:nth-of-type(2) > div:nth-of-type(2) > div:nth-of-type(2)').should_not be_nil
#    @driver.page_source.scan("related_content").should_not be_nil
#    @driver.page_source.scan("comments").should_not be_nil

    #Comments box
#    @driver.find_element(:class, 'comments-count comments-count-top js-open-comments').click

    #Begin slideshow
#    @driver.find_element(:css => '#slide-header > div:nth-of-type(1) > div:nth-of-type(2)').click
#    @driver.find_element(:css => '#article-container > div:nth-of-type(1) > div:nth-of-type(2) > div:nth-of-type(2) > div:nth-of-type(1) > img:nth-of-type(1)').should_not be_nil
#    @driver.find_element(:css => '#article-container > div:nth-of-type(1) > div:nth-of-type(2) > div:nth-of-type(2) > div:nth-of-type(2)').should_not be_nil

    #Next slide
#    @driver.find_element(:css=> '#slide-header > div:nth-of-type(1) > div:nth-of-type(2)').click
  end
end


text:
import pymysql
import uuid
import datetime
import os
import base64
from werkzeug.security import generate_password_hash, check_password_hash

class Database:
    def __init__(self): # WORKS
        self.db = pymysql.connect(host="localhost", user="root", passwd="*********", db="video")
        self.cur = self.db.cursor()

    def get_most_viewed(self): # WORKS
        """
        - Returns a list of top 10 video IDs in the descending order of view count from the VIDEOS table.
        """
        self.cur.execute("SELECT video_ID FROM videos ORDER BY CAST(view_count as decimal) DESC LIMIT 10")
        most_viewed_video_IDs = []
        for ID in self.cur.fetchall():
            most_viewed_video_IDs.append(ID[0])
        return most_viewed_video_IDs

    def is_valid_user(self, username, password): # WORKS
        """
        - Checks if the entered username and password corresponds to a valid user in the USERS and ADMINS table.
        """
        done1 = self.cur.execute("SELECT password FROM users WHERE username=\"{}\"".format(username))
        done2 = self.cur.execute("SELECT username FROM admins WHERE username=\"{}\"".format(username))
        if done1 == 0 and done2 == 0: # If both queries are unsuccessful, username doesn't exist in both tables.
            return False
        else:
            if done1 == 1: # If username exists in USERS table.
                self.cur.execute("SELECT password FROM users WHERE username=\"{}\"".format(username))
                stored_password = self.cur.fetchone()[0]
                return check_password_hash(stored_password, password) # Returns True if the hashes match.
            else: # If username exists in ADMINS table.
                self.cur.execute("SELECT password FROM admins WHERE username=\"{}\"".format(username))
                stored_password = self.cur.fetchone()[0]
                return check_password_hash(stored_password, password) # Returns True if the hashes match.

    def is_valid_username(self, username): # WORKS
        """
        - Checks if the username is already present in the USERS table.
        """
        done1 = self.cur.execute("SELECT username FROM users WHERE username=\"{}\"".format(username))
        done2 = self.cur.execute("SELECT username FROM admins WHERE username=\"{}\"".format(username))
        if done1 == 0 and done2 == 0: # If both queries are unsuccessful, username doesn't exist in both tables.
            return False
        else:
            return True

    def is_admin(self, username): #WORKS
        """
        - Checks if a user is an admin in the ADMINS table..
        """
        done = self.cur.execute("SELECT username FROM admins WHERE username=\"{}\"".format(username))
        if done == 0: # If query is unsuccessful, username is not an administrator.
            return False
        else:
            return True

    def add_user(self, username, password): #WORKS
        """
        - Add the new user credentials to the USERS table.
        """
        password_hash = generate_password_hash(password) # Generates a SHA256 hash.
        try:
            self.cur.execute("INSERT INTO users VALUES(\"{}\", \"{}\")".format(username, password_hash))
            self.db.commit()
        except:
            self.db.rollback()

    def update_password(self, username, password): #WORKS
        """
        - Updates the password of the user in the USERS table.
        """
        password_hash = generate_password_hash(password)
        try:
            self.cur.execute("UPDATE users SET password = \"{}\" WHERE username = \"{}\"".format(password_hash, username))
            self.db.commit()
        except:
            self.db.rollback()

    def delete_user(self, username): #WORKS
        """
        - Deletes user credentials from the USERS table.
        """
        try:
            self.cur.execute("SELECT video_ID FROM videos WHERE uploader = \"{}\"".format(username))
            videos_to_delete = []
            for row in self.cur.fetchall():
                videos_to_delete.append(row[0]) # Get video IDs of all videos uploaded by the user.
            for ID in videos_to_delete:
                os.remove('static/videos/' + str(ID) + '.mp4') # Deletes the video from the static/videos directory.
                os.remove('static/images/' + str(ID) + '.jpg') # Deletes the image from the static/images directory.
            self.cur.execute("DELETE FROM users WHERE username = \"{}\"".format(username))
            self.db.commit()
        except:
            self.db.rollback()

    def upload_video(self, video_ID, username, title): #WORKS
        """
        - Updates VIDEOS table with video ID, uploader username and video title in the VIDEOS table.
        """
        try:
            view_count = 0
            self.cur.execute("INSERT INTO videos VALUES(\"{}\", \"{}\", \"{}\", {}, NULL)".format(video_ID, title, username, view_count))
            self.db.commit()
        except:
            self.db.rollback()

    def get_video_title(self, video_ID): #WORKS
        """
        - Returns the title of the video with the corresponding video ID from the VIDEOS table.
        """
        try:
            self.cur.execute("SELECT video_title FROM videos WHERE video_ID = \"{}\"".format(video_ID))
            title = self.cur.fetchone()[0]
            return title
        except:
            return "Error getting title"

    def update_view_count(self, video_ID): #WORKS
        """
        - Updates the view count for the corresponding video ID in the VIDEOS table.
        """
        try:
            self.cur.execute("UPDATE videos SET view_count = view_count + 1 WHERE video_ID = \"{}\"".format(video_ID)) # Adds 1 to the existing value.
            self.db.commit()
        except:
            self.db.rollback()

    def update_watched(self, username, video_ID): #WORKS
        """
        - Adds the username and video ID to the WATCHED table.
        """
        try:
            done = self.cur.execute("SELECT * FROM watched WHERE username = \"{}\" AND video_ID = \"{}\"".format(username, video_ID))
            if done == 1: # If the query was successful, one row exists
                self.cur.execute("UPDATE watched SET count =  count + 1 WHERE username = \"{}\" AND video_ID = \"{}\"".format(username, video_ID))
                try:
                    self.cur.execute("CALL add_to_fav(\"{}\", \"{}\")".format(video_ID, username))
                except:
                    pass
            if done == 0: # If the query was unsuccessful, row does not exist.
                count = 1
                self.cur.execute("INSERT INTO watched VALUES(\"{}\", \"{}\", {})".format(video_ID, username, count))
            self.db.commit()
        except:
            self.db.rollback()

    def get_video_uploader(self, video_ID): #WORKS
        """
        - Returns the username of the user that uploaded the video with the corresponding video ID.
        """
        try:
            done = self.cur.execute("SELECT uploader FROM videos WHERE video_ID = \"{}\"".format(video_ID))
            uploader = self.cur.fetchone()[0]
            return uploader
        except:
            return "Error getting username"

    def get_upload_date(self, video_ID):
        """
        - Returns the date when the video was uploaded from VIDEOS table.
        """
        self.cur.execute("SELECT upload_date FROM videos WHERE video_ID = \"{}\"".format(video_ID))
        return self.cur.fetchone()[0]

    def get_random_ID(self): # WORKS
        """
        - Returns a random video ID from the VIDEOS table.
        """
        self.cur.execute("SELECT video_ID FROM videos ORDER BY RAND() LIMIT 1") # Selects video_ID from 1 random row.
        return self.cur.fetchone()[0]

    def get_watched(self, username): # WORKS
        """
        - Returns a list of video IDs watched by the user from the WATCHED table.
        """
        self.cur.execute("SELECT video_ID FROM watched WHERE username = \"{}\"".format(username))
        watched_video_IDs = []
        for ID in self.cur.fetchall():
            watched_video_IDs.append(ID[0])
        return watched_video_IDs

    def get_views(self, video_ID): # WORKS
        """
        - Returns the view count of the video with the corresponding video_ID.
        """
        self.cur.execute("SELECT view_count FROM videos WHERE video_ID = \"{}\"".format(video_ID))
        return self.cur.fetchone()[0]

    def delete_video(self, video_ID): # WORKS
        """
        - Deletes the video from the database.
        """
        try:
            self.cur.execute("DELETE FROM videos WHERE video_ID = \"{}\"".format(video_ID))
            self.db.commit()
            os.remove('static/videos/' + str(video_ID) + '.mp4')
            os.remove('static/images/' + str(video_ID) + '.jpg')
        except:
            self.db.rollback()

    def is_available(self, video_ID): # WORKS
        """
        - Checks if the video ID is present in the database.
        """
        done = self.cur.execute("SELECT video_ID FROM videos WHERE video_ID = \"{}\"".format(video_ID))
        if done == 1:
            return True
        else:
            return False

    def get_uploaded(self, username): # WORKS
        """
        - Returns a list of all videos uploaded by the user with the corresponding username.
        """
        self.cur.execute("SELECT video_ID FROM videos WHERE uploader = \"{}\"".format(username))
        uploaded_video_IDs = []
        for ID in self.cur.fetchall():
            uploaded_video_IDs.append(ID[0])
        return uploaded_video_IDs

    def is_user_present(self, username): # WORKS
        """
        - Returns True if the username is present in the USERS table.
        """
        done = self.cur.execute("SELECT username FROM users WHERE username = \"{}\"".format(username))
        if done == 1:
            return True
        else:
            return False

    def get_five_random_IDs(self):
        """
        - Returns a maximum of 5 random video IDS from the VIDEOS table.
        """
        self.cur.execute("SELECT video_ID FROM videos ORDER BY RAND() LIMIT 5")
        IDs = []
        for ID in self.cur.fetchall():
            IDs.append(ID[0])
        return IDs

    def flag_ID(self, username, video_ID):
        """
        - Adds the video ID to the FLAGS table.
        """
        done = self.cur.execute("SELECT video_ID from flags WHERE video_ID = \"{}\"".format(video_ID))
        if done == 0: # Not yet flagged by any user.
            try:
                self.cur.execute("INSERT INTO flags VALUES(\"{}\", \"{}\")".format(video_ID, username))
                self.db.commit()
            except:
                self.db.rollback()

    def add_admin(self, username, password):
        """
        - Adds the new administrator to the ADMINS table.
        """
        password_hash = generate_password_hash(password) # Generates a SHA256 hash.
        try:
            self.cur.execute("INSERT INTO admins VALUES(\"{}\", \"{}\")".format(username, password_hash))
            self.db.commit()
        except:
            self.db.rollback()

    def get_flagger(self, video_ID):
        """
        - Returns username of flagger of the video ID.
        """
        self.cur.execute("SELECT username FROM flags WHERE video_ID = \"{}\"".format(video_ID))
        return self.cur.fetchone()[0]

    def get_flagged(self):
        """
        - Returns a list of flagged videos from FLAGS table.
        """
        self.cur.execute("SELECT video_ID FROM flags")
        flagged_IDs = []
        for ID in self.cur.fetchall():
            flagged_IDs.append(ID[0])
        return flagged_IDs

    def user_list(self):
        """
        - Returns a list of users in the USERS table.
        """
        self.cur.execute("SELECT username FROM users")
        users = []
        for username in self.cur.fetchall():
            users.append(username[0])
        return users

    def get_video_num(self, username):
        """
        - Returns the number of videos uploaded by the username.
        """
        done = self.cur.execute("SELECT video_ID FROM videos where uploader = \"{}\"".format(username))
        return done

    def get_flagged_num(self, username):
        """
        - Returns number of videos of user flagged by other users.
        """
        done = self.cur.execute("SELECT flags.video_ID FROM videos,flags WHERE videos.video_ID = flags.video_ID AND videos.uploader = \"{}\"".format(username))
        return done

    def get_user_count(self):
        """
        - Returns number of users in the USERS table.
        """
        done = self.cur.execute("SELECT username FROM users")
        return done

    def get_video_count(self):
        """
        - Returns number of videos in the VIDEOS table.
        """
        done = self.cur.execute("SELECT video_ID FROM videos")
        return done

    def get_total_view_count(self):
        """
        - Returns number of views on all videos in the VIDEOS table.
        """
        done = self.cur.execute("SELECT CAST(SUM(view_count) AS DECIMAL(10, 0)) FROM videos")
        count = self.cur.fetchone()[0]
        return count

    def get_flag_count(self):
        """
        - Returns number of flagged videos in the VIDEOS table.
        """
        done = self.cur.execute("SELECT video_ID FROM flags")
        return done

    def get_user_video_count(self, username):
        """
        - Returns number of videos uploaded by the user from VIDEOS table.
        """
        done = self.cur.execute("SELECT video_ID FROM videos WHERE uploader = \"{}\"".format(username))
        return done

    def get_user_view_count(self, username):
        """
        - Returns number of views on all videos uploaded by the user from VIDEOS table.
        """
        self.cur.execute("SELECT CAST(SUM(view_count) AS DECIMAL(10, 0)) FROM videos WHERE uploader = \"{}\"".format(username))
        return self.cur.fetchone()[0]

    def get_best_video_ID(self, username):
        """
        - Returns the video ID of the video uploaded by the user with most views.
        """
        self.cur.execute("SELECT video_ID FROM videos WHERE uploader = \"{}\" ORDER BY view_count DESC".format(username))
        return self.cur.fetchone()[0]

    def get_fav_video_ID(self, username):
        """
        - Returns the video ID of the user's favourite video.
        """
        self.cur.execute("SELECT video_ID FROM watched WHERE username = \"{}\" ORDER BY CAST(count as decimal) DESC".format(username))
        return self.cur.fetchone()[0]

    def get_favourites(self, username):
        """
        - Returns list of videos favourited by the user from FAVOURITES table.
        """
        self.cur.execute("SELECT video_ID FROM favourites WHERE username = \"{}\"".format(username))
        favourites = []
        for ID in self.cur.fetchall():
            favourites.append(ID[0])
        return favourites

    def delete_flag(self, video_ID):
        """
        - Deletes the video from FLAGS table.
        """
        try:
            self.cur.execute("DELETE FROM flags WHERE video_ID = \"{}\"".format(video_ID))
            self.db.commit()
        except:
            self.db.rollback()

    def video_dict(self):
        """
        - Returns a dictionary of video IDs, title and a list of video titles.
        - For Fuzzy Search.
        """
        self.cur.execute("SELECT video_ID, video_title FROM videos")
        videos = {}
        video_titles = []
        for video in self.cur.fetchall():
            video_titles.append(video[1])
            videos.update({video[0] : video[1]})
        return videos, video_titles


text:
var getToken = require("../service/getToken");
var getTicket = require("../service/getTicket");
var checkTicket = require("../service/checkTicket");
module.exports = function(app) {
    return function*(next) {
        if (app.ticket && app.ticket_expires && ( (Date.now() - app.ticket_expires) / 1000 ) > 7000 || !app.ticket) {
            yield createTicket(app);
        }
        yield * next;
    }
}

function* createTicket(app) {
    var res = yield getToken();
    var info = JSON.parse(res.body);
    app.access_token = info.access_token;
    console.log("token:", app.access_token);

    res = yield getTicket(app.access_token);
    info = JSON.parse(res.body);
    app.ticket = info.ticket;
    console.log("ticket:", app.ticket)

    app.ticket_expires = Date.now();
}


text: Color category for styling or testing


text:
/**
 * @file    ReferenceToolbar.cpp
 * @author  Marvin Smith
 * @date    5/18/2017
 */
#include "ReferenceToolbar.hpp"

// Qt Libraries
#include <QLabel>
#include <QLineEdit>

/************************************************/
/*         Reference Toolbar Constructor        */
/************************************************/
ReferenceToolbar::ReferenceToolbar( System_Configuration::ptr_t  sys_config,
                                    QWidget*                     parent )
  : QWidget(parent),
    m_class_name("ReferenceToolbar"),
    m_sys_config(sys_config)
{
    // Initialize the Configuration
    Initialize_Configuration();

    // Initialize the GUI
    Initialize_GUI();
}

/*************************************/
/*          Initialize the GUI       */
/*************************************/
void ReferenceToolbar::Initialize_GUI()
{
    // Create Grid Layout
    m_main_layout = new QGridLayout();

    // Build the Source Widget
    Build_Source_Widget();

    // Set the layout
    setLayout(m_main_layout);
}

/*********************************************/
/*        Initialize the Configuration       */
/*********************************************/
void ReferenceToolbar::Initialize_Configuration()
{
    // Set Default Configuration Parameters
    m_sys_config->Add_Config_Param("system.matching.reference.default.toolbutton.width",
                                   "120",
                                   "#  Default Width of Reference Panel Tool-Button",
                                   false);

    m_sys_config->Add_Config_Param("system.matching.reference.default.toolbutton.height",
                                   "120",
                                   "#  Default Height of Reference Panel Tool-Button",
                                   false);

}

/********************************************/
/*          Build the Source Widget         */
/********************************************/
void ReferenceToolbar::Build_Source_Widget()
{
    // Build the Source Widget
    QWidget*  datasource_widget = new QWidget(this);

    QHBoxLayout* datasource_layout = new QHBoxLayout();

    // Create label
    QLabel* datasource_label = new QLabel("Data Source:");
    datasource_layout->addWidget(datasource_label);

    // Create edit
    m_datasource_edit = new QLineEdit();
    datasource_layout->addWidget(m_datasource_edit);

    // Create update button
    m_datasource_update_button = new QToolButton();
    datasource_layout->addWidget(m_datasource_update_button);

    // Set layout
    datasource_widget->setLayout(datasource_layout);

    // Add to main layout
    m_main_layout->addWidget(datasource_widget, 1, 1, 1, 2);

}


text:
<?php

/* @var $this yii\web\View */

$this->title = 'Administrador de Tareas';
?>

Clima en Tepic, Nayarit

Tu tiempo

<bold>¡Bienvenido!</bold>

Ingresa para poder adminisrar tus tareas. :)

Este es nuestro crew. :)

Administra, crea, y borra tus tareas.

En este sitio puedes administrar tus tareas, puedes crear, modificar, eliminar y buscar las Tareas
                  en el sistema, además que nos gusta consentirte, por eso cada día estamos creando nuevo contenido.

Observa  quién está en nuestro sistema.

Es sencillo, sólo piensa en una persona en el sistema, busca su nombre, y checa algunos
                  de sus datos para comunicarte con él. Esto nos ayuda a estar más sincronizados con nuestras
                  tareas y nuestros horarios.

Checa todos los tipos de tareas.

¿Cansado de que todos te digan que hay y no poder elegir?. No sólo tienes el poder de
                  ver que tareas existen, también puedes crear una y borrarlas a tu antojo Cuanto más flexible para tí, mejor.
                ¡Vamos!, ¡Inténtalo!

Revisar tareas.

Buscar Personal

Tipos de tareas