text:
extern int gpu_index;

#ifdef GPU
    #define BLOCK 512

    #include "cuda_runtime.h"
    #include "curand.h"
    #include "cublas_v2.h"

    #ifdef CUDNN
    #include "cudnn.h"
    #endif
#endif

#ifndef __cplusplus
    #ifdef OPENCV
    #include "opencv2/highgui/highgui_c.h"
    #include "opencv2/imgproc/imgproc_c.h"
    #include "opencv2/core/version.hpp"
    #if CV_MAJOR_VERSION == 3
    #include "opencv2/videoio/videoio_c.h"
    #endif
    #endif
#endif

typedef struct{
    int *leaf;
    int n;
    int *parent;
    int *child;
    int *group;
    char **name;

    int groups;
    int *group_size;
    int *group_offset;
} tree;

typedef enum{
    LOGISTIC, RELU, RELIE, LINEAR, RAMP, TANH, PLSE, LEAKY, ELU, LOGGY, STAIR, HARDTAN, LHTAN
}ACTIVATION;

typedef enum {
    CONVOLUTIONAL,
    DECONVOLUTIONAL,
    CONNECTED,
    MAXPOOL,
    SOFTMAX,
    DETECTION,
    DROPOUT,
    CROP,
    ROUTE,
    COST,
    NORMALIZATION,
    AVGPOOL,
    LOCAL,
    SHORTCUT,
    ACTIVE,
    RNN,
    GRU,
    CRNN,
    BATCHNORM,
    NETWORK,
    XNOR,
    REGION,
    REORG,
    BLANK
} LAYER_TYPE;

typedef enum{
    SSE, MASKED, L1, SMOOTH
} COST_TYPE;

struct network;
typedef struct network network;

struct layer;
typedef struct layer layer;

struct layer{
    LAYER_TYPE type;
    ACTIVATION activation;
    COST_TYPE cost_type;
    void (*forward)   (struct layer, struct network);
    void (*backward)  (struct layer, struct network);
    void (*update)    (struct layer, int, float, float, float);
    void (*forward_gpu)   (struct layer, struct network);
    void (*backward_gpu)  (struct layer, struct network);
    void (*update_gpu)    (struct layer, int, float, float, float);
    int batch_normalize;
    int shortcut;
    int batch;
    int forced;
    int flipped;
    int inputs;
    int outputs;
    int nweights;
    int nbiases;
    int extra;
    int truths;
    int h,w,c;
    int out_h, out_w, out_c;
    int n;
    int max_boxes;
    int groups;
    int size;
    int side;
    int stride;
    int reverse;
    int flatten;
    int spatial;
    int pad;
    int sqrt;
    int flip;
    int index;
    int binary;
    int xnor;
    int steps;
    int hidden;
    int truth;
    float smooth;
    float dot;
    float angle;
    float jitter;
    float saturation;
    float exposure;
    float shift;
    float ratio;
    float learning_rate_scale;
    int softmax;
    int classes;
    int coords;
    int background;
    int rescore;
    int objectness;
    int does_cost;
    int joint;
    int noadjust;
    int reorg;
    int log;

    int adam;
    float B1;
    float B2;
    float eps;
    int t;

    float alpha;
    float beta;
    float kappa;

    float coord_scale;
    float object_scale;
    float noobject_scale;
    float class_scale;
    int bias_match;
    int random;
    float thresh;
    int classfix;
    int absolute;

    int onlyforward;
    int stopbackward;
    int dontload;
    int dontloadscales;

    float temperature;
    float probability;
    float scale;

    char  * cweights;
    int   * indexes;
    int   * input_layers;
    int   * input_sizes;
    int   * map;
    float * rand;
    float * cost;
    float * state;
    float * prev_state;
    float * forgot_state;
    float * forgot_delta;
    float * state_delta;

    float * concat;
    float * concat_delta;

    float * binary_weights;

    float * biases;
    float * bias_updates;

    float * scales;
    float * scale_updates;

    float * weights;
    float * weight_updates;

    float * delta;
    float * output;
    float * squared;
    float * norms;

    float * spatial_mean;
    float * mean;
    float * variance;

    float * mean_delta;
    float * variance_delta;

    float * rolling_mean;
    float * rolling_variance;

    float * x;
    float * x_norm;

    float * m;
    float * v;

    float * bias_m;
    float * bias_v;
    float * scale_m;
    float * scale_v;

    float * z_cpu;
    float * r_cpu;
    float * h_cpu;

    float * binary_input;

    struct layer *input_layer;
    struct layer *self_layer;
    struct layer *output_layer;

    struct layer *input_gate_layer;
    struct layer *state_gate_layer;
    struct layer *input_save_layer;
    struct layer *state_save_layer;
    struct layer *input_state_layer;
    struct layer *state_state_layer;

    struct layer *input_z_layer;
    struct layer *state_z_layer;

    struct layer *input_r_layer;
    struct layer *state_r_layer;

    struct layer *input_h_layer;
    struct layer *state_h_layer;

    tree *softmax_tree;

    size_t workspace_size;

    #ifdef GPU
    int *indexes_gpu;

    float *z_gpu;
    float *r_gpu;
    float *h_gpu;

    float *m_gpu;
    float *v_gpu;
    float *bias_m_gpu;
    float *scale_m_gpu;
    float *bias_v_gpu;
    float *scale_v_gpu;

    float * prev_state_gpu;
    float * forgot_state_gpu;
    float * forgot_delta_gpu;
    float * state_gpu;
    float * state_delta_gpu;
    float * gate_gpu;
    float * gate_delta_gpu;
    float * save_gpu;
    float * save_delta_gpu;
    float * concat_gpu;
    float * concat_delta_gpu;

    float *binary_input_gpu;
    float *binary_weights_gpu;

    float * mean_gpu;
    float * variance_gpu;

    float * rolling_mean_gpu;
    float * rolling_variance_gpu;

    float * variance_delta_gpu;
    float * mean_delta_gpu;

    float * x_gpu;
    float * x_norm_gpu;
    float * weights_gpu;
    float * weight_updates_gpu;

    float * biases_gpu;
    float * bias_updates_gpu;

    float * scales_gpu;
    float * scale_updates_gpu;

    float * output_gpu;
    float * delta_gpu;
    float * rand_gpu;
    float * squared_gpu;
    float * norms_gpu;
    #ifdef CUDNN
    cudnnTensorDescriptor_t srcTensorDesc, dstTensorDesc;
    cudnnTensorDescriptor_t dsrcTensorDesc, ddstTensorDesc;
    cudnnTensorDescriptor_t normTensorDesc;
    cudnnFilterDescriptor_t weightDesc;
    cudnnFilterDescriptor_t dweightDesc;
    cudnnConvolutionDescriptor_t convDesc;
    cudnnConvolutionFwdAlgo_t fw_algo;
    cudnnConvolutionBwdDataAlgo_t bd_algo;
    cudnnConvolutionBwdFilterAlgo_t bf_algo;
    #endif
    #endif
};

void free_layer(layer);

typedef enum {
    CONSTANT, STEP, EXP, POLY, STEPS, SIG, RANDOM
} learning_rate_policy;

typedef struct network{
    int n;
    int batch;
    int *seen;
    float epoch;
    int subdivisions;
    float momentum;
    float decay;
    layer *layers;
    float *output;
    learning_rate_policy policy;

    float learning_rate;
    float gamma;
    float scale;
    float power;
    int time_steps;
    int step;
    int max_batches;
    float *scales;
    int   *steps;
    int num_steps;
    int burn_in;

    int adam;
    float B1;
    float B2;
    float eps;

    int inputs;
    int outputs;
    int truths;
    int notruth;
    int h, w, c;
    int max_crop;
    int min_crop;
    int center;
    float angle;
    float aspect;
    float exposure;
    float saturation;
    float hue;

    int gpu_index;
    tree *hierarchy;

    float *input;
    float *truth;
    float *delta;
    float *workspace;
    int train;
    int index;
    float *cost;

    #ifdef GPU
    float *input_gpu;
    float *truth_gpu;
    float *delta_gpu;
    float *output_gpu;
    #endif

} network;

typedef struct {
    int w;
    int h;
    float scale;
    float rad;
    float dx;
    float dy;
    float aspect;
} augment_args;

typedef struct {
    int h;
    int w;
    int c;
    float *data;
} image;

typedef struct{
    float x, y, w, h;
} box;

typedef struct matrix{
    int rows, cols;
    float **vals;
} matrix;

typedef struct{
    int w, h;
    matrix X;
    matrix y;
    int shallow;
    int *num_boxes;
    box **boxes;
} data;

typedef enum {
    CLASSIFICATION_DATA, DETECTION_DATA, CAPTCHA_DATA, REGION_DATA, IMAGE_DATA, COMPARE_DATA, WRITING_DATA, SWAG_DATA, TAG_DATA, OLD_CLASSIFICATION_DATA, STUDY_DATA, DET_DATA, SUPER_DATA, LETTERBOX_DATA, REGRESSION_DATA, SEGMENTATION_DATA
} data_type;

typedef struct load_args{
    int threads;
    char **paths;
    char *path;
    int n;
    int m;
    char **labels;
    int h;
    int w;
    int out_w;
    int out_h;
    int nh;
    int nw;
    int num_boxes;
    int min, max, size;
    int classes;
    int background;
    int scale;
    int center;
    float jitter;
    float angle;
    float aspect;
    float saturation;
    float exposure;
    float hue;
    data *d;
    image *im;
    image *resized;
    data_type type;
    tree *hierarchy;
} load_args;

typedef struct{
    int id;
    float x,y,w,h;
    float left, right, top, bottom;
} box_label;

network load_network(char *cfg, char *weights, int clear);
load_args get_base_args(network net);

void free_data(data d);

typedef struct node{
    void *val;
    struct node *next;
    struct node *prev;
} node;

typedef struct list{
    int size;
    node *front;
    node *back;
} list;

pthread_t load_data(load_args args);
list *read_data_cfg(char *filename);
list *read_cfg(char *filename);

#include "activation_layer.h"
#include "activations.h"
#include "avgpool_layer.h"
#include "batchnorm_layer.h"
#include "blas.h"
#include "box.h"
#include "classifier.h"
#include "col2im.h"
#include "connected_layer.h"
#include "convolutional_layer.h"
#include "cost_layer.h"
#include "crnn_layer.h"
#include "crop_layer.h"
#include "cuda.h"
#include "data.h"
#include "deconvolutional_layer.h"
#include "demo.h"
#include "detection_layer.h"
#include "dropout_layer.h"
#include "gemm.h"
#include "gru_layer.h"
#include "im2col.h"
#include "image.h"
#include "layer.h"
#include "list.h"
#include "local_layer.h"
#include "matrix.h"
#include "maxpool_layer.h"
#include "network.h"
#include "normalization_layer.h"
#include "option_list.h"
#include "parser.h"
#include "region_layer.h"
#include "reorg_layer.h"
#include "rnn_layer.h"
#include "route_layer.h"
#include "shortcut_layer.h"
#include "softmax_layer.h"
#include "stb_image.h"
#include "stb_image_write.h"
#include "tree.h"
#include "utils.h"
#endif


text:
using System.Collections.Generic;

namespace Pliant.Utilities
{
    class HashCodeEqualityComparer<T> : IEqualityComparer<T>
    {
        public bool Equals(T x, T y)
        {
            return x.GetHashCode().Equals(y.GetHashCode());
        }

