text:
package org.elasticsearch;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.rest.HasRestHeaders;
import org.elasticsearch.rest.RestStatus;

import java.util.List;
import java.util.Map;

/**
 * A base class for all elasticsearch exceptions.
 */
public class ElasticsearchException extends RuntimeException {

    /**
     * Construct a ElasticsearchException with the specified detail message.
     *
     * @param msg the detail message
     */
    public ElasticsearchException(String msg) {
        super(msg);
    }

    /**
     * Construct a ElasticsearchException with the specified detail message
     * and nested exception.
     *
     * @param msg   the detail message
     * @param cause the nested exception
     */
    public ElasticsearchException(String msg, Throwable cause) {
        super(msg, cause);
    }

    /**
     * Returns the rest status code associated with this exception.
     */
    public RestStatus status() {
        Throwable cause = unwrapCause();
        if (cause == this) {
            return RestStatus.INTERNAL_SERVER_ERROR;
        } else if (cause instanceof ElasticsearchException) {
            return ((ElasticsearchException) cause).status();
        } else if (cause instanceof IllegalArgumentException) {
            return RestStatus.BAD_REQUEST;
        } else {
            return RestStatus.INTERNAL_SERVER_ERROR;
        }
    }

    /**
     * Unwraps the actual cause from the exception for cases when the exception is a
     * {@link ElasticsearchWrapperException}.
     *
     * @see org.elasticsearch.ExceptionsHelper#unwrapCause(Throwable)
     */
    public Throwable unwrapCause() {
        return ExceptionsHelper.unwrapCause(this);
    }

    /**
     * Return the detail message, including the message from the nested exception
     * if there is one.
     */
    public String getDetailedMessage() {
        if (getCause() != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(toString()).append("; ");
            if (getCause() instanceof ElasticsearchException) {
                sb.append(((ElasticsearchException) getCause()).getDetailedMessage());
            } else {
                sb.append(getCause());
            }
            return sb.toString();
        } else {
            return super.toString();
        }
    }

    /**
     * Retrieve the innermost cause of this exception, if none, returns the current exception.
     */
    public Throwable getRootCause() {
        Throwable rootCause = this;
        Throwable cause = getCause();
        while (cause != null && cause != rootCause) {
            rootCause = cause;
            cause = cause.getCause();
        }
        return rootCause;
    }

    /**
     * Retrieve the most specific cause of this exception, that is,
     * either the innermost cause (root cause) or this exception itself.
     *
Differs from {@link #getRootCause()} in that it falls back
     * to the present exception if there is no root cause.
     *
     * @return the most specific cause (never null)
     */
    public Throwable getMostSpecificCause() {
        Throwable rootCause = getRootCause();
        return (rootCause != null ? rootCause : this);
    }

    /**
     * Check whether this exception contains an exception of the given type:
     * either it is of the given class itself or it contains a nested cause
     * of the given type.
     *
     * @param exType the exception type to look for
     * @return whether there is a nested exception of the specified type
     */
    public boolean contains(Class exType) {
        if (exType == null) {
            return false;
        }
        if (exType.isInstance(this)) {
            return true;
        }
        Throwable cause = getCause();
        if (cause == this) {
            return false;
        }
        if (cause instanceof ElasticsearchException) {
            return ((ElasticsearchException) cause).contains(exType);
        } else {
            while (cause != null) {
                if (exType.isInstance(cause)) {
                    return true;
                }
                if (cause.getCause() == cause) {
                    break;
                }
                cause = cause.getCause();
            }
            return false;
        }
    }

    /**
     * A base class for exceptions that should carry rest headers
     */
    @SuppressWarnings("unchecked")
    public static class WithRestHeaders extends ElasticsearchException implements HasRestHeaders {

        private final ImmutableMap<String, List<String>> headers;

        public WithRestHeaders(String msg, Tuple<String, String[]>... headers) {
            super(msg);
            this.headers = headers(headers);
        }

        public WithRestHeaders(String msg, @Nullable ImmutableMap<String, List<String>> headers) {
            super(msg);
            this.headers = headers != null ? headers : ImmutableMap.<String, List<String>>of();
        }

        public WithRestHeaders(String msg, Throwable cause, Tuple<String, String[]>... headers) {
            super(msg, cause);
            this.headers = headers(headers);
        }

        public WithRestHeaders(String msg, Throwable cause, @Nullable ImmutableMap<String, List<String>> headers) {
            super(msg, cause);
            this.headers = headers != null ? headers : ImmutableMap.<String, List<String>>of();
        }

        public ImmutableMap<String, List<String>> getHeaders() {
            return headers;
        }

        protected static Tuple<String, String[]> header(String name, String... values) {
            return Tuple.tuple(name, values);
        }

        private static ImmutableMap<String, List<String>> headers(Tuple<String, String[]>... headers) {
            Map<String, List<String>> map = Maps.newHashMap();
            for (Tuple<String, String[]> header : headers) {
                List<String> list = map.get(header.v1());
                if (list == null) {
                    list = Lists.newArrayList(header.v2());
                    map.put(header.v1(), list);
                } else {
                    for (String value : header.v2()) {
                        list.add(value);
                    }
                }
            }
            return ImmutableMap.copyOf(map);
        }
    }
}


text:
module Potatochop
  class FileSystemInterface
    attr_reader :source

    def initialize(source, options = {})
      @source = source
    end

    def exists?(file_name)
      file_path = File.join(@source, file_name)
      File.exists? file_path
    end

    def read(file_name)
      file_path = File.join(@source, file_name)
      File.read(file_path)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php
//
// Copyright (c) 2020-2022 Grigore Stefan <g_stefan@yahoo.com>
// Created by Grigore Stefan <g_stefan@yahoo.com>
//
// MIT License (MIT) <http://opensource.org/licenses/MIT>
//

defined("XYO_CLOUD") or die("Access is denied");

$this->generateComponent("xui.form-action-begin");

echo "
";
$this->generateComponent("xui.form-submit-button-group",array("group"=>array(
	"back"=>"disabled",
	"try"=>"disabled",
	"next"=>"primary"
)));
echo "
";
echo "

";
echo "
";

if ($this->isError()) {
	$this->generateView("msg-error");
}

$this->generateViewLanguage("form-settings");

$this->eFormRequest(array(
	"back" => "install",
	"this" => "settings",
	"next" => "settings-step",
	"website_language" => $this->getSystemLanguage(),
	"select" => "settings"
));

$this->generateComponent("xui.form-action-end");


text:
/**
#******************************************************************************
#
# PACS online system
# ---------------------------------------------------------
# Parameterless automatic classification system.
#
#******************************************************************************
*/
package edu.gmu.csiss.automation.pacs.servlet;

import java.util.*;
import java.io.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;

/**
 * The servlet for uploading a file
 * @author Ziheng Sun
 */
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/FileUploadServlet"})
public class FileUploadServlet extends HttpServlet {
    private String relativePath;
    private String filePath;
    private String tempPath;
    private String prefix_url;
    private String callback;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        relativePath = config.getInitParameter("filepath");
        tempPath = config.getInitParameter("temppath");

        javax.servlet.ServletContext context = getServletContext();

