text:
1. in BUILD file, at the top, add the following line
    ```
    load("//tools:cpplint.bzl", "cpplint")
    ```
2. in BUILD file, at the bottom, add the following line
    ```
    cpplint()
    ```
3. run `apollo.sh check` to verify if the directory passes style check.

### Please use the [BUILD](https://github.com/ApolloAuto/apollo/blob/master/modules/canbus/BUILD) file of canbus module as an example.
```
load("//tools:cpplint.bzl", "cpplint")

package(default_visibility = ["//visibility:public"])

cc_library(
    name = "canbus_lib",
    srcs = ["canbus.cc"],
    hdrs = ["canbus.h"],
    deps = [
        "//modules/canbus/can_client:can_client_factory",
        "//modules/canbus/can_comm:can_receiver",
        "//modules/canbus/can_comm:can_sender",
        "//modules/canbus/vehicle:vehicle_factory",
        "//modules/common",
        "//modules/common:apollo_app",
        "//modules/common/adapters:adapter_manager",
        "//modules/common/monitor",
        "//modules/hmi/utils:hmi_status_helper",
    ],
)

cc_test(
    name = "canbus_test",
    size = "small",
    srcs = ["canbus_test.cc"],
    deps = [
        "//modules/canbus:canbus_lib",
        "@gtest//:main",
    ],
)

cc_binary(
    name = "canbus",
    srcs = ["main.cc"],
    deps = [
        ":canbus_lib",
        "//external:gflags",
        "//modules/canbus/can_client",
        "//modules/canbus/common:canbus_common",
        "//modules/common:log",
        "//modules/common/monitor",
        "//third_party/ros:ros_common",
    ],
)

filegroup(
    name = "canbus_testdata",
    srcs = glob(["testdata/**"]),
)

cpplint()
```


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/stand_bg"
    android:orientation="vertical"
    tools:context="net.coding.program.project.detail.wiki.WikiHistoryDetailActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

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

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

            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="?attr/actionBarSize"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="15dp" />

        </LinearLayout>
    </ScrollView>

    <FrameLayout
        android:id="@+id/rollbackLayout"
        android:layout_width="match_parent"
        android:layout_height="49dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="恢复至该版本"
            android:textColor="@color/font_2"
            android:textSize="15sp" />

        <View style="@style/DivideLine" />

    </FrameLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
package main

import (

	// Import the snap plugin library
	"github.com/intelsdi-x/snap-plugin-lib-go/v1/plugin"

	// Import our collector plugin implementation
	"github.com/intelsdi-x/snap-plugin-collector-ceph/ceph"
)

// meta data about plugin
const (
	name    = "ceph"
	version = 7
)

// plugin bootstrap
func main() {
	plugin.StartCollector(ceph.New(), name, version, plugin.ConcurrencyCount(1))
}


text:
import { Common } from "./common";

export class SyncBranch {
    static async runAsync(repoUrl: string, docfxHomeDir: string, fromBranch: string, targetBranch: string): Promise<void> {
        await Common.execAsync("git", ["remote", "set-url", "origin", repoUrl], docfxHomeDir);
        await Common.execAsync("git", ["push", "origin", fromBranch + ":" + targetBranch], docfxHomeDir);
        console.log("Sync successfully");
    }
}


text:
Contains productivity extension methods and custom stamp types for PDFsharp.

## Image/Pdf Import
One-liner that allows you to import multi-page images/pdf sources into another pdf.

## Javascript
Add javascript action on document open and set additional actions.

## Annotations
Additional annotation types include arrow, free text, square-circle, and standard business stamps (Adobe).


text:
<!DOCTYPE html>

        <title>PLUME | Wedding</title>

        <meta name="author" content="Graphicfort">
        <meta name="robots" content="index follow">
        <meta name="googlebot" content="index follow">
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <meta name="keywords" content="PLUME, HTML5, CSS3, Creative, Multipurpose, Template, Create a website fast">
        <meta name="description" content="HTML5 Multipurpose Template, Create a website fast">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="shortcut icon" href="images/icons/favicon.ico">
        <link rel="apple-touch-icon" sizes="57x57" href="images/icons/apple-touch-icon-57x57.png">
        <link rel="apple-touch-icon" sizes="60x60" href="images/icons/apple-touch-icon-60x60.png">
        <link rel="apple-touch-icon" sizes="72x72" href="images/icons/apple-touch-icon-72x72.png">
        <link rel="apple-touch-icon" sizes="76x76" href="images/icons/apple-touch-icon-76x76.png">
        <link rel="apple-touch-icon" sizes="114x114" href="images/icons/apple-touch-icon-114x114.png">
        <link rel="apple-touch-icon" sizes="120x120" href="images/icons/apple-touch-icon-120x120.png">
        <link rel="apple-touch-icon" sizes="144x144" href="images/icons/apple-touch-icon-144x144.png">
        <link rel="apple-touch-icon" sizes="152x152" href="images/icons/apple-touch-icon-152x152.png">
        <link rel="apple-touch-icon" sizes="180x180" href="images/icons/apple-touch-icon-180x180.png">

        <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700%7CPoppins:400,500,600" rel="stylesheet">

        <link rel="stylesheet" href="js/vendor/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="fonts/font-awesome/css/font-awesome.min.css">

        <link rel="stylesheet" href="css/plugins.css">
        <link rel="stylesheet" href="css/index/wedding/style.css">
        <link rel="stylesheet" href="css/responsive.css">

                                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                                                Menu

                                            </button>

                                                        Home

                                                        Our Story

                                                        Join US

                                                        Send a Gift

                                                        Gallery

                                                        Location

                                        <div
                                            class="tp-caption tp-shape tp-shapewrapper"
                                            data-x="center"
                                            data-hoffset="0"
                                            data-y="middle"
                                            data-voffset="0"
                                            data-width="full"
                                            data-height="full"
                                            data-whitespace="nowrap"
                                            data-type="shape"
                                            data-basealign="slide"
                                            data-responsive_offset="on"
                                            data-responsive="off"
                                            data-frames='[
                                                {
                                                    "from":"opacity:0;",
                                                    "speed":1500,
                                                    "to":"o:1;",
                                                    "delay":750,
                                                    "ease":"Power3.easeInOut"
                                                },
                                                {
                                                    "delay":"wait",
                                                    "speed":300,
                                                    "ease":"nothing"
                                                }
                                            ]'
                                            data-textAlign="left"
                                            data-paddingtop="0"
                                            data-paddingright="15"
                                            data-paddingbottom="0"
                                            data-paddingleft="15"
                                            style="z-index: 5; background-color:rgba(0, 0, 0, 0.40);">

                                        <div
                                            class="tp-caption rs-heading-title light-color tp-resizeme"
                                            data-x="center"
                                            data-hoffset="0"
                                            data-y="middle"
                                            data-voffset="-35"
                                            data-fontsize="60"
                                            data-lineheight="60"
                                            data-width="1170"
                                            data-height="none"
                                            data-whitespace="normal"
                                            data-type="text"
                                            data-responsive_offset="on"
                                            data-frames='[
                                                {
                                                    "delay":1000,
                                                    "split":"chars",
                                                    "splitdelay":0.05,
                                                    "speed":2000,
                                                    "frame":"0",
                                                    "from":"y:[100%];z:0;rZ:-35deg;sX:1;sY:1;skX:0;skY:0;",
                                                    "mask":"x:0px;y:0px;s:inherit;e:inherit;",
                                                    "to":"o:1;",
                                                    "ease":"Power4.easeInOut"
                                                },
                                                {
                                                    "delay":"wait",
                                                    "speed":300,
                                                    "frame":"999",
                                                    "to":"auto:auto;",
                                                    "ease":"noting"
                                                }
                                            ]'
                                            data-textAlign="center"
                                            data-paddingtop="0"
                                            data-paddingright="15"
                                            data-paddingbottom="0"
                                            data-paddingleft="15">
                                            ARTHUR & ABELLE

                                        <div
                                            class="tp-caption rs-heading-title light-color tp-resizeme"
                                            data-x="center"
                                            data-hoffset="0"
                                            data-y="middle"
                                            data-voffset="35"
                                            data-fontsize="60"
                                            data-lineheight="60"
                                            data-width="1170"
                                            data-height="none"
                                            data-whitespace="normal"
                                            data-type="text"
                                            data-responsive_offset="on"
                                            data-frames='[
                                                {
                                                    "delay":2000,
                                                    "split":"chars",
                                                    "splitdelay":0.05,
                                                    "speed":2000,
                                                    "frame":"0",
                                                    "from":"y:[100%];z:0;rZ:-35deg;sX:1;sY:1;skX:0;skY:0;",
                                                    "mask":"x:0px;y:0px;s:inherit;e:inherit;",
                                                    "to":"o:1;",
                                                    "ease":"Power4.easeInOut"
                                                },
                                                {
                                                    "delay":"wait",
                                                    "speed":300,
                                                    "frame":"999",
                                                    "to":"auto:auto;",
                                                    "ease":"noting"
                                                }
                                            ]'
                                            data-textAlign="center"
                                            data-paddingtop="0"
                                            data-paddingright="15"
                                            data-paddingbottom="0"
                                            data-paddingleft="15">
                                            6 NOV 2017

                                                        00

DAYS

                                                        00

HOURS

                                                        00

MINUTES

                                                        00

SECONDS

OUR STORY

Fusce volutpat dolor pellentesque, consequat nibh nec, ultrices urna. Proin id eros scelerisque, posuere dolor laoreet, pretium ligula. Donec auctor eget tellus quis imperdiet. Morbi aliquet et orci in ultricies. Duis auctor diam eu massa maximus ultrices. Integer quis neque et tortor fermentum ultricies. Sed laoreet ipsum neque, id dignissim dolor tempus ut. Nulla tincidunt semper quam. Ut a ante sit amet felis vehicula mollis. Nullam at fermentum ipsum, ac vehicula urna.