        public int GetHashCode(T obj)
        {
            return obj.GetHashCode();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.fxmisc.richtext.demo;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.IndexRange;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import org.fxmisc.richtext.StyleClassedTextArea;

public class ManualHighlighting extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private final StyleClassedTextArea area = new StyleClassedTextArea();

    @Override
    public void start(Stage primaryStage) {
        Button red = createColorButton(Color.RED, "red");
        Button green = createColorButton(Color.GREEN, "green");
        Button blue = createColorButton(Color.BLUE, "blue");
        Button bold = createBoldButton("bold");
        HBox panel = new HBox(red, green, blue, bold);

        VBox.setVgrow(area, Priority.ALWAYS);
        area.setWrapText(true);
        VBox vbox = new VBox(panel, area);

        Scene scene = new Scene(vbox, 600, 400);
        scene.getStylesheets().add(ManualHighlighting.class.getResource("manual-highlighting.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setTitle("Manual Highlighting Demo");
        primaryStage.show();

        area.requestFocus();
    }

    private Button createBoldButton(String styleClass) {
        Button button = new Button("B");
        button.styleProperty().set("-fx-font-weight: bold;");
        setPushHandler(button, styleClass);
        return button;
    }

    private Button createColorButton(Color color, String styleClass) {
        Rectangle rect = new Rectangle(20, 20, color);
        Button button = new Button(null, rect);
        setPushHandler(button, styleClass);
        return button;
    }

    private void setPushHandler(Button button, String styleClass) {
        button.onActionProperty().set(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent evt) {
                IndexRange range = area.getSelection();
                area.setStyleClass(range.getStart(), range.getEnd(), styleClass);
                area.requestFocus();
            }
        });
    }

}


text:
module Toolsmith
  module Views
    class DefinitionList < Base
      DEFAULT_OPTIONS = { horizontal: true }

      attr_reader :content_block, :options

      def initialize(context, options={}, &block)
        @content_block = block if block_given?
        @options = DEFAULT_OPTIONS.merge(options)
        super(context, &nil)
      end

      def define(term, description)
        description = description.blank? ? " ".html_safe : description
        content_tag(:dt, term) + content_tag(:dd, description)
      end

      def to_s
        content = context.capture(self, &content_block)
        content_tag :dl, content, dl_options
      end

      private

      def dl_options
        {
          class: options[:horizontal] ? "dl-horizontal" : nil
        }
      end
    end
  end
end


text:
package org.gradle.api.internal.file.archive.compression;

import org.gradle.api.resources.ReadableResource;

public interface CompressedReadableResource extends ReadableResource {
}


text:
source "$(dirname "${BASH_SOURCE}")/lib/init.sh"

SCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..
CODEGEN_PKG=${CODEGEN_PKG:-$(cd ${SCRIPT_ROOT}; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../../../k8s.io/code-generator)}
verify="${VERIFY:-}"

go install ./${CODEGEN_PKG}/cmd/deepcopy-gen

function codegen::join() { local IFS="$1"; shift; echo "$*"; }

# enumerate group versions
ALL_FQ_APIS=(
    github.com/openshift/origin/pkg/cmd/server/apis/config
    github.com/openshift/origin/pkg/cmd/server/apis/config/v1
    github.com/openshift/origin/pkg/cmd/server/apis/config/v1/testing
    github.com/openshift/origin/pkg/image/apiserver/admission/apis/imagepolicy
    github.com/openshift/origin/pkg/image/apiserver/admission/apis/imagepolicy/v1
    github.com/openshift/origin/pkg/project/apiserver/admission/apis/requestlimit
    github.com/openshift/origin/pkg/project/apiserver/admission/apis/requestlimit/v1
    github.com/openshift/origin/pkg/quota/apiserver/admission/apis/clusterresourceoverride
    github.com/openshift/origin/pkg/quota/apiserver/admission/apis/clusterresourceoverride/v1
    github.com/openshift/origin/pkg/quota/apiserver/admission/apis/runonceduration
    github.com/openshift/origin/pkg/quota/apiserver/admission/apis/runonceduration/v1
    github.com/openshift/origin/pkg/route/apiserver/admission/apis/ingressadmission
    github.com/openshift/origin/pkg/route/apiserver/admission/apis/ingressadmission/v1
    github.com/openshift/origin/pkg/scheduler/admission/apis/podnodeconstraints
    github.com/openshift/origin/pkg/scheduler/admission/apis/podnodeconstraints/v1
    github.com/openshift/origin/pkg/service/admission/apis/externalipranger
    github.com/openshift/origin/pkg/service/admission/apis/externalipranger/v1
    github.com/openshift/origin/pkg/service/admission/apis/restrictedendpoints
    github.com/openshift/origin/pkg/service/admission/apis/restrictedendpoints/v1
    github.com/openshift/origin/pkg/template/servicebroker/apis/config
    github.com/openshift/origin/pkg/template/servicebroker/apis/config/v1
    github.com/openshift/origin/pkg/util/testing
    github.com/openshift/origin/pkg/apps/apis/apps
    github.com/openshift/origin/pkg/authorization/apis/authorization
    github.com/openshift/origin/pkg/build/apis/build
    github.com/openshift/origin/pkg/image/apis/image
    github.com/openshift/origin/pkg/network/apis/network
    github.com/openshift/origin/pkg/oauth/apis/oauth
    github.com/openshift/origin/pkg/project/apis/project
    github.com/openshift/origin/pkg/quota/apis/quota
    github.com/openshift/origin/pkg/route/apis/route
    github.com/openshift/origin/pkg/security/apis/security
    github.com/openshift/origin/pkg/template/apis/template
    github.com/openshift/origin/pkg/user/apis/user
)

echo "Generating deepcopy funcs"
${GOPATH}/bin/deepcopy-gen --input-dirs $(codegen::join , "${ALL_FQ_APIS[@]}") -O zz_generated.deepcopy --bounding-dirs $(codegen::join , "${ALL_FQ_APIS[@]}") --go-header-file ${SCRIPT_ROOT}/hack/boilerplate.txt ${verify} "$@"


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/hero_image"
        android:contentDescription="@string/app_name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true" />

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:layout_above="@+id/adview">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:theme="@style/AppTheme.AppBarOverlay"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

            <android.support.v4.widget.NestedScrollView
                android:id="@+id/nested_scroll"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"
                app:layout_behavior="@string/appbar_scrolling_view_behavior">

                <include layout="@layout/nested_scroll" />

            </android.support.v4.widget.NestedScrollView>

        </LinearLayout>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            style="@style/FAB" />

    </android.support.design.widget.CoordinatorLayout>