        filePath = context.getRealPath(relativePath);
        tempPath = context.getRealPath(tempPath);
    }

    /**
     * Processes requests for both HTTP
     * GET and
     * POST methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/plain;charset=gbk");

        res.setContentType("text/html; charset=utf-8");
        PrintWriter pw = res.getWriter();
        try{
            //initialize the prefix url
            if(prefix_url==null){
//                String hostname = req.getServerName ();
//                int port = req.getServerPort ();
//                prefix_url = "http://"+hostname+":"+port+"/igfds/"+relativePath+"/";
            	//updated by Ziheng - on 8/27/2015
            	//This method should be used everywhere.
                int num = req.getRequestURI().indexOf("/PACS");
                String prefix = req.getRequestURI().substring(0, num+"/PACS".length()); //in case there is something before PACS
                prefix_url = req.getScheme() + "://" +
                        req.getServerName() +
                        ("http".equals(req.getScheme()) && req.getServerPort() == 80 || "https".equals(req.getScheme()) && req.getServerPort() == 443 ? "" : ":" + req.getServerPort() ) +
                        prefix+"/"+relativePath+"/";
            }
            pw.println("<!DOCTYPE html>");
            pw.println("");
            String head = "" +
        "<title>File Uploading Response</title>" +
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
        ""+
        "";
            pw.println(head);
            pw.println("");

            DiskFileItemFactory diskFactory = new DiskFileItemFactory();
            // threshold  2M
            //extend to 2M - updated by ziheng - 9/25/2014
            diskFactory.setSizeThreshold(2 * 1024);
            // repository
            diskFactory.setRepository(new File(tempPath));

            ServletFileUpload upload = new ServletFileUpload(diskFactory);
            // 2M
            upload.setSizeMax(2 * 1024 * 1024);
            // HTTP
            List fileItems = upload.parseRequest(req);
            Iterator iter = fileItems.iterator();
            while(iter.hasNext())
            {
                FileItem item = (FileItem)iter.next();
                if(item.isFormField())
                {
                    processFormField(item, pw);
                }else{
                    processUploadFile(item, pw);
                }
            }// end while()
            //add some buttons for further process
            pw.println("<input type=\"button\" id=\"bt\" value=\"load\" onclick=\"load();\">");
            pw.println("<input type=\"button\" id=\"close\" value=\"close window\" onclick=\"window.close();\">");
            pw.println("");
            pw.println("");
        }catch(Exception e){
            e.printStackTrace();
            pw.println("ERR:"+e.getClass().getName()+":"+e.getLocalizedMessage());
        }finally{
            pw.flush();
            pw.close();
        }
    }
    /**
     * Information of the fields except file fields
     * @param item
     * @param pw
     * @throws Exception
     */
    private void processFormField(FileItem item, PrintWriter pw)
        throws Exception
    {
        String name = item.getFieldName();
        String value = item.getString();
        System.out.println(name + " : " + value + "\r\n");
        if(name.equals("script")){
            pw.println("");
        }
//        pw.println(name + " : " + value + "\r\n");
    }

    private void processUploadFile(FileItem item, PrintWriter pw)
        throws Exception
    {
        String filename = item.getName();
        System.out.println( filename);
        int index = filename.lastIndexOf("\\");
        filename = filename.substring(index + 1, filename.length());

        long fileSize = item.getSize();

        if("".equals(filename) && fileSize == 0)
        {
            throw new RuntimeException("You didn't upload a file.");
            //return;
        }

        File uploadFile = new File(filePath + "/" + filename);
        item.write(uploadFile);
        pw.println("Link to the uploaded file : "+filename);
        System.out.println( fileSize + "\r\n");
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}


text:
namespace Carnage.Core.Rules.Data.Visitors
{
    using System.Collections.Generic;
    using Microsoft.SqlServer.TransactSql.ScriptDom;

    internal class AvoidUsingGlobalVariableForIdentityVisitor : TSqlFragmentVisitor
    {
        public AvoidUsingGlobalVariableForIdentityVisitor()
        {
            this.InvalidVariables = new List<GlobalVariableExpression>();
        }

        public IList<GlobalVariableExpression> InvalidVariables { get; private set; }

        public override void ExplicitVisit(GlobalVariableExpression node)
        {
                if (node.Name.ToLower().Contains("identity"))
                {
                    this.InvalidVariables.Add(node);
                }
        }
    }
}


text:
export default {
  props: {
    button: {type: Boolean, default: false},
    disabled: {type: Boolean, default: false},
    falseValue: {default: false},
    name: {type: String, default: null},
    readonly: {type: Boolean, default: false},
    trueValue: {default: true},
    type: {type: String, default: "primary"},
    value: {default: false}
  },
  data () {
    return {
      checked: (this.value === this.trueValue)
    }
  },
  computed: {
    inGroup () { return this.$parent && this.$parent.btnGroup && !this.$parent._radioGroup },
    isButton () { return this.button || (this.$parent && this.$parent.btnGroup && this.$parent.buttons) },
    isFalse () { return this.value === this.falseValue },
    isTrue () { return this.value === this.trueValue },
    parentValue () { return this.$parent.val },
    typeColor () { return (this.type || (this.$parent && this.$parent.type)) || 'default' }
  },
  watch: {
    checked (val) {
      let value = val ? this.trueValue : this.falseValue
      this.$emit('checked', val)
      this.$emit('input', value);
      this.updateParent()
    },
    parentValue () {
      this.updateFromParent();
    },
    value (val) {
      let checked = val === this.trueValue
      if (this.checked !== checked) {
        this.checked = checked
      }
    }
  },
  created () {
    if (this.inGroup) {
      const parent = this.$parent
      parent._checkboxGroup = true
      if (!(parent.val instanceof Array)) { parent.val = [] }
    }
  },
  mounted () {
    this.updateFromParent();
  },
  methods: {
    // called @ mounted(), or whenever $parent.val changes
    // sync our state with the $parent.val
    updateFromParent () {
      if (this.inGroup) {
        let index = this.$parent.val.indexOf(this.trueValue)
        this.checked = ~index
      }
    },
    // called when our checked state changes
    updateParent () {
      if (this.inGroup) {
        let index = this.$parent.val.indexOf(this.trueValue)
        if (this.checked && !~index) this.$parent.val.push(this.trueValue)
        if (!this.checked && ~index) this.$parent.val.splice(index, 1)
      }
    },
    toggle () {
      if (this.disabled || this.readonly) { return }
      this.checked = !this.checked
    }
  }
}


text:
const { UserSearchResult } = require("../../../src/core/searchResult/User"),
  { User } = require("../../../src/core/security/User"),
  sinon = require("sinon"),
  should = require("should");