Donec pulvinar quam dolor, vitae semper ligula pretium eu. Phasellus vitae turpis vel nisi vehicula pharetra. Nunc ullamcorper commodo facilisis. Donec dapibus sapien finibus elit semper, a volutpat nisi pellentesque. Sed ac orci nulla. Sed finibus sapien vel velit viverra rhoncus.

JOIN US

Capitalise on low hanging fruit to identify a ballpark value added activity to beta test. Override the digital divide with additional clickthroughs from DevOps.

                                                    <form method="post" action="php/wedding.php">

                                                                Name *
                                                                <input type="text" class="form-control" name="form_name" id="form_name">

                                                                Email Address *
                                                                <input type="email" class="form-control" name="form_email" id="form_email">

                                                                I will attend to *
                                                                <select name="form_attend" class="form-control" id="form_attend">
                                                                    <option value="Wedding">Wedding Day</option>
                                                                    <option value="Ceremony">Ceremony Day</option>
                                                                    <option value="Party">The Party</option>
                                                                </select>

                                                                <button type="submit" class="btn btn-gfort-white" style="width: 100%; margin-top: 32px;">Send</button>

                                                    </form>

GIFT REGISTRATION

Capitalise on low hanging fruit to identify a ballpark value added activity to beta test. Override the digital divide with additional clickthroughs from DevOps.

Also we can accept paypal payments

                                                        PAY VIA PAYPAL

Don't Get Lost

Capitalise on low hanging fruit to identify a ballpark value added activity to beta test. Override the digital divide with additional clickthroughs from DevOps.

Ceremony 5 PM

                                                        MONDAY, NOVEMBER 6TH 2017

                                                        16 Rue de Turbigo, 12345 Paris, France

Wedding 6 PM

                                                        MONDAY, NOVEMBER 6TH 2017

                                                        6 rue Saint-Martin, 12345 Paris, France

The Party 10 PM

                                                        MONDAY, NOVEMBER 6TH 2017

                                                        69 Rue des Gravilliers, 12345 Paris, France

Ceremony 5 PM

                                                                MONDAY, NOVEMBER 6TH 2017

                                                                16 Rue de Turbigo, 12345 Paris, France

Wedding 6 PM

                                                                MONDAY, NOVEMBER 6TH 2017

                                                                6 rue Saint-Martin, 12345 Paris, France

The Party 10 PM

                                                                MONDAY, NOVEMBER 6TH 2017

                                                                69 Rue des Gravilliers, 12345 Paris, France

Have any question call us at +1 123 456-7890

Home

About

Portfolio

Contact

© 2017 Graphicfort, all rights reserved.

        <link rel="stylesheet" href="js/plugins/slider-revolution/css/settings.css">
        <link rel="stylesheet" href="js/plugins/slider-revolution/css/layers.css">
        <link rel="stylesheet" href="js/plugins/slider-revolution/css/navigation.css">


text:
/*
*  BeHappy
*
* Remplaçant d'OutlineListView optimisé pour BeHappy
*
*/

#ifndef HAPPYLISTVIEW_H
#define HAPPYLISTVIEW_H

#include <View.h>
#include <Point.h>
#include <List.h>

class BListItem;
class BPoint;

class HappyListView : public BView
{
public:
	HappyListView(BRect frame, const char *name, uint32 type=0,
		uint32 resizing_mode = B_FOLLOW_LEFT | B_FOLLOW_TOP,
		uint32 flags = B_WILL_DRAW | B_FRAME_EVENTS | B_NAVIGABLE);
	~HappyListView();

	bool AddItem(BListItem *item, int index=0);
	bool AddUnder(BListItem *item, BListItem *superItem);
	BListItem *ItemAt(int index);
	BListItem *RemoveItem(int index);
	int IndexOf(BListItem *myItem);
	int IndexOf(BPoint point);

	void MakeEmpty();
	bool IsEmpty();

	void Select(int index);
	int CurrentSelection();
	void ScrollToSelection();

	int FullListCountItems();
	void FullListDoForEach(bool (*)(BListItem *, void *), void *);
	BListItem *Superitem(BListItem *);
	int CountItems();

	void Collapse(BListItem *);
	void Expand(BListItem *);

	BRect ItemFrame(int i);

	virtual void FrameResized(float width, float height);

private:
	BList m_ItemList;
	int m_CurrentSelection;
};

#endif


text:
namespace TableTennisChampionshipMain.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using TableTennisChampionship.Model.DataBaseModel;
    using TableTennisChampionshipMain.Infrastructure;

    public class TournamentInfo : IMapFrom<Tournament>, IHaveCustomMappings
    {
        public TournamentInfo()
        {
            this.NewPlayer = new TournamentPlayerInfo();
        }
        public int TournamentID { get; set; }
        [Required(ErrorMessage="Не сте задали наименование на турнира")]
        [Display(Name="Наименование на турнир")]
        public string TournamentName { get; set; }
        [Required(ErrorMessage = "Не сте задали начална дата на турнира")]
        [Display(Name = "Начална дата")]
        public DateTime StartDate { get; set; }
        [Display(Name = "Крайна дата")]
        public DateTime EndDate { get; set; }
        [Display(Name="Вид на турнира")]
        public string TournamentTypeDesc { get; set; }
        [Display(Name="Критерии за продъллжаване в групата")]
        public string AdvanceGroupDesc { get; set; }
        [Required]
        public int TournamentTypeID { get; set; }
        [Required]
        public int AdvanceGroupCriteriaID { get; set; }
        [Display(Name="Победител")]
        public string WinnerFullName { get; set; }
        public ICollection<TournamentPlayer> PlayerList { get; set; }
        public TournamentPlayerInfo NewPlayer { get; set; }
        #region IHaveCustomMappings Members

        public void CreateMappings(AutoMapper.IConfiguration configuration)
        {
            //Mapping advance criteria
            configuration.CreateMap<Tournament, TournamentInfo>()
                .ForMember(m => m.AdvanceGroupDesc, opt => opt.MapFrom(b => b.AdvanceGroupCriteria.AdvanceGroupCriteriaDescription));
            configuration.CreateMap<Tournament, TournamentInfo>()
                .ForMember(m => m.AdvanceGroupCriteriaID, opt => opt.MapFrom(b => b.AdvanceGroupCriteria.AdvanceGroupCriteriaID));
            // Mapping TournamentType
            configuration.CreateMap<Tournament, TournamentInfo>()
                .ForMember(m => m.TournamentTypeDesc, opt => opt.MapFrom(b => b.TournamentType.TournamentTypeName));
            configuration.CreateMap<Tournament, TournamentInfo>()
                .ForMember(m => m.TournamentTypeID, opt => opt.MapFrom(b => b.TournamentType.TournamentTypeID ));

            configuration.CreateMap<Tournament, TournamentInfo>()
               .ForMember(m => m.WinnerFullName, opt => opt.MapFrom(b => b.PlayerList.Where(x => x.Rank == 1).Select(p => p.Player.FirstName +" "+ p.Player.LastName).FirstOrDefault()));

        }

        #endregion
    }
}


text:
package com.creactiviti.piper.taskhandler.media;

import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.arakelian.jq.ImmutableJqLibrary;
import com.arakelian.jq.ImmutableJqRequest;
import com.arakelian.jq.JqResponse;
import com.creactiviti.piper.core.task.TaskExecution;
import com.creactiviti.piper.core.task.TaskHandler;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *
 * @author Arik Cohen
 * @since Jun 2, 2017
 */
@Component("media/framerate")
class Framerate implements TaskHandler<Double> {

  private final Ffprobe ffprobe = new Ffprobe();
  private final ObjectMapper jsonMapper = new ObjectMapper ();

  @Override
  public Double handle (TaskExecution aTask) throws Exception {
    Map<?,?> ffprobeResult = ffprobe.handle(aTask);

    JqResponse response = ImmutableJqRequest.builder() //
        .lib(ImmutableJqLibrary.of())
        .input(jsonMapper.writeValueAsString(ffprobeResult))
        .filter(".streams[] | select (.codec_type==\"video\") | .r_frame_rate")
        .build()
        .execute();

    String frameRateStr = response.getOutput();
    Assert.notNull(frameRateStr, "can not determine framerate");
    String[] frate = frameRateStr.replaceAll("[^0-9/\\.]", "").split("/");
    return Double.valueOf(frate[0])/Double.valueOf(frate[1]);
  }

}


text:
package com.vitco.app.importer;

import com.vitco.app.core.data.Data;
import com.vitco.app.util.file.FileIn;
import com.vitco.app.util.file.RandomAccessFileIn;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;

/**
 * Importer contract for (all?) voxel formats
 */
public abstract class AbstractImporter {

    // true if loading was successful
    private final boolean hasLoaded;
    public final boolean hasLoaded() {
        return hasLoaded;
    }

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

    // contains a layer object
    public final static class Layer {
        public final String name;
        // contains the voxel that were read
        private ArrayList<int[]> voxel = new ArrayList<int[]>();
        // constructor
        private Layer(String name) {
            this.name = name;
        }

        // for sanity testing
        private final HashSet<String> known = new HashSet<String>();

        private void addVoxel(int x, int y, int z, int color) {
            voxel.add(new int[]{x,y,z,color});
            // for sanity testing
            assert known.add(x+"_"+y+"_"+z);
        }

        // ----

        public final boolean isEmpty() {
            return voxel.isEmpty();
        }

        int i = 0;
        public final int[] next() {
            return voxel.get(i++);
        }

        public final boolean hasNext() {
            return i < voxel.size();
        }