    <com.google.android.gms.ads.AdView
        android:id="@+id/adview"
        ads:adUnitId="@string/adunit_detail"
        ads:adSize="SMART_BANNER"
        style="@style/AdView" />

</RelativeLayout>


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

@Component({
  selector: 'router-history-test',
  template: `<div>This is router history test for window.state.showHistory()</div>`
})

export class RouterHistoryTestComponent {

}


text: require 'devise_gullible'


text:
#ifndef __CC3000_NVRAM_H__
#define __CC3000_NVRAM_H__

#include "cc3000_common.h"

//*****************************************************************************
//
// If building with a C++ compiler, make all of the definitions in this header
// have a C binding.
//
//*****************************************************************************
#ifdef  __cplusplus
extern "C" {
#endif

//*****************************************************************************
//
//! \addtogroup nvmem_api
//! @{
//
//*****************************************************************************

/****************************************************************************
**
**	Definitions for File IDs
**
****************************************************************************/
/* NVMEM file ID - system files*/
#define NVMEM_NVS_FILEID 							(0)
#define NVMEM_NVS_SHADOW_FILEID 					(1)
#define NVMEM_WLAN_CONFIG_FILEID 					(2)
#define NVMEM_WLAN_CONFIG_SHADOW_FILEID 			(3)
#define NVMEM_WLAN_DRIVER_SP_FILEID					(4)
#define NVMEM_WLAN_FW_SP_FILEID						(5)
#define NVMEM_MAC_FILEID 							(6)
#define NVMEM_FRONTEND_VARS_FILEID 					(7)
#define NVMEM_IP_CONFIG_FILEID 						(8)
#define NVMEM_IP_CONFIG_SHADOW_FILEID 				(9)
#define NVMEM_BOOTLOADER_SP_FILEID 					(10)
#define NVMEM_RM_FILEID			 					(11)

/* NVMEM file ID - user files*/
#define NVMEM_AES128_KEY_FILEID	 					(12)
#define NVMEM_SHARED_MEM_FILEID	 					(13)

/*  max entry in order to invalid nvmem              */
#define NVMEM_MAX_ENTRY                              (16)

//*****************************************************************************
//
//!  nvmem_read
//!
//!  @param  ulFileId   nvmem file id:\n
//!                     NVMEM_NVS_FILEID, NVMEM_NVS_SHADOW_FILEID,
//!                     NVMEM_WLAN_CONFIG_FILEID, NVMEM_WLAN_CONFIG_SHADOW_FILEID,
//!                     NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID,
//!                     NVMEM_MAC_FILEID, NVMEM_FRONTEND_VARS_FILEID,
//!                     NVMEM_IP_CONFIG_FILEID, NVMEM_IP_CONFIG_SHADOW_FILEID,
//!                     NVMEM_BOOTLOADER_SP_FILEID, NVMEM_RM_FILEID,
//!                     and user files 12-15.
//!  @param  ulLength    number of bytes to read
//!  @param  ulOffset    ulOffset in file from where to read
//!  @param  buff        output buffer pointer
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief       Reads data from the file referred by the ulFileId parameter.
//!               Reads data from file ulOffset till length. Err if the file can't
//!               be used, is invalid, or if the read is out of bounds.
//!
//*****************************************************************************

extern INT32 nvmem_read(UINT32 file_id, UINT32 length, UINT32 offset, UINT8 *buff);

//*****************************************************************************
//
//!  nvmem_write
//!
//!  @param  ulFileId nvmem file id:\n
//!                   NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID,
//!                   NVMEM_MAC_FILEID, NVMEM_BOOTLOADER_SP_FILEID,
//!                   and user files 12-15.
//!  @param  ulLength       number of bytes to write
//!  @param  ulEntryOffset  offset in file to start write operation from
//!  @param  buff           data to write
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief       Write data to nvmem.
//!               writes data to file referred by the ulFileId parameter.
//!               Writes data to file ulOffset till ulLength.The file id will be
//!               marked invalid till the write is done. The file entry doesn't
//!               need to be valid - only allocated.
//!
//*****************************************************************************

extern INT32 nvmem_write(UINT32 ulFileId, UINT32 ulLength, UINT32 ulEntryOffset, UINT8 *buff);

//*****************************************************************************
//
//!  nvmem_set_mac_address
//!
//!  @param  mac   mac address to be set
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief       Write MAC address to EEPROM.
//!               mac address as appears over the air (OUI first)
//!
//*****************************************************************************
extern UINT8 nvmem_set_mac_address(UINT8 *mac);

//*****************************************************************************
//
//!  nvmem_get_mac_address
//!
//!  @param[out]  mac   mac address
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief       Read MAC address from EEPROM.
//!               mac address as appears over the air (OUI first)
//!
//*****************************************************************************
extern UINT8 nvmem_get_mac_address(UINT8 *mac);

//*****************************************************************************
//
//!  nvmem_write_patch
//!
//!  @param  ulFileId   nvmem file id:\n
//!                     NVMEM_WLAN_DRIVER_SP_FILEID, NVMEM_WLAN_FW_SP_FILEID,
//!  @param  spLength   number of bytes to write
//!  @param  spData     SP data to write
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief      program a patch to a specific file ID.
//!              The SP data is assumed to be organized in 2-dimensional.
//!              Each line is SP_PORTION_SIZE bytes long. Actual programming is
//!              applied in SP_PORTION_SIZE bytes portions.
//!
//*****************************************************************************
extern UINT8 nvmem_write_patch(UINT32 ulFileId, UINT32 spLength, const UINT8 *spData);

//*****************************************************************************
//
//!  nvmem_read_sp_version
//!
//!  @param[out]  patchVer    first number indicates package ID and the second
//!                           number indicates package build number
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief      Read patch version. read package version (WiFi FW patch,
//!              driver-supplicant-NS patch, bootloader patch)
//!
//*****************************************************************************
#ifndef CC3000_TINY_DRIVER
extern UINT8 nvmem_read_sp_version(UINT8* patchVer);
#endif

//*****************************************************************************
//
//!  nvmem_create_entry
//!
//!  @param       ulFileId    nvmem file Id:\n
//!                           * NVMEM_AES128_KEY_FILEID: 12
//!                           * NVMEM_SHARED_MEM_FILEID: 13
//!                           * and fileIDs 14 and 15
//!  @param       ulNewLen    entry ulLength
//!
//!  @return       on success 0, error otherwise.
//!
//!  @brief      Create new file entry and allocate space on the NVMEM.
//!              Applies only to user files.
//!              Modify the size of file.
//!              If the entry is unallocated - allocate it to size
//!              ulNewLen (marked invalid).
//!              If it is allocated then deallocate it first.
//!              To just mark the file as invalid without resizing -
//!              set ulNewLen=0.
//!
//*****************************************************************************
extern INT32 nvmem_create_entry(UINT32 file_id, UINT32 newlen);

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************

#ifdef  __cplusplus
}
#endif // __cplusplus

#endif // __CC3000_NVRAM_H__


text:
using System;
using System.Text;
using Arch.CMessaging.Client.Net.Core.Session;

namespace Arch.CMessaging.Client.Net.Filter.Codec.PrefixedString
{
    public class PrefixedStringCodecFactory : IProtocolCodecFactory
    {
        public const Int32 DefaultPrefixLength = 4;
        public const Int32 DefaultMaxDataLength = 2048;

        private readonly PrefixedStringEncoder _encoder;
        private readonly PrefixedStringDecoder _decoder;

        public PrefixedStringCodecFactory()
            : this(Encoding.Default)
        { }

        public PrefixedStringCodecFactory(Encoding encoding)
        {
            _encoder = new PrefixedStringEncoder(encoding);
            _decoder = new PrefixedStringDecoder(encoding);
        }

        public Int32 EncoderPrefixLength
        {
            get { return _encoder.PrefixLength; }
            set { _encoder.PrefixLength = value; }
        }

        public Int32 EncoderMaxDataLength
        {
            get { return _encoder.MaxDataLength; }
            set { _encoder.MaxDataLength = value; }
        }

        public Int32 DecoderPrefixLength
        {
            get { return _decoder.PrefixLength; }
            set { _decoder.PrefixLength = value; }
        }

        public Int32 DecoderMaxDataLength
        {
            get { return _decoder.MaxDataLength; }
            set { _decoder.MaxDataLength = value; }
        }

        public IProtocolEncoder GetEncoder(IoSession session)
        {
            return _encoder;
        }

        public IProtocolDecoder GetDecoder(IoSession session)
        {
            return _decoder;
        }
    }
}


text:
package org.encog.examples.proben;

import org.encog.EncogError;

public class ProBenError extends EncogError {

	public ProBenError(String msg, Throwable t) {
		super(msg, t);
	}

	public ProBenError(Throwable t) {
		super(t);
	}

	public ProBenError(String msg) {
		super(msg);
	}

}


text:
#include <common.h>
#include <command.h>
#include <netdev.h>
#include <asm/processor.h>
#include <asm/cache.h>

int checkcpu(void)
{
	puts("CPU: SH4\n");
	return 0;
}

int cpu_init (void)
{
	return 0;
}

int cleanup_before_linux (void)
{
	disable_interrupts();
	return 0;
}

int do_reset (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	disable_interrupts();
	reset_cpu (0);
	return 0;
}

void flush_cache (unsigned long addr, unsigned long size)
{
	invalidate_dcache_range(addr , addr + size);
}

void icache_enable (void)
{
	cache_control(0);
}

void icache_disable (void)
{
	cache_control(1);
}

int icache_status (void)
{
	return 0;
}

void dcache_enable (void)
{
}

void dcache_disable (void)
{
}

int dcache_status (void)
{
	return 0;
}

int cpu_eth_init(bd_t *bis)
{
#ifdef CONFIG_SH_ETHER
	sh_eth_initialize(bis);
#endif
	return 0;
}


text: I'll add it later


text:
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<constant name="struts.enable.SlashesInActionNames" value="true" />
	<constant name="struts.mapper.alwaysSelectFullNamespace" value="true" />
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true" />
	<constant name="struts.custom.i18n.resources" value="global" />

	<package name="yama-default" extends="struts-default">
		<interceptors>
			<interceptor-stack name="adminStack">
				<interceptor-ref name="exception" />
				<interceptor-ref name="logger" />
				<interceptor-ref name="timer" />
				<interceptor-ref name="alias" />
				<interceptor-ref name="servletConfig" />
				<interceptor-ref name="prepare" />
				<interceptor-ref name="chain" />
				<interceptor-ref name="scopedModelDriven" />
				<interceptor-ref name="modelDriven" />
				<interceptor-ref name="fileUpload" />
				<interceptor-ref name="checkbox" />
				<interceptor-ref name="multiselect" />
				<interceptor-ref name="staticParams" />
				<interceptor-ref name="actionMappingParams" />
				<interceptor-ref name="params">
					<param name="excludeParams">dojo\..*,^struts\..*</param>
				</interceptor-ref>
				<interceptor-ref name="store">
					<param name="operationMode">AUTOMATIC</param>
				</interceptor-ref>
				<interceptor-ref name="conversionError" />
				<interceptor-ref name="validation">
					<param name="validateAnnotatedMethodOnly">true</param>
					<param name="excludeMethods">input,back,cancel,browse</param>
				</interceptor-ref>
				<interceptor-ref name="workflow">
					<param name="excludeMethods">input,back,cancel,browse</param>
				</interceptor-ref>
			</interceptor-stack>
		</interceptors>

		<default-interceptor-ref name="adminStack" />
		<default-class-ref class="org.meruvian.yama.actions.DefaultAction" />

		<global-results>
			<result name="login" type="redirect">/logout</result>
			<result name="home" type="redirect">/home</result>
		</global-results>
	</package>

	<include file="struts-feelest-webapp.xml" />
</struts>


text:
var ListingView = Backbone.View.extend({
  initialize: function(){
    _.bindAll(this, 'renderComplete', 'renderSmall', 'renderForm', 'checkDisables', 'contentChanged', 'submitForm');
  },
  events: {
    'change [id="listType"]': 'checkDisables',
    'change [id="criteriaForm"]': 'contentChanged',
    'change [id="listingForm"]': 'contentChanged',
    'submit': 'submitForm',
  },
  renderComplete: function(){
    this.$el.html( Handlebars.templates.listingViewComplete( this.model));
    return this;
  },
  renderSmall: function(){
    //TODO
    this.$el.html( Handlebars.templates.listingViewSmall( this.model));
    return this;
  },
  renderForm: function(){
    this.$el.html( Handlebars.templates.listingViewForm( this.model));
    return this;
  },
  checkDisables: function(event){
    console.log(event.target.value);
    //TODO
  },
  contentChanged: function(event){
    this.model.set(event.target.name,event.target.value);
  },
  submitForm: function(event){
    event.preventDefault();
    this.model.save({}, {
      success: function( model, response){
        if( response.error === true){
          $(document).foundation('reflow');
          $('#'+response.type).foundation('reveal','open');
        }
        else{
          $(document).foundation('reflow');
          $('#'+response.type).foundation('reveal','open');
          $('#submit').attr('disabled', true);
        }
      },
      error: function( model, response){
        console.log("LISTING MESSAGE ERROR");
      }
    });
  }
})


text:
namespace SwqlStudio
{
    public interface IConnectionTab
    {
        IApplicationService ApplicationService { get; set; }
        ConnectionInfo ConnectionInfo { get; set; }
    }
}


text:
import { Component } from '@angular/core';
import { ProjectService } from './project.service';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
import {
  Project,
  CMakePackage,
  CMAKE_PACKAGE_TO_NAME,
  Executable,
  Library,
  ThirdPartySource,
  ThirdPartyProject,
  VersionControlSource,
  FileSource,
  FindPackageProject,
  VersionControlSystem,
  BuildTool,
  CMakeBuildTool,
  MakeBuildTool

} from './models';

@Component({
  selector: 'add-project',
  templateUrl: './add-project.component.html',
  styles: [`
md-select {
  margin: 1em 0em;
}
button {
  margin: 2em 0em;
}
`]
})
export class AddProjectComponent {

  constructor(
    private projectService: ProjectService,
    private location: Location,
    private router: Router
  ) { }

  projectName: string;
  projectSource: string;
  projectBuildTool: string;
  isThirdPartyProject: boolean = false;
  isLibrary: boolean = false;
  cmakePackage: CMakePackage = CMakePackage.Boost;
  cmakePackageToName: Array<String> = CMAKE_PACKAGE_TO_NAME;

  cancel(): void {
    this.router.navigate(['/solution']);
  }

  submit(): void {

    let project: Project;
    if (this.isThirdPartyProject) {

      if (this.projectSource === 'findpackage') {

        project = {
          id: 0,
          kind: 'findpackage',
          package: this.cmakePackage,
          required: true
        };

      } else {

        let source: ThirdPartySource;

        if (this.projectSource === 'vcs') {

          source = {
            kind: 'vcs',
            versionControlSystem: VersionControlSystem.Git,
            repoUrl: ''
          }

        } else if (this.projectSource === 'file') {

          source = {
            kind: 'file',
            fileUrl: ''
          };
        }

        let buildTool: BuildTool = undefined;
        if (this.projectBuildTool === 'cmake') {
          buildTool = {
            kind: 'cmake',
            cmakeArguments: [
              '-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}',
              '-DCMAKE_INSTALL_PREFIX=${THIRD_PARTY_INSTALL_PREFIX}'
            ]
          }

        } else if (this.projectBuildTool === 'make') {
          buildTool = {
            kind: 'make',
            configureCommand: '',
            buildCommand: '',
            installCommand: ''
          }
        }

        project = {
          id: 0,
          kind: 'thirdparty',
          name: '',
          source: source,
          buildTool: buildTool,
          libraryOutputs: []
        };

      }

    } else { // not a third party project or findpackage project

      if (this.isLibrary) {
        project = {
          id: 0,
          kind: 'library',
          name: this.projectName
        };
      } else {
        project = {
          id: 0,
          kind: 'executable',
          name: this.projectName,
        };
      }
    }

    this.projectService.addProject(project)
      .then(id => this.router.navigate(['/detail', id]));

  }
}


text:
Tinytest.add('SecurityAcl - SecurityIdentity', function (test) {

  test.throws(function () {
    SecurityAcl.UserSecurityIdentity('username', 'className');
  }, 'Use "new" to construct a SecurityAcl.UserSecurityIdentity');

  test.throws(function () {
    new SecurityAcl.UserSecurityIdentity(null, 'className');
  }, 'Username cannot be null or undefined.');

  test.throws(function () {
    new SecurityAcl.UserSecurityIdentity('username', null);
  }, 'ClassName cannot be null or undefined.');

  var sid = new SecurityAcl.UserSecurityIdentity('username', 'className');
  test.isTrue(sid instanceof SecurityAcl.SecurityIdentity, 'UserSecurityIdentity from SecurityIdentity');
  test.equal(sid.username(), 'username', 'Username() returns the username value.');
  test.equal(sid.className(), 'className', 'className() returns the className value.');

  var sid2 = 'invalidSid';
  test.isFalse(sid.equals(sid2), 'Equals methods returns false if sid is not an instance of UserSecurityIdentity.');

  var sid2 = new SecurityAcl.UserSecurityIdentity('username2', 'className');
  test.isFalse(sid.equals(sid2), 'Equals methods returns false if username of sid is different.');

  var sid2 = new SecurityAcl.UserSecurityIdentity('username', 'className2');
  test.isFalse(sid.equals(sid2), 'Equals methods returns false if className of sid is different.');

  var sid2 = new SecurityAcl.UserSecurityIdentity('username', 'className');
  test.isTrue(sid.equals(sid2), 'Equals methods returns true if sid is equal.');

  test.throws(function () {
    SecurityAcl.RoleSecurityIdentity('role');
  }, 'Use "new" to construct a SecurityAcl.RoleSecurityIdentity');

  test.throws(function () {
    new SecurityAcl.RoleSecurityIdentity(null);
  }, 'Role cannot be null or undefined.');

  var sid = new SecurityAcl.RoleSecurityIdentity('role');
  test.isTrue(sid instanceof SecurityAcl.SecurityIdentity, 'RoleSecurityIdentity from SecurityIdentity');
  test.equal(sid.role(), 'role', 'Role() returns the role value.');

  var sid2 = 'invalidSid';
  test.isFalse(sid.equals(sid2), 'Equals methods returns false if sid is not an instance of RoleSecurityIdentity.');
  test.isFalse(sid.equals(sid2), 'Equals methods returns false if sid is not an instance of RoleSecurityIdentity.');

  var sid2 = new SecurityAcl.RoleSecurityIdentity('role2');
  test.isFalse(sid.equals(sid2), 'Equals methods returns false if role of sid is different.');

  var sid2 = new SecurityAcl.RoleSecurityIdentity('role');
  test.isTrue(sid.equals(sid2), 'Equals methods returns true if sid is equal.');

});


text:
require 'spec_helper'
require 'unit/response_stubs/get_donor_cofs_stubs'

describe NFGClient::Client do
  let(:nfg_client) { NFGClient.new('aiduuad', 'aooaid', 'sosois', 'ksidi', true) }
  subject { nfg_client.get_donor_cofs(get_donor_cofs_params) }
  describe "#get_donor_cofs" do
    context "with a successful response" do
      it "should return a hash with a an array of COFs" do
        nfg_client.expects(:ssl_post).returns(nfg_response('200',successful_get_donor_cofs_response('ISUDUD')))
        expect(subject['StatusCode']).to eq('Success')
        expect(subject['DonorToken']).to eq('ISUDUD')
        expect(subject['Cards'].length).to eq(2)
        expect(subject['Cards'].first['COFId']).to eq('33333333')
        expect(subject['Cards'].last['COFId']).to eq('44444444')
      end
    end

    context "with a server error" do
      it "should return an UnexpectedError" do
        nfg_client.expects(:ssl_post).returns(nfg_response('500',server_error_response))
        expect(subject['StatusCode']).to eq('UnexpectedError')
      end
    end

    context "with an unsuccessful response" do
      it "should return the appropriate error with the DonorToken" do
        nfg_client.expects(:ssl_post).returns(nfg_response('200',unsuccessful_get_donor_cofs_response('ISUDUD')))
        expect(subject['StatusCode']).to eq('ValidationFailed')
        expect(subject['DonorToken']).to eq('ISUDUD')

      end
    end
  end
end


text:
if(-not (Get-Module omsAgent))
{
	$here = (Split-Path -Parent $MyInvocation.MyCommand.Path).Replace('tests\functions\public', '')
	Import-Module (Join-Path $here 'omsAgent.psd1')
}

InModuleScope -moduleName omsAgent {
	Describe 'Remove-omsAgentProxy' {
		BeforeAll {
			Mock Invoke-Command {}
		}

		Context 'Logic' {
			it 'Parameters' {
				{Remove-omsAgentProxy -comt -ErrorAction Stop -WhatIf:$false -Confirm:$false} | Should Throw
			}

			it 'Proxy Does Not Exist' {
				Mock Get-omsAgentProxyInternal { $null }

				Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null

				Assert-MockCalled Invoke-Command -Exactly 0 -Scope It
			}

			it 'Proxy Does Exists - No Workspaces' {
				Mock Get-omsAgentProxyInternal { $true }
				Mock Get-omsAgentWorkSpaceInternal { $null }

				Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null

				Assert-MockCalled Invoke-Command -Exactly 1 -Scope It
			}

			it 'Proxy Does Exists - Workspace Exists' {
				Mock Get-omsAgentProxyInternal { $true }
				Mock Get-omsAgentWorkSpaceInternal { $true }

				Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null

				Assert-MockCalled Invoke-Command -Exactly 2 -Scope It
			}

			it 'Creates\Removes A PsSession' {
				Mock New-PSSession { 'sessionData' }
				Mock Remove-PSSession {}
				Mock Get-omsAgentProxyInternal { $null }

				Remove-omsAgentProxy -ErrorAction SilentlyContinue -WhatIf:$false -Confirm:$false | Out-Null

				Assert-MockCalled New-PSSession -Exactly 1 -Scope It
				Assert-MockCalled Remove-PSSession -Exactly 1 -Scope It
			}
		}
	}
}


text:
from pyembed.core import consumer
from pyembed.core.error import PyEmbedError
from pyembed.core.discovery import DefaultDiscoverer, PyEmbedDiscoveryError
from pyembed.core.response import OEmbedLinkResponse
from pyembed.core import parse

import requests
import urlparse
import urllib

from HTMLParser import HTMLParser

class CustomDiscoverer(DefaultDiscoverer):
    def get_oembed_urls(self, url, oembed_format=None):
        response = requests.get(url)

        if not response.ok:
            raise PyEmbedDiscoveryError(
                'Failed to get %s (status code %s)' % (url, response.status_code))

        content_type = response.headers['content-type'].split(';')[0]
        if content_type in ["application/json", "text/xml", "application/xml"]:
            return [url]
        # Special case oembed
        if "soundcloud.com".find(url):
            oembed_format = "json"
            return super(CustomDiscoverer, self).get_oembed_urls(url, oembed_format)

class OEmbedNewLinkResponse(OEmbedLinkResponse):
    def fields(self):
        return super(OEmbedNewLinkResponse, self).fields() + ['url']

# Monkey-patch the RESPONSE CLASSES
parse.RESPONSE_CLASSES["link"] = OEmbedNewLinkResponse

def oembed_discover(url):
    oembed_data = {}
    if not url:
        return oembed_data, None
    try:
        oembed_urls = CustomDiscoverer().get_oembed_urls(url)
        oembed_response = consumer.get_first_oembed_response(oembed_urls)
    except (PyEmbedDiscoveryError, PyEmbedError), ex:
        return {}, unicode(ex)
    except requests.RequestException:
        return {}, "Invalid/Malform URL"
    for field in oembed_response.fields():
        oembed_data[field] = getattr(oembed_response, field)
        if oembed_response.type == "link":
            thumbnail = oembed_response.title
            if oembed_response.thumbnail_url:
                thumbnail = ('').format(oembed_response.thumbnail_url,
                                                oembed_response.title)
            link_url = oembed_response.url or url
            oembed_data["html"] = ('{1}').format(link_url,
                                                                     thumbnail)
    oembed_data = process_oembed_data(oembed_data)
    return oembed_data, None

class YTIframeParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        tag_attr_dict = dict(attrs)
        parts = urlparse.urlsplit(tag_attr_dict["src"])
        url_attrs = dict(urlparse.parse_qsl(parts.query))
        url_attrs["controls"] = "1"
        url_attrs["showinfo"] = "0"
        url_attrs["rel"] = "0"
        url_attrs["autohide"] = "1"
        url_attrs["modestbranding"] = "1"
        # Enable captions
        url_attrs["cc_load_policy"] = "1"
        src_url = urlparse.urlunsplit((parts.scheme, parts.netloc,
                                       parts.path, urllib.urlencode(url_attrs),
                                       parts.fragment))
        tag_attr_dict["src"] = src_url
        attr_str = ""
        for (key, val) in tag_attr_dict.iteritems():
            attr_str += " {0}".format(key)
            if val:
                attr_str += "=\"{0}\"".format(val)
        self.yt_url = "".format(attr_str)

def process_oembed_data(oembed_data):
    if oembed_data.get("provider_name") and oembed_data["provider_name"].lower() == "youtube":
        iframe_tag = oembed_data["html"]
        ytp = YTIframeParser()
        ytp.feed(iframe_tag)
        oembed_data["html"] = ytp.yt_url
    return oembed_data


text:
#pragma once
#include <element/boss_image.hpp>

namespace BOSS
{
    class R
    {
    public:
        R(chars name);
        ~R();

    public:
        static void SetAtlasDir(chars dirname);
        static void AddAtlas(chars key_filename, chars map_filename, const Context& ctx);
        static void SaveAtlas(Context& ctx);
        static bool IsAtlasUpdated();
        static void RebuildAll();

    public:
        inline bool exist() const {return mExist;}
        inline sint32 w() const {return (mImage)? mImage->GetWidth() : 0;}
        inline sint32 h() const {return (mImage)? mImage->GetHeight() : 0;}

    public:
        inline operator const Image&() const
        {
            BOSS_ASSERT("이미지가 로드되지 않았습니다", mImage);
            return *mImage;
        }
        inline const Image* operator->() const
        {
            BOSS_ASSERT("이미지가 로드되지 않았습니다", mImage);
            return mImage;
        }

    private:
        Image* mImage;
        bool mExist;
    };
}


text:
    OpenGL ES 3.0 V@14.0 (GIT@Iabe52cfaeae4c5fab1acacfe6f056ba15fa93274)

# Vendor

    Qualcomm

# Renderer

    Adreno (TM) 320

# Extensions

    GL_AMD_compressed_ATC_texture
    GL_AMD_performance_monitor
    GL_AMD_program_binary_Z400
    GL_EXT_color_buffer_float
    GL_EXT_color_buffer_half_float
    GL_EXT_debug_labelGL_EXT_debug_markerGL_EXT_robustness
    GL_EXT_sRGB
    GL_EXT_texture_format_BGRA8888
    GL_EXT_texture_type_2_10_10_10_REV
    GL_NV_fence
    GL_OES_EGL_image
    GL_OES_EGL_image_external
    GL_OES_compressed_ETC1_RGB8_texture
    GL_OES_depth24
    GL_OES_depth_texture
    GL_OES_depth_texture_cube_map
    GL_OES_element_index_uint
    GL_OES_fbo_render_mipmap
    GL_OES_fragment_precision_high
    GL_OES_get_program_binary
    GL_OES_packed_depth_stencil
    GL_OES_rgb8_rgba8
    GL_OES_standard_derivatives
    GL_OES_texture_3D
    GL_OES_texture_float
    GL_OES_texture_half_float
    GL_OES_texture_half_float_linear
    GL_OES_texture_npot
    GL_OES_vertex_array_object
    GL_OES_vertex_half_float
    GL_OES_vertex_type_10_10_10_2
    GL_QCOM_alpha_test
    GL_QCOM_binning_control
    GL_QCOM_driver_control
    GL_QCOM_extended_get
    GL_QCOM_extended_get2
    GL_QCOM_perfmon_global_mode
    GL_QCOM_tiled_rendering
    GL_QCOM_writeonly_rendering


text:
'use strict';

var zloggerControllers = angular.module('zlogger.controllers', ['ui.bootstrap']);

zloggerControllers.constant('REFRESH_INTERVAL', 300000);

/* Controllers */

zloggerControllers.controller('postCommentsCtrl', ['$scope', '$http', '$interval',
    'postId', 'REFRESH_INTERVAL', function ($scope, $http, $interval, postId, REFRESH_INTERVAL) {

		$scope.commentaries = [];
		$scope.filteredComments = [];
		$scope.sent = false;
		$scope.message = "";
		$scope.paginationProperties = {
			numPerPage : 10,
			maxSize : 5,
			currentPage : 1
		};

		var COMMENTS_LOAD_URL = "/post/" + postId + "/commentaries";
		var COMMENTS_ADD_URL = "/user/addcomment/" + postId;
		var model = this;

		model.commentary = {
			message: ""
		};

		var applyPagination = function() {
			var begin = (($scope.paginationProperties.currentPage - 1) *
				$scope.paginationProperties.numPerPage)
			, end = begin + $scope.paginationProperties.numPerPage;
			$scope.filteredComments = $scope.commentaries.slice(begin, end);
		};

		var receive = function() {
			$http.get(COMMENTS_LOAD_URL)
			.success(function (data) {
				$scope.commentaries = data;
				applyPagination();
			});
		};

		receive();
		var receivePromise = $interval(receive, REFRESH_INTERVAL);

		$scope.$watch('paginationProperties.currentPage + paginationProperties.numPerPage', applyPagination);

		this.submit = function(isValid) {
			if(!$scope.sent && isValid) {
				$scope.sent = true;
				$scope.message = "";
				$http.post(COMMENTS_ADD_URL, model.commentary).
				success(function() {
					model.commentary.message = "";
					receive();
					$scope.currentPage = 1;
					$scope.sent = false;
				}).
				error(function() {
					$scope.sent = false;
					$scope.message = "Could not save commentary. Please try again later.";
				});
			}
		};
	}]);

zloggerControllers.controller('registrationController', ['$http', '$window', '$scope', function($http, $window, $scope) {

	var model = this;
	$scope.message = "";
	$scope.sent = false;

	model.user = {
		userName: "",
		password: "",
		confirmPassword: ""
	};

	this.submit = function(isValid) {
		if(!$scope.sent && isValid) {
			$scope.sent = true;
			$scope.message = "";
			$http.post("/signup", model.user).
			success(function() {
				$window.location.href = "http://" + $window.location.host + "/login";
			}).
			error(function() {
				$scope.sent = false;
				$scope.message = "This username is already taken. Please try another one.";
			});
		}
	};
}]);

zloggerControllers.controller('loginCtrl', ['$http', '$window', '$scope', function($http, $window, $scope) {

	var model = this;
	$scope.message = "";
	$scope.sent = false;

	model.auth = {
		username: "",
		password: ""
	};

	this.submit = function(isValid) {
		if(!$scope.sent && isValid) {
			$scope.message = "";
			$scope.sent = true;
			$http({
				method: 'POST',
				url : "/j_spring_security_check",
				params : model.auth,
				headers: {'Content-Type': 'application/x-www/form-urlencoded'}
			}).success(function() {
				$window.location.href = "http://" + $window.location.host + "/";
			}).
			error(function() {
				$scope.sent = false;
				$scope.message = "This login/password pair is invalid. Try again?";
			});
		}
	};
}]);

zloggerControllers.controller('blogCtrl', ['$http', '$window', '$scope', function($http, $window, $scope) {
	var model = this;

	$scope.buttonCaption = "Add post";
	$scope.labelCaption = "New post";
	$scope.message = "";
	$scope.edit = false;
	$scope.sent = false;

	$scope.post = {
		id : "",
		title: "",
		message: ""
	};

	this.windowReload = function() {
		$window.location.reload();
	};

	this.submit = function(isValid) {
		if(!$scope.sent && isValid) {
			$scope.sent = true;
			$scope.message = "";
			if(!$scope.edit) {
				$http.post("/user/addpost", $scope.post)
				.success(function() {
					$scope.post.title = "";
					$scope.post.message = "";
					model.windowReload();
				})
				.error(function() {
					$scope.sent = false;
					$scope.message = "Saving post was unsuccessfull";
				});
			} else {
				$http.put("/user/editpost", $scope.post)
				.success(function() {
					$scope.post.title = "";
					$scope.post.message = "";
					$scope.post.id = "";
					model.windowReload();
				})
				.error(function() {
					$scope.sent = false;
					$scope.message = "Editing post was unsuccessfull";
				});
			}
		}
	};

	this.del = function(id) {
		if(!$scope.sent) {
			$scope.sent = true;
			$http.delete("/user/deletepost/" + id)
			.success(function() {
				model.windowReload();
			})
			.error(function() {
				$scope.sent = false;
			});
		}
	};
}]);

zloggerControllers.controller('avatarCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
	$scope.sent = false;
	$scope.message = "";

	$scope.uploadFile = function(){
		var file = $scope.myFile;
		var uploadUrl = "/user/changeavatar";
		fileUpload.uploadFileToUrl(file, uploadUrl, $scope);
	};
}]);

zloggerControllers.controller('detailsCtrl',
	['$http', '$window', '$scope', 'email', 'about', 'site',
	function($http, $window, $scope, email, about, site) {

		var model = this;
		$scope.message = "";
		$scope.sent = "";

		model.details = {
			email: email,
			about: about,
			site: site
		};

		model.saved = angular.copy(model.details);

		$scope.reset = function() {
			model.details = angular.copy(model.saved);
		};

		this.submit = function(isValid) {
			if(!$scope.sent && isValid) {
				$scope.message = "";
				$scope.sent = true;
				$http.put("/user/changedetails", model.details).
				success(function() {
					model.saved = angular.copy(model.details);
					$scope.sent = false;
				}).
				error(function() {
					$scope.sent = false;
					$scope.message = "Saving details was unsuccessfull.";
				});
			}
		};
	}]);

zloggerControllers.controller('changePasswordCtrl', ['$http', '$scope', function($http, $scope) {

	var model = this;
	$scope.message = "";
	$scope.sent = false;

	model.password = {
		currentPassword: "",
		newPassword: "",
		confirmPassword: ""
	};

	this.submit = function(isValid) {
		if(!$scope.sent && isValid) {
			$scope.message = "";
			$scope.sent = true;
			$http.post("/user/changepassword", model.password).
			success(function() {
				model.password.currentPassword = "";
				model.password.newPassword = "";
				model.password.confirmPassword = "";
				$scope.sent = false;
			}).
			error(function() {
				$scope.message = "Wrong current password.";
				$scope.sent = false;
			});
		}
	};
}]);


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**address_line1** | **string** | Address line 1 for employee home address |
**address_line2** | **string** | Address line 2 for employee home address | [optional]
**city** | **string** | Suburb for employee home address |
**suburb** | **string** | Suburb for employee home address | [optional]
**post_code** | **string** | PostCode for employee home address |
**country_name** | **string** | Country of HomeAddress | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
		Show additional content