describe("UserSearchResult", () => {
  const options = { opt: "in" };

  let kuzzle, request, result, searchResult;

  beforeEach(() => {
    kuzzle = {
      query: sinon.stub().resolves(),
    };

    request = {
      body: { query: { foo: "bar" } },
      controller: "security",
      action: "searchUsers",
    };
  });

  describe("constructor", () => {
    it("should create a UserSearchResult instance with good properties", () => {
      result = {
        hits: [
          {
            _id: "uid1",
            _version: 1,
            _source: { profileIds: ["profile1"], name: "John Doe" },
          },
          {
            _id: "uid2",
            _version: 3,
            _source: { profileIds: ["admin"], name: "Jane Doe" },
          },
        ],
        total: 3,
      };

      searchResult = new UserSearchResult(kuzzle, request, options, result);

      should(searchResult._request).be.equal(request);
      should(searchResult._options).be.equal(options);
      should(searchResult._result).be.equal(result);

      should(searchResult.fetched).be.equal(2);
      should(searchResult.total).be.equal(3);

      should(searchResult._controller).be.equal("security");
      should(searchResult._searchAction).be.equal("searchUsers");
      should(searchResult._scrollAction).be.equal("scrollUsers");

      should(searchResult.hits).be.an.Array();
      should(searchResult.hits.length).be.equal(2);

      should(searchResult.hits[0]).be.an.instanceOf(User);
      should(searchResult.hits[0]._id).be.eql("uid1");
      should(searchResult.hits[0].content).be.eql({
        name: "John Doe",
        profileIds: ["profile1"],
      });
      should(searchResult.hits[0].profileIds).be.eql(["profile1"]);

      should(searchResult.hits[1]).be.an.instanceOf(User);
      should(searchResult.hits[1]._id).be.eql("uid2");
      should(searchResult.hits[1].content).be.eql({
        name: "Jane Doe",
        profileIds: ["admin"],
      });
      should(searchResult.hits[1].profileIds).be.eql(["admin"]);
    });
  });

  describe("next", () => {
    it("should resolve null without calling kuzzle query if all results are already fetched", () => {
      result = {
        scrollId: "scroll-id",
        hits: [
          {
            _id: "uid1",
            _version: 1,
            _source: { profileIds: ["profile1"], name: "John Doe" },
          },
          {
            _id: "uid2",
            _version: 3,
            _source: { profileIds: ["admin"], name: "Jane Doe" },
          },
        ],
        total: 2,
      };

      searchResult = new UserSearchResult(kuzzle, request, options, result);

      return searchResult.next().then((res) => {
        should(kuzzle.query).not.be.called();
        should(res).be.Null();
      });
    });

    it("should reject with an error if neither scroll, nor size/sort, nor size/from parameters are set", () => {
      result = {
        scrollId: "scroll-id",
        hits: [
          {
            _id: "uid1",
            _version: 1,
            _source: { profileIds: ["profile1"], name: "John Doe" },
          },
          {
            _id: "uid2",
            _version: 3,
            _source: { profileIds: ["admin"], name: "Jane Doe" },
          },
        ],
        total: 30,
      };

      searchResult = new UserSearchResult(kuzzle, request, options, result);

      return should(searchResult.next()).be.rejectedWith(
        "Unable to retrieve next results from search: missing scrollId, from/sort, or from/size params"
      );
    });

    describe("#with scroll option", () => {
      const nextResponse = {
        scrollId: "scroll-id",
        hits: [
          {
            _id: "uid3",
            _version: 2,
            _source: {
              profileIds: ["profile1", "admin"],
              name: "Sarah Connor",
            },
          },
          {
            _id: "uid4",
            _version: 12,
            _source: {
              profileIds: ["profile2", "guest"],
              name: "Obiwan Kenobi",
            },
          },
        ],
        total: 30,
      };

      beforeEach(() => {
        request.scroll = "10s";

        result = {
          scrollId: "scroll-id",
          hits: [
            {
              _id: "uid1",
              _version: 1,
              _source: { profileIds: ["profile1"], name: "John Doe" },
            },
            {
              _id: "uid2",
              _version: 3,
              _source: { profileIds: ["admin"], name: "Jane Doe" },
            },
          ],
          total: 30,
        };
        searchResult = new UserSearchResult(kuzzle, request, options, result);

        kuzzle.query.resolves({ result: nextResponse });
      });

      it("should call security/scrollUsers action with scrollnextSearchResultparameter and resolve to a new UserSearchResult", () => {
        return searchResult.next().then((nextSearchResult) => {
          should(kuzzle.query).be.calledOnce().be.calledWith({
            controller: "security",
            action: "scrollUsers",
            scroll: "10s",
            scrollId: "scroll-id",
          });
          should(nextSearchResult).not.be.equal(searchResult);
          should(nextSearchResult).be.instanceOf(UserSearchResult);
        });
      });

      it('should set the result and increment the "fetched" property', () => {
        should(searchResult.fetched).be.equal(2);
        should(searchResult._result).be.equal(result);
        return searchResult.next().then((nextSearchResult) => {
          should(nextSearchResult.fetched).be.equal(4);
          should(nextSearchResult._result).be.equal(nextResponse);

          should(nextSearchResult.hits).be.an.Array();
          should(nextSearchResult.hits.length).be.equal(2);

          should(nextSearchResult.hits[0]).be.an.instanceOf(User);
          should(nextSearchResult.hits[0]._id).be.eql("uid3");
          should(nextSearchResult.hits[0].content).be.eql({
            name: "Sarah Connor",
            profileIds: ["profile1", "admin"],
          });
          should(nextSearchResult.hits[0].profileIds).be.eql([
            "profile1",
            "admin",
          ]);

          should(nextSearchResult.hits[1]).be.an.instanceOf(User);
          should(nextSearchResult.hits[1]._id).be.eql("uid4");
          should(nextSearchResult.hits[1].content).be.eql({
            name: "Obiwan Kenobi",
            profileIds: ["profile2", "guest"],
          });
          should(nextSearchResult.hits[1].profileIds).be.eql([
            "profile2",
            "guest",
          ]);
        });
      });
    });

    describe("#with size and sort option", () => {
      const nextResponse = {
        hits: [
          {
            _id: "uid3",
            _version: 2,
            _source: {
              profileIds: ["profile1", "admin"],
              name: "Sarah Connor",
              bar: 5678,
            },
          },
          {
            _id: "uid4",
            _version: 12,
            _source: {
              profileIds: ["profile2", "guest"],
              name: "Obiwan Kenobi",
              bar: 6789,
            },
          },
        ],
        total: 30,
      };

      beforeEach(() => {
        request.size = 2;
        request.body.sort = ["name", { bar: "asc" }];

        result = {
          hits: [
            {
              _id: "uid1",
              _version: 1,
              _source: {
                profileIds: ["profile1"],
                name: "John Doe",
                bar: 1234,
              },
            },
            {
              _id: "uid2",
              _version: 3,
              _source: { profileIds: ["admin"], name: "Jane Doe", bar: 3456 },
            },
          ],
          total: 30,
        };
        searchResult = new UserSearchResult(kuzzle, request, options, result);

        kuzzle.query.resolves({ result: nextResponse });
      });

      it("should call security/searchUsers action with search_after parameter and resolve to a new UserSearchResult", () => {
        return searchResult.next().then((nextSearchResult) => {
          should(kuzzle.query)
            .be.calledOnce()
            .be.calledWith(
              {
                body: {
                  query: { foo: "bar" },
                  sort: ["name", { bar: "asc" }],
                  search_after: ["Jane Doe", 3456],
                },
                controller: "security",
                action: "searchUsers",
                size: 2,
              },
              options
            );
          should(nextSearchResult).not.be.equal(searchResult);
          should(nextSearchResult).be.instanceOf(UserSearchResult);
        });
      });

      it('should set the result and increment the "fetched" property', () => {
        should(searchResult.fetched).be.equal(2);
        should(searchResult._result).be.equal(result);
        return searchResult.next().then((nextSearchResult) => {
          should(nextSearchResult.fetched).be.equal(4);
          should(nextSearchResult._result).be.equal(nextResponse);

          should(nextSearchResult.hits).be.an.Array();
          should(nextSearchResult.hits.length).be.equal(2);

          should(nextSearchResult.hits[0]).be.an.instanceOf(User);
          should(nextSearchResult.hits[0]._id).be.eql("uid3");
          should(nextSearchResult.hits[0].content).be.eql({
            name: "Sarah Connor",
            profileIds: ["profile1", "admin"],
            bar: 5678,
          });
          should(nextSearchResult.hits[0].profileIds).be.eql([
            "profile1",
            "admin",
          ]);

          should(nextSearchResult.hits[1]).be.an.instanceOf(User);
          should(nextSearchResult.hits[1]._id).be.eql("uid4");
          should(nextSearchResult.hits[1].content).be.eql({
            name: "Obiwan Kenobi",
            profileIds: ["profile2", "guest"],
            bar: 6789,
          });
          should(nextSearchResult.hits[1].profileIds).be.eql([
            "profile2",
            "guest",
          ]);
        });
      });
    });

    describe("#with from and size option", () => {
      const nextResponse = {
        hits: [
          {
            _id: "uid3",
            _version: 2,
            _source: {
              profileIds: ["profile1", "admin"],
              name: "Sarah Connor",
            },
          },
          {
            _id: "uid4",
            _version: 12,
            _source: {
              profileIds: ["profile2", "guest"],
              name: "Obiwan Kenobi",
            },
          },
        ],
        total: 30,
      };

      beforeEach(() => {
        request.size = 2;
        request.from = 2;

        result = {
          hits: [
            {
              _id: "uid1",
              _version: 1,
              _source: { profileIds: ["profile1"], name: "John Doe" },
            },
            {
              _id: "uid2",
              _version: 3,
              _source: { profileIds: ["admin"], name: "Jane Doe" },
            },
          ],
          total: 30,
        };
        searchResult = new UserSearchResult(kuzzle, request, options, result);

        kuzzle.query.resolves({ result: nextResponse });
      });

      it("should resolve null without calling kuzzle query if from parameter is greater than the search count", () => {
        request.from = 30;

        return searchResult.next().then((res) => {
          should(kuzzle.query).not.be.called();
          should(res).be.Null();
        });
      });

      it("should call security/searchUsers action with from/size parameters and resolve to a new UserSearchResult", () => {
        return searchResult.next().then((nextSearchResult) => {
          should(kuzzle.query)
            .be.calledOnce()
            .be.calledWith(
              {
                body: { query: { foo: "bar" } },
                controller: "security",
                action: "searchUsers",
                size: 2,
                from: 2,
              },
              options
            );
          should(nextSearchResult).not.be.equal(searchResult);
          should(nextSearchResult).be.instanceOf(UserSearchResult);
        });
      });

      it('should set the result and increment the "fetched" property', () => {
        should(searchResult.fetched).be.equal(2);
        should(searchResult._result).be.equal(result);
        return searchResult.next().then((nextSearchResult) => {
          should(nextSearchResult.fetched).be.equal(4);
          should(nextSearchResult._result).be.equal(nextResponse);

          should(nextSearchResult.hits).be.an.Array();
          should(nextSearchResult.hits.length).be.equal(2);

          should(nextSearchResult.hits[0]).be.an.instanceOf(User);
          should(nextSearchResult.hits[0]._id).be.eql("uid3");
          should(nextSearchResult.hits[0].content).be.eql({
            name: "Sarah Connor",
            profileIds: ["profile1", "admin"],
          });
          should(nextSearchResult.hits[0].profileIds).be.eql([
            "profile1",
            "admin",
          ]);

          should(nextSearchResult.hits[1]).be.an.instanceOf(User);
          should(nextSearchResult.hits[1]._id).be.eql("uid4");
          should(nextSearchResult.hits[1].content).be.eql({
            name: "Obiwan Kenobi",
            profileIds: ["profile2", "guest"],
          });
          should(nextSearchResult.hits[1].profileIds).be.eql([
            "profile2",
            "guest",
          ]);
        });
      });
    });
  });
});