        public final void reset() {
            i = 0;
        }

        private boolean visible = true;
        public void setVisible(boolean flag) {
            this.visible = flag;
        }
        public boolean isVisible() {
            return visible;
        }
    }

    // the currently active layer
    private Layer activeLayer;

    // list of layers
    public final ArrayList<Layer> getVoxel() {
        return layerList;
    }

    // add voxel to known-voxel list
    protected final void addVoxel(int x, int y, int z, int color) {
        voxelCount++;
        lx = Math.min(lx, x);
        ly = Math.min(ly, y);
        lz = Math.min(lz, z);
        hx = Math.max(hx, x);
        hy = Math.max(hy, y);
        hz = Math.max(hz, z);
        cx += x;
        cy += y;
        cz += z;
        activeLayer.addVoxel(x, y, z, color);
    }

    // contains the layer list
    private final ArrayList<Layer> layerList = new ArrayList<Layer>();
    // add a new layer that the voxels are now added to
    protected final void addLayer(String name) {
        if (activeLayer.isEmpty()) {
            layerList.remove(activeLayer);
        }
        activeLayer = new Layer(name);
        layerList.add(activeLayer);
    }
    // prepend a new layer that the voxels are now added to
    protected final void prependLayer(String name) {
        if (activeLayer.isEmpty()) {
            layerList.remove(activeLayer);
        }
        activeLayer = new Layer(name);
        layerList.add(0, activeLayer);
    }

    // set visibility of current layer
    protected final void setLayerVisibility(boolean flag) {
        activeLayer.setVisible(flag);
    }

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

    // lowest voxel value in that dimension (all layers)
    private int lx = Integer.MAX_VALUE;
    private int ly = Integer.MAX_VALUE;
    private int lz = Integer.MAX_VALUE;
    public final int[] getLowest() {
        return new int[] {lx, ly, lz};
    }

    // highest voxel value in that dimension (all layers)
    private int hx = Integer.MIN_VALUE;
    private int hy = Integer.MIN_VALUE;
    private int hz = Integer.MIN_VALUE;
    public final int[] getHighest() {
        return new int[] {hx, hy, hz};
    }

    // the amount of voxel that were added (all layers)
    private int voxelCount = 0;
    public final int getVoxelCount() {
        return voxelCount;
    }

    // weighted center (all layers)
    private long cx = 0;
    private long cy = 0;
    private long cz = 0;
    public final int[] getWeightedCenter() {
        return new int[] {(int) (cx/voxelCount), (int) (cy/voxelCount), (int) (cz/voxelCount)};
    }

    // the the center (determined by the boundaries)
    public final int[] getCenter() {
        return new int[] {Math.round(lx + (hx-lx)/2.0f), Math.round(ly + (hy-ly)/2.0f), Math.round(lz + (hz-lz)/2.0f)};
    }

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

    // constructor
    public AbstractImporter(File file, String layerName) throws IOException {
        activeLayer = new Layer(layerName);
        layerList.add(activeLayer);
        FileIn fileIn = new FileIn(file);
        try (RandomAccessFileIn raf = new RandomAccessFileIn(file, "r")) {
            hasLoaded = read(fileIn, raf);
        } finally {
            fileIn.finish();
        }
    }

    // load the data in this importer into "data"
    public void loadInto(Data data, boolean shiftToCenter) {
        if (this.hasLoaded()) {
            if (shiftToCenter) {
                int[] center = this.getWeightedCenter();
                int[] highest = this.getHighest();
                for (AbstractImporter.Layer layer : this.getVoxel()) {
                    int layerId = data.createLayer(layer.name);
                    data.selectLayer(layerId);
                    data.setVisible(layerId, layer.isVisible());
                    for (int[] vox; layer.hasNext();) {
                        vox = layer.next();
                        data.addVoxelDirect(new Color(vox[3]),
                                new int[] {vox[0] - center[0], vox[1] - highest[1], vox[2] - center[2]});
                    }
                }
            } else {
                for (AbstractImporter.Layer layer : this.getVoxel()) {
                    int layerId = data.createLayer(layer.name);
                    data.selectLayer(layerId);
                    data.setVisible(layerId, layer.isVisible());
                    for (int[] vox; layer.hasNext();) {
                        vox = layer.next();
                        data.addVoxelDirect(new Color(vox[3]),new int[] {vox[0], vox[1], vox[2]});
                    }
                }
            }
        }
    }

    // read file - returns true if file has loaded correctly
    protected abstract boolean read(FileIn fileIn, RandomAccessFileIn raf) throws IOException;
}


text:
angular.module('sampleApp', ['satellizer', 'ngRoute', 'appRoutes', 'LoginCtrl', 'UserCtrl', 'UserService', 'CompanyCtrl','CompanyService', 'TrainingCtrl', 'ProfileCtrl', 'AboutUsCtrl']).config(function($authProvider){
    $authProvider.linkedin({
      clientId: '75o7oq8qxk1g5s',
      redirectUri: 'http://menther-50757.onmodulus.net/nerds',
      scope: ['r_emailaddress', 'r_basicprofile'],
    });
});


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Input Lapangan</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="icon" href="<?php echo base_url()?>assets/img/favicon/favicon.png">

	<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Input Lapangan

Sukses

		<a href="<?php echo base_url() ?>input_lapangan">kembali


text:
package com.googlecode.jcsv;

public class CSVStrategy {

    /**
     * The default CSV strategy. - delimiter ; - quote character " - comment indicator # - do not
     * skip header - ignore empty lines
     */
    public static final CSVStrategy DEFAULT = new CSVStrategy(';', '"', '#', false, true);

    /**
     * The USA/UK csv standard. - delimiter , - quote character " - comment indicator # - do not
     * skip header - ignore empty lines
     */
    public static final CSVStrategy UK_DEFAULT = new CSVStrategy(',', '"', '#', false, true);

    private final char delimiter;
    private final char quoteCharacter;
    private final char commentIndicator;
    private final boolean skipHeader;
    private final boolean ignoreEmptyLines;

    /**
     * Creates a CSVStrategy.
     *
     * @param delimiter
     * @param quoteCharacter
     * @param commentIndicator
     * @param skipHeader
     * @param ignoreEmptyLines
     */
    public CSVStrategy(char delimiter, char quoteCharacter, char commentIndicator, boolean skipHeader, boolean ignoreEmptyLines) {
	this.delimiter = delimiter;
	this.quoteCharacter = quoteCharacter;
	this.commentIndicator = commentIndicator;
	this.skipHeader = skipHeader;
	this.ignoreEmptyLines = ignoreEmptyLines;
    }

    /**
     * Returns the delimiter character.
     */
    public char getDelimiter() {
	return this.delimiter;
    }

    /**
     * Returns the quote character.
     */
    public char getQuoteCharacter() {
	return this.quoteCharacter;
    }

    /**
     * Returns the comment indicator.
     */
    public char getCommentIndicator() {
	return this.commentIndicator;
    }

    /**
     * Skip the header?
     *
     * @return true, if the csv header should be skipped.
     */
    public boolean isSkipHeader() {
	return this.skipHeader;
    }

    /**
     * Ignore empty lines?
     *
     * @return true, if empty lines should be ignored.
     */
    public boolean isIgnoreEmptyLines() {
	return this.ignoreEmptyLines;
    }
}


text:
import {substituteFinalQuery} from "./../queryBuilderService";

test('simple substitution in final query', () => {
  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$a", inputValue: "1"}
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$a", mocked_this)).toBe("1");
});

test('multiple simple substitutions in final query', () => {
  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$a", inputValue: "1", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$b", inputValue: "2", indexInUI: 1},
      {id: 2, type: "variable", inputName: "$c", inputValue: "3", indexInUI: 2}
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$a$b$c", mocked_this)).toBe("123");
});

test('multiple nested substitutions', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$a", inputValue: "1", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$b", inputValue: "$a", indexInUI: 1},
      {id: 2, type: "variable", inputName: "$c", inputValue: "$a$b", indexInUI: 2}
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$c", mocked_this)).toBe("11");
});

test('Complex substitutions', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$time", inputValue: "1h", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$tagValue", inputValue: "hello", indexInUI: 1},
      {
        id: 2, type: "queryVariable", inputValue: "$q", queryFunction: "q", metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", endDuration: "2h", startDuration:"$time", grouptagBoxes: {},
        filtertagBoxes: {0: {key: "tagName", value: "$tagValue"}}, indexInUI: 2
      }
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$q", mocked_this)).toBe(
    "q(\"avg:1h-avg:example.metric{}{tagName=hello}\", \"1h\", \"2h\")"
  );
});

test('Flags', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {
        id: 0, type: "queryVariable", inputValue: "$q", queryFunction: "q", flags: "rate{counter,,1}", metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", endDuration: "2h", startDuration:"$time", grouptagBoxes: {},
        filtertagBoxes: {}, indexInUI: 0
      }
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$q", mocked_this)).toBe(
    "q(\"avg:$time-avg:rate{counter,,1}:example.metric{}{}\", \"$time\", \"2h\")"
  );
});
test('reordered complex substitution', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$time", inputValue: "1h", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$tagValue", inputValue: "hello", indexInUI: 2},
      {
        id: 2, type: "queryVariable", inputValue: "$q", queryFunction: "q", metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", endDuration: "2h", startDuration:"$time", grouptagBoxes: {},
        filtertagBoxes: {
          0: {key: "tagName", value: "$tagValue"}
        }, indexInUI: 1
      }
    ],
  };
  expect(substituteFinalQuery("$q", mocked_this)).toBe(
    "q(\"avg:1h-avg:example.metric{}{tagName=$tagValue}\", \"1h\", \"2h\")"
  );
});