		Hide additional content

		<ng-transclude></ng-transclude>


text:
package org.ovirt.engine.core.bll.lsm;

import org.ovirt.engine.core.bll.AbstractSPMAsyncTaskHandler;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.storage.PostZeroHandler;
import org.ovirt.engine.core.bll.tasks.TaskHandlerCommand;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.LiveMigrateDiskParameters;
import org.ovirt.engine.core.common.asynctasks.AsyncTaskType;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.DiskImageDynamic;
import org.ovirt.engine.core.common.businessentities.storage.ImageStatus;
import org.ovirt.engine.core.common.businessentities.storage.ImageStorageDomainMap;
import org.ovirt.engine.core.common.businessentities.storage.ImageStorageDomainMapId;
import org.ovirt.engine.core.common.errors.EngineException;
import org.ovirt.engine.core.common.vdscommands.DeleteImageGroupVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSParametersBase;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.common.vdscommands.VmReplicateDiskParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.TransactionScopeOption;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskImageDao;
import org.ovirt.engine.core.dao.DiskImageDynamicDao;
import org.ovirt.engine.core.dao.ImageStorageDomainMapDao;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;

public class VmReplicateDiskFinishTaskHandler extends AbstractSPMAsyncTaskHandler<TaskHandlerCommand<? extends LiveMigrateDiskParameters>> {
    private Guid sourceQuotaId;
    private Guid sourceDiskProfileId;

