text:
package org.asynchttpclient.async;

import static org.asynchttpclient.async.util.TestUtils.TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET;
import static org.asynchttpclient.async.util.TestUtils.findFreePort;
import static org.asynchttpclient.async.util.TestUtils.newJettyHttpServer;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;

import java.io.IOException;
import java.net.ConnectException;
import java.util.Enumeration;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.Response;
import org.asynchttpclient.uri.Uri;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public abstract class PerRequestRelative302Test extends AbstractBasicTest {

    private final AtomicBoolean isSet = new AtomicBoolean(false);

    private class Relative302Handler extends AbstractHandler {

        public void handle(String s, Request r, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {

            String param;
            httpResponse.setContentType(TEXT_HTML_CONTENT_TYPE_WITH_UTF_8_CHARSET);
            Enumeration<?> e = httpRequest.getHeaderNames();
            while (e.hasMoreElements()) {
                param = e.nextElement().toString();

                if (param.startsWith("X-redirect") && !isSet.getAndSet(true)) {
                    httpResponse.addHeader("Location", httpRequest.getHeader(param));
                    httpResponse.setStatus(302);
                    httpResponse.getOutputStream().flush();
                    httpResponse.getOutputStream().close();
                    return;
                }
            }
            httpResponse.setStatus(200);
            httpResponse.getOutputStream().flush();
            httpResponse.getOutputStream().close();
        }
    }

    @BeforeClass(alwaysRun = true)
    public void setUpGlobal() throws Exception {
        port1 = findFreePort();
        port2 = findFreePort();
        server = newJettyHttpServer(port1);

        server.setHandler(new Relative302Handler());
        server.start();
        logger.info("Local HTTP server started successfully");
    }

    @Test(groups = { "online", "default_provider" })
    // FIXME threadsafe
    public void runAllSequentiallyBecauseNotThreadSafe() throws Exception {
        redirected302Test();
        notRedirected302Test();
        relativeLocationUrl();
        redirected302InvalidTest();
    }

    // @Test(groups = { "online", "default_provider" })
    public void redirected302Test() throws Exception {
        isSet.getAndSet(false);
        try (AsyncHttpClient c = getAsyncHttpClient(null)) {
            Response response = c.prepareGet(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", "http://www.microsoft.com/").execute().get();

            assertNotNull(response);
            assertEquals(response.getStatusCode(), 200);

            String anyMicrosoftPage = "http://www.microsoft.com[^:]*:80";
            String baseUrl = getBaseUrl(response.getUri());

            assertTrue(baseUrl.matches(anyMicrosoftPage), "response does not show redirection to " + anyMicrosoftPage);
        }
    }

    // @Test(groups = { "online", "default_provider" })
    public void notRedirected302Test() throws Exception {
        isSet.getAndSet(false);
        AsyncHttpClientConfig cg = new AsyncHttpClientConfig.Builder().setFollowRedirect(true).build();
        try (AsyncHttpClient c = getAsyncHttpClient(cg)) {
            Response response = c.prepareGet(getTargetUrl()).setFollowRedirect(false).setHeader("X-redirect", "http://www.microsoft.com/").execute().get();
            assertNotNull(response);
            assertEquals(response.getStatusCode(), 302);
        }
    }

    private String getBaseUrl(Uri uri) {
        String url = uri.toString();
        int port = uri.getPort();
        if (port == -1) {
            port = getPort(uri);
            url = url.substring(0, url.length() - 1) + ":" + port;
        }
        return url.substring(0, url.lastIndexOf(":") + String.valueOf(port).length() + 1);
    }

    private static int getPort(Uri uri) {
        int port = uri.getPort();
        if (port == -1)
            port = uri.getScheme().equals("http") ? 80 : 443;
        return port;
    }

    // @Test(groups = { "standalone", "default_provider" })
    public void redirected302InvalidTest() throws Exception {
        isSet.getAndSet(false);
        try (AsyncHttpClient c = getAsyncHttpClient(null)) {
            // If the test hit a proxy, no ConnectException will be thrown and instead of 404 will be returned.
            Response response = c.preparePost(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", String.format("http://127.0.0.1:%d/", port2)).execute().get();

            assertNotNull(response);
            assertEquals(response.getStatusCode(), 404);
        } catch (ExecutionException ex) {
            assertEquals(ex.getCause().getClass(), ConnectException.class);
        }
    }

    // @Test(groups = { "standalone", "default_provider" })
    public void relativeLocationUrl() throws Exception {
        isSet.getAndSet(false);

        try (AsyncHttpClient c = getAsyncHttpClient(null)) {
            Response response = c.preparePost(getTargetUrl()).setFollowRedirect(true).setHeader("X-redirect", "/foo/test").execute().get();
            assertNotNull(response);
            assertEquals(response.getStatusCode(), 302);
            assertEquals(response.getUri().toString(), getTargetUrl());
        }
    }
}


text:
// Copyright 2019 Google LLC
// Licensed 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.

/*! THIS FILE IS AUTO-GENERATED */

import {AuthPlus, getAPI, GoogleConfigurable} from 'googleapis-common';
import {securitycenter_v1} from './v1';
import {securitycenter_v1beta1} from './v1beta1';
import {securitycenter_v1p1alpha1} from './v1p1alpha1';

export const VERSIONS = {
  v1: securitycenter_v1.Securitycenter,
  v1beta1: securitycenter_v1beta1.Securitycenter,
  v1p1alpha1: securitycenter_v1p1alpha1.Securitycenter,
};

export function securitycenter(version: 'v1'): securitycenter_v1.Securitycenter;
export function securitycenter(
  options: securitycenter_v1.Options
): securitycenter_v1.Securitycenter;
export function securitycenter(
  version: 'v1beta1'
): securitycenter_v1beta1.Securitycenter;
export function securitycenter(
  options: securitycenter_v1beta1.Options
): securitycenter_v1beta1.Securitycenter;
export function securitycenter(
  version: 'v1p1alpha1'
): securitycenter_v1p1alpha1.Securitycenter;
export function securitycenter(
  options: securitycenter_v1p1alpha1.Options
): securitycenter_v1p1alpha1.Securitycenter;
export function securitycenter<
  T =
    | securitycenter_v1.Securitycenter
    | securitycenter_v1beta1.Securitycenter
    | securitycenter_v1p1alpha1.Securitycenter
>(
  this: GoogleConfigurable,
  versionOrOptions:
    | 'v1'
    | securitycenter_v1.Options
    | 'v1beta1'
    | securitycenter_v1beta1.Options
    | 'v1p1alpha1'
    | securitycenter_v1p1alpha1.Options
) {
  return getAPI<T>('securitycenter', versionOrOptions, VERSIONS, this);
}

const auth = new AuthPlus();
export {auth};

redpajama_set_name: RedPajamaGithub


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Cake.Scripting.Abstractions;
using Cake.Scripting.Abstractions.Models;
using Cake.Scripting.Transport.Serialization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Cake.Scripting.Transport.Tcp.Client
{
    public sealed class ScriptGenerationClient : IScriptGenerationService, IDisposable
    {
        private readonly ManualResetEvent _initializedEvent = new ManualResetEvent(false);
        private readonly object _sendReceiveLock = new object();
        private readonly TcpListener _listener;
        private readonly IScriptGenerationProcess _process;
        private readonly CancellationTokenSource _cancellationTokenSource;
        private readonly ILogger _logger;
        private BinaryWriter _writer;
        private BinaryReader _reader;
        private NetworkStream _stream;

        public ScriptGenerationClient(string serverExecutablePath, string workingDirectory, ILoggerFactory loggerFactory)
            : this(new ScriptGenerationProcess(serverExecutablePath, loggerFactory), workingDirectory, loggerFactory)
        {
        }

        public ScriptGenerationClient(IScriptGenerationProcess process, string workingDirectory, ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory?.CreateLogger(typeof(ScriptGenerationClient)) ?? NullLogger.Instance;
            _process = process ?? throw new ArgumentNullException(nameof(process));
            _listener = new TcpListener(IPAddress.Loopback, 0);
            _listener.Start();
            _cancellationTokenSource = new CancellationTokenSource();

            RunAsync(_cancellationTokenSource.Token).ConfigureAwait(false);

            var port = ((IPEndPoint)_listener.LocalEndpoint).Port;

            _process.Start(port, workingDirectory);
        }

        public CakeScript Generate(FileChange fileChange)
        {
            _initializedEvent.WaitOne();

            lock (_sendReceiveLock)
            {
                // Send
                _logger.LogDebug("Sending request to server");
                FileChangeSerializer.Serialize(_writer, fileChange, Constants.Protocol.Latest);
                _writer.Flush();

                while (!_stream.DataAvailable)
                {
                    Task.Delay(10).Wait();
                }

                // Receive
                _logger.LogDebug("Received response from server");
                return CakeScriptSerializer.Deserialize(_reader);
            }
        }

        private async Task RunAsync(CancellationToken cancellationToken)
        {
            _logger.LogDebug("Waiting for server to connect");
            using (var client = await _listener.AcceptTcpClientAsync())
            {
                _logger.LogDebug("Server connected");
                _stream = client.GetStream();
                _reader = new BinaryReader(_stream);
                _writer = new BinaryWriter(_stream);
                _initializedEvent.Set();

                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Delay(100, cancellationToken);
                }
            }
            _logger.LogDebug("Shutting down");
            _initializedEvent.Reset();

            _listener.Stop();
        }

        public void Dispose()
        {
            _cancellationTokenSource.Cancel(false);
            _process.Dispose();
            _stream?.Dispose();
            _writer?.Dispose();
            _reader?.Dispose();
        }
    }
}


text:
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}

-- |
-- Module      : Database.HDBC.Schema.SQLServer
-- Copyright   : 2013 Shohei Murayama
-- License     : BSD3
--
-- Maintainer  : shohei.murayama@gmail.com
-- Stability   : experimental
-- Portability : unknown
module Database.HDBC.Schema.SQLServer (
  driverSQLServer,
  ) where

import qualified Database.Relational.Schema.SQLServerSyscat.Columns as Columns
import qualified Database.Relational.Schema.SQLServerSyscat.Types as Types
import qualified Language.Haskell.TH.Lib.Extra as TH

import Data.Map (fromList)
import Data.Maybe (catMaybes)
import Database.HDBC (IConnection, SqlValue)
import Database.HDBC.Record.Query (runQuery')
import Database.HDBC.Record.Persistable ()
import Database.HDBC.Schema.Driver (TypeMap, Driver, getFieldsWithMap, getPrimaryKey, emptyDriver)
import Database.Record.TH (makeRecordPersistableWithSqlTypeDefaultFromDefined)
import Database.Relational.Schema.SQLServer (columnTypeQuerySQL, getType, normalizeColumn,
                                            notNull, primaryKeyQuerySQL)
import Database.Relational.Schema.SQLServerSyscat.Columns (Columns)
import Database.Relational.Schema.SQLServerSyscat.Types (Types)
import Language.Haskell.TH (TypeQ)

$(makeRecordPersistableWithSqlTypeDefaultFromDefined
  [t| SqlValue |] ''Columns)

$(makeRecordPersistableWithSqlTypeDefaultFromDefined
  [t| SqlValue |] ''Types)

logPrefix :: String -> String
logPrefix = ("SQLServer: " ++)

putLog :: String -> IO ()
putLog = putStrLn . logPrefix

compileErrorIO :: String -> IO a
compileErrorIO = TH.compileErrorIO . logPrefix

getPrimaryKey' :: IConnection conn
               => conn
               -> String
               -> String
               -> IO [String]
getPrimaryKey' conn scm tbl = do
    prims <- catMaybes `fmap` runQuery' conn primaryKeyQuerySQL (scm,tbl)
    let primColumns = map normalizeColumn prims
    putLog $ "getPrimaryKey: keys=" ++ show primColumns
    return primColumns

getFields' :: IConnection conn
           => TypeMap
           -> conn
           -> String
           -> String
           -> IO ([(String, TypeQ)], [Int])
getFields' tmap conn scm tbl = do
    rows <- runQuery' conn columnTypeQuerySQL (scm, tbl)
    case rows of
      [] -> compileErrorIO
            $ "getFields: No columns found: schema = " ++ scm ++ ", table = " ++ tbl
      _  -> return ()
    let columnId ((cols,_),_) = Columns.columnId cols - 1
    let notNullIdxs = map (fromIntegral . columnId) . filter notNull $ rows
    putLog
        $ "getFields: num of columns = " ++ show (length rows)
        ++ ", not null columns = " ++ show notNullIdxs
    let getType' rec@((_,typs),typScms) = case getType (fromList tmap) rec of
          Nothing -> compileErrorIO
                     $ "Type mapping is not defined against SQLServer type: "
                     ++ typScms ++ "." ++ Types.name typs
          Just p  -> return p
    types <- mapM getType' rows
    return (types, notNullIdxs)

driverSQLServer :: IConnection conn => Driver conn
driverSQLServer =
    emptyDriver { getFieldsWithMap = getFields' }
                { getPrimaryKey    = getPrimaryKey' }


text:
title: 6 - Déployer
category: Machine Learning, Processus
---

Une fois que le modèle est fini, ce qu'on en fait dépend du but pour lequel il a été développé:

1. Analyses ponctuelles: pipeline
   On a développé un modèle pour analyser les données. Certains projets requièrement de répéter le processus à plusieurs reprises, lorsqu'on obtient de nouvelles données par exemple. Dans ce cas, automatiser l'apprentissage va permettre de gagner du temps: créer une *pipeline* pour automatiser le preprocessing et traitement des données.

    [Notebook: Pipelines](https://www.kaggle.com/alexisbcook/pipelines)

2. Business analysis: rapport & visualisations
   Toujours dans la même veine, si l'analyse a été demandé par un client, alors il faut présenter les résultats: formuler les hypothèses et les résultats observés en language humain, illustrer avec des graphiques faciles à comprendre pour les non-tech.

3. Fonctionnalité: application
   On a développé un modèle pour être utilisé dans le cadre d'une application.
   Dans ce cas, on exporte le modèle et

   * soit on crée une application ou ajoute la fonctionnalité à une application Python existante (typiquement, s'appuie le framework Flask ou Django).

   * soit on crée un webservice, qui pourra être requêté par des applications non Python (typiquement, uvicorn pour gérer les requêtes HTTP et FastAPI pour créer une API rapidement).

   Exemples:
   ① [Entraîner & exporter un modèle](https://github.com/a-mt/fcc-sms-text-classification/blob/deploy/fcc_sms_text_classification.ipynb)
   ② [Créer un webservice avec FastAPI](https://github.com/a-mt/fcc-sms-text-classification/blob/deploy/FastAPI.ipynb)
   ③ [Application Flask](https://github.com/yoke2/rps_tf2_flask_app)

* Déployer des applications de Machine Learning en ligne est un domaine d'expertise à part entière — particulièrement si l'application demande des resources importantes (GPU, requêtes fréquentes, etc): MLOps.

  Pour aller plus loin:
  [Running Deep Learning Algorithms as a Service](https://towardsdatascience.com/serving-deep-learning-algorithms-as-a-service-6aa610368fde)


text:
select ts, name, value, upid
from counter
inner join process_counter_track
  on counter.track_id = process_counter_track.id
where name like 'mem.mm.%'
order by ts
limit 40


text:
'use strict';

const Maki = require('maki');
const config = require('../config/maki');

module.exports = Doorman => {
  // delicious maki...
  Doorman.maki = new Maki(config);
  Doorman.maki.use(require('maki-client-level'));
  Doorman.maki.start();
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Young & Wood, Aust. Syst. Bot. 10(6): 965 (1997)

#### Original name
Hygrocybe dorothyae A.M. Young

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using AH.DRUGS.MODEL;
using AH.OPD.BLL;
using AH.DTMS.MODEL;
using AH.PRMS.BLL;
using AH.PRMS.MODEL;
using AH.PHRMS.BLL;
using AH.PHRMS.MODEL;
using AH.IPDShared.MODEL;
using AH.IPDShared.BLL;
using AH.NWMS.MODEL;
using AH.OPD.MODEL;
using AH.INVMS.MODEL;
using AH.INVMS.BLL;

namespace AH.NWMS.Facade
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "INWMSWS" in both code and config file together.
    [ServiceContract]
    public interface INWMSWS
    {

    //    [OperationContract]
    //    string VerifyInPatient(string Regno);
    //    [OperationContract]
    //    Patient GetPatreg(string Regno);
    //    [OperationContract]
    //    List<DrugDose> GetMedicineListOPD(string MedicineName, string PatAge);

        [OperationContract]
        IPDDoctor GetDoctorsDetails(string DocID);

        [OperationContract]
        List<DrugDose> GetDrugs(string age, string name, string drugID);

        //[OperationContract(Name = "GetDeptGroupWise")]
        //Dictionary<string, string> GetDepartmentsetup(string type, string deptgr);

        [OperationContract(Name = "GetDiagnGrpDeptWise")]
        Dictionary<string, string> GetDiagnGrp(string type, string department);

        [OperationContract]
        Dictionary<string, string> GetDeptUnitDic(string deptgrp, string deptid);

        [OperationContract]
        Dictionary<string, string> GetOPDDoctorsDict(string deptID, string UnitID);

        [OperationContract]
        string GetDrRoom(string DocID);

        [OperationContract]
        List<TestMain> GetTestMain(string department, string group);

        [OperationContract]
        List<TestSub> GetTestDetails(string deptid, string group, string main);

        [OperationContract]
        List<DrugDose> GetMedicineListOPD(string MedicineName, string PatAge);

        [OperationContract]
        List<DrugDose> GetDrugDoseList(string patage);

        [OperationContract]
        InPatient GetAdmittedPatient(string RegistrationNo);

        [OperationContract]
        short SaveNurseRequisition(NurseRequisition nrq);

        [OperationContract]
        string VerifyInPatient(string regNo);

        [OperationContract]
        List<DrugDose> GetDrugDoseListForAll();

        [OperationContract]
        InPatient GetPatRegID(string bedID);

        [OperationContract]
        short ChangeBedStatus(Bed bdst);

        [OperationContract]
        List<NWMSReceiveRequisition> ReceiveRequisition(string regId);
        [OperationContract]
        List<NWMSReceiveRequisition> ReceiveReqTest(string regId);

        [OperationContract]
        short SaveDrugReqRcv(NWMSReceiveRequisition DrugRcv);

        [OperationContract]
        List<TestSub> GetTestDets(string deptid, string group, string main);

        [OperationContract]
        List<DrugIssue> GetIssueDetails(string issueID);

        [OperationContract]
        short CheckIssueIDforRcv(string issue_id);
        [OperationContract]
        short VerifyIssueID(string issue_id, string Reg_id);

        [OperationContract]
        Dictionary<string, string> GetDepartmentsetupDic(string type, string deptgr);

       /* [OperationContract]
        OPDDoctorCallQ GetPatHealthInfo(string Hcn);*/
        [OperationContract]
        short AdviceSetupInsert(OPDAdvice oAdvice);
        [OperationContract]
        short SaveIPDPrescription(IPDPrescription prs);
        [OperationContract]
        short EditIPDPrescription(IPDPrescription Iprs);

        [OperationContract]
        List<Complaints> GetComplaints();

        [OperationContract]
        List<ClinicalDiagnosis> GetClinicalDiagnosis();

        [OperationContract]
        Dictionary<string, string> getConsumptionForm(string type);

        [OperationContract]
        List<DrugDose> GetDrugDoseByDrugIPD(string patage, string drugname);
        [OperationContract]
        List<DrugDose> GetDrugDoseByGroupNameIPD(string patage, string groupname);

        [OperationContract]
        List<DrugDose> GetDrugDoseListByDrugName(string patage, string groupname);

        [OperationContract]
        List<DrugDose> GetDrugDoseListByGroupName(string patage, string groupname);

        [OperationContract]
        List<OPDAdvice> AdviceSetupGET();

        [OperationContract]
        List<IPDPrescription> GetPrescribedDrugs(string regId);

        [OperationContract]
        List<IPDPrescription> GetPrescribedTests(string regId);

        [OperationContract]
        List<TestFee> GetAllMappingTest(string mode, string FeeCatagory);

        [OperationContract(Name = "GetFeecatDict")]
        Dictionary<string, string> GetFeecats(string type);
        [OperationContract]
        List<DrugDose> GetAllProvidedDrugs(string regID);

        [OperationContract]
        short InsertIPDDoctors(IPDDoctor oIPDDOc);

        [OperationContract]
        Dictionary<string, string> GetDeptGroupDicByType(string type);

        [OperationContract]
        Dictionary<string, string> GetOPDDoctorDict(string DeptID, string UnitID);

        [OperationContract]
        List<IPDDoctor> GetIPDDoctorsList();

        [OperationContract]
        List<IPDDoctor> GetIPDVisitingFeeDetails(string reg_ID);

        [OperationContract]
        short CancelIPDDrugs(NurseRequisition nrq);
        [OperationContract]

        short SaveDischargeAdvices(IPDPrescription prs);

        [OperationContract]
        Dictionary<string, string> GetIPDDoctorsDict(string deptID, string UnitID);

        [OperationContract]
        short IsDischargeAdvCreated(string regId);
        [OperationContract]
        IPDPrescription GetDischargeAdvicesForEdit(string regId);
        [OperationContract]
        short EditDischargeAdvices(IPDPrescription Iprs);

        [OperationContract]
        List<GroupDetails> GetGroupByMajorGrp(string strtype, string majorgrp);
       // [OperationContract]
       // List<ItemMaster> GetItemMasterByGroup(string grpid);
       // [OperationContract]
       // List<ItemMaster> GetItemStockForNS(string strid, string grpid);
        [OperationContract]
        List<ItemOrder> GetItemStockForNS(string grpid, string strid);

        [OperationContract]
        short IssueFromNurseStn(NurseRequisition nrq);

        [OperationContract]
        IPDPrescription GetIPDPrescriptionForEdit(string visit_no, string Reg_ID);

        [OperationContract]
        short IsDrugReqDone(string visit_id, string drug_id);

#region Report
        [OperationContract]
        List<NWMSReportRO> GetDischargeSummary(string reg_ID);

        [OperationContract]
        List<NWMSReportRO> DischargeAdvice(string reg_ID);

#endregion Report
    }
}


text:
cage
====

*A python package for analyzing cage molecules.*

Usage
-----

Still very much in development. We're currently working on providing a CLI program to make
the package more user friendly.


text:
var EventEmitter = require('events').EventEmitter;

var _ = require('lodash');
var minimist = require('minimist');
var flatten = require('flat-arguments');
var async = require('async');

var commandFactory = require('./command');
var commands = require('./commands');
var flags = require('./flags');
var flagFactory = require('./flag');
var wrappers = require('./wrappers');
var parseCommand = require('./utils/parse-command');
var extendFlags = require('./utils/extend-flags');
var bindAll = require('./utils/bind-all-fns');
var flagRunner = require('./utils/flag-runner');

function parseArgv (processArgv, rawFlags) {

  // WIP: parse flags with defaults
  var argvOptions = {
    alias: {},
    default: {}
  };

  rawFlags.forEach(function (flag) {

    var names = flag.name().map(flagFactory.unprefix);
    var baseName = names[0];
    var aliases = [];

    if (names.length > 1) {
      aliases = _.rest(names);
    }

    argvOptions.alias[baseName] = aliases;
  });

  return minimist(_.slice(processArgv, 2), argvOptions);
}

var Cli = exports.Cli = function (options) {

  this.process = {};
  this.attributes = {};
  this.options = options || {};
  this.internals = {
    commands: commands(),
    flags: flags(),
    beforeAlls: wrappers(),
    afterAlls: wrappers(),
    decorators: {},
    plugins: []
  };

  _.extend(this, EventEmitter.prototype);
};

module.exports = function createCli (options) {
  return new Cli(options);
};

// Instantiators

Cli.prototype.command = function () {

  var names = flatten(arguments);
  var command = commandFactory(names);

  this.internals.commands.add(command);

  return this.findCommand(names);
};

Cli.prototype.flag = function () {

  var names = flatten(arguments);
  var flag = flagFactory(names);

  this.internals.flags.add(flag);

  return this.findFlag(names);
};

Cli.prototype.beforeAll = function () {

  this.internals.beforeAlls.add(bindAll(this, arguments));

  return this;
};

Cli.prototype.afterAll = function () {

  this.internals.afterAlls.add(bindAll(this, arguments));

  return this;
};

Cli.prototype.default = function () {

  var command = commandFactory();
  this.internals.defaultCommand = this.internals.defaultCommand || command;

  return command;
};

Cli.prototype.run = function (processArgv, runDone) {

  runDone = runDone || function () {};

  var self = this;
  var command = parseCommand(minimist(_.slice(processArgv, 2)));

  // Set up decorators
  command.decorators = this.internals.decorators.command;

  // Execute command, task, or nothing
  var commandToRun =
    self.findCommandTask(command.name, command.task) ||
    self.findCommand(command.name);

  // Parse all falgs with aliases, defaults, etc.
  this.argv = parseArgv(
    processArgv,
    extendFlags(
      self.internals.flags.all(),
      commandToRun ? commandToRun.internals.flags.all() : []
    )
  );
  command.flags = _.omit(this.argv);

  // Set process data
  this.process = Object.freeze({
    command: command.name,
    task: command.task,
    data: command.data,
    flags: _.omit(this.argv, '_')
  });

  // Run everything
  async.series({
    beforeAlls: function (done) {

      self.runBeforeAlls(command.data, command.flags, done);
    },
    flags: function (done) {

      var commandFlags;

      // If command that is getting run has flags that match
      // global flags, we need to run those too
      if (commandToRun) {
        commandFlags = commandToRun.internals.flags.all();
      }

      self.runFlags(command.flags, done, commandFlags);
    },
    command: function (done) {

      self.internals.commands.run(command, function (err) {

        // Try running default command
        if (err && self.internals.defaultCommand) {
          command.data = self.argv._;
          return self.internals.defaultCommand.run(command.data, command.flags, done);
        }

        // Finish up no matter what
        done();
      });
    },
    afterAlls: function (done) {

      self.runAfterAlls(command.data, command.flags, done);
    }
  }, runDone);

  return this;
};

// Runners

Cli.prototype.runFlags = function (flagMap, done, _commandFlags_) {

  // Combine global and command-level flags
  var flgs = extendFlags(this.internals.flags.all(), _commandFlags_);

  // Run flags from flag map
  flagRunner(flagMap, flgs, done);
};

Cli.prototype.runFlag = function (name, data, done) {

  done = done || function () {};

  var flag = this.findFlag(name);

  if (!flag) {
    throw new Error('Flag does not exist');
  }

  flag.run(data, done);

  return this;
};

Cli.prototype.runBeforeAlls = function (data, flgs, done) {

  this.internals.beforeAlls.run(data, flgs, done);

  return this;
};

Cli.prototype.runAfterAlls = function (data, flgs, done) {

  this.internals.afterAlls.run(data, flgs, done);

  return this;
};

// Finders

Cli.prototype.findCommand = function () {

  return this.internals.commands.findByName(arguments);
};

Cli.prototype.findCommandTask = function (commandName, taskName) {

  var cmd = this.findCommand(commandName);

  if (!cmd) {
    return;
  }

  return cmd.findTask(taskName);
};

Cli.prototype.findFlag = function () {

  return this.internals.flags.findByName(arguments);
};

Cli.prototype.decorate = function (target, name, handler) {

  if (target === 'flag') {
    flagFactory.decorators.push({
      name: name,
      handler: handler
    });
  }

  if (target === 'command') {
    commandFactory.decorators.push({
      name: name,
      handler: handler
    });
  }

  return this;
};

Cli.prototype.set = function (name, value) {

  if (_.isObject(name)) {

    _.each(name, function (val, key) {

      this.attributes[key] = val;
    }, this);
  }
  else {

    this.attributes[name] = value;
  }

  return this;
};

Cli.prototype.get = function (name) {

  return this.attributes[name];
};

Cli.prototype.register = function (plugins, done) {

  var self = this;

  done = done || function () {};

  // Force object to array
  if (plugins.register) {
    plugins = [plugins];
  }

  async.eachSeries(plugins, function (plugin, doneRegistering) {

    plugin.register(self, plugin.options || {}, doneRegistering);
  }, done);

  return this;
};


text:
package org.netbeans.modules.atom.electron.actions;

import org.netbeans.modules.atom.electron.glue.Preferences;
import org.netbeans.modules.atom.electron.glue.CommandType;

/**
 * Defines thy type of the required command with additional preferences.
 *
 * @author spindizzy
 */
class DefaultCommandType implements CommandType{

    private Preferences preferences;

    private Type type;

    public DefaultCommandType(Type type) {
        this(type, null);
    }

    public DefaultCommandType(Type type, Preferences preferences) {
        this.type = type;
        this.preferences = preferences;
    }

    @Override
    public Preferences getPreferences() {
        return preferences;
    }

    @Override
    public Type getType() {
        return type;
    }
}


text:
package org.apache.accumulo.manager.tableOps.clone;

import org.apache.accumulo.core.client.NamespaceNotFoundException;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.clientImpl.Namespaces;
import org.apache.accumulo.core.clientImpl.thrift.TableOperation;
import org.apache.accumulo.core.util.tables.TableNameUtil;
import org.apache.accumulo.fate.Repo;
import org.apache.accumulo.manager.Manager;
import org.apache.accumulo.manager.tableOps.ManagerRepo;
import org.apache.accumulo.manager.tableOps.Utils;

class CloneZookeeper extends ManagerRepo {

  private static final long serialVersionUID = 1L;

  private CloneInfo cloneInfo;

  public CloneZookeeper(CloneInfo cloneInfo, ClientContext context)
      throws NamespaceNotFoundException {
    this.cloneInfo = cloneInfo;
    this.cloneInfo.namespaceId = Namespaces.getNamespaceId(context,
        TableNameUtil.qualify(this.cloneInfo.tableName).getFirst());
  }

  @Override
  public long isReady(long tid, Manager environment) throws Exception {
    long val = 0;
    if (!cloneInfo.srcNamespaceId.equals(cloneInfo.namespaceId))
      val += Utils.reserveNamespace(environment, cloneInfo.namespaceId, tid, false, true,
          TableOperation.CLONE);
    val +=
        Utils.reserveTable(environment, cloneInfo.tableId, tid, true, false, TableOperation.CLONE);
    return val;
  }

  @Override
  public Repo<Manager> call(long tid, Manager environment) throws Exception {
    Utils.getTableNameLock().lock();
    try {
      // write tableName & tableId to zookeeper

      Utils.checkTableDoesNotExist(environment.getContext(), cloneInfo.tableName, cloneInfo.tableId,
          TableOperation.CLONE);

      environment.getTableManager().cloneTable(cloneInfo.srcTableId, cloneInfo.tableId,
          cloneInfo.tableName, cloneInfo.namespaceId, cloneInfo.propertiesToSet,
          cloneInfo.propertiesToExclude);
      environment.getContext().clearTableListCache();

      return new CloneMetadata(cloneInfo);
    } finally {
      Utils.getTableNameLock().unlock();
    }
  }

  @Override
  public void undo(long tid, Manager environment) throws Exception {
    environment.getTableManager().removeTable(cloneInfo.tableId);
    if (!cloneInfo.srcNamespaceId.equals(cloneInfo.namespaceId))
      Utils.unreserveNamespace(environment, cloneInfo.namespaceId, tid, false);
    Utils.unreserveTable(environment, cloneInfo.tableId, tid, true);
    environment.getContext().clearTableListCache();
  }

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../../../libc/constant.RTA_NEWDST.html">

Redirecting to ../../../../../libc/constant.RTA_NEWDST.html...


text:
'use strict';
const settings = require('electron-settings');
const {touchFileSync} = require('./util');

touchFileSync(settings.file());

settings.setAll({
  alwaysOnTop: settings.get('alwaysOnTop', false),
  autoLaunch: settings.get('autoLaunch', false),
  autoNightMode: settings.get('autoNightMode', false),
  disableAutoUpdateCheck: settings.get('disableAutoUpdateCheck', false),
  hideTray: settings.get('hideTray', false),
  lastWindowState: {
    x: settings.get('lastWindowState.x'),
    y: settings.get('lastWindowState.y'),
    width: settings.get('lastWindowState.width'),
    height: settings.get('lastWindowState.height')
  },
  launchMinimized: settings.get('launchMinimized', false),
  menuBarHidden: settings.get('menuBarHidden', false),
  mode: {
    black: settings.get('mode.black', false),
    dark: settings.get('mode.dark', false),
    sepia: settings.get('mode.sepia', false)
  },
  requestExitConfirmation: settings.get('requestExitConfirmation', true),
  sideBarHidden: settings.get('sideBarHidden', false),
  updateCheckPeriod: settings.get('updateCheckPeriod', '4'),
  useGlobalShortcuts: settings.get('useGlobalShortcuts', false),
  zoomFactor: settings.get('zoomFactor', 1)
});

module.exports = settings;


text:
package org.jenkins.ci.plugins.jobimport.model;

import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.security.ACL;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;

import java.util.Collections;

public class JenkinsSite extends AbstractDescribableImpl<JenkinsSite> {

    private final String name;
    private final String url;
    private String defaultCredentialsId;

    @DataBoundConstructor
    public JenkinsSite(String name, String url) {
        this.name = name;
        this.url = url;
    }

    @DataBoundSetter
    public void setDefaultCredentialsId(String defaultCredentialsId) {
        this.defaultCredentialsId = defaultCredentialsId;
    }

    public String getDefaultCredentialsId() {
        return defaultCredentialsId;
    }

    public String getUrl() {
        return url;
    }

    public String getName() {
        return name;
    }

    @Extension
    public static final class DescriptorImpl extends Descriptor<JenkinsSite> {
        @Override
        public String getDisplayName() {
            return "";
        }
        public ListBoxModel doFillDefaultCredentialsIdItems() {
            return new StandardListBoxModel()
                    .includeEmptyValue()
                    .includeMatchingAs(
                            Jenkins.getAuthentication(),
                            Jenkins.getInstance(),
                            StandardUsernamePasswordCredentials.class,
                            Collections.<DomainRequirement>emptyList(),
                            CredentialsMatchers.always()
                    ).includeMatchingAs(
                            ACL.SYSTEM,
                            Jenkins.getInstance(),
                            StandardUsernamePasswordCredentials.class,
                            Collections.<DomainRequirement>emptyList(),
                            CredentialsMatchers.always()
                    );
        }

    }

}


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">

    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="stylesheets/pygment_trac.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />

    <title>/etc/issue by kmf</title>

/etc/issue

my little nest on github

          View on GitHub

oh hai

I like shells, not seashells or cshells, more bash shells :)

$ touch "Karl_Fischer"
$ ln -s "Karl_Fischer" kmf
$ whoami kmf

I like to fiddle and tinker, if I have an itch I like to scratch ... I rarely write from scratch, but only if I met my match

seriously

My name is Karl, I stay in South Africa, Pretoria to be exact.
I love Open Source and Free\Libre Software, Follow me here or on Twitter @kmf


text:
namespace device {
namespace usb {
namespace {

class TestUsbDevice : public UsbDevice {
 public:
  TestUsbDevice(const std::string& name,
                const std::string& serial_number,
                const GURL& landing_page);

  // device::UsbDevice overrides:
  void Open(OpenCallback callback) override;

 private:
  ~TestUsbDevice() override;

  DISALLOW_COPY_AND_ASSIGN(TestUsbDevice);
};

TestUsbDevice::TestUsbDevice(const std::string& name,
                             const std::string& serial_number,
                             const GURL& landing_page)
    : UsbDevice(0x0210,
                0xff,
                0xff,
                0xff,
                0x0000,
                0x000,
                0x0100,
                base::string16(),
                base::UTF8ToUTF16(name),
                base::UTF8ToUTF16(serial_number),
                0,
                0) {
  device_info_->webusb_landing_page = landing_page;
}

void TestUsbDevice::Open(OpenCallback callback) {
  std::move(callback).Run(nullptr);
}

TestUsbDevice::~TestUsbDevice() {}

}  // namespace

DeviceManagerTest::DeviceManagerTest(UsbService* usb_service)
    : usb_service_(usb_service) {}

DeviceManagerTest::~DeviceManagerTest() {}

void DeviceManagerTest::BindReceiver(
    mojo::PendingReceiver<device::mojom::UsbDeviceManagerTest> receiver) {
  receivers_.Add(this, std::move(receiver));
}

void DeviceManagerTest::AddDeviceForTesting(
    const std::string& name,
    const std::string& serial_number,
    const std::string& landing_page,
    AddDeviceForTestingCallback callback) {
  if (usb_service_) {
    GURL landing_page_url(landing_page);
    if (!landing_page_url.is_valid()) {
      std::move(callback).Run(false, "Landing page URL is invalid.");
      return;
    }

    usb_service_->AddDeviceForTesting(
        new TestUsbDevice(name, serial_number, landing_page_url));
    std::move(callback).Run(true, "Added.");
  } else {
    std::move(callback).Run(false, "USB service unavailable.");
  }
}

void DeviceManagerTest::RemoveDeviceForTesting(
    const std::string& guid,
    RemoveDeviceForTestingCallback callback) {
  if (usb_service_)
    usb_service_->RemoveDeviceForTesting(guid);

  std::move(callback).Run();
}

void DeviceManagerTest::GetTestDevices(GetTestDevicesCallback callback) {
  std::vector<scoped_refptr<UsbDevice>> devices;
  if (usb_service_)
    usb_service_->GetTestDevices(&devices);

  std::vector<mojom::TestDeviceInfoPtr> result;
  result.reserve(devices.size());
  for (const auto& device : devices) {
    auto device_info = mojom::TestDeviceInfo::New();
    device_info->guid = device->guid();
    device_info->name = base::UTF16ToUTF8(device->product_string());
    device_info->serial_number = base::UTF16ToUTF8(device->serial_number());
    device_info->landing_page = device->webusb_landing_page();
    result.push_back(std::move(device_info));
  }
  std::move(callback).Run(std::move(result));
}

}  // namespace usb
}  // namespace device


text:
using System;
using System.Linq;
using Tt195361.Casl2Simulator.Common;
using Tt195361.Casl2Simulator.Utils;

namespace Tt195361.Casl2Simulator.Comet2
{
    /// <summary>
    /// COMET II の 8 個の汎用レジスタ (General Register) を表わします。
    /// </summary>
    internal class GeneralRegisters
    {
        #region Instance Fields
        private readonly CpuRegister[] m_grArray;
        #endregion

        /// <summary>
        /// <see cref="GeneralRegisters"/> のインスタンスを初期化します。
        /// </summary>
        internal GeneralRegisters()
        {
            m_grArray = RegisterDef.GrNames
                                   .Select((name) => new CpuRegister(name))
                                   .ToArray();
        }

        /// <summary>
        /// 指定の GR を取得します。
        /// </summary>
        /// <param name="grNumber">取得する GR を指定する値です。</param>
        /// <returns>指定の GR を返します。</returns>
        internal CpuRegister this[Int32 grNumber]
        {
            get
            {
                ArgChecker.CheckRange(grNumber, 0, RegisterDef.GrCount - 1, nameof(grNumber));
                return m_grArray[grNumber];
            }
        }

        /// <summary>
        /// それぞれの汎用レジスタの値を初期化します。
        /// </summary>
        internal void Reset()
        {
            m_grArray.ForEach((gr) => gr.Reset());
        }
    }
}


text:
#ifndef POCL_IMAGE_UTIL_H
#define POCL_IMAGE_UTIL_H

#include "pocl_cl.h"

#ifdef __GNUC__
#pragma GCC visibility push(hidden)
#endif

void origin_to_bytes (cl_mem mem, const size_t *origin, size_t *byte_offset);

POCL_EXPORT
cl_int opencl_image_type_to_index (cl_mem_object_type  image_type);

extern cl_int
pocl_check_image_origin_region (const cl_mem image,
                                const size_t *origin,
                                const size_t *region);

extern void
pocl_get_image_information (cl_channel_order  ch_order,
                            cl_channel_type   ch_type,
                            int*           host_channels,
                            int*           host_elem_size);

extern cl_int pocl_check_device_supports_image (
    cl_device_id device, const cl_image_format *image_format,
    const cl_image_desc *image_desc, cl_uint image_type_idx,
    cl_bool is_gl_texture, int *device_support);

void pocl_write_pixel_zero (void *data, const cl_uint4 input_color, int order,
                            int elem_size, int channel_type);

cl_char4 convert_char4_sat (cl_float4 x);
cl_char convert_char_sat (cl_float x);
cl_char4 convert_char4_sat_int (cl_int4 x);
cl_char convert_char_sat_int (cl_int x);
cl_uchar4 convert_uchar4_sat (cl_float4 x);
cl_uchar convert_uchar_sat (cl_float x);
cl_uchar4 convert_uchar4_sat_int (cl_uint4 x);
cl_uchar convert_uchar_sat_int (cl_uint x);

cl_short4 convert_short4_sat (cl_float4 x);
cl_short convert_short_sat (cl_float x);
cl_short4 convert_short4_sat_int (cl_int4 x);
cl_short convert_short_sat_int (cl_int x);
cl_ushort4 convert_ushort4_sat (cl_float4 x);
cl_ushort convert_ushort_sat (cl_float x);
cl_ushort4 convert_ushort4_sat_int (cl_uint4 x);
cl_ushort convert_ushort_sat_int (cl_uint x);

#ifdef __GNUC__
#pragma GCC visibility pop
#endif

#endif


text:
"""
Create an argparser from a Schema
>>>

"""

import argparse
import logging
from functools import singledispatch

from ..config import Config
from ..schema_section import SchemaSection
from ..times import DateTime, Date, Time, TimeDelta
from ..toolbox.unrepr import unrepr
from ..utils import get_validator_argument
from .. import validator as _validator
from .undefined import UNDEFINED

__author__ = "Simone Campagna"
__copyright__ = 'Copyright (c) 2015 Simone Campagna'
__license__ = 'Apache License Version 2.0'
__all__ = [
    'argument_name',
    'argument_dest',
    'update_argparser',
    'create_argparser',
    'read_namespace',
]

LOG = logging.getLogger(__name__)

def _make_fqname(fqname):
    """Make an fqname tuple"""
    if isinstance(fqname, tuple):
        return fqname
    elif fqname is None:
        return ()
    elif isinstance(fqname, str):
        return tuple(fqname.split("."))
    else:
        raise TypeError("invalid fqname {!r}".format(fqname))

def argument_name(fqname):
    """Returns the argument name"""
    return "--" + "-".join(_make_fqname(fqname))

def argument_dest(fqname):
    """Returns the argument dest"""
    return "_".join(_make_fqname(fqname))

def _argdata(validator, defaults, fqname):
    """Creates standard args, kwargs for the parser.add_argument method"""
    fqname = _make_fqname(fqname)
    argname = argument_name(fqname)
    args = (argname,)
    dest = argument_dest(fqname)
    has_doc, doc = get_validator_argument(validator, "doc")
    if not has_doc:
        doc = "set option {!r}".format(dest)
    kwargs = {
        "dest": dest,
        "help": doc,
        "metavar": fqname[-1].upper(),
        "default": UNDEFINED,
    }
    if defaults:
        has_default, default = get_validator_argument(validator, "default")
        if has_default:
            kwargs["default"] = default
    return args, kwargs

def boolean(value):
    """Converts a string to boolean"""
    value = value.lower()
    if value in {'on', 'true'}:
        return True
    elif value in {'off', 'false'}:
        return False
    else:
        try:
            return bool(int(value))
        except ValueError:
            raise ValueError("invalid bool value {!r}".format(value)) from None

class _ArgType(object):
    """Standard argument type based on validator"""
    # pylint: disable=too-few-public-methods
    def __init__(self, validator, name):
        self._validator = validator
        self._name = name
        self._gdict = {
            'DateTime': DateTime,
            'Date': Date,
            'Time': Time,
            'TimeDelta': TimeDelta,
        }

    def __call__(self, string):
        try:
            value = unrepr(string, globals_d=self._gdict)
            return self._validator.validate(name=self._name, value=value, defined=True)
        except:
            LOG.exception("argument parsing error:")
            raise ValueError(string)

    def __repr__(self):  # pragma: no cover
        return type(self._validator).__name__

@singledispatch
def _argtype(validator, name):
    """Returns the argparse argument type"""
    return _ArgType(validator, name)

@_argtype.register(_validator.Str)
@_argtype.register(_validator.StrChoice)
def _(validator, name):  # flake8: noqa
    # pylint: disable=function-redefined
    # pylint: disable=unused-argument
    """Overrides argtype for Str validator"""
    return str

@_argtype.register(_validator.DateTimeOption)
def _(validator, name):  # flake8: noqa
    # pylint: disable=function-redefined
    # pylint: disable=unused-argument
    """Overrides argtype for Str validator"""
    return DateTime

@_argtype.register(_validator.DateOption)
def _(validator, name):  # flake8: noqa
    # pylint: disable=function-redefined
    # pylint: disable=unused-argument
    """Overrides argtype for Str validator"""
    return Date

@_argtype.register(_validator.TimeOption)
def _(validator, name):  # flake8: noqa
    # pylint: disable=function-redefined
    # pylint: disable=unused-argument
    """Overrides argtype for Str validator"""
    return Time

@_argtype.register(_validator.TimeDeltaOption)
def _(validator, name):  # flake8: noqa
    # pylint: disable=function-redefined
    # pylint: disable=unused-argument
    """Overrides argtype for Str validator"""
    return TimeDelta

@_argtype.register(_validator.Bool)
def _(validator, name):  # flake8: noqa
    # pylint: disable=function-redefined
    # pylint: disable=unused-argument
    """Overrides argtype for Bool validator"""
    return boolean

@singledispatch
def _add_argument(validator, argparser, defaults, fqname):
    # pylint: disable=unused-argument
    """Adds argument(s) to argparser based on the validator"""
    pass  # raise TypeError("cannot compile validator {!r}".format(validator))

@_add_argument.register(_validator.Int)
@_add_argument.register(_validator.IntList)
@_add_argument.register(_validator.IntTuple)
@_add_argument.register(_validator.Float)
@_add_argument.register(_validator.FloatList)
@_add_argument.register(_validator.FloatTuple)
@_add_argument.register(_validator.Str)
@_add_argument.register(_validator.StrList)
@_add_argument.register(_validator.StrTuple)
@_add_argument.register(_validator.Bool)
@_add_argument.register(_validator.BoolList)
@_add_argument.register(_validator.BoolTuple)
@_add_argument.register(_validator.DateTimeOption)
@_add_argument.register(_validator.DateOption)
@_add_argument.register(_validator.TimeOption)
@_add_argument.register(_validator.TimeDeltaOption)
def _(validator, argparser, defaults, fqname):  # flake8: noqa
    # pylint: disable=function-redefined
    """Standard _add_argument function"""
    args, kwargs = _argdata(validator, defaults, fqname)
    kwargs["type"] = _argtype(validator, name=kwargs["dest"])
    argparser.add_argument(
        *args,
        **kwargs)

@_add_argument.register(_validator.IntChoice)
@_add_argument.register(_validator.FloatChoice)
@_add_argument.register(_validator.StrChoice)
@_add_argument.register(_validator.BoolChoice)
def _(validator, argparser, defaults, fqname):  # flake8: noqa
    # pylint: disable=function-redefined
    """Overridden _add_argument function for *Choice"""
    args, kwargs = _argdata(validator, defaults, fqname)
    kwargs["choices"] = get_validator_argument(validator, "choices")[1]
    kwargs["type"] = _argtype(validator, name=kwargs["dest"])
    argparser.add_argument(
        *args,
        **kwargs)

def update_argparser(schema, argparser, *, defaults=True, prefix=None, group_depth=1):
    """Update an argparse parser based on a schema

    Parameters
    ----------
    schema: :class:`SchemaSection`
        the schema instance
    argparser: :class:`argparse.ArgumentParser`
        the argument parser
    defaults: bool, optional
        if True, set the validator default (defaults to True)
    prefix: str, optional
        a prefix for options (defaults to None)
    group_depth: int, optional
        maximum depth for argument grouping (defaults to 1)
    """
    if not isinstance(schema, SchemaSection):
        raise TypeError("{!r}: not a schema".format(schema))
    fqname = _make_fqname(prefix)
    return _impl_update_argparser(
        schema=schema,
        argparser=argparser,
        defaults=defaults,
        fqname=fqname,
        group_depth=group_depth)

def _impl_update_argparser(schema, argparser, fqname, *, defaults=True, group_depth=1, group=None):
    """Update an argparse parser based on a schema (implementation)

    Parameters
    ----------
    schema: :class:`SchemaSection`
        the schema instance
    argparser: :class:`argparse.ArgumentParser`
        the argument parser
    fqname: tuple
        fully qualified name
    defaults: bool, optional
        if True, set the validator default (defaults to True)
    group_depth: int, optional
        maximum depth for argument grouping (defaults to 1)
    group: object, optional
        argument group to be used
    """
    subgroup_depth = group_depth
    if group_depth == 0 and group is None:  # pragma: no cover
        group = argparser
    if group_depth > 0:
        subgroup_depth -= 1
    for key, value in schema.items():
        if key in {SchemaSection.__default_option__, SchemaSection.__default_section__}:
            continue
        elif isinstance(value, SchemaSection):
            if group is None or group_depth != 0:
                group_name = ".".join(fqname + (key,))
                subgroup = argparser.add_argument_group("configuration options for package {!r}".format(group_name))
            else:
                subgroup = group
            _impl_update_argparser(
                value,
                argparser,
                defaults=defaults,
                fqname=fqname + (key,),
                group_depth=subgroup_depth,
                group=subgroup)
        else:
            if group is None:
                argument_group = argparser
            else:
                argument_group = group
            _add_argument(value, argparser=argument_group, defaults=defaults, fqname=fqname + (key,))

def create_argparser(schema, *, defaults=True, prefix=None, group_depth=1, **kwargs):
    r"""Creates an argparse parser based on a schema

    Parameters
    ----------
    schema: :class:`Schema`
        the schema instance or source
    argparser: :class:`argparse.ArgumentParser`
        the argument parser
    defaults: bool, optional
        if True, set the validator default (defaults to True)
    group_depth: int, optional
        maximum depth for argument grouping (defaults to 1)
    prefix: str
        a prefix for options
    \*\*kwargs: dict, optional
        passed to the :class:`argparse.ArgumentParser` constructor

    Returns
    -------
    :class:`argparse.ArgumentParser`
        the argument parser
    """
    argparser = argparse.ArgumentParser(**kwargs)
    update_argparser(schema=schema, argparser=argparser, defaults=defaults, prefix=prefix, group_depth=group_depth)
    return argparser

def read_namespace(schema, namespace, *, config=None, prefix=None, validate=True):
    """Read config data from a namespace

    Parameters
    ----------
    schema: :class:`Schema`
        the schema instance or source
    argparser: :class:`argparse.ArgumentParser`
        the argument parser
    config: :class:`Config`, optional
        the config object to be modified and returned (defaults to None, which means
        that a new empty Config is created)
    prefix: str, optional
        a prefix for options (defaults to None)
    validate: bool, optional
        if True performs validation

    Returns
    -------
    tuple
        a 2-tuple (config, validation_result); validation_result is None if validate == False
    """
    if not isinstance(schema, SchemaSection):
        raise TypeError("{!r}: not a Schema".format(schema))
    if prefix:
        if isinstance(prefix, str):
            fqname = (prefix,)
        else:
            fqname = tuple(prefix)
    else:
        fqname = ()
    if config is None:
        config = Config()
    _read_namespace_impl(schema=schema, namespace=namespace, config=config, fqname=fqname)
    if validate:
        validation_result = schema.validate(config)
    else:
        validation_result = None
    return config, validation_result

def _read_namespace_impl(schema, namespace, *, config, fqname):
    """read_namespace implementation"""
    for key, value in schema.items():
        if key in {SchemaSection.__default_option__, SchemaSection.__default_section__}:
            continue
        elif isinstance(value, SchemaSection):
            subconfig = config.setdefault(key, {})
            _read_namespace_impl(schema=value, namespace=namespace, config=subconfig, fqname=fqname + (key,))
        else:
            dest = argument_dest(fqname + (key,))
            val = getattr(namespace, dest, None)
            if val is not UNDEFINED:
                config[key] = val


text:
package io.proleap.cobol.asg.metamodel.procedure.perform;

import io.proleap.cobol.asg.metamodel.CobolDivisionElement;
import io.proleap.cobol.asg.metamodel.valuestmt.ValueStmt;

public interface Times extends CobolDivisionElement {

	ValueStmt getTimesValueStmt();

	void setTimesValueStmt(ValueStmt timesValueStmt);
}


text:
@interface CRBaseNavigationViewController : UINavigationController

@end


text:
package org.keycloak.models.sessions.infinispan.entities.wildfly;

import org.keycloak.models.sessions.infinispan.entities.ActionTokenValueEntity;

public class ActionTokenValueEntityWFExternalizer extends InfinispanExternalizerAdapter<ActionTokenValueEntity> {

    public ActionTokenValueEntityWFExternalizer() {
        super(ActionTokenValueEntity.class, new ActionTokenValueEntity.ExternalizerImpl());
    }
}


text:
import { combineReducers } from 'redux'
import { errorMessage } from './ErrorReducer'
import item from './ProductReducers'

const AppReducers = combineReducers({
  item,
  errorMessage
})

export default AppReducers


text:
TiledSprite::TiledSprite(
	ALLEGRO_BITMAP* bitmap,
	int columnsCount,
	int rowsCount,
	float positionX,
	float positionY
	) :
Sprite(bitmap, positionX, positionY)
{
	this->rowsCount = rowsCount;
	this->columnsCount = columnsCount;
	countRegionSize();
}

void TiledSprite::countRegionSize(){
	regionWidth = getWidth() / columnsCount;
	regionHeight = getHeight() / rowsCount;
}

void TiledSprite::drawRegion(int row, int column){
	float x = getRegionWidth();
	float y = getRegionHeight();
	al_draw_bitmap_region(
		bitmap,
		column * getRegionWidth(),
		row * getRegionHeight(),
		getRegionWidth(),
		getRegionHeight(),
		positionX - getRegionWidth() / 2.0f,
		positionY - getRegionHeight() / 2.0f,
		0);
}

float TiledSprite::getRegionWidth(){
	return regionWidth;
}

float TiledSprite::getRegionHeight(){
	return regionHeight;
}

int TiledSprite::getColumnsCount(){
	return columnsCount;
}

int TiledSprite::getRowsCount(){
	return rowsCount;
}


text:
A simple progress bar for Nim.

![Demo](https://raw.githubusercontent.com/euantorano/progress.nim/master/progress.gif)

## Installation

```
nimble install progress
```

## [API Documentation](https://htmlpreview.github.io/?https://github.com/euantorano/progress.nim/blob/master/docs/progress.html)

## Usage

```nim
# os is only needed for `sleep`
import progress, os

var bar = newProgressBar()
bar.start()

for i in 1..100:
  # Do some work
  sleep(100)
  bar.increment()

bar.finish()
```


text:
var _ = require('../lodash-local')
var util = require('../util')

// task definition function
var echo = function(msg) {
  return _.assign({}, { msg }, { op: 'echo' })
}

echo.toCode = function(json, Flexio) {
  var params = util.getTaskParams(json)
  var msg = JSON.stringify(params.msg) || '""'
  return 'echo(' + msg + ')'
}

module.exports = echo


text:
Document All The Things
=======================

## Goal

**To prove the feasibility of a P2P publishing market where content ownership remains with the author and moderation choice remains with the user.**

## Principles

**The following principles are essential to DATT:**

 - The network should be uncensorable and users must have final say in content filtering (or the lack of it)
 - Strong anonymity by default, users may optionally assign a stickier identity to themselves via cryptographic signatures
 - We aim for a truly decentralized solution without the need for central servers to hold any content or any registration of users; nor should they be aware of the specific content users are sharing and accessing.
 - Nothing more than a web browser should be required to participate on the network
 - A user should have plausible deniability that they have accepted/stored/consumed/propagated any content item

**Secondary principles that arise from the core principles but are not essential:**

 - Content encryption should be pervasive until a user chooses to decrypt the content
 - Publishers should be incentivised to create quality/popular content

## MVP

There are many contributors working on aspects of the MVP. Some direction and prioritization of MVP features are below.

**It must be possible to:**

 - Post markdown formatted body text with a title | Post a link with a title
 - Distribute post content between peers
 - Sort content for display (chronological, total views, active peers, tips:peer ratio, average comment karma)
 - Comment on posts and have the comments also distribute to peers
 - Tag or Categorize posts
 - Allow for peers to participate as Moderators listing the content that they have curated
 - Create a BIP39 address for the user
 - Monetarily incentivize contributors (Content creators)

**It is desirable to be able to:**

 - Monetarily incentivize network participants (Moderators & Nodes)
 - Optionally include a Title image
 - Crawl link posts to pull a thumbnail image from the source content
 - Display only comments above a defined karma threshold
 - Allow nested comment threads
 - Throttle content submissions to reduce spam
 - Allow users to withdraw funds (CoinJoin?)
 - Derive BIP32/BIP44 addresses
 - Multi-sig addresses between devices the user controls | Multi-sig addresses where a 3rd party controls an address
 - Identity management using signed messages | Keybase.io or other integration for identity

**It is not necessary to:**

 - Allow editing of the body text or title after publishing
 - Decentralize Facebook | Slack | [insert other social/collaboration platform]
 - Integrate directly with existing Bitcoin wallets


text:
require 'test_helper'

class GroupHelperTest < ActionView::TestCase
end


text:
FactoryGirl.define do
  factory :image do
    name "MyString"
    img "MyString"
    artwork nil
  end
end


text:
viewModel.regionalDistributor = new Object()
let rd = viewModel.regionalDistributor

rd.contentIsLoading = ko.observable(false)
rd.title = ko.observable('RD Analysis')
rd.level = ko.observable(2)

rd.breakdownBy = ko.observable('customer.reportsubchannel')
rd.breakdownByCity = ko.observable('customer.areaname')
rd.breakdownByFiscalYear = ko.observable('date.fiscal')

rd.filterDistributor = ko.observableArray([])
rd.optionDistributor = ko.computed(() => {
	return rpt.masterData.Distributor().filter((d) => d._id != '')
}, rpt.masterData.Distributor)

rd.data = ko.observableArray([])
rd.fiscalYear = ko.observable(rpt.value.FiscalYear())
rd.breakdownValue = ko.observableArray([])

rd.refresh = (useCache = false) => {
	if (rd.breakdownValue().length == 0) {
		toolkit.showError('Please choose at least breakdown value')
		return
	}

	let param = {}
	param.pls = []
	param.groups = rpt.parseGroups([rd.breakdownByCity(), rd.breakdownBy()])
	param.aggr = 'sum'
	param.filters = rpt.getFilterValue(false, rd.fiscalYear)
	param.filters.push({
		Field: 'customer.channelname',
		Op: '$in',
		Value: ['I1']
	})

	if (rd.filterDistributor().length > 0) {
		param.filters.push({
			Field: 'customer.reportsubchannel',
			Op: '$in',
			Value: rd.filterDistributor()
		})
	}

	let breakdownValue = rd.breakdownValue().filter((d) => d != 'All')
	if (breakdownValue.length > 0) {
		param.filters.push({
			Field: rd.breakdownByCity(),
			Op: '$in',
			Value: rd.breakdownValue()
		})
	}
	console.log("bdk", param.filters)

	rd.contentIsLoading(true)

	let fetch = () => {
		rpt.injectMonthQuarterFilter(param.filters)
		toolkit.ajaxPost(viewModel.appName + "report/getpnldatanew", param, (res) => {
			if (res.Status == "NOK") {
				setTimeout(() => {
					fetch()
				}, 1000 * 5)
				return
			}

			if (rpt.isEmptyData(res)) {
				rd.contentIsLoading(false)
				return
			}

			res.Data = rpt.hardcodePLGA(res.Data.Data, res.Data.PLModels)
			let data = rd.buildStructure(res.Data.Data)
			rd.data(data)
			rpt.plmodels(res.Data.PLModels)
			rd.emptyGrid()
			rd.contentIsLoading(false)
			rd.render()
			rpt.prepareEvents()
		}, () => {
			rd.emptyGrid()
			rd.contentIsLoading(false)
		}, {
			cache: (useCache == true) ? 'breakdown chart' : false
		})
	}

	fetch()
}

rd.emptyGrid = () => {
	$('.breakdown-view').replaceWith(`<div class="breakdown-view ez" id="rd-analysis"></div>`)
}

rd.buildStructure = (data) => {
	let groupThenMap = (data, group) => {
		let op1 = _.groupBy(data, (d) => group(d))
		let op2 = _.map(op1, (v, k) => {
			let key = { _id: k, subs: v }
			let sample = v[0]

			for (let prop in sample) {
				if (sample.hasOwnProperty(prop) && prop != '_id') {
					key[prop] = toolkit.sum(v, (d) => d[prop])
				}
			}

			return key
		})

		return op2
	}

	let parsed = groupThenMap(data, (d) => {
		return d._id[`_id_${toolkit.replace(rd.breakdownByCity(), '.', '_')}`]
	}).map((d) => {
		let subs = groupThenMap(d.subs, (e) => {
			return e._id[`_id_${toolkit.replace(rd.breakdownBy(), '.', '_')}`]
		}).map((e) => {
			e.breakdowns = e.subs[0]._id
			d.count = 1
			return e
		})

		d.subs = _.orderBy(subs, (e) => e.PL8A, 'desc')
		d.breakdowns = d.subs[0]._id
		d.count = d.subs.length
		return d
	})

	rd.level(2)
	let newParsed = _.orderBy(parsed, (d) => d.PL8A, 'desc')
	return newParsed
}

rd.render = () => {
	if (rd.data().length == 0) {
		$('.breakdown-view').html('No data found.')
		return
	}

	// ========================= TABLE STRUCTURE

	let percentageWidth = 100

	let wrapper = toolkit.newEl('div')
		.addClass('pivot-pnl-branch pivot-pnl')
		.appendTo($('.breakdown-view'))

	let tableHeaderWrap = toolkit.newEl('div')
		.addClass('table-header')
		.appendTo(wrapper)

	let tableHeader = toolkit.newEl('table')
		.addClass('table')
		.appendTo(tableHeaderWrap)

	let tableContentWrap = toolkit.newEl('div')
		.appendTo(wrapper)
		.addClass('table-content')

	let tableContent = toolkit.newEl('table')
		.addClass('table')
		.appendTo(tableContentWrap)

	let trHeader = toolkit.newEl('tr')
		.appendTo(tableHeader)

	toolkit.newEl('th')
		.html('P&L')
		.css('height', `${rpt.rowHeaderHeight() * rd.level()}px`)
		.attr('data-rowspan', rd.level())
		.css('vertical-align', 'middle')
		.addClass('cell-percentage-header')
		.appendTo(trHeader)

	toolkit.newEl('th')
		.html('Total')
		.css('height', `${rpt.rowHeaderHeight() * rd.level()}px`)
		.attr('data-rowspan', rd.level())
		.css('vertical-align', 'middle')
		.addClass('cell-percentage-header align-right')
		.appendTo(trHeader)

	toolkit.newEl('th')
		.html('% of N Sales')
		.css('height', `${rpt.rowHeaderHeight() * rd.level()}px`)
		.css('vertical-align', 'middle')
		.css('font-weight', 'normal')
		.css('font-style', 'italic')
		.width(percentageWidth - 20)
		.attr('data-rowspan', rd.level())
		.css('vertical-align', 'middle')
		.addClass('cell-percentage-header align-right')
		.appendTo(trHeader)

	let trContents = []
	for (let i = 0; i < rd.level(); i++) {
		trContents.push(toolkit.newEl('tr')
			.appendTo(tableContent)
			.css('height', `${rpt.rowHeaderHeight()}px`))
	}

	// ========================= BUILD HEADER

	let data = rd.data()

	let columnWidth = 130
	let totalColumnWidth = 0
	let pnlTotalSum = 0
	let dataFlat = []

	let countWidthThenPush = (thheader, each, key) => {
		let currentColumnWidth = each._id.length * 8
		if (currentColumnWidth < columnWidth) {
			currentColumnWidth = columnWidth
		}

		if (each.hasOwnProperty('width')) {
			currentColumnWidth = each.width
		}

		each.key = key.join('_')
		dataFlat.push(each)

		totalColumnWidth += currentColumnWidth
		thheader.width(currentColumnWidth)
	}

	data.forEach((lvl1, i) => {
		let thheader1 = toolkit.newEl('th')
			.html(lvl1._id.replace(/\ /g, ' '))
			.attr('colspan', lvl1.count)
			.addClass('align-center')
			.appendTo(trContents[0])
			.css('border-top', 'none')

		let thheader2p = $('<div />')

		if (rd.level() == 1) {
			countWidthThenPush(thheader1, lvl1, [lvl1._id])

			totalColumnWidth += percentageWidth
			let thheader1p = toolkit.newEl('th')
				.html('% of N Sales'.replace(/\ /g, ' '))
				.width(percentageWidth)
				.addClass('align-center')
				.css('font-weight', 'normal')
				.css('font-style', 'italic')
				.addClass('align-center')
				.appendTo(trContents[0])
				.css('border-top', 'none')

			if (rpt.showPercentOfTotal()) {
				totalColumnWidth += percentageWidth
				thheader2p = toolkit.newEl('th')
					.html('% of Total'.replace(/\ /g, ' '))
					.width(percentageWidth)
					.addClass('align-center')
					.css('font-weight', 'normal')
					.css('font-style', 'italic')
					.addClass('align-center')
					.appendTo(trContents[0])
					.css('border-top', 'none')
			}

			return
		}
		thheader1.attr('colspan', lvl1.count * (rpt.showPercentOfTotal() ? 3 : 2))

		lvl1.subs.forEach((lvl2, j) => {
			let thheader2 = toolkit.newEl('th')
				.html(lvl2._id.replace(/\ /g, ' '))
				.addClass('align-center')
				.appendTo(trContents[1])

			if (rd.level() == 2) {
				countWidthThenPush(thheader2, lvl2, [lvl1._id, lvl2._id])

				totalColumnWidth += percentageWidth
				let thheader1p = toolkit.newEl('th')
					.html('% of N Sales'.replace(/\ /g, ' '))
					.width(percentageWidth)
					.addClass('align-center')
					.css('font-weight', 'normal')
					.css('font-style', 'italic')
					.addClass('align-center')
					.appendTo(trContents[1])

				if (rpt.showPercentOfTotal()) {
					totalColumnWidth += percentageWidth
					thheader2p = toolkit.newEl('th')
						.html('% of Total'.replace(/\ /g, ' '))
						.width(percentageWidth)
						.addClass('align-center')
						.css('font-weight', 'normal')
						.css('font-style', 'italic')
						.addClass('align-center')
						.appendTo(trContents[1])
				}

				return
			}
			thheader2.attr('colspan', lvl2.count)
		})
	})

	tableContent.css('min-width', totalColumnWidth)

	// ========================= CONSTRUCT DATA

	let plmodels = _.sortBy(rpt.plmodels(), (d) => parseInt(d.OrderIndex.replace(/PL/g, '')))
	let exceptions = ["PL94C" /* "Operating Income" */, "PL39B" /* "Earning Before Tax" */, "PL41C" /* "Earning After Tax" */, "PL6A" /* "Discount" */]
	let netSalesPLCode = 'PL8A'
	let netSalesRow = {}
	let grossSalesPLCode = 'PL0'
	let grossSalesRow = {}
	let discountActivityPLCode = 'PL7A'
	let rows = []

	rpt.fixRowValue(dataFlat)

	console.log("dataFlat", dataFlat)

	dataFlat.forEach((e) => {
		let breakdown = e.key
		netSalesRow[breakdown] = e[netSalesPLCode]
		grossSalesRow[breakdown] = e[grossSalesPLCode]
	})

	plmodels.forEach((d) => {
		let row = { PNL: d.PLHeader3, PLCode: d._id, PNLTotal: 0, Percentage: 0 }
		dataFlat.forEach((e) => {
			let breakdown = e.key
			let value = e[`${d._id}`];
			row[breakdown] = value

			if (toolkit.isDefined(e.excludeFromTotal)) {
				return
			}

			row.PNLTotal += value
		})
		dataFlat.forEach((e) => {
			let breakdown = e.key
			let percentage = 100
			let percentageOfTotal = toolkit.number(row[breakdown] / row.PNLTotal) * 100

			if (d._id == discountActivityPLCode) {
				percentage = toolkit.number(row[breakdown] / grossSalesRow[breakdown]) * 100
			} else if (d._id != netSalesPLCode) {
				percentage = toolkit.number(row[breakdown] / netSalesRow[breakdown]) * 100
			}

			if (percentage < 0)
				percentage = percentage * -1

			row[`${breakdown} %`] = percentage
			row[`${breakdown} %t`] = percentageOfTotal
		})

		if (exceptions.indexOf(row.PLCode) > -1) {
			return
		}

		rows.push(row)
	})

	console.log("rows", rows)

	let TotalNetSales = _.find(rows, (r) => { return r.PLCode == netSalesPLCode }).PNLTotal
	let TotalGrossSales = _.find(rows, (r) => { return r.PLCode == grossSalesPLCode }).PNLTotal
	rows.forEach((d, e) => {
		let TotalPercentage = (d.PNLTotal / TotalNetSales) * 100
		if (d.PLCode == discountActivityPLCode) {
			TotalPercentage = (d.PNLTotal / TotalGrossSales) * 100
		}

		if (TotalPercentage < 0)
			TotalPercentage = TotalPercentage * -1
		rows[e].Percentage = toolkit.number(TotalPercentage)
	})

	// ========================= PLOT DATA

	rows.forEach((d, i) => {
		pnlTotalSum += d.PNLTotal

		let PL = d.PLCode
		PL = PL.replace(/\s+/g, '')
		let trHeader = toolkit.newEl('tr')
			.addClass(`header${PL}`)
			.attr(`idheaderpl`, PL)
			.attr(`data-row`, `row-${i}`)
			.css('height', `${rpt.rowContentHeight()}px`)
			.appendTo(tableHeader)

		trHeader.on('click', () => {
			rd.clickExpand(trHeader)
		})

		toolkit.newEl('td')
			.html('<i></i>' + d.PNL)
			.appendTo(trHeader)

		let pnlTotal = kendo.toString(d.PNLTotal, 'n0')
		toolkit.newEl('td')
			.html(pnlTotal)
			.addClass('align-right')
			.appendTo(trHeader)

		toolkit.newEl('td')
			.html(kendo.toString(d.Percentage, 'n2') + ' %')
			.addClass('align-right')
			.appendTo(trHeader)

		let trContent = toolkit.newEl('tr')
			.addClass(`column${PL}`)
			.attr(`idpl`, PL)
			.attr(`data-row`, `row-${i}`)
			.css('height', `${rpt.rowContentHeight()}px`)
			.appendTo(tableContent)

		dataFlat.forEach((e, f) => {
			let key = e.key
			let value = kendo.toString(d[key], 'n0')
			let percentage = kendo.toString(d[`${key} %`], 'n2') + ' %'
			let percentageOfTotal = kendo.toString(d[`${key} %t`], 'n2') + ' %'

			if ($.trim(value) == '') {
				value = 0
			}

			let cell = toolkit.newEl('td')
				.html(value)
				.addClass('align-right')
				.appendTo(trContent)

			let cellPercentage = toolkit.newEl('td')
				.html(percentage)
				.addClass('align-right')
				.appendTo(trContent)

			if (rpt.showPercentOfTotal()) {
				toolkit.newEl('td')
					.html(percentageOfTotal)
					.addClass('align-right')
					.appendTo(trContent)
			}

			$([cell, cellPercentage]).on('click', () => {
				rd.renderDetail(d.PLCode, e.breakdowns)
			})
		})

		rpt.putStatusVal(trHeader, trContent)
	})

	// ========================= CONFIGURE THE HIRARCHY
	rpt.buildGridLevels(rows)
}

rd.clickExpand = (e) => {
	let right = $(e).find('i.fa-chevron-right').length, down = 0
		if (e.attr('idheaderpl') == 'PL0')
			down = $(e).find('i.fa-chevron-up').length
		else
			down = $(e).find('i.fa-chevron-down').length
	if (right > 0){
		if (['PL28', 'PL29A', 'PL31'].indexOf($(e).attr('idheaderpl')) > -1) {
			$('.pivot-pnl .table-header').css('width', rpt.pnlTableHeaderWidth())
			$('.pivot-pnl .table-content').css('margin-left', rpt.pnlTableHeaderWidth())
		}

		$(e).find('i').removeClass('fa-chevron-right')
		if (e.attr('idheaderpl') == 'PL0')
			$(e).find('i').addClass('fa-chevron-up')
		else
			$(e).find('i').addClass('fa-chevron-down')
		$(`tr[idparent=${e.attr('idheaderpl')}]`).css('display', '')
		$(`tr[idcontparent=${e.attr('idheaderpl')}]`).css('display', '')
		$(`tr[statusvaltemp=hide]`).css('display', 'none')
		rpt.refreshHeight(e.attr('idheaderpl'))
		rpt.refreshchildadd(e.attr('idheaderpl'))
	}
	if (down > 0) {
		if (['PL28', 'PL29A', 'PL31'].indexOf($(e).attr('idheaderpl')) > -1) {
			$('.pivot-pnl .table-header').css('width', '')
			$('.pivot-pnl .table-content').css('margin-left', '')
		}

		$(e).find('i').removeClass('fa-chevron-up')
		$(e).find('i').removeClass('fa-chevron-down')
		$(e).find('i').addClass('fa-chevron-right')
		$(`tr[idparent=${e.attr('idheaderpl')}]`).css('display', 'none')
		$(`tr[idcontparent=${e.attr('idheaderpl')}]`).css('display', 'none')
		rpt.hideAllChild(e.attr('idheaderpl'))
	}
}

rd.optionBreakdownValues = ko.observableArray(rpt.masterData.Area())
rd.breakdownValueAll = { _id: 'All', Name: 'All' }
rd.changeBreakdown = () => {
	let all = rd.breakdownValueAll
	setTimeout(() => {
		rd.optionBreakdownValues([all].concat(rpt.masterData.Area()))
		rd.breakdownValue([all._id])
	}, 100)
}
rd.changeBreakdownValue = () => {
	let all = rd.breakdownValueAll
	setTimeout(() => {
		let condA1 = rd.breakdownValue().length == 2
		let condA2 = rd.breakdownValue().indexOf(all._id) == 0
		if (condA1 && condA2) {
			rd.breakdownValue.remove(all._id)
			return
		}

		let condB1 = rd.breakdownValue().length > 1
		let condB2 = rd.breakdownValue().reverse()[0] == all._id
		if (condB1 && condB2) {
			rd.breakdownValue([all._id])
			return
		}

		let condC1 = rd.breakdownValue().length == 0
		if (condC1) {
			rd.breakdownValue([all._id])
		}
	}, 100)
}

vm.currentMenu('Analysis')
vm.currentTitle('RD Analysis')
vm.breadcrumb([
	{ title: 'Godrej', href: '#' },
	{ title: 'Analysis', href: '#' },
	{ title: 'RD Analysis', href: '#' }
])

rd.title(' ')

rpt.refresh = () => {
	rd.changeBreakdown()
	setTimeout(() => {
		rd.breakdownValue(['All'])
		rd.refresh(false)
	}, 200)
}

$(() => {
	rpt.refresh()
	rpt.showExport(true)
})


text:
package util;

public class JavaMethods<T> {
  public static Object nArray(double [] d)
  {
    return null;
  }

  public static Object nArray(int[] iA)
  {
    return null;
  }

  public static Object nArray(String[] iS)
  {
    return null;
  }

  public Object typeparam(T iS)
  {
    return null;
  }

  public Object typeparam2(T[] iS)
  {
    return null;
  }
}


text:
package org.artifactory.webapp.wicket.actionable.tree;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.tree.ITreeState;
import org.artifactory.common.wicket.component.panel.shortcutkey.KeyEventHandler;
import org.artifactory.common.wicket.component.panel.shortcutkey.KeyListener;
import org.artifactory.common.wicket.component.panel.shortcutkey.KeyReleasedEvent;

import javax.swing.tree.TreeNode;

import static java.awt.event.KeyEvent.*;

/**
 * Handles keyboard events when browsing an ActionableItemsTree.
 *
 * @author Yossi Shaul
 */
public class TreeKeyEventHandler extends KeyEventHandler {

    public TreeKeyEventHandler(String id, final ActionableItemsTree tree) {
        super(id);

        addKeyListener(new KeyListener() {
            @Override
            public void keyReleased(KeyReleasedEvent e) {
                TreeNode selectedNode = tree.getSelectedNode();
                if (selectedNode == null) {
                    return;
                }

                ITreeState state = tree.getTreeState();
                boolean expanded = state.isNodeExpanded(selectedNode);
                AjaxRequestTarget target = e.getTarget();
                if (!expanded && !selectedNode.isLeaf() && selectedNode.getAllowsChildren()) {
                    state.expandNode(selectedNode);
                    tree.onJunctionLinkClicked(target, selectedNode);
                    target.add(tree);
                    target.appendJavaScript("Browser.scrollToSelectedNode();");
                } else {
                    tree.selectNode(selectedNode, tree.getNextTreeNode(selectedNode), target);
                }
            }
        }, VK_RIGHT, VK_ADD);

        addKeyListener(new KeyListener() {
            @Override
            public void keyReleased(KeyReleasedEvent e) {
                TreeNode selectedNode = tree.getSelectedNode();
                if (selectedNode == null) {
                    return;
                }

                ITreeState state = tree.getTreeState();
                boolean expanded = state.isNodeExpanded(selectedNode);
                AjaxRequestTarget target = e.getTarget();
                if (expanded) {
                    state.collapseNode(selectedNode);
                    tree.onJunctionLinkClicked(target, selectedNode);
                    target.add(tree);
                    target.appendJavaScript("Browser.scrollToSelectedNode();");
                } else {
                    tree.selectNode(selectedNode, tree.getPrevTreeNode(selectedNode), target);
                }
            }
        }, VK_LEFT, VK_SUBTRACT);

        addKeyListener(new KeyListener() {
            @Override
            public void keyReleased(KeyReleasedEvent e) {
                TreeNode selectedNode = tree.getSelectedNode();
                if (selectedNode != null) {
                    tree.selectNode(selectedNode, tree.getPrevTreeNode(selectedNode), e.getTarget());
                }

            }
        }, VK_UP);

        addKeyListener(new KeyListener() {
            @Override
            public void keyReleased(KeyReleasedEvent e) {
                TreeNode selectedNode = tree.getSelectedNode();
                if (selectedNode != null) {
                    tree.selectNode(selectedNode, tree.getNextTreeNode(selectedNode), e.getTarget());
                }
            }
        }, VK_DOWN);
    }
}