test('error case - query function not set', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {
        id: 0, type: "queryVariable", inputValue: "$q", queryFunction: undefined, metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", endDuration: "2h", startDuration:"$time", indexInUI: 0
      }
    ],
    //Simpler than trying to mock HTMLCollection
    variableOrder: []
  };
  try{
    substituteFinalQuery("$q", mocked_this);
  }catch (e) {
    expect(e.message).toBe("Query function not set");
  }
});

test('query types with `num` arg are built correctly', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$time", inputValue: "1h", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$tagValue", inputValue: "hello1", indexInUI: 1},
      {
        id: 2, type: "queryVariable", inputValue: "$q", queryFunction: "over", metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", duration: "7d", num: "3", period: "period", grouptagBoxes: {},
        filtertagBoxes: {0: {key: "tagName", value: "$tagValue"}}, indexInUI: 2
      }
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$q", mocked_this)).toBe(
    "over(\"avg:1h-avg:example.metric{}{tagName=hello1}\", \"7d\", \"period\", 3)"
  );
});

test('Group tags', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$time", inputValue: "1h", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$tagValue", inputValue: "hello1", indexInUI: 1},
      {
        id: 2, type: "queryVariable", inputValue: "$q", queryFunction: "over", metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", duration: "7d", num: "3", period: "period", grouptagBoxes:
          {0: {key: "tagName1", value: "$tagValue"}, 1: {key: "tagName2", value: "hello2"}},
        filtertagBoxes: {}, indexInUI: 2
      }
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$q", mocked_this)).toBe(
    "over(\"avg:1h-avg:example.metric{tagName1=hello1,tagName2=hello2}{}\", \"7d\", \"period\", 3)"
  );
});

test('Multiple of both tag types', () => {

  const myMock = jest.fn()
  const mocked_this = new myMock();
  mocked_this.target = {
    variables: [
      {id: 0, type: "variable", inputName: "$time", inputValue: "1h", indexInUI: 0},
      {id: 1, type: "variable", inputName: "$tagValue1", inputValue: "hello1", indexInUI: 1},
      {id: 1, type: "variable", inputName: "$tagValue2", inputValue: "hello2", indexInUI: 1},
      {
        id: 2, type: "queryVariable", inputValue: "$q", queryFunction: "over", metric: "example.metric", queryAgg: "avg",
        downsampleTime: "$time", downsampleAgg: "avg", duration: "7d", num: "3", period: "period", grouptagBoxes:
          {0: {key: "groupTag1", value: "$tagValue1"}, 1: {key: "groupTag2", value: "a"}},
        filtertagBoxes: {0: {key: "filterTag1", value: "b"}, 1: {key: "filterTag2", value: "$tagValue2"}}, indexInUI: 2
      }
    ],
    variableOrder: []
  };
  expect(substituteFinalQuery("$q", mocked_this)).toBe(
    "over(\"avg:1h-avg:example.metric{groupTag1=hello1,groupTag2=a}{filterTag1=b,filterTag2=hello2}\", \"7d\", \"period\", 3)"
  );
});


text:
namespace CqlSharp.Linq.Mutations
{
    /// <summary>
    ///   State of a tracked object
    /// </summary>
    public enum EntityState
    {
        /// <summary>
        ///   Indicates that an entity has not changed any values
        /// </summary>
        Unchanged,

        /// <summary>
        ///   Indicates that an entity has been added to a table
        /// </summary>
        Added,

        /// <summary>
        ///   Indicates that an entity has different values compared to the loaded database values
        /// </summary>
        Modified,

        /// <summary>
        ///   Indicates that an entity has been deleted from a table
        /// </summary>
        Deleted,

        /// <summary>
        ///   Indicates that an entity has no longer refers to a row in a database table
        /// </summary>
        Detached
    }
}


text:
<?php

  // para listar images de qualquer modelo em questão
  Router::connect(
    '/admin/:parent/images/:id',
    array(
      'plugin'=>'images',
      'controller'=>'images',
      'prefix'=>'admin',
    ),
    array('named'=>'parent', 'pass'=>array('id'))
  );

  // Para o post em ajax para adicionar imagens
  Router::connect(
    '/admin/:parent/images/:id/add',
    array(
      'plugin'=>'images',
      'controller'=>'images',
      //'prefix'=>'admin',
      'action'=>'add',
    ),
    array('named'=>'parent', 'pass'=>array('id'))
  );

  // Para deletar todas as imagens selecionadas
  // /admin/pages/images/7/delete/delete_all
  Router::connect(
    '/admin/:parent/images/:id/delete_all',
    array(
      'plugin'=>'images',
      'controller'=>'images',
      'prefix'=>'admin',
      'action'=>'delete_all',
    ),
    array('named'=>'parent', 'pass'=>array('id', 'image_id'))
  );

  // Para deletar uma imagem específica de um modelo
  // /admin/pages/images/7/delete/1
  Router::connect(
    '/admin/:parent/images/:id/delete/:image_id',
    array(
      'plugin'=>'images',
      'controller'=>'images',
      'prefix'=>'admin',
      'action'=>'delete',
    ),
    array('named'=>'parent', 'pass'=>array('id', 'image_id'))
  );


text:
package org.apache.http.impl.client;

import org.apache.http.HttpResponse;
import org.apache.http.client.ConnectionBackoffStrategy;

/**
 * This is a {@link ConnectionBackoffStrategy} that never backs off,
 * for compatibility with existing behavior.
 *
 * @since 4.2
 */
public class NullBackoffStrategy implements ConnectionBackoffStrategy {

    @Override
    public boolean shouldBackoff(final Throwable t) {
        return false;
    }

    @Override
    public boolean shouldBackoff(final HttpResponse resp) {
        return false;
    }
}


text:
import styled from 'styled-components'

export const Container = styled.div`
  display: flex;
  flex-flow: row wrap;
`


text:
"""
EasyBuild configuration (paths, preferences, etc.)

@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
@author: Toon Willems (Ghent University)
@author: Ward Poelmans (Ghent University)
"""
import copy
import os
import random
import string
import tempfile
import time
from vsc.utils import fancylogger
from vsc.utils.missing import FrozenDictKnownKeys
from vsc.utils.patterns import Singleton

import easybuild.tools.environment as env
from easybuild.tools import run
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.run import run_cmd

_log = fancylogger.getLogger('config', fname=False)

DEFAULT_LOGFILE_FORMAT = ("easybuild", "easybuild-%(name)s-%(version)s-%(date)s.%(time)s.log")
DEFAULT_MNS = 'EasyBuildMNS'
DEFAULT_MODULE_SYNTAX = 'Tcl'
DEFAULT_MODULES_TOOL = 'EnvironmentModulesC'
DEFAULT_PATH_SUBDIRS = {
    'buildpath': 'build',
    'installpath': '',
    'repositorypath': 'ebfiles_repo',
    'sourcepath': 'sources',
    'subdir_modules': 'modules',
    'subdir_software': 'software',
}
DEFAULT_PREFIX = os.path.join(os.path.expanduser('~'), ".local", "easybuild")
DEFAULT_REPOSITORY = 'FileRepository'
DEFAULT_STRICT = run.WARN

# utility function for obtaining default paths
def mk_full_default_path(name, prefix=DEFAULT_PREFIX):
    """Create full path, avoid '/' at the end."""
    args = [prefix]
    path = DEFAULT_PATH_SUBDIRS[name]
    if path:
        args.append(path)
    return os.path.join(*args)

# build options that have a perfectly matching command line option, listed by default value
BUILD_OPTIONS_CMDLINE = {
    None: [
        'aggregate_regtest',
        'download_timeout',
        'dump_test_report',
        'easyblock',
        'external_modules_metadata',
        'filter_deps',
        'hide_deps',
        'from_pr',
        'github_user',
        'group',
        'ignore_dirs',
        'modules_footer',
        'only_blocks',
        'optarch',
        'regtest_output_dir',
        'skip',
        'stop',
        'suffix_modules_path',
        'test_report_env_filter',
        'testoutput',
        'umask',
    ],
    False: [
        'allow_modules_tool_mismatch',
        'debug',
        'experimental',
        'force',
        'hidden',
        'module_only',
        'robot',
        'sequential',
        'set_gid_bit',
        'skip_test_cases',
        'sticky_bit',
        'upload_test_report',
        'update_modules_tool_cache',
    ],
    True: [
        'cleanup_builddir',
    ],
    DEFAULT_STRICT: [
        'strict',
    ],
}
# build option that do not have a perfectly matching command line option
BUILD_OPTIONS_OTHER = {
    None: [
        'build_specs',
        'command_line',
        'pr_path',
        'robot_path',
        'valid_module_classes',
        'valid_stops',
    ],
    False: [
        'dry_run',
        'recursive_mod_unload',
        'retain_all_deps',
        'silent',
        'try_to_generate',
    ],
    True: [
        'check_osdeps',
        'validate',
    ],
}

# based on
# https://wickie.hlrs.de/platforms/index.php/Module_Overview
# https://wickie.hlrs.de/platforms/index.php/Application_software_packages
DEFAULT_MODULECLASSES = [
    ('base', "Default module class"),
    ('bio', "Bioinformatics, biology and biomedical"),
    ('cae', "Computer Aided Engineering (incl. CFD)"),
    ('chem', "Chemistry, Computational Chemistry and Quantum Chemistry"),
    ('compiler', "Compilers"),
    ('data', "Data management & processing tools"),
    ('debugger', "Debuggers"),
    ('devel', "Development tools"),
    ('geo', "Earth Sciences"),
    ('ide', "Integrated Development Environments (e.g. editors)"),
    ('lang', "Languages and programming aids"),
    ('lib', "General purpose libraries"),
    ('math', "High-level mathematical software"),
    ('mpi', "MPI stacks"),
    ('numlib', "Numerical Libraries"),
    ('perf', "Performance tools"),
    ('phys', "Physics and physical systems simulations"),
    ('system', "System utilities (e.g. highly depending on system OS and hardware)"),
    ('toolchain', "EasyBuild toolchains"),
    ('tools', "General purpose tools"),
    ('vis', "Visualization, plotting, documentation and typesetting"),
]