    public VmReplicateDiskFinishTaskHandler(TaskHandlerCommand<? extends LiveMigrateDiskParameters> cmd) {
        super(cmd);
    }

    @Override
    protected void beforeTask() {
        // Split the image
        VmReplicateDiskParameters migrationCompleteParams = new VmReplicateDiskParameters
                (getEnclosingCommand().getParameters().getVdsId(),
                        getEnclosingCommand().getParameters().getVmId(),
                        getEnclosingCommand().getParameters().getStoragePoolId(),
                        getEnclosingCommand().getParameters().getSourceStorageDomainId(),
                        getEnclosingCommand().getParameters().getTargetStorageDomainId(),
                        getEnclosingCommand().getParameters().getImageGroupID(),
                        getEnclosingCommand().getParameters().getDestinationImageId()
                );

        // Update the DB before sending the command (perform rollback on failure)
        moveDiskInDB(getEnclosingCommand().getParameters().getSourceStorageDomainId(),
                getEnclosingCommand().getParameters().getTargetStorageDomainId(),
                getEnclosingCommand().getParameters().getQuotaId(),
                getEnclosingCommand().getParameters().getDiskProfileId());

        VDSReturnValue ret = null;
        try {
            ret = runVdsCommand(VDSCommandType.VmReplicateDiskFinish, migrationCompleteParams);

            if (ret.getSucceeded()) {
                updateImagesInfo();
                ImagesHandler.updateAllDiskImageSnapshotsStatus(
                        getEnclosingCommand().getParameters().getImageGroupID(), ImageStatus.OK);
            }
            else {
                throw new EngineException(ret.getVdsError().getCode(), ret.getVdsError().getMessage());
            }
        } catch (Exception e) {
            moveDiskInDB(getEnclosingCommand().getParameters().getTargetStorageDomainId(),
                    getEnclosingCommand().getParameters().getSourceStorageDomainId(),
                    sourceQuotaId,
                    sourceDiskProfileId);
            log.error("Failed VmReplicateDiskFinish (Disk '{}', VM '{}')",
                    getEnclosingCommand().getParameters().getImageGroupID(),
                    getEnclosingCommand().getParameters().getVmId());
            throw e;
        }
    }

    private void moveDiskInDB(final Guid sourceStorageDomainId,
            final Guid targetStorageDomainId,
            final Guid targetQuota,
            final Guid targetDiskProfile) {
        if (isMoveDiskInDbSucceded(targetStorageDomainId)) {
            return;
        }

        TransactionSupport.executeInScope(TransactionScopeOption.Required,
                new TransactionMethod<Object>() {
                    @SuppressWarnings("synthetic-access")
                    @Override
                    public Object runInTransaction() {
                        for (DiskImage di : getDiskImageDao().getAllSnapshotsForImageGroup
                                (getEnclosingCommand().getParameters().getImageGroupID())) {
                            getImageStorageDomainMapDao().remove
                                    (new ImageStorageDomainMapId(di.getImageId(),
                                            sourceStorageDomainId));
                            getImageStorageDomainMapDao().save
                                    (new ImageStorageDomainMap(di.getImageId(),
                                            targetStorageDomainId,
                                            targetQuota,
                                            targetDiskProfile));
                            // since moveDiskInDB can be called to 'rollback' the entity in case of
                            // an exception, we store locally the old quota and disk profile id.
                            if (sourceQuotaId == null) {
                                sourceQuotaId = di.getQuotaId();
                            }

                            if (sourceDiskProfileId == null) {
                                sourceDiskProfileId = di.getDiskProfileId();
                            }
                        }
                        return null;
                    }
                });
    }