text:
/* global describe expect it beforeEach */
import queryAction from '../../../src/actions/query'
import {
  watchEvent,
  unWatchEvent,
  watchEvents,
  unWatchEvents
} from '../../../src/actions/query'
import {
  unsetWatcher
} from '../../../src/utils/query'
let spy, unWatch
const dispatch = () => {

}
describe('Actions: Query', () => {
  beforeEach(() => {
    spy = sinon.spy(dispatch)
  })
  describe('watchEvent', () => {
    it('is exported', () => {
      expect(watchEvent).to.be.a.function
    })
    it('runs given basic params', () => {
      return watchEvent(firebase, dispatch, { type: 'once', path: 'projects' }, 'projects')
        .then((snap) => {
          expect(snap).to.be.an.object
        })
    }, 4000)
    it('runs value query', () => {
      expect(watchEvent(firebase, dispatch, { type: 'value', path: 'projects' }, 'projects'))
    })
    it('handles populates', () => {
      expect(watchEvent(firebase, dispatch, { type: 'value', path: 'projects', populates: [{ child: 'uid', root: 'users' }] }, 'projects'))
    })
    it('throws for null type', () => {
      expect(() => watchEvent(firebase, dispatch, { path: 'projects' }, 'projects')).to.Throw
    })
  })
  describe('unWatchEvent', () => {
    it('is exported', () => {
      expect(unWatchEvent).to.be.a.function
    })
    it('runs given basic params', () => {
      expect(unWatchEvent(firebase, 'once', 'projects')).to.be.a.function
    })
  })
  describe('watchEvents', () => {
    it('is exported', () => {
      expect(watchEvents).to.be.a.function
    })
    it('runs given basic params', () => {
      const events = [{type: 'once', path: 'test'}]
      spy = sinon.spy(events, 'forEach')
      watchEvents(firebase, dispatch, events)
      expect(spy).to.be.calledOnce
    })
  })
  describe('unWatchEvents', () => {
    it('is exported', () => {
      expect(unWatchEvents).to.be.a.function
    })
    it('runs given basic params', () => {
      const events = [{type: 'value', path: 'test'}]
      spy = sinon.spy(events, 'forEach')
      unWatchEvents(firebase, events)
      expect(spy).to.be.calledOnce
    })
    it('throws for bad type', () => {
      const events = [{type: '', path: 'test'}]
      spy = sinon.spy(events, 'forEach')
      unWatchEvents(firebase, events)
      expect(spy).to.Throw
    })
  })
})


text:
import logging

from telemetry import decorators
from telemetry.core import cros_interface
from telemetry.core import platform
from telemetry.core import util
from telemetry.internal.forwarders import cros_forwarder
from telemetry.internal.platform import cros_device
from telemetry.internal.platform import linux_based_platform_backend
from telemetry.internal.platform.power_monitor import cros_power_monitor
from telemetry.internal.util import ps_util

class CrosPlatformBackend(
    linux_based_platform_backend.LinuxBasedPlatformBackend):
  def __init__(self, device=None):
    super(CrosPlatformBackend, self).__init__(device)
    if device and not device.is_local:
      self._cri = cros_interface.CrOSInterface(
          device.host_name, device.ssh_port, device.ssh_identity)
      self._cri.TryLogin()
    else:
      self._cri = cros_interface.CrOSInterface()
    self._powermonitor = cros_power_monitor.CrosPowerMonitor(self)

  @classmethod
  def IsPlatformBackendForHost(cls):
    return util.IsRunningOnCrosDevice()

  @classmethod
  def SupportsDevice(cls, device):
    return isinstance(device, cros_device.CrOSDevice)

  @classmethod
  def CreatePlatformForDevice(cls, device, finder_options):
    assert cls.SupportsDevice(device)
    return platform.Platform(CrosPlatformBackend(device))

  @property
  def cri(self):
    return self._cri

  @property
  def forwarder_factory(self):
    if not self._forwarder_factory:
      self._forwarder_factory = cros_forwarder.CrOsForwarderFactory(self._cri)
    return self._forwarder_factory

  def GetRemotePort(self, port):
    if self._cri.local:
      return port
    return self._cri.GetRemotePort()

  def IsThermallyThrottled(self):
    raise NotImplementedError()

  def HasBeenThermallyThrottled(self):
    raise NotImplementedError()

  def RunCommand(self, args):
    if not isinstance(args, list):
      args = [args]
    stdout, stderr = self._cri.RunCmdOnDevice(args)
    if stderr:
      raise IOError('Failed to run: cmd = %s, stderr = %s' %
                    (str(args), stderr))
    return stdout

  def GetFileContents(self, filename):
    try:
      return self.RunCommand(['cat', filename])
    except AssertionError:
      return ''

  def GetPsOutput(self, columns, pid=None):
    return ps_util.GetPsOutputWithPlatformBackend(self, columns, pid)

  @staticmethod
  def ParseCStateSample(sample):
    sample_stats = {}
    for cpu in sample:
      values = sample[cpu].splitlines()
      # There are three values per state after excluding the single time value.
      num_states = (len(values) - 1) / 3
      names = values[:num_states]
      times = values[num_states:2 * num_states]
      latencies = values[2 * num_states:]
      # The last line in the sample contains the time.
      cstates = {'C0': int(values[-1]) * 10 ** 6}
      for i, state in enumerate(names):
        if names[i] == 'POLL' and not int(latencies[i]):
          # C0 state. Kernel stats aren't right, so calculate by
          # subtracting all other states from total time (using epoch
          # timer since we calculate differences in the end anyway).
          # NOTE: Only x86 lists C0 under cpuidle, ARM does not.
          continue
        cstates['C0'] -= int(times[i])
        if names[i] == '<null>':
          # Kernel race condition that can happen while a new C-state gets
          # added (e.g. AC->battery). Don't know the 'name' of the state
          # yet, but its 'time' would be 0 anyway.
          continue
        cstates[state] = int(times[i])
      sample_stats[cpu] = cstates
    return sample_stats

  def GetDeviceTypeName(self):
    return self._cri.GetDeviceTypeName()

  @decorators.Cache
  def GetArchName(self):
    return self._cri.GetArchName()

  def GetOSName(self):
    return 'chromeos'

  def GetOSVersionName(self):
    return ''  # TODO: Implement this.

  def GetChildPids(self, pid):
    """Returns a list of child pids of |pid|."""
    all_process_info = self._cri.ListProcesses()
    processes = [(curr_pid, curr_ppid, curr_state)
                 for curr_pid, _, curr_ppid, curr_state in all_process_info]
    return ps_util.GetChildPids(processes, pid)

  def GetCommandLine(self, pid):
    procs = self._cri.ListProcesses()
    return next((proc[1] for proc in procs if proc[0] == pid), None)

  def CanFlushIndividualFilesFromSystemCache(self):
    return True

  def FlushEntireSystemCache(self):
    raise NotImplementedError()

  def FlushSystemCacheForDirectory(self, directory):
    flush_command = (
        '/usr/local/telemetry/src/src/out/Release/clear_system_cache')
    self.RunCommand(['chmod', '+x', flush_command])
    self.RunCommand([flush_command, '--recurse', directory])

  def CanMonitorPower(self):
    return self._powermonitor.CanMonitorPower()

  def StartMonitoringPower(self, browser):
    self._powermonitor.StartMonitoringPower(browser)

  def StopMonitoringPower(self):
    return self._powermonitor.StopMonitoringPower()

  def PathExists(self, path, timeout=None, retries=None):
    if timeout or retries:
      logging.warning(
          'PathExists: params timeout and retries are not support on CrOS.')
    return self._cri.FileExistsOnDevice(path)

  def CanTakeScreenshot(self):
    # crbug.com/609001: screenshots don't work on VMs.
    return not self.cri.IsRunningOnVM()

  def TakeScreenshot(self, file_path):
    return self._cri.TakeScreenshot(file_path)