class ConfigurationVariables(FrozenDictKnownKeys):
    """This is a dict that supports legacy config names transparently."""

    # singleton metaclass: only one instance is created
    __metaclass__ = Singleton

    # list of known/required keys
    REQUIRED = [
        'buildpath',
        'config',
        'installpath',
        'installpath_modules',
        'installpath_software',
        'logfile_format',
        'moduleclasses',
        'module_naming_scheme',
        'module_syntax',
        'modules_tool',
        'prefix',
        'repository',
        'repositorypath',
        'sourcepath',
        'subdir_modules',
        'subdir_software',
        'tmp_logdir',
    ]
    KNOWN_KEYS = REQUIRED  # KNOWN_KEYS must be defined for FrozenDictKnownKeys functionality

    def get_items_check_required(self):
        """
        For all known/required keys, check if exists and return all key/value pairs.
            no_missing: boolean, when True, will throw error message for missing values
        """
        missing = [x for x in self.KNOWN_KEYS if not x in self]
        if len(missing) > 0:
            raise EasyBuildError("Cannot determine value for configuration variables %s. Please specify it.", missing)

        return self.items()

class BuildOptions(FrozenDictKnownKeys):
    """Representation of a set of build options, acts like a dictionary."""

    # singleton metaclass: only one instance is created
    __metaclass__ = Singleton

    KNOWN_KEYS = [k for kss in [BUILD_OPTIONS_CMDLINE, BUILD_OPTIONS_OTHER] for ks in kss.values() for k in ks]

def get_pretend_installpath():
    """Get the installpath when --pretend option is used"""
    return os.path.join(os.path.expanduser('~'), 'easybuildinstall')

def init(options, config_options_dict):
    """
    Gather all variables and check if they're valid
    Variables are read in this order of preference: generaloption > legacy environment > legacy config file
    """
    tmpdict = copy.deepcopy(config_options_dict)

    # make sure source path is a list
    sourcepath = tmpdict['sourcepath']
    if isinstance(sourcepath, basestring):
        tmpdict['sourcepath'] = sourcepath.split(':')
        _log.debug("Converted source path ('%s') to a list of paths: %s" % (sourcepath, tmpdict['sourcepath']))
    elif not isinstance(sourcepath, (tuple, list)):
        raise EasyBuildError("Value for sourcepath has invalid type (%s): %s", type(sourcepath), sourcepath)

    # initialize configuration variables (any future calls to ConfigurationVariables() will yield the same instance
    variables = ConfigurationVariables(tmpdict, ignore_unknown_keys=True)

    _log.debug("Config variables: %s" % variables)

def init_build_options(build_options=None, cmdline_options=None):
    """Initialize build options."""

    active_build_options = {}

    if cmdline_options is not None:
        # building a dependency graph implies force, so that all dependencies are retained
        # and also skips validation of easyconfigs (e.g. checking os dependencies)
        retain_all_deps = False
        if cmdline_options.dep_graph:
            _log.info("Enabling force to generate dependency graph.")
            cmdline_options.force = True
            retain_all_deps = True

        if cmdline_options.dep_graph or cmdline_options.dry_run or cmdline_options.dry_run_short:
            _log.info("Ignoring OS dependencies for --dep-graph/--dry-run")
            cmdline_options.ignore_osdeps = True

        cmdline_build_option_names = [k for ks in BUILD_OPTIONS_CMDLINE.values() for k in ks]
        active_build_options.update(dict([(key, getattr(cmdline_options, key)) for key in cmdline_build_option_names]))
        # other options which can be derived but have no perfectly matching cmdline option
        active_build_options.update({
            'check_osdeps': not cmdline_options.ignore_osdeps,
            'dry_run': cmdline_options.dry_run or cmdline_options.dry_run_short,
            'recursive_mod_unload': cmdline_options.recursive_module_unload,
            'retain_all_deps': retain_all_deps,
            'validate': not cmdline_options.force,
            'valid_module_classes': module_classes(),
        })

    if build_options is not None:
        active_build_options.update(build_options)

    # seed in defaults to make sure all build options are defined, and that build_option() doesn't fail on valid keys
    bo = {}
    for build_options_by_default in [BUILD_OPTIONS_CMDLINE, BUILD_OPTIONS_OTHER]:
        for default in build_options_by_default:
            bo.update(dict([(opt, default) for opt in build_options_by_default[default]]))
    bo.update(active_build_options)

    # BuildOptions is a singleton, so any future calls to BuildOptions will yield the same instance
    return BuildOptions(bo)

def build_option(key):
    """Obtain value specified build option."""
    return BuildOptions()[key]

def build_path():
    """
    Return the build path
    """
    return ConfigurationVariables()['buildpath']

def source_paths():
    """
    Return the list of source paths
    """
    return ConfigurationVariables()['sourcepath']

def source_path():
    """NO LONGER SUPPORTED: use source_paths instead"""
    _log.nosupport("source_path() is replaced by source_paths()", '2.0')

def install_path(typ=None):
    """
    Returns the install path
    - subdir 'software' for actual installation (default)
    - subdir 'modules' for environment modules (typ='mod')
    """
    if typ is None:
        typ = 'software'
    elif typ == 'mod':
        typ = 'modules'

    known_types = ['modules', 'software']
    if typ not in known_types:
        raise EasyBuildError("Unknown type specified in install_path(): %s (known: %s)", typ, ', '.join(known_types))

    variables = ConfigurationVariables()

    key = 'installpath_%s' % typ
    res = variables[key]
    if res is None:
        key = 'subdir_%s' % typ
        res = os.path.join(variables['installpath'], variables[key])
        _log.debug("%s install path as specified by 'installpath' and '%s': %s", typ, key, res)
    else:
        _log.debug("%s install path as specified by '%s': %s", typ, key, res)

    return res

def get_repository():
    """
    Return the repository (git, svn or file)
    """
    return ConfigurationVariables()['repository']

def get_repositorypath():
    """
    Return the repository path
    """
    return ConfigurationVariables()['repositorypath']

def get_modules_tool():
    """
    Return modules tool (EnvironmentModulesC, Lmod, ...)
    """
    # 'modules_tool' key will only be present if EasyBuild config is initialized
    return ConfigurationVariables().get('modules_tool', None)

def get_module_naming_scheme():
    """
    Return module naming scheme (EasyBuildMNS, HierarchicalMNS, ...)
    """
    return ConfigurationVariables()['module_naming_scheme']

def get_module_syntax():
    """
    Return module syntax (Lua, Tcl)
    """
    return ConfigurationVariables()['module_syntax']

def log_file_format(return_directory=False):
    """Return the format for the logfile or the directory"""
    idx = int(not return_directory)
    return ConfigurationVariables()['logfile_format'][idx]

def log_format():
    """
    Return the logfilename format
    """
    # TODO needs renaming, is actually a formatter for the logfilename
    return log_file_format(return_directory=False)

def log_path():
    """
    Return the log path
    """
    return log_file_format(return_directory=True)

def get_build_log_path():
    """
    Return (temporary) directory for build log
    """
    variables = ConfigurationVariables()
    if variables['tmp_logdir'] is not None:
        res = variables['tmp_logdir']
    else:
        res = tempfile.gettempdir()
    return res

def get_log_filename(name, version, add_salt=False):
    """
    Generate a filename to be used for logging
    """
    date = time.strftime("%Y%m%d")
    timeStamp = time.strftime("%H%M%S")

    filename = log_file_format() % {
        'name': name,
        'version': version,
        'date': date,
        'time': timeStamp,
    }

    if add_salt:
        salt = ''.join(random.choice(string.letters) for i in range(5))
        filename_parts = filename.split('.')
        filename = '.'.join(filename_parts[:-1] + [salt, filename_parts[-1]])

    filepath = os.path.join(get_build_log_path(), filename)

    # Append numbers if the log file already exist
    counter = 1
    while os.path.isfile(filepath):
        counter += 1
        filepath = "%s.%d" % (filepath, counter)

    return filepath

def read_only_installdir():
    """
    Return whether installation dir should be fully read-only after installation.
    """
    # FIXME (see issue #123): add a config option to set this, should be True by default (?)
    # this also needs to be checked when --force is used;
    # install dir will have to (temporarily) be made writeable again for owner in that case
    return False

def module_classes():
    """
    Return list of module classes specified in config file.
    """
    return ConfigurationVariables()['moduleclasses']

def read_environment(env_vars, strict=False):
    """NO LONGER SUPPORTED: use read_environment from easybuild.tools.environment instead"""
    _log.nosupport("read_environment has moved to easybuild.tools.environment", '2.0')