    private void updateImagesInfo() {
        for (DiskImage image : getDiskImageDao().getAllSnapshotsForImageGroup
                (getEnclosingCommand().getParameters().getImageGroupID())) {
            VDSReturnValue ret = runVdsCommand(
                    VDSCommandType.GetImageInfo,
                    new GetImageInfoVDSCommandParameters(getEnclosingCommand().getParameters().getStoragePoolId(),
                            getEnclosingCommand().getParameters().getTargetStorageDomainId(),
                            getEnclosingCommand().getParameters().getImageGroupID(),
                            image.getImageId()));

            DiskImage imageFromIRS = (DiskImage) ret.getReturnValue();
            DiskImageDynamic diskImageDynamic = getDiskImageDynamicDao().get(image.getImageId());

            // Update image's actual size in DB
            if (imageFromIRS != null && diskImageDynamic != null) {
                diskImageDynamic.setactual_size(imageFromIRS.getActualSizeInBytes());
                getDiskImageDynamicDao().update(diskImageDynamic);
            }
        }
    }

    private static DiskImageDao getDiskImageDao() {
        return DbFacade.getInstance().getDiskImageDao();
    }

    private static ImageStorageDomainMapDao getImageStorageDomainMapDao() {
        return DbFacade.getInstance().getImageStorageDomainMapDao();
    }

    private static DiskImageDynamicDao getDiskImageDynamicDao() {
        return DbFacade.getInstance().getDiskImageDynamicDao();
    }

    @Override
    protected VDSCommandType getVDSCommandType() {
        return VDSCommandType.DeleteImageGroup;
    }

    @Override
    protected VDSParametersBase getVDSParameters() {
        return PostZeroHandler.fixParametersWithPostZero(
                new DeleteImageGroupVDSCommandParameters(
                        getEnclosingCommand().getParameters().getStoragePoolId(),
                        getEnclosingCommand().getParameters().getSourceStorageDomainId(),
                        getEnclosingCommand().getParameters().getImageGroupID(),
                        DbFacade.getInstance()
                                .getDiskImageDao()
                                .get(getEnclosingCommand().getParameters().getDestinationImageId())
                                .isWipeAfterDelete(),
                        getEnclosingCommand().getParameters().getForceDelete()));
    }

    @Override
    public void endWithFailure() {
        super.endWithFailure();
        revertTask();
    }

    @Override
    protected VdcObjectType getTaskObjectType() {
        return VdcObjectType.VM;
    }

    @Override
    protected Guid[] getTaskObjects() {
        return new Guid[] { getEnclosingCommand().getParameters().getVmId() };
    }

    @Override
    public AsyncTaskType getTaskType() {
        return AsyncTaskType.deleteImage;
    }

    @Override
    protected void revertTask() {
        // Preventing rollback on VmReplicateDiskFinish success
        // (checks whether the disk moved successfully to the target storage domain)
        Guid targetStorageDomainId = getEnclosingCommand().getParameters().getTargetStorageDomainId();
        if (isMoveDiskInDbSucceded(targetStorageDomainId)) {
            getEnclosingCommand().preventRollback();
        }
    }

    private boolean isMoveDiskInDbSucceded(Guid targetStorageDomainId) {
        Guid destinationImageId = getEnclosingCommand().getParameters().getDestinationImageId();
        DiskImage diskImage = getDiskImageDao().get(destinationImageId);
        return diskImage != null && targetStorageDomainId.equals(diskImage.getStorageIds().get(0));
    }

    @Override
    protected VDSCommandType getRevertVDSCommandType() {
        // No revert task - reverting is handled in the previous handler
        return null;
    }

    @Override
    protected VDSParametersBase getRevertVDSParameters() {
        // No revert task - reverting is handled in the previous handler
        return null;
    }

    @Override
    public AsyncTaskType getRevertTaskType() {
        // No revert task - reverting is handled in the previous handler
        return null;
    }

}


text:
class CreatePdus < ActiveRecord::Migration
  def change
    create_table :pdus do |t|
      t.string :name, limit: 64
      t.text :description

      t.timestamps
    end
    add_index :pdus, :name, unique: true
  end
end


text: puts "Seeding #{__FILE__} from Spina::Engine"


text:
package org.zstack.sdk;

import org.zstack.sdk.CloneVmInstanceResults;

public class CloneVmInstanceResult {
    public CloneVmInstanceResults result;
    public void setResult(CloneVmInstanceResults result) {
        this.result = result;
    }
    public CloneVmInstanceResults getResult() {
        return this.result;
    }

}


text:
module user {
    interface LogoutButtonScope extends ng.IScope {
        logout?: () => void;
    }

    export class LogoutButtonDirective {
        public template = 'Logout';
        public restrict = 'E';
        public replace = true;
        public scope = false;
        public link: (scope: LogoutButtonScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;
        static $inject = ['$rootScope', 'UserService'];

        constructor(private $rootScope: ng.IRootScopeService, private UserService: services.UserService) {
            LogoutButtonDirective.prototype.link = (scope: LogoutButtonScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
                scope.logout = () => {
                    UserService.logout();
                }
            }
        }

        static factory() {
            var directive = ($rootScope: ng.IRootScopeService, UserService: services.UserService) => new LogoutButtonDirective($rootScope, UserService);
            directive.$inject = LogoutButtonDirective.$inject;
            return directive;
        }
    }
}

(() => {
    angular.module('user').directive('fsLogoutButton', user.LogoutButtonDirective.factory());
})();


text:
package com.google.cloud.genomics.dataflow.readers;

import java.util.logging.Logger;

import com.google.api.services.genomics.Genomics;
import com.google.api.services.genomics.model.Read;
import com.google.api.services.genomics.model.SearchReadsRequest;
import com.google.cloud.genomics.dataflow.utils.GenomicsOptions;
import com.google.cloud.genomics.utils.OfflineAuth;
import com.google.cloud.genomics.utils.Paginator;
import com.google.cloud.genomics.utils.ShardBoundary;

/**
 * ReadReader is a DoFn that takes SearchReadsRequests, submits them
 * to the Genomics API, and gives you Reads in return.
 * It will take care of paging for you. You can optionally specify
 * which fields you'd like returned.
 */
public class ReadReader extends GenomicsApiReader<SearchReadsRequest, Read> {
  private static final Logger LOG = Logger.getLogger(ReadReader.class.getName());
  private final ShardBoundary.Requirement shardBoundary;

  /**
   * Create a ReadReader using a auth and fields parameter. All fields not specified under
   * readFields will not be returned in the API response.
   *
   * @param auth Auth class containing credentials.
   * @param readFields Fields to return in responses.
   */
  public ReadReader(OfflineAuth auth, ShardBoundary.Requirement shardBoundary, String readFields) {
    super(auth, readFields);
    this.shardBoundary = shardBoundary;
  }

  /**
   * Create a ReadReader with no fields parameter, all information will be returned.
   * @param auth Auth class containing credentials.
   */
  public ReadReader(OfflineAuth auth, ShardBoundary.Requirement shardBoundary) {
    this(auth, shardBoundary, null);
  }

  @Override
  protected void processApiCall(Genomics genomics, ProcessContext c, SearchReadsRequest request) {
    LOG.info("Starting Reads read loop");

    GenomicsOptions options = c.getPipelineOptions().as(GenomicsOptions.class);
    if (options.getPageSize() > 0) {
      request.setPageSize(options.getPageSize());
    }

    for (Read read : Paginator.Reads.create(genomics, shardBoundary).search(request, fields)) {
      c.output(read);
      itemCount.addValue(1L);
    }
  }
}


text:
      {H_LOGO_MINI}

      {H_LOGO_LG}

        Toggle navigation

      [NAVBAR_MENU]


text:
#include <signal.h>

extern void handle_signal(int sig, struct sigcontext *sc);

void hard_handler(int sig)
{
	handle_signal(sig, (struct sigcontext *) (&sig + 1));
}


text:
require 'spec_helper'

describe Weka::Core::Attribute do
  let(:values) { %w[true false] }
  let(:name)   { 'name' }
  let(:format) { 'yyyy-MM-dd HH:mm' }

  subject { Weka::Core::Attribute.new(name, values) }

  it { is_expected.to respond_to :values }
  it { is_expected.to respond_to :internal_value_of }

  describe '.new_numeric' do
    subject { Weka::Core::Attribute.new_numeric(name) }

    it 'returns a numeric Attribute' do
      expect(subject.numeric?).to be true
    end

    it 'returns an Attribute with the given name' do
      expect(subject.name).to eq name
    end
  end

  describe '.new_nominal' do
    subject { Weka::Core::Attribute.new_nominal(name, values) }

    it 'returns a nominal Attribute' do
      expect(subject.nominal?).to be true
    end

    it 'returns an Attribute with the given name' do
      expect(subject.name).to eq name
    end
  end

  describe '.new_date' do
    subject { Weka::Core::Attribute.new_date(name, format) }

    it 'returns a date Attribute' do
      expect(subject.date?).to be true
    end

    it 'returns an Attribute with the given name' do
      expect(subject.name).to eq name
    end
  end

  describe '.new_string' do
    subject { Weka::Core::Attribute.new_string(name) }

    it 'returns a string Attribute' do
      expect(subject.string?).to be true
    end

    it 'returns an Attribute with the given name' do
      expect(subject.name).to eq name
    end
  end

  describe '#values' do
    it 'returns an array of the values' do
      expect(subject.values).to eq values
    end
  end

  describe '#internal_value_of' do
    context 'for a numeric attribute' do
      subject { Weka::Core::Attribute.new_numeric(name) }

      it 'returns the value as a float' do
        expect(subject.internal_value_of(3.5)).to eq 3.5
      end

      it 'returns the value as a float if given as string' do
        expect(subject.internal_value_of('3.5')).to eq 3.5
      end

      it 'returns NaN if the given value is Float::NAN' do
        expect(subject.internal_value_of(Float::NAN)).to be Float::NAN
      end

      it 'returns NaN if the given value is nil' do
        expect(subject.internal_value_of(nil)).to be Float::NAN
      end

      it 'returns NaN if the given value is "?"' do
        expect(subject.internal_value_of('?')).to be Float::NAN
      end
    end

    context 'for a nominal attribute' do
      subject { Weka::Core::Attribute.new_nominal(name, values) }

      it 'returns the correct internal index' do
        expect(subject.internal_value_of('true')).to  eq 0
        expect(subject.internal_value_of('false')).to eq 1
      end

      it 'returns the correct internal index as given as a non-String' do
        expect(subject.internal_value_of(true)).to eq 0
        expect(subject.internal_value_of(false)).to eq 1

        expect(subject.internal_value_of(:true)).to eq 0
        expect(subject.internal_value_of(:false)).to eq 1
      end

      it 'returns NaN if the given value is Float::NAN' do
        expect(subject.internal_value_of(Float::NAN)).to be Float::NAN
      end

      it 'returns NaN if the given value is nil' do
        expect(subject.internal_value_of(nil)).to be Float::NAN
      end

      it 'returns NaN if the given value is "?"' do
        expect(subject.internal_value_of('?')).to be Float::NAN
      end
    end

    context 'for a data attribute' do
      let(:datetime)       { '2015-12-24 11:11' }
      let(:unix_timestamp) { 1_450_955_460_000.0 }

      subject { Weka::Core::Attribute.new_date(name, format) }

      before do
        allow(subject)
          .to receive(:parse_date)
          .with(datetime)
          .and_return(unix_timestamp)
      end

      it 'returns the right date timestamp value' do
        expect(subject.internal_value_of(datetime)).to eq unix_timestamp
      end

      it 'returns NaN if the given value is Float::NAN' do
        expect(subject.internal_value_of(Float::NAN)).to be Float::NAN
      end