text:
package projects.Distribution;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.Vector;

import javax.swing.JOptionPane;

import projects.Distribution.nodes.edges.EdgeETX;
import projects.Distribution.nodes.nodeImplementations.SimpleNode;
import projects.hopBet.nodes.edges.EdgeWeightHopSbet;
import projects.hopBet.nodes.nodeImplementations.NodeHopSbet;
import sinalgo.configuration.Configuration;
import sinalgo.configuration.CorruptConfigurationEntryException;
import sinalgo.nodes.Node;
import sinalgo.nodes.Position;
import sinalgo.nodes.edges.Edge;
import sinalgo.runtime.AbstractCustomGlobal;
import sinalgo.runtime.Global;
import sinalgo.runtime.Runtime;
import sinalgo.tools.Tools;
import sinalgo.tools.logging.Logging;

/**
 * This class holds customized global state and methods for the framework.
 * The only mandatory method to overwrite is
 * hasTerminated
 *

 * Optional methods to override are
 *

 *
customPaint

 *
handleEmptyEventQueue

 *
onExit

 *
preRun

 *
preRound

 *
postRound

 *
checkProjectRequirements

 *

 * @see sinalgo.runtime.AbstractCustomGlobal for more details.
 *

 * In addition, this class also provides the possibility to extend the framework with
 * custom methods that can be called either through the menu or via a button that is
 * added to the GUI.
 */
public class CustomGlobal extends AbstractCustomGlobal{

	private Logging Topology;
	private Logging conectionEtx;
	private Logging NodesEvents;
	private int NumberNodes = 0, idTopology = 0, rMax = 0;

	private int ev = 0;	// % de nodes que vao emitir eventos
	//variavel para gerar numeros aleatorios
	private Random gerador = new Random();
	//variavel para indicar quais nodos emitirao eventos
	private static Set<Integer>  setNodesEv = new HashSet<Integer>();

	public void preRun() {

		try {
			NumberNodes = Configuration.getIntegerParameter("NumberNodes");
			idTopology = Configuration.getIntegerParameter("idTopology");
			rMax = Configuration.getIntegerParameter("UDG/rMax");
			ev = Configuration.getIntegerParameter("EV");
			//System.out.println(NumberNodes);
			//System.out.println(ev);
		} catch (CorruptConfigurationEntryException e) {
			Tools.fatalError("Alguma das variaveis (NumberNodes, idTopology) nao estao presentes no arquivo de configuracao ");
		}

		String str = "";
		str += idTopology;
		str += "_"+Configuration.dimX+"X"+Configuration.dimY;
		str += "_"+NumberNodes;
		str += "_"+rMax;

		Topology = Logging.getLogger(str+"_topology.txt", true);

		conectionEtx = Logging.getLogger(str+"_conection.txt", true);

		NodesEvents = Logging.getLogger(str+"_NodesEvents.txt", true);

		int nNodesEv = (NumberNodes * ev) / 100;
		if(nNodesEv <= 0) nNodesEv = 1;
		//System.out.println(nNodesEv);

		while(setNodesEv.size() != nNodesEv){
			setNodesEv.add(new Integer(gerador.nextInt(NumberNodes-1) + 2));
		}
		Iterator<Integer> it = setNodesEv.iterator();
		while(it.hasNext()){
			Integer idNode = (Integer) it.next();
			NodesEvents.logln(idNode.toString()+" "+gerador.nextInt(1000));
		}

	}

	public void postRound(){
		if(Global.currentTime == 5){

			try {
		        Process p = java.lang.Runtime.getRuntime().exec("pwd");
		        BufferedReader stdInput = new BufferedReader(new  InputStreamReader(p.getInputStream()));
		        String s, s1;

		        if((s = stdInput.readLine()) != null){
		        	s += "/topology/";
		    		s += idTopology;
		    		s += "_"+Configuration.dimX+"X"+Configuration.dimY;
		    		s += "_"+NumberNodes;
		    		s += "_"+rMax;
		    		s1 = s;

		    		s += "_conection.txt";
		    		s1 += "_NodesEvents.txt";

		        	File arquivo = new File(s);
		        	File arquivo1 = new File(s1);

		        	if (!arquivo.exists()) {
		        		System.out.println("Erro arquivo nao existe");
	        		}

		        	if (!arquivo1.exists()) {
		        		System.out.println("Erro arquivo nao existe");
	        		}

		        	//faz a leitura do arquivo
		        	FileReader fr = new FileReader(arquivo);

		        	BufferedReader br = new BufferedReader(fr);

		        	//equanto houver mais linhas
		        	while (br.ready()) {
		        		//lê a proxima linha

		        		String linha = br.readLine();
			        	String[] vet = linha.split(" ");
			        	//System.out.println(vet[0]+" "+vet[1]+"   "+vet[2]);
			        	int id_u, id_v;
			        	id_u = Integer.parseInt(vet[0]);
			        	id_v = Integer.parseInt(vet[1]);
			        	double etx;
			        	etx = Double.parseDouble(vet[2]);

			        	System.out.println(id_u+" "+id_v+"    "+etx);

		        		Node u, v;
		        		u = Tools.getNodeByID(id_u);
		        		v = Tools.getNodeByID(id_v);

		        		Iterator<Edge> it = u.outgoingConnections.iterator();

		        		while(it.hasNext()){
		        			EdgeETX e = (EdgeETX) it.next();
		        			if(e.startNode.equals(u) && e.endNode.equals(v)){
		        				e.setETX(etx);
		        			}
		        		}

		        		//faz algo com a linha
		        		//System.out.println(id_u+" "+id_v+"   "+etx);

		        	}

		        	br.close();
		        	fr.close();

		        	//faz a leitura do arquivo
		        	fr = new FileReader(arquivo1);

		        	br = new BufferedReader(fr);

		        	//equanto houver mais linhas
		        	while (br.ready()) {
		        		String linha = br.readLine();
		        		String[] vet = linha.split(" ");

		        		int id = Integer.parseInt(vet[0]);
		        		int time = Integer.parseInt(vet[1]);
		        		System.out.println(id+" "+time);
		        	}

		        	br.close();
		        	fr.close();

		        }

		    } catch(Exception e) {
		        System.out.println(e.toString());
		        e.printStackTrace();
		    }
		}
	}

	/* (non-Javadoc)
	 * @see runtime.AbstractCustomGlobal#hasTerminated()
	 */
	public boolean hasTerminated() {

		/*Iterator<Node> it = Tools.getNodeList().iterator();
		String str;
		it = Tools.getNodeList().iterator();
		while(it.hasNext()){
			Node n = it.next();
			str = "";
			Iterator<Edge> itEdg = n.outgoingConnections.iterator();

			while(itEdg.hasNext()){
				EdgeETX e = (EdgeETX)itEdg.next();
				str += n.ID;
				str += " -["+e.getETX()+"]-> ";
				str += e.endNode.ID+"\n";
			}
			//System.out.println(str);
		}*/
		return false;
	}

	public void onExit() {
		Iterator<Node> it = Tools.getNodeList().iterator();
		String str, aux;
		while(it.hasNext()){
			Node n = it.next();
			str = "";
			aux = "";

			aux = n.getPosition().toString();
			aux = aux.replace("[", "");
			aux = aux.replace("]", "");
			aux = aux.replace(", ", " ");
			str += aux;
			Topology.logln(str);
		}

		it = Tools.getNodeList().iterator();
		while(it.hasNext()){
			Node n = it.next();
			str = "";
			Iterator<Edge> itEdg = n.outgoingConnections.iterator();

			while(itEdg.hasNext()){
				EdgeETX e = (EdgeETX)itEdg.next();
				str += n.ID;
				str += " "+e.endNode.ID;
				str += " "+e.getETX()+"\n";

			}
			//System.out.println(str);
			conectionEtx.log(str);

		}

	}