def set_tmpdir(tmpdir=None, raise_error=False):
    """Set temporary directory to be used by tempfile and others."""
    try:
        if tmpdir is not None:
            if not os.path.exists(tmpdir):
                os.makedirs(tmpdir)
            current_tmpdir = tempfile.mkdtemp(prefix='eb-', dir=tmpdir)
        else:
            # use tempfile default parent dir
            current_tmpdir = tempfile.mkdtemp(prefix='eb-')
    except OSError, err:
        raise EasyBuildError("Failed to create temporary directory (tmpdir: %s): %s", tmpdir, err)

    _log.info("Temporary directory used in this EasyBuild run: %s" % current_tmpdir)

    for var in ['TMPDIR', 'TEMP', 'TMP']:
        env.setvar(var, current_tmpdir)

    # reset to make sure tempfile picks up new temporary directory to use
    tempfile.tempdir = None

    # test if temporary directory allows to execute files, warn if it doesn't
    try:
        fd, tmptest_file = tempfile.mkstemp()
        os.close(fd)
        os.chmod(tmptest_file, 0700)
        if not run_cmd(tmptest_file, simple=True, log_ok=False, regexp=False):
            msg = "The temporary directory (%s) does not allow to execute files. " % tempfile.gettempdir()
            msg += "This can cause problems in the build process, consider using --tmpdir."
            if raise_error:
                raise EasyBuildError(msg)
            else:
                _log.warning(msg)
        else:
            _log.debug("Temporary directory %s allows to execute files, good!" % tempfile.gettempdir())
        os.remove(tmptest_file)

    except OSError, err:
        raise EasyBuildError("Failed to test whether temporary directory allows to execute files: %s", err)

    return current_tmpdir


text:
Authentication
==============

> Note: This section is under development.

Authentication is the act of verifying who a user is, and is the basis of the login process. Typically, authentication uses the combination of an identifier--a username or email address--and a password. The user submits these values  through a form, and the application then compares the submitted information against that previously stored (e.g., upon registration).

In Yii, this entire process is performed semi-automatically, leaving the developer to merely implement [[yii\web\IdentityInterface]], the most important class in the authentication system. Typically, implementation of `IdentityInterface` is accomplished using the `User` model.

You can find a fully featured example of authentication in the
[advanced application template](tutorial-advanced-app.md). Below, only the interface methods are listed:

```php
class User extends ActiveRecord implements IdentityInterface
{
    // ...

    /**
     * Finds an identity by the given ID.
     *
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface|null the identity object that matches the given ID.
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * Finds an identity by the given token.
     *
     * @param string $token the token to be looked for
     * @return IdentityInterface|null the identity object that matches the given token.
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    /**
     * @return int|string current user ID
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string current user auth key
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @param string $authKey
     * @return boolean if auth key is valid for current user
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }
}
```

Two of the outlined methods are simple: `findIdentity` is provided with an  ID value and returns a model instance
associated with that ID. The `getId` method returns the ID itself. Two of the other methods – `getAuthKey` and
`validateAuthKey` – are used to provide extra security to the "remember me" cookie. The `getAuthKey` method should
return a string that is unique for each user. You can reliably create a unique string using
`Yii::$app->getSecurity()->generateRandomString()`. It's a good idea to also save this as part of the user's record:

```php
public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {
        if ($this->isNewRecord) {
            $this->auth_key = Yii::$app->getSecurity()->generateRandomString();
        }
        return true;
    }
    return false;
}
```

The `validateAuthKey` method just needs to compare the `$authKey` variable, passed as parameter (itself retrieved from a cookie), with the value fetched from database.


text:
const IndexView = Marionette.CompositeView.extend({
    template: 'index',
    initialize(options) {
        this.views = options.di.views;
        this.regionManager = new options.di.regionManager();
        this.playerDataProvider = options.di.playerDataProvider;
    },
    onRender() {
        this.createRegions();
        this.renderViews();
        console.log(this.playerDataProvider());
    },
    createRegions() {
        this.regionManager.addRegion('content', '.js-content');
    },
    renderViews() {
        for (const view in this.views) {
            const region = this.regionManager.get(view);
            if (region) {
                region.show(this.views[view]);
            }
        }
    }
});

export default IndexView;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="header_bg">#349B30</color>
    <color name="white">#fff</color>
</resources>


text:
from __future__ import division

from file_archive.parser import parse_expression

from vistrails.core.modules.basic_modules import Constant, Integer, String
from vistrails.core.modules.config import IPort, OPort
from vistrails.core.modules.vistrails_module import Module, ModuleError

def find_subclass(cls, subname):
    """Find a subclass by name.
    """
    l = [cls]
    while l:
        l2 = []
        for c in l:
            if c.__name__ == subname:
                return c
            l2 += c.__subclasses__()
        l = l2
    return None

class QueryCondition(Constant):
    """Base class for query conditions.

    This is abstract and implemented by modules Query*
    """
    _input_ports = [
            IPort('key', String)]

    @staticmethod
    def translate_to_python(c, top_class=None, text_query=True):
        try:
            i = c.index('(')
        except ValueError:
            if text_query:
                return TextQuery(c)
            raise ValueError("Invalid QueryCondition syntax")
        clsname = c[:i]
        cls = find_subclass(top_class or QueryCondition, clsname)
        if cls is not None:
            return cls(*eval(c[i+1:-1]))
        elif text_query:
            return TextQuery(c)
        else:
            raise ValueError("No such condition type: %s" % clsname)

    @staticmethod
    def translate_to_string(cond):
        return str(cond)

    @staticmethod
    def validate(cond):
        return isinstance(cond, QueryCondition)

    def __str__(self):
        raise NotImplementedError

    def __repr__(self):
        return self.__str__()

QueryCondition._output_ports = [
        OPort('value', QueryCondition)]

class TextQuery(QueryCondition):
    """A query from a text expression.
    """
    def __init__(self, text):
        self.query = text
        self.conditions = parse_expression(text)

    def __str__(self):
        return self.query

class Metadata(QueryCondition):
    """Base class for metadata pairs.

    This is abstract and implemented by modules Equal*

    This both provides a metadata pair, as the 'metadata' attribute, for
    inserting, and conditions, through the 'conditions' attribute.
    """
    _input_ports = [
            IPort('key', String),
            IPort('value', Module)]

    def __init__(self, *args):
        super(Metadata, self).__init__()

        if args:
            self.key, self.value = args
            self.set_results()
        else:
            self.key, self.value = None, None

    @staticmethod
    def translate_to_python(c):
        return QueryCondition.translate_to_python(
                c,
                top_class=Metadata, text_query=False)

    def compute(self):
        self.key = self.get_input('key')
        self.value = self.get_input('value')

        self.set_results()

    def set_results(self):
        self.conditions = {self.key: {'type': self._type, 'equal': self.value}}
        self.metadata = (self.key, self.value)
        self.set_output('value', self)

    def __str__(self):
        return '%s(%r, %r)' % (self.__class__.__name__, self.key, self.value)

    @staticmethod
    def get_widget_class():
        from .widgets import MetadataConstantWidget
        return MetadataConstantWidget

Metadata._output_ports = [
        OPort('value', Metadata)]

class EqualString(Metadata):
    """A string metadata.

    A piece of metadata with a value of type string. When used in a query,
    means "key has a value of type string equal to <value>".
    """
    _input_ports = [
            IPort('key', String),
            IPort('value', String)]

    _type = 'str'

class EqualInt(Metadata):
    """An integer metadata.

    A piece of metadata with a value of type integer. When used in a query,
    means "key has a value of type integer equal to <value>".
    """
    _input_ports = [
            IPort('key', String),
            IPort('value', Integer)]

    _type = 'int'

    def __init__(self, *args):
        if args:
            key, value = args
            assert isinstance(value, (int, long))
        Metadata.__init__(self, *args)

class IntInRange(QueryCondition):
    """An integer range condition.

    Means "key has a value of type integer which lies between <lower_bound> and
    <higher_bound>".

    Note that you can omit one of the bounds.
    """
    _input_ports = [
            IPort('key', String),
            IPort('lower_bound', Integer, optional=True),
            IPort('higher_bound', Integer, optional=True)]

    def __init__(self, *args):
        super(IntInRange, self).__init__()

        if args:
            self.key, self.low, self.high = args
            assert isinstance(self.low, (int, long))
            assert isinstance(self.high, (int, long))
            self.set_results()
        else:
            self.key, self.low, self.high = None, None, None

    def compute(self):
        self.key = self.get_input('key')
        if self.has_input('lower_bound'):
            self.low = self.get_input('lower_bound')
        if self.has_input('higher_bound'):
            self.high = self.get_input('higher_bound')
        if not (self.low is not None or self.high is not None):
            raise ModuleError(self, "No bound set")
        self.set_results()

    def set_results(self):
        dct = {}
        if self.low is not None:
            dct['gt'] = self.low
        if self.high is not None:
            dct['lt'] = self.high
        dct['type'] = 'int'

        self.conditions = {self.key: dct}
        self.set_output('value', self)

    def __str__(self):
        return '%s(%r, %r, %r)' % ('IntInRange', self.key, self.low, self.high)


text:
<?php

namespace Phwoolcon\Exception;

use LogicException;

class SessionException extends LogicException
{
}


text:
package rpcd

import (
	"github.com/Symantec/Dominator/lib/errors"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/hypervisor"
)

func (t *srpcType) ChangeVmDestroyProtection(conn *srpc.Conn,
	request hypervisor.ChangeVmDestroyProtectionRequest,
	reply *hypervisor.ChangeVmDestroyProtectionResponse) error {
	*reply = hypervisor.ChangeVmDestroyProtectionResponse{
		errors.ErrorToString(
			t.manager.ChangeVmDestroyProtection(request.IpAddress,
				conn.GetAuthInformation(),
				request.DestroyProtection))}
	return nil
}


text:
package com.hazelcast.query;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.MapEntry;
import com.hazelcast.impl.CMap;
import com.hazelcast.util.Clock;
import com.hazelcast.impl.Record;
import com.hazelcast.impl.TestUtil;
import org.junit.*;
import org.junit.runner.RunWith;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static org.junit.Assert.*;

@RunWith(com.hazelcast.util.RandomBlockJUnit4ClassRunner.class)
public class MapIndexServiceTest extends TestUtil {

    @BeforeClass
    @AfterClass
    public static void init() throws Exception {
        Hazelcast.shutdownAll();
    }