      it 'returns NaN if the given value is nil' do
        expect(subject.internal_value_of(nil)).to be Float::NAN
      end

      it 'returns NaN if the given value is "?"' do
        expect(subject.internal_value_of('?')).to be Float::NAN
      end
    end

    context 'for a string attribute' do
      let(:string_values)        { %w[first_string second_string] }
      let(:phantom_string_value) { 'i_do_not_exist' }

      subject do
        attribute = Weka::Core::Attribute.new_string(name)
        string_values.each { |value| attribute.add_string_value(value) }
        attribute
      end

      it 'returns the correct internal index' do
        expect(subject.internal_value_of(string_values[0])).to eq 0
        expect(subject.internal_value_of(string_values[1])).to eq 1
      end

      it 'returns -1 as internal index for non-existent string values' do
        expect(subject.internal_value_of(phantom_string_value)).to eq(-1)
      end

      it 'returns the correct internal index as given as a non-String' do
        expect(subject.internal_value_of(:first_string)).to eq 0
        expect(subject.internal_value_of(:second_string)).to eq 1
      end

      it 'returns -1 as internal index for non-existent non-String values' do
        expect(subject.internal_value_of(:phantom_string_value)).to eq(-1)
      end

      it 'returns NaN if the given value is Float::NAN' do
        expect(subject.internal_value_of(Float::NAN)).to be Float::NAN
      end

      it 'returns NaN if the given value is nil' do
        expect(subject.internal_value_of(nil)).to be Float::NAN
      end

      it 'returns NaN if the given value is "?"' do
        expect(subject.internal_value_of('?')).to be Float::NAN
      end
    end
  end

  describe '#type' do
    context 'for a numeric attribute' do
      subject { Weka::Core::Attribute.new_numeric(name) }

      it 'returns "numeric"' do
        expect(subject.type).to eq 'numeric'
      end
    end

    context 'for a nominal attribute' do
      subject { Weka::Core::Attribute.new_nominal(name, values) }

      it 'returns "nominal"' do
        expect(subject.type).to eq 'nominal'
      end
    end

    context 'for a string attribute' do
      subject { Weka::Core::Attribute.new_string(name) }

      it 'returns "string"' do
        expect(subject.type).to eq 'string'
      end
    end

    context 'for a data attribute' do
      let(:datetime)       { '2015-12-24 11:11' }
      let(:unix_timestamp) { 1_450_955_460_000.0 }

      subject { Weka::Core::Attribute.new_date(name, format) }

      before do
        allow(subject)
          .to receive(:parse_date)
          .with(datetime)
          .and_return(unix_timestamp)
      end

      it 'returns "date"' do
        expect(subject.type).to eq 'date'
      end
    end
  end
end


text:
interface PropertyEvent {
  id: string;
  mainImage: string;
  price: string;
  agency: {
    brandingColors: {
      primary: string;
    },
    logo: string;
  };
  isSaved: boolean;
}

export default PropertyEvent;


text:
require 'caracal/core/models/base_model'

module Caracal
  module Core
    module Models

      # This class handles block options passed to the img method.
      #
      class ImageModel < BaseModel

        #-------------------------------------------------------------
        # Configuration
        #-------------------------------------------------------------

        # constants
        const_set(:DEFAULT_IMAGE_PPI,     72)       # pixels per inch
        const_set(:DEFAULT_IMAGE_WIDTH,   0)        # units in pixels. (will cause error)
        const_set(:DEFAULT_IMAGE_HEIGHT,  0)        # units in pixels. (will cause error)
        const_set(:DEFAULT_IMAGE_ALIGN,   :left)
        const_set(:DEFAULT_IMAGE_TOP,     8)        # units in pixels.
        const_set(:DEFAULT_IMAGE_BOTTOM,  8)        # units in pixels.
        const_set(:DEFAULT_IMAGE_LEFT,    8)        # units in pixels.
        const_set(:DEFAULT_IMAGE_RIGHT,   8)        # units in pixels.

        # accessors
        attr_reader :image_url
        attr_reader :image_data
        attr_reader :image_ppi
        attr_reader :image_width
        attr_reader :image_height
        attr_reader :image_align
        attr_reader :image_top
        attr_reader :image_bottom
        attr_reader :image_left
        attr_reader :image_right

        # initialization
        def initialize(options={}, &block)
          @image_ppi    = DEFAULT_IMAGE_PPI
          @image_width  = DEFAULT_IMAGE_WIDTH
          @image_height = DEFAULT_IMAGE_HEIGHT
          @image_align  = DEFAULT_IMAGE_ALIGN
          @image_top    = DEFAULT_IMAGE_TOP
          @image_bottom = DEFAULT_IMAGE_BOTTOM
          @image_left   = DEFAULT_IMAGE_LEFT
          @image_right  = DEFAULT_IMAGE_RIGHT

          super options, &block
        end

        #-------------------------------------------------------------
        # Public Methods
        #-------------------------------------------------------------

        #=============== GETTERS ==============================

        [:width, :height].each do |m|
          define_method "formatted_#{ m }" do
            value = send("image_#{ m }")
            pixels_to_emus(value, image_ppi)
          end
        end

        [:top, :bottom, :left, :right].each do |m|
          define_method "formatted_#{ m }" do
            value = send("image_#{ m }")
            pixels_to_emus(value, 72)
          end
        end

        def relationship_target
          image_url || image_data
        end

        #=============== SETTERS ==============================

        # integers
        [:ppi, :width, :height, :top, :bottom, :left, :right].each do |m|
          define_method "#{ m }" do |value|
            instance_variable_set("@image_#{ m }", value.to_i)
          end
        end

        # strings
        [:data, :url].each do |m|
          define_method "#{ m }" do |value|
            instance_variable_set("@image_#{ m }", value.to_s)
          end
        end

        # symbols
        [:align].each do |m|
          define_method "#{ m }" do |value|
            instance_variable_set("@image_#{ m }", value.to_s.to_sym)
          end
        end

        #=============== VALIDATION ==============================

        def valid?
          dims = [:ppi, :width, :height, :top, :bottom, :left, :right].map { |m| send("image_#{ m }") }
          dims.all? { |d| d > 0 }
        end

        #-------------------------------------------------------------
        # Private Methods
        #-------------------------------------------------------------
        private

        def option_keys
          [:url, :width, :height, :align, :top, :bottom, :left, :right]
        end

        def pixels_to_emus(value, ppi)
          pixels        = value.to_i
          inches        = pixels / ppi.to_f
          emus_per_inch = 914400

          emus = (inches * emus_per_inch).to_i
        end

      end

    end
  end
end


text:
package me.yokeyword.sample.demo_flow.base;

import androidx.appcompat.widget.Toolbar;
import android.view.View;

import me.yokeyword.sample.R;

/**
 * Created by YoKeyword on 16/2/7.
 */
public class BaseBackFragment extends MySupportFragment {

    protected void initToolbarNav(Toolbar toolbar) {
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
    }
}


text:
<?php

defined('JPATH_PLATFORM') or die;

/**
 * Feed Parser class.
 *
 * @package     Joomla.Platform
 * @subpackage  Feed
 * @since       12.3
 */
abstract class JFeedParser
{
	/**
	 * @var    string  The feed element name for the entry elements.
	 * @since  12.3
	 */
	protected $entryElementName = 'entry';

	/**
	 * @var    array
	 * @since  12.3
	 */
	protected $namespaces = array();

	/**
	 * @var    XMLReader
	 * @since  12.3
	 */
	protected $stream;

	/**
	 * Constructor.
	 *
	 * @param   XMLReader  $stream  The XMLReader stream object for the feed.
	 *
	 * @since   12.3
	 */
	public function __construct(XMLReader $stream)
	{
		$this->stream  = $stream;
	}

	/**
	 * Method to parse the feed into a JFeed object.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function parse()
	{
		$feed = new JFeed;

		// Detect the feed version.
		$this->initialise();

		// Let's get this party started...
		do
		{
			// Expand the element for processing.
			$el = new SimpleXMLElement($this->stream->readOuterXml());

			// Get the list of namespaces used within this element.
			$ns = $el->getNamespaces(true);

			// Get an array of available namespace objects for the element.
			$namespaces = array();

			foreach ($ns as $prefix => $uri)
			{
				// Ignore the empty namespace prefix.
				if (empty($prefix))
				{
					continue;
				}

				// Get the necessary namespace objects for the element.
				$namespace = $this->fetchNamespace($prefix);

				if ($namespace)
				{
					$namespaces[] = $namespace;
				}
			}

			// Process the element.
			$this->processElement($feed, $el, $namespaces);

			// Skip over this element's children since it has been processed.
			$this->moveToClosingElement();
		}
		while ($this->moveToNextElement());

		return $feed;
	}

	/**
	 * Method to register a namespace handler object.
	 *
	 * @param   string                $prefix     The XML namespace prefix for which to register the namespace object.
	 * @param   JFeedParserNamespace  $namespace  The namespace object to register.
	 *
	 * @return  JFeed
	 *
	 * @since   12.3
	 */
	public function registerNamespace($prefix, JFeedParserNamespace $namespace)
	{
		$this->namespaces[$prefix] = $namespace;

		return $this;
	}

	/**
	 * Method to initialise the feed for parsing.  If child parsers need to detect versions or other
	 * such things this is where you'll want to implement that logic.
	 *
	 * @return  void
	 *
	 * @since   12.3
	 */
	abstract protected function initialise();

	/**
	 * Method to parse a specific feed element.
	 *
	 * @param   JFeed             $feed        The JFeed object being built from the parsed feed.
	 * @param   SimpleXMLElement  $el          The current XML element object to handle.
	 * @param   array             $namespaces  The array of relevant namespace objects to process for the element.
	 *
	 * @return  void
	 *
	 * @since   12.3
	 */
	protected function processElement(JFeed $feed, SimpleXMLElement $el, array $namespaces)
	{
		// Build the internal method name.
		$method = 'handle' . ucfirst($el->getName());

		// If we are dealing with an item then it is feed entry time.
		if ($el->getName() == $this->entryElementName)
		{
			// Create a new feed entry for the item.
			$entry = new JFeedEntry;

			// First call the internal method.
			$this->processFeedEntry($entry, $el);

			foreach ($namespaces as $namespace)
			{
				if ($namespace instanceof JFeedParserNamespace)
				{
					$namespace->processElementForFeedEntry($entry, $el);
				}
			}

			// Add the new entry to the feed.
			$feed->addEntry($entry);
		}
		// Otherwise we treat it like any other element.
		else
		{
			// First call the internal method.
			if (is_callable(array($this, $method)))
			{
				$this->$method($feed, $el);
			}

			foreach ($namespaces as $namespace)
			{
				if ($namespace instanceof JFeedParserNamespace)
				{
					$namespace->processElementForFeed($feed, $el);
				}
			}
		}
	}

	/**
	 * Method to get a namespace object for a given namespace prefix.
	 *
	 * @param   string  $prefix  The XML prefix for which to fetch the namespace object.
	 *
	 * @return  mixed  JFeedParserNamespace or false if none exists.
	 *
	 * @since   12.3
	 */
	protected function fetchNamespace($prefix)
	{
		if (isset($this->namespaces[$prefix]))
		{
			return $this->namespaces[$prefix];
		}

		$className = get_class($this) . ucfirst($prefix);

		if (class_exists($className))
		{
			$this->namespaces[$prefix] = new $className;

			return $this->namespaces[$prefix];
		}

		return false;
	}