	/**
	 * An example of a method that will be available through the menu of the GUI.
	 */
	@AbstractCustomGlobal.GlobalMethod(menuText="Echo")
	public void echo() {
		// Query the user for an input
		String answer = JOptionPane.showInputDialog(null, "This is an example.\nType in any text to echo.");
		// Show an information message
		JOptionPane.showMessageDialog(null, "You typed '" + answer + "'", "Example Echo", JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * An example to add a button to the user interface. In this sample, the button is labeled
	 * with a text 'GO'. Alternatively, you can specify an icon that is shown on the button. See
	 * AbstractCustomGlobal.CustomButton for more details.
	 */
	@AbstractCustomGlobal.CustomButton(buttonText="GO", toolTipText="A sample button")
	public void sampleButton() {
		JOptionPane.showMessageDialog(null, "You Pressed the 'GO' button.");
	}

	/**
	 * Dummy button to create a tree.
	 */
	@AbstractCustomGlobal.CustomButton(buttonText="Graphics", toolTipText="Show Graphics")
	public void Button3() {
		//int numNodes = Integer.parseInt(Tools.showQueryDialog("Number of nodes:"));
		//int fanOut = Integer.parseInt(Tools.showQueryDialog("Max fanout:"));
		//buildTree(fanOut, numLeaves);
		printGraphicsINGuI();
	}

	public void printGraphicsINGuI(){
		Vector<SimpleNode> myNodes = new Vector<SimpleNode>();

		SimpleNode n = new SimpleNode();
		n.setPosition(300, 500, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(350, 500, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(400, 450, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(400, 550, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(450, 500, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(450, 400, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(500, 450, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(500, 500, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);

		n = new SimpleNode();
		n.setPosition(550, 550, 0);
		n.finishInitializationWithDefaultModels(true);
		myNodes.add(n);
		// Repaint the GUI as we have added some nodes
		Tools.repaintGUI();

	}

	/**
	 * Dummy button to create a tree.
	 */
	@AbstractCustomGlobal.CustomButton(buttonText="ETX", toolTipText="Insert ETX")
	public void Button() {
		//int numNodes = Integer.parseInt(Tools.showQueryDialog("Number of nodes:"));
		//int fanOut = Integer.parseInt(Tools.showQueryDialog("Max fanout:"));
		//buildTree(fanOut, numLeaves);
		insertETX();
	}

	public void insertETX(){
		Iterator<Node> it = Runtime.nodes.iterator();
		SimpleNode n;
		/*Iterator<Node> it = Runtime.nodes.iterator();
		Node n;
		Random generator = new Random(1);
		while(it.hasNext()){
			n = it.next();
			System.out.println(n);
			Iterator<Edge> it2 = n.outgoingConnections.iterator();
			EdgeWeightHopSbet e;
			while(it2.hasNext()){
				e = (EdgeWeightHopSbet) it2.next();
				//e.setETX(UniformDistribution.nextUniform(0, 1));
				//e.setETX(generator.nextDouble());
				e.setETX(1+generator.nextInt(9));

			}
		}*/

		while(it.hasNext()){
			n = (SimpleNode) it.next();
			//System.out.println(n);
			Iterator<Edge> it2 = n.outgoingConnections.iterator();
			EdgeETX e;
			while(it2.hasNext()){
				e = (EdgeETX) it2.next();
				if(n.ID == 1){
					if(e.endNode.ID == 2)
						e.setETX(2);
				}

				if(n.ID == 2){
					if(e.endNode.ID == 1)
						e.setETX(1);
					if(e.endNode.ID == 3)
						e.setETX(1);
					if(e.endNode.ID == 4)
						e.setETX(1);
				}

				if(n.ID == 3){
					if(e.endNode.ID == 2)
						e.setETX(2);
					if(e.endNode.ID == 5)
						e.setETX(1);
					if(e.endNode.ID == 6)
						e.setETX(1);
				}

				if(n.ID == 4){
					if(e.endNode.ID == 2)
						e.setETX(2);
					if(e.endNode.ID == 5)
						e.setETX(1);
				}

				if(n.ID == 5){
					if(e.endNode.ID == 3)
						e.setETX(2);
					if(e.endNode.ID == 4)
						e.setETX(2);
					if(e.endNode.ID == 7)
						e.setETX(1);
					if(e.endNode.ID == 8)
						e.setETX(1);
				}

				if(n.ID == 6){
					if(e.endNode.ID == 3)
						e.setETX(9);
					if(e.endNode.ID == 7)
						e.setETX(1);
				}

				if(n.ID == 7){
					if(e.endNode.ID == 5)
						e.setETX(2);
					if(e.endNode.ID == 6)
						e.setETX(1);
					if(e.endNode.ID == 8)
						e.setETX(2);
				}

				if(n.ID == 8){
					if(e.endNode.ID == 5)
						e.setETX(4);
					if(e.endNode.ID == 7)
						e.setETX(2);
					if(e.endNode.ID == 9)
						e.setETX(2);
				}

				if(n.ID == 9){
					if(e.endNode.ID == 8)
						e.setETX(1);
				}

				//e.setETX(1+generator.nextInt(9));
				System.out.println("ID "+ e.getID()+"      " +n.ID+" ~["+e.getETX()+"]> "+e.endNode.ID);

			}
		}
	}

}


text:
package redisapi

import original "github.com/Azure/azure-sdk-for-go/services/redis/mgmt/2018-03-01/redis/redisapi"

type ClientAPI = original.ClientAPI
type FirewallRulesClientAPI = original.FirewallRulesClientAPI
type LinkedServerClientAPI = original.LinkedServerClientAPI
type OperationsClientAPI = original.OperationsClientAPI
type PatchSchedulesClientAPI = original.PatchSchedulesClientAPI


text:
#pragma once

#include <vector>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/variate_generator.hpp>
#include <folly/ThreadLocal.h>
#include <folly/dynamic.h>
#include <thrift/lib/cpp/test/loadgen/RNG.h>

namespace apache {
namespace thrift {
namespace loadgen {

/**
 * A Gaussian Mixture Model (GMM) that relies on the loadgen::RNG and
 * boost::normal_distribution
 *
 * A GMM config looks like:
 * ```json
 * {
 *   "id": "cost_model_name",
 *   "metrics": {
 *     "cpu_time": {
 *       "log_transformed": true,
 *       "min": 0.0,
 *       "max": 10.0,
 *       "mean": 5.0,
 *       "strip_left": 0,
 *       "strip_right": 0.01,
 *       "gmm": {
 *         "n_components": 3,
 *         "mus": [
 *           5.052434022867472,
 *           5.797919361306436,
 *           4.560631557715017
 *         ],
 *         "sigmas": [
 *           0.22243745992799488,
 *           0.2534454625260933,
 *           0.22913981810890852
 *         ],
 *         "weights": [
 *           0.37574910896323904,
 *           0.2817285538897495,
 *           0.34252233714701397
 *         ]
 *       }
 *     },
 *     "off_cpu_time": {
 *       ... // same as the above "cpu_time"
 *     }
 *   }
 * }
 * ```
 *
 * Config semantics:
 *   - "id": the identifier of the config.
 *   - "cpu_time": the distribution of time spent on CPU (i.e. emulated by
 *   `burn` in the loadgen)
 *   - "off_cpu_time": the distribution of time spent off-CPU (i.e. emulated by
 *   `sleep` in the loadgen).
 *     - "log_transformed": whether the random variable (cpu/off_cpu time) has
 *     been log-transformed before fitting to GMM. If true, the random variable
 *     is actually modeled as a mixture of log-normal distribution.
 *     - "min", "max", "mean": some high-level statistics of the raw data used
 *     to fit the GMM.
 *     - "strip_left": the percentile on the left tail of the distribution that
 *     got discard in the GMM. This parameter documents how outliers were
 *     removed from the original dataset.
 *     - "strip_right": the percentile on the right tail of the distribution
 *     that got discarded in the GMM. E.g., 0.01 means only model up to p99.
 *     - "gmm": the parameters of the fitted GMM
 *       - "n_components": the number of independent normal distribution
 *       - "mus": the $\mu$ in each normal distribution $N(\mu, \sigma^2)$
 *       - "sigmas": the $\sigma$ in each $N(\mu, \sigma^2)$
 *       - "weights": how different normal distributions are mixed together. Sum
 *       should be 1.0
 *
 * How samples are generated from a GaussianMixtureModel:
 *   1. Uniformly sample one normal distribution based on the "weights" of all
 *   components.
 *   2. Take a sample X from the chosen normal distribution
 *   3. If the random variable was log-transformed, return exp(X) instead of X.
 */
class GaussianMixtureModel {
 public:
  explicit GaussianMixtureModel(const folly::dynamic& cfgDict);
  double getSample();

 private:
  bool logTransformed;
  uint32_t nComponents;
  std::vector<double> mus; // location
  std::vector<double> sigmas; // scale
  // accumulated sum of weights, last element should be 1.0
  std::vector<double> weightsCumsum;
  // the normal distribution generators, one for each gaussian component
  // the vector of generators is ThreadLocal because:
  //   1. the boost normal distribution sampling relies on
  //   apache::thrift::loadgen::RNG
  //   2. the underlying RNG is ThreadLocal
  typedef std::vector<
      boost::variate_generator<RNG, boost::normal_distribution<double>>>
      TGaussianGenerators;
  folly::ThreadLocal<TGaussianGenerators> threadLocalGaussianGenerators;
};

} // namespace loadgen
} // namespace thrift
} // namespace apache


text:
PLEASE NOTE: This document applies to the HEAD of the source tree

If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.

The latest release of this document can be found
[here](http://releases.k8s.io/release-1.4/examples/sharing-clusters/README.md).

Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).

--

# Sharing Clusters

This example demonstrates how to access one kubernetes cluster from another. It only works if both clusters are running on the same network, on a cloud provider that provides a private ip range per network (eg: GCE, GKE, AWS).

## Setup

Create a cluster in US (you don't need to do this if you already have a running kubernetes cluster)

```shell
$ cluster/kube-up.sh
```

Before creating our second cluster, lets have a look at the kubectl config:

```yaml
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: REDACTED
    server: https://104.197.84.16
  name: <clustername_us>
...
current-context: <clustername_us>
...
```

Now spin up the second cluster in Europe

```shell
$ ./cluster/kube-up.sh
$ KUBE_GCE_ZONE=europe-west1-b KUBE_GCE_INSTANCE_PREFIX=eu ./cluster/kube-up.sh
```

Your kubectl config should contain both clusters:

```yaml
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: REDACTED
    server: https://146.148.25.221
  name: <clustername_eu>
- cluster:
    certificate-authority-data: REDACTED
    server: https://104.197.84.16
  name: <clustername_us>
...
current-context: kubernetesdev_eu
...
```

And kubectl get nodes should agree:

```
$ kubectl get nodes
NAME             LABELS                                  STATUS
eu-node-0n61     kubernetes.io/hostname=eu-node-0n61     Ready
eu-node-79ua     kubernetes.io/hostname=eu-node-79ua     Ready
eu-node-7wz7     kubernetes.io/hostname=eu-node-7wz7     Ready
eu-node-loh2     kubernetes.io/hostname=eu-node-loh2     Ready

$ kubectl config use-context <clustername_us>
$ kubectl get nodes
NAME                     LABELS                                                            STATUS
kubernetes-node-5jtd     kubernetes.io/hostname=kubernetes-node-5jtd                       Ready
kubernetes-node-lqfc     kubernetes.io/hostname=kubernetes-node-lqfc                       Ready
kubernetes-node-sjra     kubernetes.io/hostname=kubernetes-node-sjra                       Ready
kubernetes-node-wul8     kubernetes.io/hostname=kubernetes-node-wul8                       Ready
```

## Testing reachability

For this test to work we'll need to create a service in europe:

```
$ kubectl config use-context <clustername_eu>
$ kubectl create -f /tmp/secret.json
$ kubectl create -f examples/https-nginx/nginx-app.yaml
$ kubectl exec -it my-nginx-luiln -- echo "Europe nginx" >> /usr/share/nginx/html/index.html
$ kubectl get ep
NAME         ENDPOINTS
kubernetes   10.240.249.92:443
nginxsvc     10.244.0.4:80,10.244.0.4:443
```

Just to test reachability, we'll try hitting the Europe nginx from our initial US central cluster. Create a basic curl pod in the US cluster:

```yaml
apiVersion: v1
kind: Pod
metadata:
  name: curlpod
spec:
  containers:
  - image: radial/busyboxplus:curl
    command:
      - sleep
      - "360000000"
    imagePullPolicy: IfNotPresent
    name: curlcontainer
  restartPolicy: Always
```

And test that you can actually reach the test nginx service across continents

```
$ kubectl config use-context <clustername_us>
$ kubectl -it exec curlpod -- /bin/sh
[ root@curlpod:/ ]$ curl http://10.244.0.4:80
Europe nginx
```

## Granting access to the remote cluster

We will grant the US cluster access to the Europe cluster. Basically we're going to setup a secret that allows kubectl to function in a pod running in the US cluster, just like it did on our local machine in the previous step. First create a secret with the contents of the current .kube/config:

```shell
$ kubectl config use-context <clustername_eu>
$ go run ./make_secret.go --kubeconfig=$HOME/.kube/config > /tmp/secret.json
$ kubectl config use-context <clustername_us>
$ kubectl create -f /tmp/secret.json
```

Create a kubectl pod that uses the secret, in the US cluster.

```json
{
  "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "kubectl-tester"
  },
  "spec": {
    "volumes": [
       {
            "name": "secret-volume",
            "secret": {
                "secretName": "kubeconfig"
            }
        }
    ],
    "containers": [
      {
        "name": "kubectl",
        "image": "bprashanth/kubectl:0.0",
        "imagePullPolicy": "Always",
        "env": [
            {
                "name": "KUBECONFIG",
                "value": "/.kube/config"
            }
        ],
        "args": [
          "proxy", "-p", "8001"
        ],
        "volumeMounts": [
          {
              "name": "secret-volume",
               "mountPath": "/.kube"
          }
        ]
      }
    ]
  }
}
```

And check that you can access the remote cluster

```shell
$ kubectl config use-context <clustername_us>
$ kubectl exec -it kubectl-tester bash

kubectl-tester $ kubectl get nodes
NAME             LABELS                                  STATUS
eu-node-0n61     kubernetes.io/hostname=eu-node-0n61     Ready
eu-node-79ua     kubernetes.io/hostname=eu-node-79ua     Ready
eu-node-7wz7     kubernetes.io/hostname=eu-node-7wz7     Ready
eu-node-loh2     kubernetes.io/hostname=eu-node-loh2     Ready
```

For a more advanced example of sharing clusters, see the [service-loadbalancer](https://github.com/kubernetes/contrib/tree/master/service-loadbalancer/README.md)

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/examples/sharing-clusters/README.md?pixel)]()


text:
package net.devh.boot.grpc.server.event;

import java.time.Clock;

import io.grpc.Server;
import net.devh.boot.grpc.server.serverfactory.GrpcServerLifecycle;

/**
 * This event will be fired before the server starts to shutdown. The server will no longer process new requests.
 *
 * @see Server#shutdown()
 * @see Server#isShutdown()
 *
 * @author Daniel Theuke (daniel.theuke@heuboe.de)
 */
public class GrpcServerShutdownEvent extends GrpcServerLifecycleEvent {

    private static final long serialVersionUID = 1L;

    /**
     * Creates a new GrpcServerShutdownEvent.
     *
     * @param lifecyle The lifecycle that caused this event.
     * @param clock The clock used to determine the timestamp.
     * @param server The server related to this event.
     */
    public GrpcServerShutdownEvent(
            final GrpcServerLifecycle lifecyle,
            final Clock clock,
            final Server server) {

        super(lifecyle, clock, server);
    }

    /**
     * Creates a new GrpcServerShutdownEvent.
     *
     * @param lifecyle The lifecycle that caused this event.
     * @param server The server related to this event.
     */
    public GrpcServerShutdownEvent(
            final GrpcServerLifecycle lifecyle,
            final Server server) {

        super(lifecyle, server);
    }

}


text:
<?php

namespace datork\io;

class CsvReadOptions
{
    public $delimiter = ",";
    public $enclosure = '"';
    public $escapeChar = "\\";         // means \
}


text:
package au.edu.ersa.reporting.http.api;

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

public class ReportingResponse {
    public final Map<String,String> response = init();

    private static final Map<String,String> init() {
        Map<String,String> map = new HashMap<>();

        map.put("id", UUID.randomUUID().toString().toLowerCase());
        map.put("timestamp", Long.toString(System.currentTimeMillis()));

        return map;
    }
}


text:
<?xml version="1.0"?>
<!--
  ~ Licensed to Booz Allen Hamilton under one or more contributor
  ~ license agreements. See the NOTICE file distributed with
  ~ this work for additional information regarding copyright
  ~ ownership. Booz Allen Hamilton 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.
  -->

<configuration scan="true" scanPeriod="60 seconds">
  <appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
    <remoteHost>LOGSTASH-HOST</remoteHost>
    <port>4561</port>
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
      <fieldNames>
        <level>priority</level>
        <thread_name>thread</thread_name>
      </fieldNames>
      <customFields>{"application":"storm"}</customFields>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="logstash"/>
  </root>
</configuration>


text:
package org.opensingular.form.persistence;

import java.util.HashMap;
import java.util.Objects;
import java.util.StringJoiner;

import javax.annotation.Nonnull;

import org.opensingular.form.SInstance;

/**
 * Generic form key for relational persistence.
 *
 * @author Edmundo Andrade
 */
public class FormKeyRelational extends AbstractFormKey<HashMap<String, Object>> {
    private static final long serialVersionUID = 1L;
    private static final String SERIALIZATION_SEPARATOR = "___";
    private static final String IMPLICIT_JAVA_PACKAGE = "java.lang.";

    public FormKeyRelational(@Nonnull String persistenceString) {
        super(persistenceString);
    }

    public FormKeyRelational(@Nonnull HashMap<String, Object> keyValue) {
        super(keyValue);
    }

    public Object getColumnValue(String keyColumn) {
        return getValue().get(keyColumn);
    }

    /**
     * Returns the column value present in the persistence key assigned to a given
     * SInstance.
     */
    public static Object columnValuefromInstance(String keyColumn, @Nonnull SInstance instance) {
        Objects.requireNonNull(instance);
        return ((FormKeyRelational) FormKey.fromInstance(instance)).getColumnValue(keyColumn);
    }

    /**
     * Method responsible to convert objects to a valid FormKeyRelational instance.
     *
     * This method is intended to be called by {@link FormKeyManager}.
     *
     * @param objectValueToBeConverted
     *            non-null object to be converted
     * @return a valid FormKeyRelational instance
     */
    @SuppressWarnings("unchecked")
    public static FormKeyRelational convertToKey(Object objectValueToBeConverted) {
        if (objectValueToBeConverted == null) {
            throw new SingularFormPersistenceException("Null value cannot be converted to a valid FormKey.");
        } else if (objectValueToBeConverted instanceof FormKeyRelational) {
            return (FormKeyRelational) objectValueToBeConverted;
        } else if (objectValueToBeConverted instanceof HashMap<?, ?>) {
            return new FormKeyRelational((HashMap<String, Object>) objectValueToBeConverted);
        } else if (objectValueToBeConverted instanceof String) {
            return new FormKeyRelational((String) objectValueToBeConverted);
        }
        throw new SingularFormPersistenceException("The given value cannot be converted to a valid FormKey.")
                .add("value", objectValueToBeConverted).add("value type", objectValueToBeConverted.getClass());
    }

    @Override
    protected HashMap<String, Object> parseValuePersistenceString(String persistenceString) {
        HashMap<String, Object> result = new HashMap<>();
        String[] pairs = persistenceString.split(SERIALIZATION_SEPARATOR);
        for (String pair : pairs) {
            String[] parts = pair.split("\\$", 3);
            result.put(parts[0], columnValue(parts[1], parts[2]));
        }
        return result;
    }

    @Override
    public String toStringPersistence() {
        StringJoiner sj = new StringJoiner(SERIALIZATION_SEPARATOR);
        getValue().keySet().forEach(
                column -> sj.add(column + "$" + className(getValue().get(column)) + "$" + getValue().get(column)));
        return sj.toString();
    }

    private Object columnValue(String className, String value) {
        try {
            return Class.forName(resolveClassName(className)).getConstructor(String.class).newInstance(value);
        } catch (ReflectiveOperationException e) {
            SingularFormPersistenceException ex = new SingularFormPersistenceException(
                    "A column value defined in FormKey cannot be deserialized.", e);
            ex.add("className", className).add("value", value);
            throw ex;
        }
    }

    private String className(Object value) {
        return value.getClass().getName().replace(IMPLICIT_JAVA_PACKAGE, "");
    }

    private String resolveClassName(String className) {
        return className.contains(".") ? className : IMPLICIT_JAVA_PACKAGE + className;
    }
}


text:
package org.gradle.tooling.internal.protocol.events;

/**
 * DO NOT CHANGE THIS INTERFACE. It is part of the cross-version protocol.
 *
 * @since 2.5
 */
public interface InternalFailureResult extends InternalOperationResult {
}


text:
.PHONY: $(shell find * -type d -depth 0)

PREFIX = onedata-makefile-test-release

cross-support-job-1p: onedata-1p
cross-support-job-1p: build-cross-support-job-1p

cross-support-job-3p: onedata-3p
cross-support-job-3p: build-cross-support-job-3p

onedata-1p: onedata-chart-utils oneprovider onezone onedata-cli oneclient
onedata-1p: build-onedata-1p

onedata-3p: onedata-chart-utils oneprovider onezone onedata-cli oneclient
onedata-3p: build-onedata-3p

onedata: onedata-chart-utils oneprovider onezone onedata-cli oneclient
onedata: build-onedata

onedata-cli: onedata-chart-utils
onedata-cli: build-onedata-cli

onezone: onedata-chart-utils
onezone: build-onezone

oneprovider: onedata-chart-utils volumes
oneprovider: build-oneprovider

oneclient: onedata-chart-utils
oneclient: build-oneclient

test: test-onedata-chart-utils test-volume-s3 test-volume-ceph test-volume-nfs test-oneclient test-oneprovider test-onezone test-onedata-cli test-onedata test-onedata-3p test-cross-support-job-3p

#volumes
volumes: volume-s3 volume-nfs volume-ceph
volume-s3: onedata-chart-utils build-volume-s3
volume-nfs: onedata-chart-utils build-volume-nfs
volume-ceph: onedata-chart-utils build-volume-ceph

onedata-chart-utils: build-onedata-chart-utils

volumes-test: test-volume-s3 test-volume-ceph test-volume-nfs
helm-test-volumes: helm-test-volume-s3 helm-test-volume-ceph helm-test-volume-nfs

build-%:
	if [ -f $*/requirements.yaml ]; then helm dependency update $*; fi
	helm package $*

install-%:
	if [ -f $*/requirements.yaml ]; then helm dependency update $*; fi
	helm install $*

test-%: build-onedata-chart-utils
	helm dependency update $*
	helm lint --strict --debug $*
	helm install --dry-run  --debug $*

helm-test-%:
	if [ ! -f $*/templates/test.yaml ]; then helm install $* --name $(PREFIX)-$* ; fi
	if [ ! -f $*/templates/test.yaml ]; then helm test --cleanup $(PREFIX)-$* ; fi
	if [ ! -f $*/templates/test.yaml ]; then helm delete --purge $(PREFIX)-$* ; fi

clean-%:
	helm delete --purge `helm ls --all -q | grep $(PREFIX)`

clean:
	if [ "`helm ls --all -q | grep $(PREFIX)`" != "" ]; then helm delete --purge `helm ls --all -q | grep $(PREFIX)`; fi
	find . -name "*.tgz" -exec rm '{}' +


text:
<?php
/**
 * ThemeEvent.php
 * avanzu-admin
 * Date: 23.02.14
 */

namespace Avanzu\AdminThemeBundle\Event;

use Symfony\Component\EventDispatcher\Event;

/**
 * Base event class to make theme related events easier to detect
 *
 */
class ThemeEvent extends Event
{
}