    @After
    @Before
    public void cleanup() throws Exception {
        Hazelcast.shutdownAll();
    }

    @Test
    public void testAndWithSingleEntry() throws Exception {
        CMap cmap = mockCMap("default");
        MapIndexService mapIndexService = new MapIndexService(false);
        Map<Expression, Index> indexes = mapIndexService.getIndexes();
        assertFalse(mapIndexService.hasIndexedAttributes());
        Expression nameExpression = Predicates.get("name");
        Expression ageExpression = Predicates.get("age");
        Expression salaryExpression = Predicates.get("salary");
        mapIndexService.addIndex(nameExpression, false, 0);
        mapIndexService.addIndex(ageExpression, true, 1);
        mapIndexService.addIndex(salaryExpression, false, 2);
        assertTrue(indexes.containsKey(nameExpression));
        assertTrue(indexes.containsKey(ageExpression));
        assertTrue(indexes.containsKey(salaryExpression));
//        assertEquals(2, indexes.size());
        assertTrue(mapIndexService.hasIndexedAttributes());
        for (int i = 0; i < 20000; i++) {
            Employee employee = new Employee(i + "Name", i % 80, (i % 2 == 0), 100 + (i % 1000));
            Record record = newRecord(cmap, i, "key" + i, employee);
            record.setIndexes(mapIndexService.getIndexValues(employee), mapIndexService.getIndexTypes());
            mapIndexService.index(record);
        }
        int count = 1000;
        Set<String> ages = new HashSet<String>(count);
        for (int i = 0; i < count; i++) {
            ages.add(String.valueOf(i));
        }
        final EntryObject entryObject = new PredicateBuilder().getEntryObject();
        final PredicateBuilder predicate = entryObject.get("name").equal("140Name").and(entryObject.get("age").in(ages.toArray(new String[0])));
        long total = Runtime.getRuntime().totalMemory();
        long free = Runtime.getRuntime().freeMemory();
        System.out.println("Used Memory:" + ((total - free) / 1024 / 1024));
        for (int i = 0; i < 10000; i++) {
            long start = Clock.currentTimeMillis();
            QueryContext queryContext = new QueryContext("default", predicate, mapIndexService);
            Set<MapEntry> results = mapIndexService.doQuery(queryContext);
//            System.out.println("result size " + results.size() + " took " + (Clock.currentTimeMillis() - start));
            assertEquals(1, results.size());
        }
        cmap.getNode().connectionManager.shutdown();
    }

    @Test
    public void testIndex() throws Exception {
        CMap cmap = mockCMap("default");
        MapIndexService mapIndexService = new MapIndexService(false);
        Map<Expression, Index> indexes = mapIndexService.getIndexes();
        assertFalse(mapIndexService.hasIndexedAttributes());
        Expression nameExpression = Predicates.get("name");
        Expression ageExpression = Predicates.get("age");
        Expression salaryExpression = Predicates.get("salary");
        mapIndexService.addIndex(nameExpression, false, 0);
        mapIndexService.addIndex(ageExpression, true, 1);
        mapIndexService.addIndex(salaryExpression, false, 2);
        assertTrue(indexes.containsKey(nameExpression));
        assertTrue(indexes.containsKey(ageExpression));
        assertTrue(indexes.containsKey(salaryExpression));
//        assertEquals(2, indexes.size());
        assertTrue(mapIndexService.hasIndexedAttributes());
        for (int i = 0; i < 20000; i++) {
            Employee employee = new Employee(i + "Name", i % 80, (i % 2 == 0), 100 + (i % 1000));
            Record record = newRecord(cmap, i, "key" + i, employee);
            record.setIndexes(mapIndexService.getIndexValues(employee), mapIndexService.getIndexTypes());
            mapIndexService.index(record);
        }
        long total = Runtime.getRuntime().totalMemory();
        long free = Runtime.getRuntime().freeMemory();
        System.out.println("Used Memory:" + ((total - free) / 1024 / 1024));
        for (int i = 0; i < 10000; i++) {
            long start = Clock.currentTimeMillis();
            QueryContext queryContext = new QueryContext("default", new SqlPredicate("salary=161 and age >20 and age <23"), mapIndexService);
            Set<MapEntry> results = mapIndexService.doQuery(queryContext);
//            for (MapEntry result : results) {
//                System.out.println(((Record)result).getRecordEntry().getValue());
//            }
//            System.out.println("result size " + results.size() + " took " + (Clock.currentTimeMillis() - start));
            assertEquals(10, results.size());
        }
        cmap.getNode().connectionManager.shutdown();
    }
}


text:
package com.jzh.service;

import com.jzh.dto.Result;
import com.jzh.model.Customer;

import java.util.List;

/**
 * @author Junhao Zhou 2016/11/25
 * @version 1.0
 */
public interface CustomerService extends GenericService<Customer, Long> {

    @Override
    List<Customer> listAll();

    @Override
    Customer get(final Long id);

    @Override
    int insert(Customer entity);

    @Override
    int update(Customer entity);

    @Override
    int delete(final Long id);

    /**
     * 普通登录
     *
     * @param phone      用户手机号
     * @param password   密码
     * @param rememberMe 是否"记住我"
     * @return 登录结果
     */
    Result login(String phone, char[] password, boolean rememberMe);

    /**
     * 登出
     *
     * @return 登出结果
     */
    Result logout();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:text="原图:" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:text="提取主色彩之后" />

    <ImageView
        android:id="@+id/result0"
        android:layout_marginTop="10dp"
        android:layout_width="50dp"
        android:layout_height="10dp" />

    <ImageView
        android:id="@+id/result1"
        android:layout_marginTop="10dp"
        android:layout_width="50dp"
        android:layout_height="10dp" />

    <ImageView
        android:id="@+id/result2"
        android:layout_marginTop="10dp"
        android:layout_width="50dp"
        android:layout_height="10dp" />

    <ImageView
        android:id="@+id/result3"
        android:layout_marginTop="10dp"
        android:layout_width="50dp"
        android:layout_height="10dp" />

    <ImageView
        android:id="@+id/result4"
        android:layout_marginTop="10dp"
        android:layout_width="50dp"
        android:layout_height="10dp" />
</LinearLayout>


text:
typedef enum {
    STAGender_Undefined = 0,
    STAGender_Female = 1,
    STAGender_Male=2
} STAGender;

// STAAdPreferences holds params specific to an ad
@interface STASDKPreferences : NSObject
@property (nonatomic,assign) NSUInteger age;
@property (nonatomic,strong) NSString* ageStr;

@property (nonatomic, assign) STAGender gender;

+ (instancetype)prefrencesWithAge:(NSUInteger)age andGender:(STAGender)gender;
+ (instancetype)prefrencesWithAgeStr:(NSString *)ageStr andGender:(STAGender)gender;

@end

@interface STAStartAppSDK : NSObject

+ (STAStartAppSDK*) sharedInstance;
- (void) SDKInitialize:(NSString*)devID andAppID:(NSString*) appID;

@property (nonatomic, strong) NSString* appID;
@property (nonatomic, strong) NSString* devID;
@property (nonatomic, strong) NSString* accountID;
@property (nonatomic, strong) STASDKPreferences* preferences;

// Disable Return Ad
- (void)disableReturnAd;

// Initialize Splash Ad
- (void)showSplashAd;
- (void)showSplashAdWithDelegate:(id<STADelegateProtocol>)delegate;
- (void)showSplashAdWithPreferences:(STASplashPreferences *)splashPreferences;
- (void)showSplashAdWithDelegate:(id<STADelegateProtocol>)delegate withPreferences:(STASplashPreferences *)splashPreferences;
- (void)showSplashAdWithDelegate:(id<STADelegateProtocol>)delegate withAdPreferences:(STAAdPreferences*) adPrefs withPreferences:(STASplashPreferences *)splashPreferences;
- (void)showSplashAdWithDelegate:(id<STADelegateProtocol>)delegate withAdPreferences:(STAAdPreferences*) adPrefs withPreferences:(STASplashPreferences *)splashPreferences withAdTag:(NSString*)adTag;

-(void)inAppPurchaseMade;
-(void)inAppPurchaseMadeWithAmount:(float)amount;
-(void)startNewSession;

//Unity methods
- (void)unitySDKInitialize;
- (void)unityAppWillEnterForeground;
- (void)unityAppDidEnterBackground;
- (void)setUnitySupportedOrientations:(int)supportedOrientations;
- (void)setUnityAutoRotation:(int)autoRotation;
- (void)setUnityVersion:(NSString *)unityVersion;

@property (readonly)  NSString* version;
@property (readonly)  long buildNumber;

@property (nonatomic)BOOL isUnityEnvironment;
@property (nonatomic)BOOL isCoronaEnvironment;
@property (nonatomic)BOOL isCocos2DXEnvironment;
@property (nonatomic)BOOL isAdMobMediationEnvironment;
@property (nonatomic)BOOL isMoPubMediationEnvironment;
@property (nonatomic)BOOL isSwiftEnvironment;

@end


text:
'use strict';

const SubDevice = require('./subdevice');

const PowerChannels = require('../capabilities/power-channels');

/**
 * Wall plug. Can be turned on or off.
 */
class Plug extends SubDevice {
	constructor(parent, info) {
		super(parent, info);

		this.type = 'power-plug';
		this.model = 'lumi.plug';

		this.defineProperty('status', {
			name: 'powerChannel0',
			mapper: v => v == 'on'
		});
		PowerChannels.extend(this, {
			channels: [ 0 ],
			set: (channel, power) => this.call('toggle_plug', [ 'neutral_' + channel, power ? 'on' : 'off' ])
		});

		this.defineProperty('load_voltage', {
			name: 'loadVoltage',
			mapper: parseInt
		});
		this.defineProperty('load_power', {
			name: 'loadPower',
			mapper: parseInt
		});
		this.defineProperty('power_consumed', {
			name: 'powerConsumed',
			mapper: parseFloat
		});

		this.capabilities.push('power-load');
		this.capabilities.push('power-usage');
	}