	/**
	 * Method to move the stream parser to the next XML element node.
	 *
	 * @param   string  $name  The name of the element for which to move the stream forward until is found.
	 *
	 * @return  boolean  True if the stream parser is on an XML element node.
	 *
	 * @since   12.3
	 */
	protected function moveToNextElement($name = null)
	{
		// Only keep looking until the end of the stream.
		while ($this->stream->read())
		{
			// As soon as we get to the next ELEMENT node we are done.
			if ($this->stream->nodeType == XMLReader::ELEMENT)
			{
				// If we are looking for a specific name make sure we have it.
				if (isset($name) && ($this->stream->name != $name))
				{
					continue;
				}

				return true;
			}
		}

		return false;
	}

	/**
	 * Method to move the stream parser to the closing XML node of the current element.
	 *
	 * @return  void
	 *
	 * @since   12.3
	 * @throws  RuntimeException  If the closing tag cannot be found.
	 */
	protected function moveToClosingElement()
	{
		// If we are on a self-closing tag then there is nothing to do.
		if ($this->stream->isEmptyElement)
		{
			return;
		}

		// Get the name and depth for the current node so that we can match the closing node.
		$name  = $this->stream->name;
		$depth = $this->stream->depth;

		// Only keep looking until the end of the stream.
		while ($this->stream->read())
		{
			// If we have an END_ELEMENT node with the same name and depth as the node we started with we have a bingo. :-)
			if (($this->stream->name == $name) && ($this->stream->depth == $depth) && ($this->stream->nodeType == XMLReader::END_ELEMENT))
			{
				return;
			}
		}

		throw new RuntimeException('Unable to find the closing XML node.');
	}
}


text:
'use strict';

// Flags: --expose-internals

require('../common');
const { WPTRunner } = require('../common/wpt');
const { performance, PerformanceObserver } = require('perf_hooks');

const runner = new WPTRunner('hr-time');

runner.copyGlobalsFromObject(global, [
  'setInterval',
  'clearInterval',
  'setTimeout',
  'clearTimeout'
]);

runner.defineGlobal('performance', {
  get() {
    return performance;
  }
});
runner.defineGlobal('PerformanceObserver', {
  value: PerformanceObserver
});

runner.runJsTests();


text:
/*

©2009-2018 OSIsoft, LLC. All Rights Reserved.

No Warranty or Liability.  The OSIsoft Samples contained herein are being supplied to Licensee
"AS IS" without any warranty of any kind.  OSIsoft DISCLAIMS ALL EXPRESS AND IMPLIED WARRANTIES,
INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE and NONINFRINGEMENT. In no event will OSIsoft be liable to Licensee or to any third party
for damages of any kind arising from Licensee's use of the OSIsoft Samples OR OTHERWISE, including
but not limited to direct, indirect, special, incidental and consequential damages, and Licensee
expressly assumes the risk of all such damages.  FURTHER, THE OSIsoft SAMPLES ARE NOT ELIGIBLE FOR
SUPPORT UNDER EITHER OSISOFT'S STANDARD OR ENTERPRISE LEVEL SUPPORT AGREEMENTS

*/

/* buildData.h */

#include "deviceSimulator.h"

#pragma once
JsonNode* objArrNumVal(const char* stream, const char* idxDT, const char* szTag, const char* szTime, int sLength, double* dVal, int nVal);

char* sendOneVal(const char* valStream, const char* dateTimeKey, const char* szTime, char* szTag, double dVal);
char* sendOneValStr(const char* valStream, const char* dateTimeKey, const char* szTime, char* szTag, char* szVal);

char* val_Link_Asset_RT(
	const char* source_type,
	const char* source_typeversion,
	const char* containerid_prefix, /* a value such as "VStr_vRPM") */
	char* source_indexes, /* array of AF element names; e.g., Engine_1, Engine_2, Engine_3 */
	const int nElements,  /* number of elements */
	const int nStringLength  /* string length of the name of AF elements */
);

JsonNode* objArrNumVals(
	const char* stream,  /* streamID such as "VStr_vRPM_Engine_1 */
	const char* idxDT,   /* timestamp index indicator; e.g., IndexedDateTime */
	const char* szTime,   /* array of timestamps */
	int sLength,    /* length of szTime string */
	int nTime,   /* size of timestamp array */
	const char* szTag,   /* real-time value name; e.g., vRMP */
	int sTagLength,   /* length of szTag strings */
	int nTags,
	double* dVal    /* array of values */
);


text:
angular-borderlayout
====================

A set of Angular.js components to manage and define border layouts

[![Dependency Status](https://david-dm.org/e-cloud/angular-borderlayout.svg)](https://david-dm.org/e-cloud/angular-borderlayout)
[![DevDependency Status](https://david-dm.org/e-cloud/angular-borderlayout/dev-status.svg)](https://david-dm.org/e-cloud/angular-borderlayout?type=dev)
[![DevDependency Status](https://david-dm.org/e-cloud/angular-borderlayout/peer-status.svg)](https://david-dm.org/e-cloud/angular-borderlayout?type=peer)

[![npm version](https://img.shields.io/npm/v/angular-borderlayout2.svg?maxAge=86400)](https://www.npmjs.com/package/angular-borderlayout2)
![License](https://img.shields.io/badge/License-MIT-blue.svg?maxAge=86400)


text:
id: 5900f39e1000cf542c50feb1
title: 'Problema 50: Soma dos números primos consecutivos'
challengeType: 5
forumTopicId: 302161
dashedName: problem-50-consecutive-prime-sum
---

# --description--

O número primo 41 pode ser escrito como a soma de seis números primos consecutivos:

41 = 2 + 3 + 5 + 7 + 11 + 13

Esta é a soma mais longa de números primos consecutivos abaixo de 100 que resultam em um número primo.

A soma mais longa de números primos consecutivos abaixo de 1000 contém 21 termos e resulta em 953.

Qual número primo, abaixo de um milhão, é o resultado da soma da maior sequência de números primos?

# --hints--

`consecutivePrimeSum(1000)` deve retornar um número.

```js
assert(typeof consecutivePrimeSum(1000) === 'number');
```

`consecutivePrimeSum(1000)` deve retornar 953.

```js
assert.strictEqual(consecutivePrimeSum(1000), 953);
```

`consecutivePrimeSum(1000000)` deve retornar 997651.

```js
assert.strictEqual(consecutivePrimeSum(1000000), 997651);
```

# --seed--

## --seed-contents--

```js
function consecutivePrimeSum(limit) {

  return true;
}

consecutivePrimeSum(1000000);
```

# --solutions--

```js
function consecutivePrimeSum(limit) {
  function isPrime(num) {
    if (num < 2) {
      return false;
    } else if (num === 2) {
      return true;
    }
    const sqrtOfNum = Math.floor(num ** 0.5);
    for (let i = 2; i <= sqrtOfNum + 1; i++) {
      if (num % i === 0) {
        return false;
      }
    }
    return true;
  }
  function getPrimes(limit) {
    const primes = [];
    for (let i = 0; i <= limit; i++) {
      if (isPrime(i)) primes.push(i);
    }
    return primes;
  }

  const primes = getPrimes(limit);
  let primeSum = [...primes];
  primeSum.reduce((acc, n, i) => {
    primeSum[i] += acc;
    return acc += n;
  }, 0);

  for (let j = primeSum.length - 1; j >= 0; j--) {
    for (let i = 0; i < j; i++) {
      const sum = primeSum[j] - primeSum[i];
      if (sum > limit) break;
      if (isPrime(sum) && primes.indexOf(sum) > -1) return sum;
    }
  }
}
```


text:
;(function($) {
  $.fn.ft_fileinfo = function(options) {
    return this.each(function() {
      $(this).find('span.addfileinfo').click(function(){
        parent = $(this).parents('tr');
        if (parent.find('p.fileinfo').length > 0) {
          // Description already present. Cancel.
          parent.find('p.fileinfo').remove();
        } else {
          $(this).after('
<input type="text" size="30" name="fileinfo" value="Add description">
');
        }
      });

    });
  };
})(jQuery);


text:
<tool-header headerText="Car Tool"></tool-header>

<car-table [cars]="cars$ | async" [editCarId]="editCarId$ | async"
  (editCar)="doEditCar($event)"
  (deleteCar)="doDeleteCar($event)"
  (saveCar)="doReplaceCar($event)"
  (cancelCar)="doCancelCar()"></car-table>

<car-form buttonText="Add Car" (submitCar)="doAppendCar($event)"></car-form>


text:
package org.apache.hadoop.flume.interceptor;

import org.apache.flume.Event;
import org.apache.flume.event.JSONEvent;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.HashMap;
import java.util.Map;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

@RunWith(JUnit4.class)
public class HeaderRegexInterceptorTest {

    private static final String BODY = "this is my body";
    private static final String HEADER_KEY = "filename";
    private static final String HEADER_VALUE = "testfile-on-12.10.2014.txt";
    private static final String REGEX_PATTERN =
	"^(?<basename>\\w+)-on-(?<date>\\d+\\.\\d+\\.\\d+)\\.txt";
    private Map<String,String> groupToStringMap;

    private Event event;
    private Map<String, String> headers;
    private HeaderRegexInterceptor interceptor;

    @Before
    public void prepare() {

	groupToStringMap = new HashMap<String, String>();
	groupToStringMap.put("basename", "basename");
	groupToStringMap.put("date", "timestamp");

        headers = new HashMap<String, String>(1);
        headers.put(HEADER_KEY, HEADER_VALUE);

        event = new JSONEvent();
        event.setBody(BODY.getBytes());
        event.setHeaders(headers);

        interceptor = new HeaderRegexInterceptor(
	    HEADER_KEY, REGEX_PATTERN, groupToStringMap);
        interceptor.initialize();
    }

    @Test
    public void testInterception(){

        Event interceptedEvent =
                interceptor.intercept(event);

        assertEquals("event body should not have been altered",
                BODY,
                new String(interceptedEvent.getBody()));

	assertEquals("event filename header should not have been altered",
                HEADER_VALUE,
                interceptedEvent.getHeaders().get(HEADER_KEY));

        assertEquals("header should now contain basename",
		"testfile",
                interceptedEvent.getHeaders().get("basename"));

        assertEquals("header should now contain timestamp",
		"12.10.2014",
                interceptedEvent.getHeaders().get("timestamp"));
    }

}


text:
require 'spec_helper'

describe Api::SessionsController do

  describe "create" do
    it "should not create new session on auth failure" do
      Session.should_not_receive(:create)
      Donor.stub(:authenticate).and_return(nil)
      post :create, :format => :json, :email => 'meh', :password => 'meh'
      response.status.should == 401
    end

    pending "should create new session on auth success" do
      sess = Session.new(:donor => create(:donor))
      Session.stub(:create).and_return(sess)
      Donor.stub(:authenticate).and_return(Donor.new(:email => 'jim@jim.com'))
      post :create, :format => :json, :email => 'meh', :password => 'meh'
      response.status.should == 201
      resp = JSON.parse(response.body)
      resp['token'].should == sess.token
    end
  end # end create

  describe "destroy" do
    it "should destroy with token" do
      sess = Session.create(:donor => create(:donor))
      token = sess.token
      sess.should_not be_nil
      request.env['HTTP_AUTHORIZATION'] = "Token token=#{token}"
      Session.should_receive(:find_by_token).once.with(token).and_return(sess)
      post :destroy, :format => :json
      response.status.should == 200
    end

    it "should destroy with bad token" do
      token = '12345asdf'
      Session.find_by_token(token).should be_nil
      request.env['HTTP_AUTHORIZATION'] = "Token token=#{token}"
      Session.should_receive(:find_by_token).once.with(token).and_return(nil)
      post :destroy, :format => :json
      response.status.should == 200
    end

    it "should destroy without token" do
      Session.should_not_receive(:find_by_token)
      post :destroy, :format => :json
      response.status.should == 200
    end
  end # end destroy

end