	get loadVoltage() {
		return this.property('loadVoltage');
	}

	get loadPower() {
		return this.property('loadPower');
	}

	get powerConsumed() {
		return this.property('powerConsumed');
	}
}

module.exports = Plug;


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

<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<parent>
		<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
		<artifactId>iot-base-plugin-feature</artifactId>
		<version>2.2.5-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<modelVersion>4.0.0</modelVersion>
	<artifactId>org.wso2.carbon.device.mgt.iot.feature</artifactId>
	<packaging>pom</packaging>
	<version>2.2.5-SNAPSHOT</version>
	<name>WSO2 Carbon - IoT Device Management Feature</name>
	<url>http://wso2.org</url>
	<description>This feature contains the core bundles required for IoT Server</description>

	<dependencies>
		<dependency>
			<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
			<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
		</dependency>
		<dependency>
			<groupId>org.json.wso2</groupId>
			<artifactId>json</artifactId>
		</dependency>
		<!--Dependencies on XMPP Client Library-->
		<dependency>
			<groupId>org.igniterealtime.smack.wso2</groupId>
			<artifactId>smack</artifactId>
		</dependency>
		<dependency>
			<groupId>org.igniterealtime.smack.wso2</groupId>
			<artifactId>smackx</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-resources-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-resources</id>
						<phase>generate-resources</phase>
						<goals>
							<goal>copy-resources</goal>
						</goals>
						<configuration>
							<outputDirectory>src/main/resources</outputDirectory>
							<resources>
								<resource>
									<directory>resources</directory>
									<includes>
										<include>build.properties</include>
										<include>p2.inf</include>
									</includes>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
                    <execution>
                        <id>unpack</id>
                        <phase>package</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
                                    <artifactId>org.wso2.carbon.device.mgt.iot.ui
                                    </artifactId>
                                    <version>${project.version}</version>
                                    <type>zip</type>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>
                                        ${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
                                    </outputDirectory>
                                    <includes>**/*</includes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.wso2.maven</groupId>
				<artifactId>carbon-p2-plugin</artifactId>
				<version>${carbon.p2.plugin.version}</version>
				<executions>
					<execution>
						<id>p2-feature-generation</id>
						<phase>package</phase>
						<goals>
							<goal>p2-feature-gen</goal>
						</goals>
						<configuration>
							<id>org.wso2.carbon.device.mgt.iot</id>
							<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
							<adviceFile>
								<properties>
									<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
									<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
								</properties>
							</adviceFile>
							<bundles>
								<bundleDef>
									org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot:${carbon.devicemgt.plugins.version}
								</bundleDef>
								<bundleDef>
									org.json.wso2:json:${commons-json.version}
								</bundleDef>
							</bundles>
							<importFeatures>
								<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
								</importFeatureDef>
								<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.devicemgt.version}
								</importFeatureDef>
							</importFeatures>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
package com.qualogy.qafe.gwt.client.component;

import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasAllFocusHandlers;
import com.google.gwt.event.dom.client.HasAllKeyHandlers;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.ui.Focusable;
import com.google.gwt.user.client.ui.HasName;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * This class is a SimplePanel, but implements all the interfaces of the
 * TextBox class,so that it can be used a special kind of textbox.
 * @author rjankie
 *
 */
public class LabeledPasswordFieldWidget extends SimplePanel implements TitledComponent,HasPrompt, EventListener, Focusable, HasName, HasText, HasEditable, HasValueChangeHandlers, HasClickHandlers, HasAllFocusHandlers, HasAllKeyHandlers {

	private Label label = new Label();
	private QPasswordTextBox textbox ;
	private final static String ORIENTATION_UPDOWN="updown";
	private final static String ORIENTATION_LEFTRIGHT="leftright";

	public LabeledPasswordFieldWidget(String labelText, String orientation){
		textbox = new QPasswordTextBox();
		label.setText(labelText);
		label.setStylePrimaryName("label");
		if (ORIENTATION_LEFTRIGHT.equals(orientation)) {
			HorizontalPanel horizontalPanel = new HorizontalPanel();
			horizontalPanel.add(label);
			horizontalPanel.add(textbox);
			add(horizontalPanel);
		} else if (ORIENTATION_UPDOWN.equals(orientation)) {
			VerticalPanel verticalPanel = new VerticalPanel();
			verticalPanel.add(label);
			verticalPanel.add(textbox);
			add(verticalPanel);
		}
	}

	public String getText() {
		return textbox.getText();
	}

	public void setText(String text) {
		textbox.setText(text);
	}

	public Label getLabel() {
		return label;
	}

	public void setLabel(Label label) {
		this.label = label;
	}

	public int getTabIndex() {
		return textbox.getTabIndex();
	}

	public void setTabIndex(int arg0) {
		textbox.setTabIndex(arg0);
	}

	public void setAccessKey(char arg0) {
		textbox.setAccessKey(arg0);
	}

	public void setFocus(boolean arg0) {
		textbox.setFocus(arg0);
	}

	public String getName() {
		return textbox.getName();
	}

	public void setName(String arg0) {
		textbox.setName(arg0);
	}

	public boolean isEditable() {
		if (textbox instanceof HasEditable) {
			HasEditable hasEditable = (HasEditable)textbox;
			return hasEditable.isEditable();
		}
		return false;
	}

	public void setEditable(boolean editable) {
		if (textbox instanceof HasEditable) {
			HasEditable hasEditable = (HasEditable)textbox;
			hasEditable.setEditable(editable);
		}
	}

	public String getPrompt() {
		return label.getText();
	}

	public void setPrompt(String prompt) {
		label.setText(prompt);
	}

	public UIObject getDataComponent() {
		return textbox;
	}

	public UIObject getTitleComponent() {
		return label;
	}

	public HandlerRegistration addClickHandler(ClickHandler handler) {
		return textbox.addClickHandler(handler);
	}

	public HandlerRegistration addValueChangeHandler(ValueChangeHandler handler) {
		return textbox.addValueChangeHandler(handler);
	}

	public HandlerRegistration addFocusHandler(FocusHandler handler) {
		return textbox.addFocusHandler(handler);
	}

	public HandlerRegistration addBlurHandler(BlurHandler handler) {
		return textbox.addBlurHandler(handler);
	}

	public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) {
		return textbox.addKeyUpHandler(handler);
	}

	public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) {
		return textbox.addKeyDownHandler(handler);
	}

	public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) {
		return textbox.addKeyPressHandler(handler);
	}

	@Override
	public void addStyleName(String style) {
		getDataComponent().setStyleName(getDataComponent().getElement(), style, true);
	}

	@Override
	public void removeStyleName(String style) {
		getDataComponent().setStyleName(getDataComponent().getElement(), style, false);
	}

	@Override
	public void setStylePrimaryName(String style) {
		getDataComponent().setStylePrimaryName(getDataComponent().getElement(), style);
	}
}


text:
from shellwrapper import BaseShellCommand

class OptiPNGShellCommand(BaseShellCommand):
    """
    Command to optimize PNG files. Files will be optimized in place.
    """

    def __init__(self, files=None, file=None, optimization_level=2, logger=None):
        if files is None and file is None:
            raise ValueError("Either files or file must be specified")

        if files is not None and file is not None:
            raise ValueError("Can only specify either file or files")

        if files is None:
            self.files = [file]
        else:
            self.files = files

        self.optimization_level = optimization_level

        super(OptiPNGShellCommand, self).__init__(["optipng"], logger)

    def execute(self):
        """
        Execute the command.
        """
        args = [
            "-o", self.optimization_level]

        args = args + self.files

        return self._execute_command(args)


text: /*memoryleakfix*/


text:
<?xml version="1.0"?>

<actor>

		<Properties>
			<Name>APU Battery Switch Placer</Name>
			<Position x="3.022" y="0.97" z="5.833" />
			<Rotation x="0.0" y="0.0" z="0.0" />
			<Scale x="1" y="1" z="1" />
		</Properties>

		<RenderComponent castshadow="true" >
			<Mesh file="basic_switch_placer.dae">
				<DiffuseTexture name="batt_switch_placer" file="toggle_switch.jpg" />
				<NormalTexture name="batt_switch_placer_normal" file="default_normal.jpg" />
			</Mesh>
		</RenderComponent>

		<PhysicsComponent active="true">
			<material static="0.5" dynamic="0.5" restitution="0.1" />
			<mesh from="file" file="basic_switch_placer.dae" />

			<actorType>STATIC</actorType>
			<meshType>TRIANGLE</meshType>
		</PhysicsComponent>

		<actor>

			<Properties>
				<Name>APU Battery Switch Actual</Name>
				<Position x="0" y="0" z="0" />
				<Rotation x="25.0" y="0.0" z="0.0" />
				<Scale x="1" y="1" z="1" />
			</Properties>

			<RenderComponent castshadow="true" >
				<Mesh file="basic_switch.dae">
					<DiffuseTexture name="batt_switch_placer" file="toggle_switch_actual.jpg" />
					<NormalTexture name="batt_switch_placer_normal" file="toggle_switch_actual_normal.jpg" />
				</Mesh>
			</RenderComponent>

			<PhysicsComponent active="true">
				<material static="0.5" dynamic="0.5" restitution="0.1" />
				<mesh from="file" file="basic_switch.dae" />

				<actorType>STATIC</actorType>
				<meshType>TRIANGLE</meshType>
			</PhysicsComponent>

		</actor>

	</actor>