text:
class THistManager;
class AliPIDResponse;
class AliESDtrackCuts;

class AliAnalysisTaskSigma1385PM : public AliAnalysisTaskSE {
 public:
  AliAnalysisTaskSigma1385PM();
  AliAnalysisTaskSigma1385PM(const char* name, Bool_t MCcase);
  virtual ~AliAnalysisTaskSigma1385PM();

  virtual void UserCreateOutputObjects();
  virtual void UserExec(Option_t* option);
  virtual void Terminate(Option_t* option);
  void SetFillQAPlot(Bool_t input) { fFillQAPlot = input; }
  void SetMixerTask(AliAnalysisTaskTrackMixer* mixerTask) {
    fMixingPool = mixerTask;
  }
  void SetUseBuiltinMixer(Bool_t builtinmixer) {
    fUseBuiltinMixer = builtinmixer;
  }
  void SetMixing(Bool_t setmixing) { fSetMixing = setmixing; }
  void SetnMix(Int_t nMix) { fnMix = nMix; }
  void SetIsPrimaryMC(Bool_t isprimarymc) { fIsPrimaryMC = isprimarymc; }
  void SetINEL(Bool_t input) { fIsINEL = input; }
  void SetHighMult(Bool_t input) { fIsHM = input; }
  void SetAsymmCut(Bool_t input) { fUseAsymmCut = input; }
  void SetOnlyUseOnTheFlyV0(Bool_t input) { fOnlyUseOnTheFlyV0 = input; }
  void SetFillnTuple(Bool_t fillntuple) { fFillnTuple = fillntuple; }

  // Setter for cut variables
  void SetFilterbitSigmaStarPion(Double_t lParameter) {
    fFilterBit = lParameter;
  }
  void SetMaxNsigSigmaStarPion(Double_t lParameter) {
    fTPCNsigSigmaStarPionCut = lParameter;
  }
  void SetMaxEtaSigmaStarPion(Double_t lParameter) {
    fSigmaStarPionEtaCut = lParameter;
  }
  void SetMaxVertexZSigmaStarPion(Double_t lParameter) {
    fSigmaStarPionZVertexCut = lParameter;
  }
  void SetMaxVertexXYsigSigmaStarPion(Double_t lParameter) {
    fSigmaStarPionXYVertexSigmaCut = lParameter;
  }

  void SetMaxNsigV0Proton(Double_t lParameter) {
    fTPCNsigLambdaProtonCut = lParameter;
  }
  void SetMaxNsigV0Pion(Double_t lParameter) {
    fTPCNsigLambdaPionCut = lParameter;
  }
  void SetMaxDCAV0daughters(Double_t lParameter) {
    fDCADistLambdaDaughtersCut = lParameter;
  }
  void SetMaxDCAPVV0(Double_t lParameter) { fDCArDistLambdaPVCut = lParameter; }
  void SetMaxDCAPVV0PosDaughter(Double_t lParameter) {
    fDCAPositiveTrack = lParameter;
  }
  void SetMaxDCAPVV0NegDaughter(Double_t lParameter) {
    fDCANegativeTrack = lParameter;
  }
  void SetMinCPAV0(Double_t lParameter) {
    fV0CosineOfPointingAngleCut = lParameter;
  }
  void SetMaxRapidityV0(Double_t lParameter) {
    fMaxLambdaRapidity = lParameter;
  }
  void SetLowRadiusV0(Double_t lParameter) { fLambdaLowRadius = lParameter; }
  void SetHighRadiusV0(Double_t lParameter) { fLambdaHighRadius = lParameter; }
  void SetLifetimeV0(Double_t lParameter) { fLambdaLifetime = lParameter; }
  void SetMaxMassWindowV0(Double_t lParameter) {
    fV0MassWindowCut = lParameter;
  }

  void SetSigmaStarRapidityCutHigh(Double_t lParameter) {
    fSigmaStarYCutHigh = lParameter;
  }
  void SetSigmaStarRapidityCutLow(Double_t lParameter) {
    fSigmaStarYCutLow = lParameter;
  }
  void SetSigmaStarAsymmCutHigh(Double_t lParameter) {
    fSigmaStarAsymmCutHigh = lParameter;
  }
  void SetSigmaStarAsymmCutLow(Double_t lParameter) {
    fSigmaStarAsymmCutLow = lParameter;
  }

  Bool_t GoodTracksSelection();
  Bool_t GoodV0Selection();
  void FillTracks();
  void FillNtuples();
  void FillMCinput(AliMCEvent* fMCEvent, int Fillbin = 0);
  void FillTrackToEventPool();
  Bool_t IsTrueSigmaStar(UInt_t v0, UInt_t pion, UInt_t BkgCheck = 0);
  double GetTPCnSigma(AliVTrack* track, AliPID::EParticleType type);
  void GetImpactParam(AliVTrack* track, Float_t p[2], Float_t cov[3]);

  Bool_t IsSelectedTPCGeoCut(AliAODTrack* track);
  Bool_t IsSelectedTPCGeoCut(AliESDtrack* track);
  void SetCutOpen();

  // helper
  THnSparse* CreateTHnSparse(TString name,
                             TString title,
                             Int_t ndim,
                             std::vector<TAxis> bins,
                             Option_t* opt = "");
  THnSparse* CreateTHnSparse(TString name,
                             TString title,
                             TString templ,
                             Option_t* opt = "");
  Long64_t FillTHnSparse(TString name,
                         std::vector<Double_t> x,
                         Double_t w = 1.);
  Long64_t FillTHnSparse(THnSparse* h,
                         std::vector<Double_t> x,
                         Double_t w = 1.);
  TAxis AxisFix(TString name, int nbin, Double_t xmin, Double_t xmax);
  TAxis AxisVar(TString name, std::vector<Double_t> bin);
  TAxis AxisStr(TString name, std::vector<TString> bin);

  AliEventCuts fEventCuts;  // Event cuts
  // TPC GeoCut
  Bool_t fCheckTPCGeo;                   //
  Double_t fTPCActiveLengthCutDeltaY;    //
  Double_t fTPCActiveLengthCutDeltaZ;    //
  Double_t fRequireCutGeoNcrNclLength;   //
  Double_t fRequireCutGeoNcrNclGeom1Pt;  //
  Double_t fCutGeoNcrNclFractionNcr;     //
  Double_t fCutGeoNcrNclFractionNcl;     //

 private:
  typedef std::vector<AliVTrack*> tracklist;
  typedef std::deque<tracklist> eventpool;
  typedef std::vector<std::vector<eventpool>> mixingpool;

  AliESDtrackCuts* fTrackCuts;             //!
  AliPIDResponse* fPIDResponse;            //!
  AliAnalysisTaskTrackMixer* fMixingPool;  //!

  AliVEvent* fEvt;             //!
  AliMCEvent* fMCEvent;        //!
  THistManager* fHistos;       //!
  AliAODVertex* fVertex;       //!
  TNtupleD* fNtupleSigma1385;  //!
  TClonesArray* fMCArray;      //!

  Bool_t fIsAOD;              //!
  Bool_t fIsNano;             //!
  Bool_t fSetMixing;          //
  Bool_t fUseBuiltinMixer;    //
  Bool_t fFillQAPlot;         //
  Bool_t fIsMC;               //
  Bool_t fIsPrimaryMC;        //
  Bool_t fFillnTuple;         //
  Bool_t fIsINEL;             //
  Bool_t fIsHM;               //
  Bool_t fUseAsymmCut;        //
  Bool_t fOnlyUseOnTheFlyV0;  //

  mixingpool fEMpool;  //!
  TAxis fBinCent;      //!
  TAxis fBinZ;         //!
  Double_t fPosPV[3];  //!
  Double_t fMagField;  //!

  Double_t fCent;  //!
  Int_t fnMix;     //!
  Int_t fCentBin;  //!
  Int_t fZbin;     //!

  // Pion cuts
  UInt_t fFilterBit;                        //
  Double_t fTPCNsigSigmaStarPionCut;        //
  Double_t fSigmaStarPionEtaCut;            //
  Double_t fSigmaStarPionZVertexCut;        //
  Double_t fSigmaStarPionXYVertexSigmaCut;  //

  // Lambda cuts
  Double_t fTPCNsigLambdaProtonCut;      //
  Double_t fTPCNsigLambdaPionCut;        //
  Double_t fDCADistLambdaDaughtersCut;   //
  Double_t fDCArDistLambdaPVCut;         //
  Double_t fDCAPositiveTrack;            //
  Double_t fDCANegativeTrack;            //
  Double_t fV0CosineOfPointingAngleCut;  //
  Double_t fMaxLambdaRapidity;           //
  Double_t fLambdaLowRadius;             //
  Double_t fLambdaHighRadius;            //
  Double_t fLambdaLifetime;              //
  Double_t fV0MassWindowCut;             //

  // Sigma Star cut
  Double_t fSigmaStarYCutHigh;      //
  Double_t fSigmaStarYCutLow;       //
  Double_t fSigmaStarAsymmCutHigh;  //
  Double_t fSigmaStarAsymmCutLow;   //

  // Good track/v0 vector array
  std::vector<UInt_t> fGoodTrackArray;
  std::vector<std::vector<UInt_t>> fGoodV0Array;

  ClassDef(AliAnalysisTaskSigma1385PM, 12);
  // Add rapidity/radius/Lifetime/Y cut of lambda
  // Add NanoOption
  // 4: Add GetImpactParm function for nano
  // 5: Seprate MC Sparse, INEL study capability
  // 6: Update some of deafult vaules
  // 7: Add skipping option for QA histos
  // 8: Rebuild MC part
  // 9: Update class format
  // 10: Fix streamer issue
  // 11: Add Asymm cut option
  // 12: Add OnTheFlyV0 option
};

#endif


text:
function withKeysMethod(callback, obj) {
  return defineKnownProperty(
    callback.bind(obj),
    "keys",
    keys.bind(null, obj)
  );
}

redpajama_set_name: RedPajamaGithub


text:
import Express from 'express';
import GraphHTTP from 'express-graphql';
import Schema from './schema';

// Config
const APP_POST = 3000;

const app = Express();

app.use('/graphql', GraphHTTP({
	schema: Schema,
	rootValue: {test: 'test rootValue'},
	pretty: true,
	graphiql: true
}));

app.listen(APP_POST, () => {
	console.log(`App listening on port ${APP_POST}`);
});


text:
package controllers;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class AbstractController {

	// Logger -----------------------------------------------------------------

	private static final Logger log = Logger.getLogger(AbstractController.class);

	// Panic handler ----------------------------------------------------------

	@ExceptionHandler(Throwable.class)
	public ModelAndView panic(Throwable oops) {

		log.debug("AbstractController - panic()");

		Assert.notNull(oops);

		ModelAndView result;

		result = new ModelAndView("misc/panic");
		result.addObject("name", ClassUtils.getShortName(oops.getClass()));
		result.addObject("message", oops.getMessage());
		result.addObject("stackTrace", ExceptionUtils.getStackTrace(oops));

		return result;
	}

	// Transaction management -------------------------------------------------

	@Autowired
	private PlatformTransactionManager transactionManager;
	private TransactionStatus txStatus;

	protected void beginTransaction() {
		Assert.isNull(txStatus);

		beginTransaction(false);
	}

	protected void beginTransaction(boolean readOnly) {
		Assert.isNull(txStatus);

		DefaultTransactionDefinition definition;

		definition = new DefaultTransactionDefinition();
		definition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_DEFAULT);
		definition.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
		definition.setReadOnly(readOnly);
		txStatus = transactionManager.getTransaction(definition);
	}

	protected void commitTransaction() {
		Assert.notNull(txStatus);

		try {
			transactionManager.commit(txStatus);
			txStatus = null;
		} catch (Throwable oops) {
			throw oops;
		}
	}

	protected void rollbackTransaction() {
		Assert.notNull(txStatus);

		try {
			if (!txStatus.isCompleted())
				transactionManager.rollback(txStatus);
			txStatus = null;
		} catch (Throwable oops) {
			throw oops;
		}
	}

}


text:
FOUNDATION_EXPORT double iOSScriptsCarthageVersionNumber;

//! Project version string for iOSScriptsCarthage.
FOUNDATION_EXPORT const unsigned char iOSScriptsCarthageVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <iOSScriptsCarthage/PublicHeader.h>


text:
const asciify = require('asciify');
exports.run = (client, message, args) => {
    let textasciify = args.join(" ")
    if (!textasciify) return message.edit("Turning no text into ascii would be pointless")
    asciify(textasciify, {font: 'standard'}, function (err, res) {
      if (err) {
        console.error(err)
        message.channel.send(`There was an error when trying to convert text. Error: \`\`\`${err}\`\`\``)
        return
      }

      message.edit("```\n" + res + "```\n");
    }
};


text:
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Dmytrii Wittmann");
MODULE_DESCRIPTION("First timer");
MODULE_VERSION("0.1");

static char* data = "data to print on timer event";
module_param(data, charp, S_IRUGO);
MODULE_PARM_DESC(data, "Data to print on timer event");

static int delay = 1;
module_param(delay, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(delay, "Timer delay in seconds");

static struct timer_list timer;

void timer_func(unsigned long data)
{
	char* str = (char*) data;
	printk(KERN_INFO " %s ", str);
}

static int __init init(void)
{
	printk(KERN_INFO "init " __FILE__);

	timer.data = (unsigned long) data;
	timer.expires = jiffies + delay * HZ;
	timer.function = timer_func;
	init_timer(&timer);
	add_timer(&timer);

	return 0;
}

static void __exit exit(void)
{
	del_timer_sync(&timer);
	printk(KERN_INFO "exit " __FILE__);

}

module_init(init);
module_exit(exit);


text:
"""
Train ds2-style speech model on Librispeech
"""

import os
import numpy as np

from neon.backends import gen_backend
from neon.callbacks.callbacks import Callbacks
from neon.initializers import GlorotUniform, Constant, Gaussian
from neon.layers import Conv, GeneralizedCost, Affine, DeepBiRNN
from neon.models import Model
from neon.transforms import Rectlin, Identity, Rectlinclip
from neon.optimizers import GradientDescentMomentum
from neon.util.argparser import NeonArgparser, extract_valid_args

from ctc import CTC
from decoder import ArgMaxDecoder
from sample_proposals_callback import WordErrorRateCallback
from data.dataloader import make_loader

# Parse the command line arguments
arg_defaults = {'batch_size': 32}

parser = NeonArgparser(__doc__, default_overrides=arg_defaults)
parser.add_argument('--nfilters', type=int,
                    help='no. of conv filters', default=1152)
parser.add_argument('--filter_width', type=int,
                    help='width of conv filter', default=11)
parser.add_argument('--str_w', type=int, help='stride in time', default=3)
parser.add_argument('--depth', type=int, help='rnn depth', default=9)
parser.add_argument('--hidden_size', type=int,
                    help='affine/rnn hidden units', default=1152)
parser.add_argument('--lr', type=float,
                    help='learning rate', default=2e-5)
parser.add_argument('--momentum', type=float,
                    help='momentum', default=0.99)
args = parser.parse_args()

# Setup model hyperparameters
# Convolution layer hyperparameters
nfilters = args.nfilters  # Number of convolutional filters
filter_width = args.filter_width  # Width of convolutional filters
str_w = args.str_w  # Convolutional filter stride

# RNN hyperparameters
depth = args.depth  # Number of BiRNN layers
hidden_size = args.hidden_size # Number of units in each BiRNN layer

# Optimization hyperparameters
learning_rate = args.lr
momentum = args.momentum
gradient_clip_norm = 400

# Setup parameters for argmax decoder
alphabet = "_'ABCDEFGHIJKLMNOPQRSTUVWXYZ "
nout = len(alphabet)
argmax_decoder = ArgMaxDecoder(alphabet, space_index=alphabet.index(" "))

# Initialize our backend
be = gen_backend(**extract_valid_args(args, gen_backend))

# Setup dataloader
nbands = 13
max_tscrpt_len = 1300
max_utt_len = 30

train_manifest = args.manifest['train']
if not os.path.exists(train_manifest):
    raise RuntimeError(
        "training manifest file {} not found".format(train_manifest))
dev_manifest = args.manifest['val']
if not os.path.exists(dev_manifest):
    raise RuntimeError(
        "validation manifest file {} not found".format(dev_manifest))

train = make_loader(train_manifest, alphabet, nbands, max_tscrpt_len, max_utt_len, backend_obj=be)
dev = make_loader(dev_manifest, alphabet, nbands, max_tscrpt_len, max_utt_len, backend_obj=be)

# Setup the layers of the DNN
# Softmax is performed in warp-ctc, so we use an Identity activation in the
# final layer.
gauss = Gaussian(scale=0.01)
glorot = GlorotUniform()
layers = [
    Conv(
        (nbands,
         filter_width,
         nfilters),
        init=gauss,
        bias=Constant(0),
        activation=Rectlin(),
        padding=dict(
            pad_h=0,
            pad_w=5),
        strides=dict(
            str_h=1,
            str_w=str_w)),
    DeepBiRNN(
        hidden_size,
        init=glorot,
        activation=Rectlinclip(),
        batch_norm=True,
        reset_cells=True,
        depth=depth),
    Affine(
        hidden_size,
        init=glorot,
        activation=Rectlinclip()),
    Affine(
        nout=nout,
        init=glorot,
        activation=Identity())]

model = Model(layers=layers)

opt = GradientDescentMomentum(learning_rate, momentum,
                              gradient_clip_norm=gradient_clip_norm,
                              stochastic_round=False,
                              nesterov=True)
callbacks = Callbacks(model, eval_set=dev, **args.callback_args)

# Print validation set word error rate at the end of every epoch
pcb = WordErrorRateCallback(dev, argmax_decoder, max_tscrpt_len, epoch_freq=1)
callbacks.add_callback(pcb)

cost = GeneralizedCost(costfunc=CTC(max_tscrpt_len, nout=nout))

# Fit the model
model.fit(train, optimizer=opt, num_epochs=args.epochs,
          cost=cost, callbacks=callbacks)


text:
<?php

class sfPhingListener implements BuildListener
{
  static protected
    $exceptions = array(),
    $errors     = array();

  static public function hasErrors()
  {
    return count(self::$errors) || count(self::$exceptions);
  }

  static public function getErrors()
  {
    return self::$errors;
  }

  static public function getExceptions()
  {
    return self::$exceptions;
  }

  /**
   * Fired before any targets are started.
   *
   * @param BuildEvent The BuildEvent
   */
  public function buildStarted(BuildEvent $event)
  {
    self::$exceptions = array();
  }

  /**
   * Fired after the last target has finished.
   *
   * @param BuildEvent The BuildEvent
   * @see BuildEvent::getException()
   */
  public function buildFinished(BuildEvent $event)
  {
  }

  /**
   * Fired when a target is started.
   *
   * @param BuildEvent The BuildEvent
   * @see BuildEvent::getTarget()
   */
  public function targetStarted(BuildEvent $event)
  {
  }

  /**
   * Fired when a target has finished.
   *
   * @param BuildEvent The BuildEvent
   * @see BuildEvent#getException()
   */
  public function targetFinished(BuildEvent $event)
  {
    if (null !== $event->getException())
    {
      self::$exceptions[] = $event->getException();
    }
  }

  /**
   * Fired when a task is started.
   *
   * @param BuildEvent The BuildEvent
   * @see BuildEvent::getTask()
   */
  public function taskStarted(BuildEvent $event)
  {
  }

  /**
   *  Fired when a task has finished.
   *
   *  @param BuildEvent The BuildEvent
   *  @see BuildEvent::getException()
   */
  public function taskFinished(BuildEvent $event)
  {
  }

  /**
   *  Fired whenever a message is logged.
   *
   *  @param BuildEvent The BuildEvent
   *  @see BuildEvent::getMessage()
   */
  public function messageLogged(BuildEvent $event)
  {
    if ($event->getPriority() == Project::MSG_ERR)
    {
      if (preg_match('/XLST transformation/', $event->getMessage()))
      {
        // not really an error
        return;
      }

      $msg = '';
      if ($event->getTask() !== null)
      {
        $msg = sprintf('[%s] ', $event->getTask()->getTaskName());
      }

      $msg .= $event->getMessage();

      self::$errors[] = $msg;
    }
  }
}


text:
package xyz.hope.fittranslucent;

import android.content.Context;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

/**
 * StatusBarSubstitutionView
 * Created by D.Hope on 2017/1/5.
 */
class StatusBarSubstitutionView extends View {

    private int height;

    public StatusBarSubstitutionView(Context context) {
        this(context, null);
    }

    public StatusBarSubstitutionView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StatusBarSubstitutionView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), height);
    }

    private void init(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            height = 0;
            setVisibility(GONE);
            return;
        }

        height = AboutSystemBar.getStatusBarHeight();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ViewCompat.setFitsSystemWindows(this, true);

            TypedValue value = new TypedValue();
            context.getTheme().resolveAttribute(R.attr.colorPrimaryDark, value, true);
            setBackgroundResource(value.resourceId);

            setVisibility(VISIBLE);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ViewCompat.setFitsSystemWindows(this, false);

            TypedValue value = new TypedValue();
            context.getTheme().resolveAttribute(R.attr.colorPrimary, value, true);
            setBackgroundResource(value.resourceId);

            setVisibility(VISIBLE);
        }
    }
}


text:
import { Fab, makeStyles, Toolbar } from '@material-ui/core';
import Container from '@material-ui/core/Container';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import AddIcon from '@material-ui/icons/Add';
import clsx from 'clsx';
import { GetServerSideProps } from 'next';
import React, { useEffect, useMemo } from 'react';
import { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { AcceptOrganizationInvite } from '../../components/organizations/accept-organization-invite';
import { CreateOrganizationModal } from '../../components/organizations/create-organization-modal';
import { OrganizationList } from '../../components/organizations/organization-list';
import { useAuthenticatedUser } from '../../src/use-authenticated-user.hook';
import { listVisible } from '../../store/common/list-state.models';
import { loadOrganizationInvite, loadOrganizations } from '../../store/organizations/organizations.actions';
import { RootState } from '../../store/store';

const useStyles = makeStyles((theme) => ({
  container: {
    paddingTop: theme.spacing(4),
    paddingBottom: theme.spacing(4),
  },
  paper: {
    padding: theme.spacing(1),
  },
}));

interface AcceptInvitePageParams {
  inviteToken: string;
}

export default function AcceptInvitePage({ inviteToken }: AcceptInvitePageParams) {
  const classes = useStyles();

  const { user } = useAuthenticatedUser(['https://swetuggtixdev.onmicrosoft.com/tix-api/access_as_backoffice']);

  const { invite } = useSelector((r: RootState) => r.organizations);

  const dispatch = useDispatch();

  useEffect(() => {
    if (user.current?.userId) {
      dispatch(loadOrganizationInvite(inviteToken));
    }
  }, [user, inviteToken]);

  return (
    <Container maxWidth={false} className={classes.container}>
      <Typography variant="h4" component="h1" gutterBottom>
        Accept Invite
      </Typography>
      <Grid container spacing={3}>
        <Grid item xs={12}>
          <Paper className={clsx(classes.paper)}>
            <AcceptOrganizationInvite invite={invite} inviteToken={inviteToken} />
          </Paper>
        </Grid>
      </Grid>
    </Container>
  );
}

export const getServerSideProps: GetServerSideProps = async (req) => {
  const inviteToken = req.query.token;

  return {
    props: {
      inviteToken,
    },
  };
};


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.branch;

import com.intellij.dvcs.DvcsUtil;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.HtmlBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcs.log.Hash;
import git4idea.changes.GitChangeUtils;
import git4idea.commands.*;
import git4idea.config.GitSaveChangesPolicy;
import git4idea.config.GitVcsSettings;
import git4idea.i18n.GitBundle;
import git4idea.repo.GitRepository;
import git4idea.util.GitPreservingProcess;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.event.HyperlinkEvent;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.intellij.dvcs.DvcsUtil.joinShortNames;
import static com.intellij.util.containers.UtilKt.getIfSingle;
import static git4idea.GitNotificationIdsHolder.CHECKOUT_ROLLBACK_ERROR;
import static git4idea.GitNotificationIdsHolder.CHECKOUT_SUCCESS;
import static git4idea.GitUtil.*;
import static git4idea.branch.GitSmartOperationDialog.Choice.FORCE;
import static git4idea.branch.GitSmartOperationDialog.Choice.SMART;
import static git4idea.util.GitUIUtil.bold;
import static git4idea.util.GitUIUtil.code;

/**
 * Represents {@code git checkout} operation.
 * Fails to checkout if there are unmerged files.
 * Fails to checkout if there are untracked files that would be overwritten by checkout. Shows the list of files.
 * If there are local changes that would be overwritten by checkout, proposes to perform a "smart checkout" which means stashing local
 * changes, checking out, and then unstashing the changes back (possibly with showing the conflict resolving dialog).
 */
class GitCheckoutOperation extends GitBranchOperation {
  private static final int REPOSITORIES_LIMIT = 4;
  @NonNls private static final String ROLLBACK_HREF_ATTRIBUTE = "rollback";

  @NotNull private final String myStartPointReference;
  private final boolean myDetach;
  private final boolean myReset;
  private final boolean myRefShouldBeValid;
  @Nullable private final String myNewBranch;

  GitCheckoutOperation(@NotNull Project project,
                       @NotNull Git git,
                       @NotNull GitBranchUiHandler uiHandler,
                       @NotNull Collection<? extends GitRepository> repositories,
                       @NotNull String startPointReference,
                       boolean detach,
                       boolean withReset,
                       boolean refShouldBeValid,
                       @Nullable String newBranch) {
    super(project, git, uiHandler, repositories);
    myStartPointReference = startPointReference;
    myDetach = detach;
    myReset = withReset;
    myRefShouldBeValid = refShouldBeValid;
    myNewBranch = newBranch;
  }

  @Override
  protected void execute() {
    saveAllDocuments();
    boolean fatalErrorHappened = false;
    notifyBranchWillChange();
    try (AccessToken ignore = DvcsUtil.workingTreeChangeStarted(myProject, getOperationName())) {
      while (hasMoreRepositories() && !fatalErrorHappened) {
        final GitRepository repository = next();
        VirtualFile root = repository.getRoot();

        Hash startHash = getHead(repository);

        GitLocalChangesWouldBeOverwrittenDetector localChangesDetector =
          new GitLocalChangesWouldBeOverwrittenDetector(root, GitLocalChangesWouldBeOverwrittenDetector.Operation.CHECKOUT);
        GitSimpleEventDetector unmergedFiles = new GitSimpleEventDetector(GitSimpleEventDetector.Event.UNMERGED_PREVENTING_CHECKOUT);
        GitSimpleEventDetector unknownPathspec = new GitSimpleEventDetector(GitSimpleEventDetector.Event.INVALID_REFERENCE);
        GitUntrackedFilesOverwrittenByOperationDetector untrackedOverwrittenByCheckout =
          new GitUntrackedFilesOverwrittenByOperationDetector(root);

        GitCommandResult result = myGit.checkout(repository, myStartPointReference, myNewBranch, false, myDetach, myReset,
                                                 localChangesDetector, unmergedFiles, unknownPathspec, untrackedOverwrittenByCheckout);
        if (result.success()) {
          updateAndRefreshChangedVfs(repository, startHash);
          markSuccessful(repository);
        }
        else if (unmergedFiles.hasHappened()) {
          fatalUnmergedFilesError();
          fatalErrorHappened = true;
        }
        else if (localChangesDetector.wasMessageDetected()) {
          boolean smartCheckoutSucceeded = smartCheckoutOrNotify(repository, localChangesDetector);
          if (!smartCheckoutSucceeded) {
            fatalErrorHappened = true;
          }
        }
        else if (untrackedOverwrittenByCheckout.wasMessageDetected()) {
          fatalUntrackedFilesError(repository.getRoot(), untrackedOverwrittenByCheckout.getRelativeFilePaths());
          fatalErrorHappened = true;
        }
        else if (!myRefShouldBeValid && unknownPathspec.hasHappened()) {
          markSkip(repository);
        }
        else {
          fatalError(getCommonErrorTitle(), result.getErrorOutputAsJoinedString());
          fatalErrorHappened = true;
        }
      }
    }

    if (!fatalErrorHappened) {
      Collection<GitRepository> repositories = getSkippedRepositories();
      String revisionNotFound = GitBundle.message("checkout.operation.revision.not.found",
                                                  repositories.size(),
                                                  joinShortNames(repositories, REPOSITORIES_LIMIT));
      if (wereSuccessful()) {
        if (!wereSkipped()) {
          notifySuccess();
        }
        else {
          Collection<GitRepository> successfulRepositories = getSuccessfulRepositories();
          HtmlBuilder builder = new HtmlBuilder();
          String mentionSuccess = GitBundle.message("checkout.operation.in", getSuccessMessage(),
                                                    successfulRepositories.size(),
                                                    joinShortNames(successfulRepositories, REPOSITORIES_LIMIT));
          builder.appendRaw(mentionSuccess);
          if (wereSkipped()) {
            builder.br().append(revisionNotFound);
          }
          builder.br().appendLink(ROLLBACK_HREF_ATTRIBUTE, GitBundle.message("checkout.operation.rollback"));

          VcsNotifier.getInstance(myProject).notifySuccess(CHECKOUT_SUCCESS, "",
                                                           builder.toString(),
                                                           new RollbackOperationNotificationListener());
        }
        notifyBranchHasChanged(myStartPointReference);
        updateRecentBranch();
      }
      else {
        LOG.assertTrue(!myRefShouldBeValid);
        notifyError(GitBundle.message("checkout.operation.could.not.checkout.error", getRefPresentation(myStartPointReference)),
                    revisionNotFound);
      }
    }
  }

  private boolean smartCheckoutOrNotify(@NotNull GitRepository repository,
                                        @NotNull GitMessageWithFilesDetector localChangesOverwrittenByCheckout) {
    Pair<List<GitRepository>, List<Change>> conflictingRepositoriesAndAffectedChanges =
      getConflictingRepositoriesAndAffectedChanges(repository, localChangesOverwrittenByCheckout, myCurrentHeads.get(repository),
                                                   myStartPointReference);
    List<GitRepository> allConflictingRepositories = conflictingRepositoriesAndAffectedChanges.getFirst();
    List<Change> affectedChanges = conflictingRepositoriesAndAffectedChanges.getSecond();

    Collection<String> absolutePaths = toAbsolute(repository.getRoot(), localChangesOverwrittenByCheckout.getRelativeFilePaths());
    GitSmartOperationDialog.Choice decision = myUiHandler.showSmartOperationDialog(myProject, affectedChanges, absolutePaths,
                                                                                GitBundle.message("checkout.operation.name"),
                                                                                GitBundle.message("checkout.operation.force.checkout"));
    if (decision == SMART) {
      Hash startHash = getHead(repository);
      boolean smartCheckedOutSuccessfully = smartCheckout(allConflictingRepositories, myStartPointReference, myNewBranch, getIndicator());
      if (smartCheckedOutSuccessfully) {
        for (GitRepository conflictingRepository : allConflictingRepositories) {
          markSuccessful(conflictingRepository);
          updateAndRefreshChangedVfs(conflictingRepository, startHash);
        }
        return true;
      }
      else {
        // notification is handled in smartCheckout()
        return false;
      }
    }
    else if (decision == FORCE) {
      Map<GitRepository, Collection<Change>> changesToRefresh = StreamEx.of(allConflictingRepositories).toMap(repo -> {
        return GitChangeUtils.getDiffWithWorkingTree(repo, myStartPointReference, false);
      });
      boolean forceCheckoutSucceeded = checkoutOrNotify(allConflictingRepositories, myStartPointReference, myNewBranch, true);
      if (forceCheckoutSucceeded) {
        markSuccessful(allConflictingRepositories.toArray(new GitRepository[0]));
        updateRepositories(allConflictingRepositories);
        allConflictingRepositories.forEach(repo -> refreshVfs(repo.getRoot(), changesToRefresh.get(repo)));
      }
      return forceCheckoutSucceeded;
    }
    else {
      fatalLocalChangesError(myStartPointReference);
      return false;
    }
  }

  @NotNull
  @Override
  protected String getRollbackProposal() {
    Collection<GitRepository> repositories = getSuccessfulRepositories();
    String previousBranch = getIfSingle(repositories.stream().map(myCurrentHeads::get).distinct());
    if (previousBranch == null) previousBranch = GitBundle.message("checkout.operation.previous.branch");
    String rollBackProposal = GitBundle.message("checkout.operation.you.may.rollback.not.to.let.branches.diverge", previousBranch);
    return new HtmlBuilder()
      .append(GitBundle.message("checkout.operation.however.checkout.has.succeeded.for.the.following", repositories.size()))
      .br()
      .appendRaw(successfulRepositoriesJoined())
      .br()
      .append(rollBackProposal)
      .toString();
  }

  @NotNull
  @Nls
  @Override
  protected String getOperationName() {
    return GitBundle.message("checkout.operation.name");
  }

  @Override
  protected void rollback() {
    GitCompoundResult checkoutResult = new GitCompoundResult(myProject);
    GitCompoundResult deleteResult = new GitCompoundResult(myProject);
    for (GitRepository repository : getSuccessfulRepositories()) {
      Hash startHash = getHead(repository);
      GitCommandResult result = myGit.checkout(repository, myCurrentHeads.get(repository), null, true, false);
      checkoutResult.append(repository, result);
      if (result.success() && myNewBranch != null) {
        /*
          force delete is needed, because we create new branch from branch other that the current one
          e.g. being on master create newBranch from feature,
          then rollback => newBranch is not fully merged to master (although it is obviously fully merged to feature).
         */
        deleteResult.append(repository, myGit.branchDelete(repository, myNewBranch, true));
      }
      updateAndRefreshChangedVfs(repository, startHash);
    }
    if (!checkoutResult.totalSuccess() || !deleteResult.totalSuccess()) {
      @NlsContexts.NotificationContent StringBuilder message = new StringBuilder();
      if (!checkoutResult.totalSuccess()) {
        message.append(GitBundle.message("checkout.operation.errors.during.checkout"));
        message.append(checkoutResult.getErrorOutputWithReposIndication());
      }
      if (!deleteResult.totalSuccess()) {
        message.append(GitBundle.message("checkout.operation.errors.during.deleting", code(myNewBranch)));
        message.append(deleteResult.getErrorOutputWithReposIndication());
      }
      VcsNotifier.getInstance(myProject).notifyError(CHECKOUT_ROLLBACK_ERROR,
                                                     GitBundle.message("checkout.operation.error.during.rollback"),
                                                     message.toString(),
                                                     true);
    }
  }

  @NotNull
  @NlsContexts.NotificationTitle
  private String getCommonErrorTitle() {
    return GitBundle.message("checkout.operation.could.not.checkout.error.title", getRefPresentation(myStartPointReference));
  }

  @NotNull
  @Override
  public String getSuccessMessage() {
    if (myNewBranch == null) {
      return GitBundle.message("checkout.operation.checked.out",
                               bold(code(myStartPointReference)));
    }
    return GitBundle.message("checkout.operation.checked.out.new.branch.from",
                             bold(code(myNewBranch)),
                             bold(code(getRefPresentation(myStartPointReference))));
  }

  @NotNull
  private static String getRefPresentation(@NotNull String reference) {
    return StringUtil.substringBeforeLast(reference, "^0");
  }

  // stash - checkout - unstash
  private boolean smartCheckout(@NotNull final List<? extends GitRepository> repositories, @NotNull @NlsSafe final String reference,
                                @Nullable final String newBranch, @NotNull ProgressIndicator indicator) {
    AtomicBoolean result = new AtomicBoolean();
    GitSaveChangesPolicy saveMethod = GitVcsSettings.getInstance(myProject).getSaveChangesPolicy();
    GitPreservingProcess preservingProcess =
      new GitPreservingProcess(myProject,
                               myGit,
                               getRootsFromRepositories(repositories),
                               GitBundle.message("checkout.operation.name"),
                               reference,
                               saveMethod,
                               indicator,
                               () -> result.set(checkoutOrNotify(repositories, reference, newBranch, false)));
    preservingProcess.execute();
    return result.get();
  }

  /**
   * Checks out or shows an error message.
   */
  private boolean checkoutOrNotify(@NotNull List<? extends GitRepository> repositories,
                                   @NotNull String reference, @Nullable String newBranch, boolean force) {
    GitCompoundResult compoundResult = new GitCompoundResult(myProject);
    for (GitRepository repository : repositories) {
      compoundResult.append(repository, myGit.checkout(repository, reference, newBranch, force, myDetach, myReset));
    }
    if (compoundResult.totalSuccess()) {
      return true;
    }
    notifyError(GitBundle.message("checkout.operation.could.not.checkout.error", reference),
                compoundResult.getErrorOutputWithReposIndication());
    return false;
  }

  private class RollbackOperationNotificationListener implements NotificationListener {
    @Override
    public void hyperlinkUpdate(@NotNull Notification notification,
                                @NotNull HyperlinkEvent event) {
      if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED && event.getDescription().equalsIgnoreCase(ROLLBACK_HREF_ATTRIBUTE)) {
        rollback();
      }
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 10: 443 (1912)

#### Original name
Stilbospora faureae Syd. & P. Syd.

### Remarks
null


text:
{-# LANGUAGE NoImplicitPrelude #-}

module Data.Geodetic(
  module G
) where

import Data.Geodetic.ECEF as G
import Data.Geodetic.Ellipsoid as G
import Data.Geodetic.EllipsoidReaderT as G
import Data.Geodetic.HasDoubles as G
import Data.Geodetic.LLH as G
import Data.Geodetic.LL as G
import Data.Geodetic.Sphere as G
import Data.Geodetic.XY as G


text:
package com.springsource.greenhouse.account;

import org.springframework.data.FileData;
import org.springframework.data.FileStorage;

public class StubFileStorage implements FileStorage {

	public String absoluteUrl(String fileName) {
		return "http://localhost:8080/resources/" + fileName;
	}

	public String storeFile(FileData file) {
		return absoluteUrl(file.getName());
	}

}


text:
/* @flow */
import actionsMenu from './actionsMenu';
import avatar from './avatar';
import cardTitle from './cardTitle';
import importSyntax from './importSyntax';
import rtl from './rtl';
import secondaryText from './secondaryText';
import variants from './variants';

export default [
  importSyntax,
  cardTitle,
  avatar,
  actionsMenu,
  secondaryText,
  variants,
  rtl
];


text: "pyokagan's personal utilities collection"


text:
from django.contrib import admin
from .conf import settings
from .models import (
    Cookie,
    CookieGroup,
    LogItem,
)

class CookieAdmin(admin.ModelAdmin):
    list_display = ('varname', 'name', 'cookiegroup', 'path', 'domain',
                    'get_version')
    search_fields = ('name', 'domain', 'cookiegroup__varname',
                     'cookiegroup__name')
    readonly_fields = ('varname',)
    list_filter = ('cookiegroup',)

class CookieGroupAdmin(admin.ModelAdmin):
    list_display = ('varname', 'name', 'is_required', 'is_deletable',
                    'get_version')
    search_fields = ('varname', 'name',)
    list_filter = ('is_required', 'is_deletable',)

class LogItemAdmin(admin.ModelAdmin):
    list_display = ('action', 'cookiegroup', 'version', 'created')
    list_filter = ('action', 'cookiegroup')
    readonly_fields = ('action', 'cookiegroup', 'version', 'created')
    date_hierarchy = 'created'

admin.site.register(Cookie, CookieAdmin)
admin.site.register(CookieGroup, CookieGroupAdmin)
if settings.COOKIE_CONSENT_LOG_ENABLED:
    admin.site.register(LogItem, LogItemAdmin)


text:
package controllers;

import javafx.event.ActionEvent;
import models.Model;

abstract public class Controller {
    protected Model model;
    protected long number1;
    protected String operator;
    protected boolean start;

    public Controller() {
        model = new Model();
        number1 = 0;
        operator = "";
        start = true;
    }

    abstract public void process(ActionEvent event);
}


text:
layout: post
date: 2018-03-08 16:58:23
title: CMSSW and Git
categories: [howto]
tags: [CMS, CMSSW, git]
---

Useful links about Git:

- <http://cms-sw.github.io/faq.html>
- <https://twiki.cern.ch/twiki/bin/view/CMS/CMSGitTutorial>
- <https://indico.cern.ch/event/726620/> (Git/GitHub HATS@LPC May 2018)

If you see this error message:

``` sh
Permission denied (publickey)
fatal : Could not read from remote repository

Please make sure you have the correct access rights
and the repository exists
```

You are probably trying to download/clone/pull from a repository using an address that looks like `git@github.com:<username>/<repo>.git`. If you just want the read-only access to the repo (not committing any changes back), you can simply change the address to `https://github.com/<username>/<repo>.git`. And you are done. :relaxed:

However, if you want to be a collaborator and get the read & write access to the repo, you have to use the `git@github.com:<username>/<repo>.git` address. (Certain CMSSW tools might force you to use it even if you don't need the read & write access). In this case, you have to follow the instructions here: <http://cms-sw.github.io/faq.html#how-do-i-subscribe-to-github>.

In particular, make sure you [register in github your ssh key](https://help.github.com/articles/generating-ssh-keys). It means that you must do the following:

1. Create a GitHub account.
2. Generate a SSH key.
  * Typically it's saved as `~/.ssh/id_rsa`
3. Associate the SSH key to your GitHub account.
4. Activate the SSH key every time you connect to GitHub.
  * On Linux, call `eval "$(ssh-agent -s)"` followed by `ssh-add ~/.ssh/id_rsa`


text:
#include "modules/prediction/prediction.h"

#include "gtest/gtest.h"

namespace apollo {
namespace prediction {

TEST(PredictionTest, Simple) {
  Prediction prediction;
  EXPECT_EQ(prediction.Name(), "prediction");
}

}  // namespace prediction
}  // namespace apollo


text:
/**
 *
 */
package io.sipstack.netty.codec.sip;

/**
 * @author jonas@jonasborjesson.com
 *
 */
public class SystemClock implements Clock {

    @Override
    public long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

}


text:
/*
 * cssText重写整个style特性
 * getPropertyValue()取得CSS属性值
 * removeProperty()移除一个属性
 * getPropertyCSSValue返回2个值
 *     cssText与getPropertyValue值相同
 *     cssValueType返回数值常量
 *         0表示继承的值
 *         1表示基本的值
 *         2表示值列表
 *         3表示自定义的值
 */
myDiv.style.cssText = "width: 25px; height: 100px; backgroud-color: green";
alert(myDiv.style.cssText);

for (var i = 0, len = myDiv.style.length; i < len; i++) {
    var prop = myDiv.style[i];    //或者myDiv.style.item[i]
    var propertyValue = myDiv.style.getPropertyValue(prop);
    alert(prop + ": " + propertyValue);
    var propertyCSSValue = myDiv.style.getPropertyCSSValue(prop);
    alert(prop + ": " + propertyCSSValue.cssText + "(" + propertyCSSValue.cssValueType + ")");
}

myDiv.style.removeProperty("backgroud-color");


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Azure.SqlDatabase.ElasticScale.Test.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement.UnitTests
{
    /// <summary>
    /// Test related to ShardKey class and date/time input values.
    /// </summary>
    [TestClass]
    public class ShardKeyTests
    {
        /// <summary>
        /// The length in bytes of each ShardKeyType.
        /// </summary>
        private readonly Dictionary<ShardKeyType, int> _shardKeyTypeLength = new Dictionary<ShardKeyType, int>
        {
            {ShardKeyType.Int32, 4},
            {ShardKeyType.Int64, 8},
            {ShardKeyType.Guid, 16},
            {ShardKeyType.Binary, 128},
            {ShardKeyType.DateTime, 8},
            {ShardKeyType.DateTimeOffset, 16},
            {ShardKeyType.TimeSpan, 8}
        };

        /// <summary>
        /// Verifies that new ShardKey(keyType, value) returns the correct ShardKey.Value
        /// </summary>
        [TestMethod]
        public void TestShardKeyValue()
        {
            foreach (ShardKeyInfo shardKeyInfo in ShardKeyInfo.AllTestShardKeyInfos)
            {
                Console.WriteLine(shardKeyInfo);

                // Verify ShardKey.Value with value type-specific Equals
                if (shardKeyInfo.KeyType == ShardKeyType.Binary && shardKeyInfo.Value != null)
                {
                    AssertExtensions.AssertScalarOrSequenceEqual(((byte[])shardKeyInfo.Value).DropTrailingZeroes(), shardKeyInfo.ShardKeyFromValue.Value, null);
                }
                else
                {
                    Assert.AreEqual(
                        shardKeyInfo.Value,
                        shardKeyInfo.ShardKeyFromValue.Value);
                }
            }
        }

        /// <summary>
        /// Verifies that new ShardKey(keyType, value) returns the correct RawValue
        /// </summary>
        [TestMethod]
        public void TestShardKeySerialization()
        {
            foreach (ShardKeyInfo shardKeyInfo in ShardKeyInfo.AllTestShardKeyInfos)
            {
                Console.WriteLine(shardKeyInfo);

                byte[] expectedSerializedValue = shardKeyInfo.RawValue;
                byte[] actualSerializedValue = shardKeyInfo.ShardKeyFromValue.RawValue;

                if (expectedSerializedValue == null)
                {
                    Assert.AreEqual(expectedSerializedValue, actualSerializedValue);
                }
                else
                {
                    AssertExtensions.AssertSequenceEqual(expectedSerializedValue, actualSerializedValue);
                }
            }
        }

        /// <summary>
        /// Verifies that ShardKey.FromRawValue(keyType, rawValue) returns the correct ShardKey and ShardKey.Value
        /// </summary>
        [TestMethod]
        public void TestShardKeyDeserialization()
        {
            foreach (ShardKeyInfo shardKeyInfo in ShardKeyInfo.AllTestShardKeyInfos)
            {
                Console.WriteLine(shardKeyInfo);

                ShardKey expectedDeserializedShardKey = shardKeyInfo.ShardKeyFromValue;
                ShardKey actualDeserializedShardKey = shardKeyInfo.ShardKeyFromRawValue;

                // Verify ShardKey with ShardKey.Equals
                Assert.AreEqual(
                    expectedDeserializedShardKey,
                    actualDeserializedShardKey);

                // Verify ShardKey.Value with value type-specific Equals
                AssertExtensions.AssertScalarOrSequenceEqual(expectedDeserializedShardKey.Value, actualDeserializedShardKey.Value, null);
            }
        }

        /// <summary>
        /// Verifies that ShardKey.FromRawValue(keyType, rawValue) returns the correct ShardKey and ShardKey.Value
        /// if extra zeroes are added to the end of rawValue
        /// </summary>
        [TestMethod]
        public void TestShardKeyDeserializationAddTrailingZeroes()
        {
            foreach (ShardKeyInfo shardKeyInfo in ShardKeyInfo.AllTestShardKeyInfos)
            {
                Console.WriteLine(shardKeyInfo);

                int dataTypeLength = _shardKeyTypeLength[shardKeyInfo.KeyType];
                if (shardKeyInfo.RawValue != null && shardKeyInfo.RawValue.Length != dataTypeLength)
                {
                    // Add trailing zeroes
                    byte[] originalRawValue = shardKeyInfo.RawValue;
                    byte[] rawValueWithTrailingZeroes = new byte[dataTypeLength];
                    originalRawValue.CopyTo(rawValueWithTrailingZeroes, 0);

                    ShardKey expectedDeserializedShardKey = shardKeyInfo.ShardKeyFromValue;
                    ShardKey actualDeserializedShardKey = ShardKey.FromRawValue(shardKeyInfo.KeyType, rawValueWithTrailingZeroes);

                    // Bug? Below fails when there are trailing zeroes even though the value is Equal
                    //// Verify ShardKey with ShardKey.Equals
                    //Assert.AreEqual(
                    //    expectedDeserializedShardKey,
                    //    actualDeserializedShardKey);

                    // Bug? Below fails for Binary type
                    if (shardKeyInfo.KeyType != ShardKeyType.Binary)
                    {
                        // Verify ShardKey.Value with value type-specific Equals
                        AssertExtensions.AssertScalarOrSequenceEqual(expectedDeserializedShardKey.Value, actualDeserializedShardKey.Value, null);
                    }
                }
            }
        }

        /// <summary>
        /// Tests that ShardKey.Min* and ShardKey.Max* have the correct KeyType, Value, and RawValue
        /// </summary>
        [TestMethod]
        public void TestShardKeyTypeInfo()
        {
            foreach (var shardKeyTypeInfo in ShardKeyTypeInfo.ShardKeyTypeInfos.Values)
            {
                Console.WriteLine(shardKeyTypeInfo.KeyType);

                // Min Value
                // Skip for DateTime & DateTimeOffset due to https://github.com/Azure/elastic-db-tools/issues/116
                if (shardKeyTypeInfo.KeyType != ShardKeyType.DateTime && shardKeyTypeInfo.KeyType != ShardKeyType.DateTimeOffset)
                {
                    Assert.AreEqual(shardKeyTypeInfo.KeyType, shardKeyTypeInfo.MinShardKey.KeyType);
                    AssertExtensions.AssertScalarOrSequenceEqual(shardKeyTypeInfo.MinValue, shardKeyTypeInfo.MinShardKey.Value, null);
                    AssertExtensions.AssertSequenceEqual(new byte[0], shardKeyTypeInfo.MinShardKey.RawValue);
                }

                // Max value
                Assert.AreEqual(shardKeyTypeInfo.KeyType, shardKeyTypeInfo.MaxShardKey.KeyType);
                AssertExtensions.AssertScalarOrSequenceEqual(null, shardKeyTypeInfo.MaxShardKey.Value, null);
                Assert.AreEqual(null, shardKeyTypeInfo.MaxShardKey.RawValue);
            }
        }

        // This is the same ordering as SQL Server
        private readonly ShardKey[] _orderedGuidsDescending =
        {
            ShardKey.MaxGuid,
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-010000000000")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-000100000000")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-000001000000")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-000000010000")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-000000000100")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-000000000001")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0100-000000000000")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0010-000000000000")),
            new ShardKey(Guid.Parse("00000000-0000-0001-0000-000000000000")),
            new ShardKey(Guid.Parse("00000000-0000-0100-0000-000000000000")),
            new ShardKey(Guid.Parse("00000000-0001-0000-0000-000000000000")),
            new ShardKey(Guid.Parse("00000000-0100-0000-0000-000000000000")),
            new ShardKey(Guid.Parse("00000001-0000-0000-0000-000000000000")),
            new ShardKey(Guid.Parse("00000100-0000-0000-0000-000000000000")),
            new ShardKey(Guid.Parse("00010000-0000-0000-0000-000000000000")),
            new ShardKey(Guid.Parse("01000000-0000-0000-0000-000000000000")),
            new ShardKey(Guid.Parse("00000000-0000-0000-0000-000000000000"))
        };

        /// <summary>
        /// Verifies that ShardKey correct orders Guids according to SQL Server ordering.
        /// </summary>
        [TestMethod]
        public void TestGuidOrdering()
        {
            for (int i = 0; i < _orderedGuidsDescending.Length - 1; i++)
            {
                Assert.IsTrue(
                    _orderedGuidsDescending[0] > _orderedGuidsDescending[1],
                    "Expected {0} to be great than {1}",
                    _orderedGuidsDescending[0],
                    _orderedGuidsDescending[1]);
            }
        }

        /// <summary>
        /// Verifies that ShardKey correct orders DateTimeOffset according to SQL Server ordering.
        /// </summary>
        [TestMethod]
        public void TestDateTimeOffsetOrdering()
        {
            ShardKeyInfo[] dateTimeOffsetShardKeyInfos =
                ShardKeyInfo.AllTestShardKeyInfosGroupedByType[ShardKeyType.DateTimeOffset]
                .ToArray();

            for (int i = 0; i < dateTimeOffsetShardKeyInfos.Length - 1; i++)
            {
                ShardKeyInfo low = dateTimeOffsetShardKeyInfos[i];
                ShardKeyInfo high = dateTimeOffsetShardKeyInfos[i + 1];

                Console.WriteLine("({0}) < ({1})", low, high);

                // https://github.com/Azure/elastic-db-tools/issues/117
                // Bug? DateTimeOffsets with the same universal time but different offset are equal as ShardKeys.
                // According to SQL (and our normalization format), they should be unequal, although according to .NET they should be equal.
                if (high.Value != null && ((DateTimeOffset)low.Value).UtcDateTime == ((DateTimeOffset)high.Value).UtcDateTime)
                {
                    Assert.AreEqual(low.ShardKeyFromValue, high.ShardKeyFromValue);
                }
                else
                {
                    AssertExtensions.AssertGreaterThan(low.ShardKeyFromValue, high.ShardKeyFromValue);
                }
            }
        }

        /// <summary>
        /// Test using ShardKey with DateTime value.
        /// </summary>
        [TestMethod()]
        [TestCategory("ExcludeFromGatedCheckin")]
        public void TestShardKeyWithDateTime()
        {
            DateTime testValue = DateTime.Now;
            TestShardKeyGeneric<DateTime>(ShardKeyType.DateTime, testValue, typeof (DateTime));
        }

        /// <summary>
        /// Test using ShardKey with TimeSpan value.
        /// </summary>
        [TestMethod()]
        [TestCategory("ExcludeFromGatedCheckin")]
        public void TestShardKeyWithTimeSpan()
        {
            TimeSpan testValue = TimeSpan.FromMinutes(6.2);
            TestShardKeyGeneric<TimeSpan>(ShardKeyType.TimeSpan, testValue, typeof (TimeSpan));
        }

        /// <summary>
        /// Test using ShardKey with DateTimeOffset value.
        /// </summary>
        [TestMethod()]
        [TestCategory("ExcludeFromGatedCheckin")]
        public void TestShardKeyWithDateTimeOffset()
        {
            DateTimeOffset testValue = DateTimeOffset.Now;
            TestShardKeyGeneric<DateTimeOffset>(ShardKeyType.DateTimeOffset, testValue, typeof (DateTimeOffset));

            DateTime d1 = DateTime.Now;
            ShardKey k1 = new ShardKey(new DateTimeOffset(d1, DateTimeOffset.Now.Offset));
            ShardKey k2 = new ShardKey(new DateTimeOffset(d1.ToUniversalTime(), TimeSpan.FromHours(0)));
            Assert.AreEqual(k1, k2);

            ShardKey k3 = ShardKey.MinDateTimeOffset;
            Assert.AreNotEqual(k1, k3);
        }

        private void TestShardKeyGeneric<TKey>(ShardKeyType keyType, TKey inputValue, Type realType)
        {
            // Excercise DetectType
            //
            ShardKey k1 = new ShardKey(inputValue);
            Assert.AreEqual(realType, k1.DataType);

            // Go to/from raw value
            ShardKey k2 = new ShardKey(keyType, inputValue);
            byte[] k2raw = k2.RawValue;

            ShardKey k3 = ShardKey.FromRawValue(keyType, k2raw);
            Assert.AreEqual(inputValue, k2.Value);
            Assert.AreEqual(inputValue, k3.Value);
            Assert.AreEqual(k2, k3);

            // verify comparisons
            Assert.AreEqual(0, k2.CompareTo(k3));

            try
            {
                k3 = k2.GetNextKey();
                Assert.IsTrue(k3 > k2);
            }
            catch (InvalidOperationException)
            {
            }
        }
    }

    internal static class ByteEnumerable
    {
        public static IEnumerable<byte> Range(byte start, byte count)
        {
            for (byte i = 0; i < count; i++)
            {
                yield return (byte) (start + count);
            }
        }

        public static IEnumerable<byte> DropTrailingZeroes(this byte[] source)
        {
            // Find last nonzero
            int lastNonzero;
            for (lastNonzero = source.Length - 1; lastNonzero >= 0 && source[lastNonzero] == 0; lastNonzero--)
            {
            }

            return source.Take(lastNonzero + 1);
        }
    }
}


text:
using System;
/// <summary>
///
/// Write a program that enters from the console a positive integer n and prints all the numbers from 1 to n, on a single line, separated by a space.
///
/// </summary>
class NumbersFrom1ToN
{
    static void Main()
    {
        Console.Write("Enter a number: ");
        int input = int.Parse(Console.ReadLine());

        for (int number = 1; number <= input; number++)
        {
            Console.Write("{0} ", number);
        }
        Console.WriteLine();
    }
}


text:
echo "Installing and updating FASTBUILD"

git pull origin master
mkdir -p /usr/local/share/fastbuild
cp -f fastbuild.py /usr/local/share/fastbuild/fastbuild.py
chmod +x /usr/local/share/fastbuild/fastbuild.py
ln -s -f /usr/local/share/fastbuild/fastbuild.py /usr/bin/fastbuild

echo ""
echo "Done."
echo ""
echo "Now you can use fastbuild by typing command \"fastbuild\" in directory where build config file exists."


text:
package com.siyeh.ig.psiutils;

import com.intellij.psi.*;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;

public class VariableAssignedVisitor extends JavaRecursiveElementVisitor{

    @NotNull private final PsiVariable variable;
    private final boolean recurseIntoClasses;
    private boolean assigned = false;

    public VariableAssignedVisitor(@NotNull PsiVariable variable,
                                   boolean recurseIntoClasses){
        super();
        this.variable = variable;
        this.recurseIntoClasses = recurseIntoClasses;
    }

    @Override public void visitElement(@NotNull PsiElement element){
        if(!assigned){
            super.visitElement(element);
        }
    }

    @Override public void visitAssignmentExpression(
            @NotNull PsiAssignmentExpression assignment){
        if(assigned){
            return;
        }
        super.visitAssignmentExpression(assignment);
        final PsiExpression arg = assignment.getLExpression();
        if(VariableAccessUtils.mayEvaluateToVariable(arg, variable)){
            assigned = true;
        }
    }

    @Override
    public void visitClass(PsiClass aClass) {
        if(!recurseIntoClasses){
            return;
        }
        if(assigned){
            return;
        }
        super.visitClass(aClass);
    }

    @Override public void visitPrefixExpression(
            @NotNull PsiPrefixExpression prefixExpression){
        if(assigned){
            return;
        }
        super.visitPrefixExpression(prefixExpression);
        final PsiJavaToken operationSign = prefixExpression.getOperationSign();
        final IElementType tokenType = operationSign.getTokenType();
        if(!tokenType.equals(JavaTokenType.PLUSPLUS) &&
                   !tokenType.equals(JavaTokenType.MINUSMINUS)){
            return;
        }
        final PsiExpression operand = prefixExpression.getOperand();
        if(VariableAccessUtils.mayEvaluateToVariable(operand, variable)){
            assigned = true;
        }
    }

    @Override public void visitPostfixExpression(
            @NotNull PsiPostfixExpression postfixExpression){
        if(assigned){
            return;
        }
        super.visitPostfixExpression(postfixExpression);
        final PsiJavaToken operationSign = postfixExpression.getOperationSign();
        final IElementType tokenType = operationSign.getTokenType();
        if(!tokenType.equals(JavaTokenType.PLUSPLUS) &&
                   !tokenType.equals(JavaTokenType.MINUSMINUS)){
            return;
        }
        final PsiExpression operand = postfixExpression.getOperand();
        if(VariableAccessUtils.mayEvaluateToVariable(operand, variable)){
            assigned = true;
        }
    }

    public boolean isAssigned(){
        return assigned;
    }
}


text:
package ec2

import (
	"github.com/jagregory/cfval/constraints"
	"github.com/jagregory/cfval/resources/common"
	. "github.com/jagregory/cfval/schema"
)

// see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html
var Volume = Resource{
	AwsType: "AWS::EC2::Volume",

	// ID
	ReturnValue: Schema{
		Type: VolumeID,
	},

	Properties: Properties{
		"AutoEnableIO": Schema{
			Type: ValueBool,
		},

		"AvailabilityZone": Schema{
			Type:     AvailabilityZone,
			Required: constraints.Always,
		},

		"Encrypted": Schema{
			Type:     ValueBool,
			Required: constraints.PropertyExists("KmsKeyId"),
		},

		"Iops": Schema{
			Type:         ValueNumber,
			Required:     constraints.PropertyIs("VolumeType", "io1"),
			ValidateFunc: IntegerRangeValidate(1, 4000),
		},

		"KmsKeyId": Schema{
			Type: ARN,
		},

		"Size": Schema{
			Type:     ValueString,
			Required: constraints.PropertyNotExists("SnapshotId"),
		},

		"SnapshotId": Schema{
			Type: ValueString,
		},

		"Tags": Schema{
			Type: Multiple(common.ResourceTag),
		},

		"VolumeType": Schema{
			Type: common.EbsVolumeType,
		},
	},
}


text:
#ifndef FOLLY_LIFOSEM_H
#define FOLLY_LIFOSEM_H

#include <string.h>
#include <stdint.h>
#include <atomic>
#include <algorithm>
#include <memory>
#include <system_error>

#include <folly/AtomicStruct.h>
#include <folly/Baton.h>
#include <folly/IndexedMemPool.h>
#include <folly/Likely.h>
#include <folly/detail/CacheLocality.h>

namespace folly {

template <template<typename> class Atom = std::atomic,
          class BatonType = Baton<Atom>>
struct LifoSemImpl;

/// LifoSem is a semaphore that wakes its waiters in a manner intended to
/// maximize performance rather than fairness.  It should be preferred
/// to a mutex+condvar or POSIX sem_t solution when all of the waiters
/// are equivalent.  It is faster than a condvar or sem_t, and it has a
/// shutdown state that might save you a lot of complexity when it comes
/// time to shut down your work pipelines.  LifoSem is larger than sem_t,
/// but that is only because it uses padding and alignment to avoid
/// false sharing.
///
/// LifoSem allows multi-post and multi-tryWait, and provides a shutdown
/// state that awakens all waiters.  LifoSem is faster than sem_t because
/// it performs exact wakeups, so it often requires fewer system calls.
/// It provides all of the functionality of sem_t except for timed waiting.
/// It is called LifoSem because its wakeup policy is approximately LIFO,
/// rather than the usual FIFO.
///
/// The core semaphore operations provided are:
///
/// -- post() -- if there is a pending waiter, wake it up, otherwise
/// increment the value of the semaphore.  If the value of the semaphore
/// is already 2^32-1, does nothing.  Compare to sem_post().
///
/// -- post(n) -- equivalent to n calls to post(), but much more efficient.
/// sem_t has no equivalent to this method.
///
/// -- bool tryWait() -- if the semaphore's value is positive, decrements it
/// and returns true, otherwise returns false.  Compare to sem_trywait().
///
/// -- uint32_t tryWait(uint32_t n) -- attempts to decrement the semaphore's
/// value by n, returning the amount by which it actually was decremented
/// (a value from 0 to n inclusive).  Not atomic.  Equivalent to n calls
/// to tryWait().  sem_t has no equivalent to this method.
///
/// -- wait() -- waits until tryWait() can succeed.  Compare to sem_wait().
///
/// LifoSem also has the notion of a shutdown state, in which any calls
/// that would block (or are already blocked) throw ShutdownSemError.
/// Note the difference between a call to wait() and a call to wait()
/// that might block.  In the former case tryWait() would succeed, and no
/// isShutdown() check is performed.  In the latter case an exception is
/// thrown.  This behavior allows a LifoSem controlling work distribution
/// to drain.  If you want to immediately stop all waiting on shutdown,
/// you can just check isShutdown() yourself (preferrably wrapped in
/// an UNLIKELY).  This fast-stop behavior is easy to add, but difficult
/// to remove if you want the draining behavior, which is why we have
/// chosen the former.  Since wait() is the only method that can block,
/// it is the only one that is affected by the shutdown state.
///
/// All LifoSem operations operations except valueGuess() are guaranteed
/// to be linearizable.
typedef LifoSemImpl<> LifoSem;

/// The exception thrown when wait()ing on an isShutdown() LifoSem
struct ShutdownSemError : public std::runtime_error {
  explicit ShutdownSemError(const std::string& msg);
  virtual ~ShutdownSemError() noexcept;
};

namespace detail {

// Internally, a LifoSem is either a value or a linked list of wait nodes.
// This union is captured in the LifoSemHead type, which holds either a
// value or an indexed pointer to the list.  LifoSemHead itself is a value
// type, the head is a mutable atomic box containing a LifoSemHead value.
// Each wait node corresponds to exactly one waiter.  Values can flow
// through the semaphore either by going into and out of the head's value,
// or by direct communication from a poster to a waiter.  The former path
// is taken when there are no pending waiters, the latter otherwise.  The
// general flow of a post is to try to increment the value or pop-and-post
// a wait node.  Either of those have the effect of conveying one semaphore
// unit.  Waiting is the opposite, either a decrement of the value or
// push-and-wait of a wait node.  The generic LifoSemBase abstracts the
// actual mechanism by which a wait node's post->wait communication is
// performed, which is why we have LifoSemRawNode and LifoSemNode.

/// LifoSemRawNode is the actual pooled storage that backs LifoSemNode
/// for user-specified Handoff types.  This is done so that we can have
/// a large static IndexedMemPool of nodes, instead of per-type pools
template <template<typename> class Atom>
struct LifoSemRawNode {
  std::aligned_storage<sizeof(void*),alignof(void*)>::type raw;

  /// The IndexedMemPool index of the next node in this chain, or 0
  /// if none.  This will be set to uint32_t(-1) if the node is being
  /// posted due to a shutdown-induced wakeup
  uint32_t next;

  bool isShutdownNotice() const { return next == uint32_t(-1); }
  void clearShutdownNotice() { next = 0; }
  void setShutdownNotice() { next = uint32_t(-1); }

  typedef folly::IndexedMemPool<LifoSemRawNode<Atom>,32,200,Atom> Pool;

  /// Storage for all of the waiter nodes for LifoSem-s that use Atom
  static Pool pool;
};

/// Use this macro to declare the static storage that backs the raw nodes
/// for the specified atomic type
#define LIFOSEM_DECLARE_POOL(Atom, capacity)                       \
    template<>                                                     \
    folly::detail::LifoSemRawNode<Atom>::Pool                      \
        folly::detail::LifoSemRawNode<Atom>::pool((capacity));

/// Handoff is a type not bigger than a void* that knows how to perform a
/// single post() -> wait() communication.  It must have a post() method.
/// If it has a wait() method then LifoSemBase's wait() implementation
/// will work out of the box, otherwise you will need to specialize
/// LifoSemBase::wait accordingly.
template <typename Handoff, template<typename> class Atom>
struct LifoSemNode : public LifoSemRawNode<Atom> {

  static_assert(sizeof(Handoff) <= sizeof(LifoSemRawNode<Atom>::raw),
      "Handoff too big for small-object optimization, use indirection");
  static_assert(alignof(Handoff) <=
                alignof(decltype(LifoSemRawNode<Atom>::raw)),
      "Handoff alignment constraint not satisfied");

  template <typename ...Args>
  void init(Args&&... args) {
    new (&this->raw) Handoff(std::forward<Args>(args)...);
  }

  void destroy() {
    handoff().~Handoff();
#ifndef NDEBUG
    memset(&this->raw, 'F', sizeof(this->raw));
#endif
  }

  Handoff& handoff() {
    return *static_cast<Handoff*>(static_cast<void*>(&this->raw));
  }

  const Handoff& handoff() const {
    return *static_cast<const Handoff*>(static_cast<const void*>(&this->raw));
  }
};

template <typename Handoff, template<typename> class Atom>
struct LifoSemNodeRecycler {
  void operator()(LifoSemNode<Handoff,Atom>* elem) const {
    elem->destroy();
    auto idx = LifoSemRawNode<Atom>::pool.locateElem(elem);
    LifoSemRawNode<Atom>::pool.recycleIndex(idx);
  }
};

/// LifoSemHead is a 64-bit struct that holds a 32-bit value, some state
/// bits, and a sequence number used to avoid ABA problems in the lock-free
/// management of the LifoSem's wait lists.  The value can either hold
/// an integral semaphore value (if there are no waiters) or a node index
/// (see IndexedMemPool) for the head of a list of wait nodes
class LifoSemHead {
  // What we really want are bitfields:
  //  uint64_t data : 32; uint64_t isNodeIdx : 1; uint64_t seq : 31;
  // Unfortunately g++ generates pretty bad code for this sometimes (I saw
  // -O3 code from gcc 4.7.1 copying the bitfields one at a time instead of
  // in bulk, for example).  We can generate better code anyway by assuming
  // that setters won't be given values that cause under/overflow, and
  // putting the sequence at the end where its planned overflow doesn't
  // need any masking.
  //
  // data == 0 (empty list) with isNodeIdx is conceptually the same
  // as data == 0 (no unclaimed increments) with !isNodeIdx, we always
  // convert the former into the latter to make the logic simpler.
  enum {
    IsNodeIdxShift = 32,
    IsShutdownShift = 33,
    SeqShift = 34,
  };
  enum : uint64_t {
    IsNodeIdxMask = uint64_t(1) << IsNodeIdxShift,
    IsShutdownMask = uint64_t(1) << IsShutdownShift,
    SeqIncr = uint64_t(1) << SeqShift,
    SeqMask = ~(SeqIncr - 1),
  };

 public:

  uint64_t bits;

  //////// getters

  inline uint32_t idx() const {
    assert(isNodeIdx());
    assert(uint32_t(bits) != 0);
    return uint32_t(bits);
  }
  inline uint32_t value() const {
    assert(!isNodeIdx());
    return uint32_t(bits);
  }
  inline constexpr bool isNodeIdx() const {
    return (bits & IsNodeIdxMask) != 0;
  }
  inline constexpr bool isShutdown() const {
    return (bits & IsShutdownMask) != 0;
  }
  inline constexpr uint32_t seq() const {
    return uint32_t(bits >> SeqShift);
  }

  //////// setter-like things return a new struct

  /// This should only be used for initial construction, not for setting
  /// the value, because it clears the sequence number
  static inline constexpr LifoSemHead fresh(uint32_t value) {
    return LifoSemHead{ value };
  }

  /// Returns the LifoSemHead that results from popping a waiter node,
  /// given the current waiter node's next ptr
  inline LifoSemHead withPop(uint32_t idxNext) const {
    assert(isNodeIdx());
    if (idxNext == 0) {
      // no isNodeIdx bit or data bits.  Wraparound of seq bits is okay
      return LifoSemHead{ (bits & (SeqMask | IsShutdownMask)) + SeqIncr };
    } else {
      // preserve sequence bits (incremented with wraparound okay) and
      // isNodeIdx bit, replace all data bits
      return LifoSemHead{
          (bits & (SeqMask | IsShutdownMask | IsNodeIdxMask)) +
          SeqIncr + idxNext };
    }
  }

  /// Returns the LifoSemHead that results from pushing a new waiter node
  inline LifoSemHead withPush(uint32_t _idx) const {
    assert(isNodeIdx() || value() == 0);
    assert(!isShutdown());
    assert(_idx != 0);
    return LifoSemHead{ (bits & SeqMask) | IsNodeIdxMask | _idx };
  }

  /// Returns the LifoSemHead with value increased by delta, with
  /// saturation if the maximum value is reached
  inline LifoSemHead withValueIncr(uint32_t delta) const {
    assert(!isNodeIdx());
    auto rv = LifoSemHead{ bits + SeqIncr + delta };
    if (UNLIKELY(rv.isNodeIdx())) {
      // value has overflowed into the isNodeIdx bit
      rv = LifoSemHead{ (rv.bits & ~IsNodeIdxMask) | (IsNodeIdxMask - 1) };
    }
    return rv;
  }

  /// Returns the LifoSemHead that results from decrementing the value
  inline LifoSemHead withValueDecr(uint32_t delta) const {
    assert(delta > 0 && delta <= value());
    return LifoSemHead{ bits + SeqIncr - delta };
  }

  /// Returns the LifoSemHead with the same state as the current node,
  /// but with the shutdown bit set
  inline LifoSemHead withShutdown() const {
    return LifoSemHead{ bits | IsShutdownMask };
  }

  inline constexpr bool operator== (const LifoSemHead& rhs) const {
    return bits == rhs.bits;
  }
  inline constexpr bool operator!= (const LifoSemHead& rhs) const {
    return !(*this == rhs);
  }
};

/// LifoSemBase is the engine for several different types of LIFO
/// semaphore.  LifoSemBase handles storage of positive semaphore values
/// and wait nodes, but the actual waiting and notification mechanism is
/// up to the client.
///
/// The Handoff type is responsible for arranging one wakeup notification.
/// See LifoSemNode for more information on how to make your own.
template <typename Handoff,
          template<typename> class Atom = std::atomic>
struct LifoSemBase : boost::noncopyable {

  /// Constructor
  explicit LifoSemBase(uint32_t initialValue = 0)
    : head_(LifoSemHead::fresh(initialValue)) {}

  /// Silently saturates if value is already 2^32-1
  void post() {
    auto idx = incrOrPop(1);
    if (idx != 0) {
      idxToNode(idx).handoff().post();
    }
  }

  /// Equivalent to n calls to post(), except may be much more efficient.
  /// At any point in time at which the semaphore's value would exceed
  /// 2^32-1 if tracked with infinite precision, it may be silently
  /// truncated to 2^32-1.  This saturation is not guaranteed to be exact,
  /// although it is guaranteed that overflow won't result in wrap-around.
  /// There would be a substantial performance and complexity cost in
  /// guaranteeing exact saturation (similar to the cost of maintaining
  /// linearizability near the zero value, but without as much of
  /// a benefit).
  void post(uint32_t n) {
    uint32_t idx;
    while (n > 0 && (idx = incrOrPop(n)) != 0) {
      // pop accounts for only 1
      idxToNode(idx).handoff().post();
      --n;
    }
  }

  /// Returns true iff shutdown() has been called
  bool isShutdown() const {
    return UNLIKELY(head_.load(std::memory_order_acquire).isShutdown());
  }

  /// Prevents blocking on this semaphore, causing all blocking wait()
  /// calls to throw ShutdownSemError.  Both currently blocked wait() and
  /// future calls to wait() for which tryWait() would return false will
  /// cause an exception.  Calls to wait() for which the matching post()
  /// has already occurred will proceed normally.
  void shutdown() {
    // first set the shutdown bit
    auto h = head_.load(std::memory_order_acquire);
    while (!h.isShutdown()) {
      if (head_.compare_exchange_strong(h, h.withShutdown())) {
        // success
        h = h.withShutdown();
        break;
      }
      // compare_exchange_strong rereads h, retry
    }

    // now wake up any waiters
    while (h.isNodeIdx()) {
      auto& node = idxToNode(h.idx());
      auto repl = h.withPop(node.next);
      if (head_.compare_exchange_strong(h, repl)) {
        // successful pop, wake up the waiter and move on.  The next
        // field is used to convey that this wakeup didn't consume a value
        node.setShutdownNotice();
        node.handoff().post();
        h = repl;
      }
    }
  }

  /// Returns true iff value was decremented
  bool tryWait() {
    uint32_t n = 1;
    auto rv = decrOrPush(n, 0);
    assert((rv == WaitResult::DECR && n == 0) ||
           (rv != WaitResult::DECR && n == 1));
    // SHUTDOWN is okay here, since we don't actually wait
    return rv == WaitResult::DECR;
  }

  /// Equivalent to (but may be much more efficient than) n calls to
  /// tryWait().  Returns the total amount by which the semaphore's value
  /// was decreased
  uint32_t tryWait(uint32_t n) {
    auto const orig = n;
    while (n > 0) {
#ifndef NDEBUG
      auto prev = n;
#endif
      auto rv = decrOrPush(n, 0);
      assert((rv == WaitResult::DECR && n < prev) ||
             (rv != WaitResult::DECR && n == prev));
      if (rv != WaitResult::DECR) {
        break;
      }
    }
    return orig - n;
  }

  /// Blocks the current thread until there is a matching post or the
  /// semaphore is shut down.  Throws ShutdownSemError if the semaphore
  /// has been shut down and this method would otherwise be blocking.
  /// Note that wait() doesn't throw during shutdown if tryWait() would
  /// return true
  void wait() {
    // early check isn't required for correctness, but is an important
    // perf win if we can avoid allocating and deallocating a node
    if (tryWait()) {
      return;
    }

    // allocateNode() won't compile unless Handoff has a default
    // constructor
    UniquePtr node = allocateNode();

    auto rv = tryWaitOrPush(*node);
    if (UNLIKELY(rv == WaitResult::SHUTDOWN)) {
      assert(isShutdown());
      throw ShutdownSemError("wait() would block but semaphore is shut down");
    }

    if (rv == WaitResult::PUSH) {
      node->handoff().wait();
      if (UNLIKELY(node->isShutdownNotice())) {
        // this wait() didn't consume a value, it was triggered by shutdown
        assert(isShutdown());
        throw ShutdownSemError(
            "blocking wait() interrupted by semaphore shutdown");
      }

      // node->handoff().wait() can't return until after the node has
      // been popped and post()ed, so it is okay for the UniquePtr to
      // recycle the node now
    }
    // else node wasn't pushed, so it is safe to recycle
  }

  /// Returns a guess at the current value, designed for debugging.
  /// If there are no concurrent posters or waiters then this will
  /// be correct
  uint32_t valueGuess() const {
    // this is actually linearizable, but we don't promise that because
    // we may want to add striping in the future to help under heavy
    // contention
    auto h = head_.load(std::memory_order_acquire);
    return h.isNodeIdx() ? 0 : h.value();
  }

 protected:

  enum class WaitResult {
    PUSH,
    DECR,
    SHUTDOWN,
  };

  /// The type of a std::unique_ptr that will automatically return a
  /// LifoSemNode to the appropriate IndexedMemPool
  typedef std::unique_ptr<LifoSemNode<Handoff, Atom>,
                          LifoSemNodeRecycler<Handoff, Atom>> UniquePtr;

  /// Returns a node that can be passed to decrOrLink
  template <typename... Args>
  UniquePtr allocateNode(Args&&... args) {
    auto idx = LifoSemRawNode<Atom>::pool.allocIndex();
    if (idx != 0) {
      auto& node = idxToNode(idx);
      node.clearShutdownNotice();
      try {
        node.init(std::forward<Args>(args)...);
      } catch (...) {
        LifoSemRawNode<Atom>::pool.recycleIndex(idx);
        throw;
      }
      return UniquePtr(&node);
    } else {
      return UniquePtr();
    }
  }

  /// Returns DECR if the semaphore value was decremented (and waiterNode
  /// was untouched), PUSH if a reference to the wait node was pushed,
  /// or SHUTDOWN if decrement was not possible and push wasn't allowed
  /// because isShutdown().  Ownership of the wait node remains the
  /// responsibility of the caller, who must not release it until after
  /// the node's Handoff has been posted.
  WaitResult tryWaitOrPush(LifoSemNode<Handoff, Atom>& waiterNode) {
    uint32_t n = 1;
    return decrOrPush(n, nodeToIdx(waiterNode));
  }

 private:

  FOLLY_ALIGN_TO_AVOID_FALSE_SHARING
  folly::AtomicStruct<LifoSemHead,Atom> head_;

  char padding_[folly::detail::CacheLocality::kFalseSharingRange -
      sizeof(LifoSemHead)];

  static LifoSemNode<Handoff, Atom>& idxToNode(uint32_t idx) {
    auto raw = &LifoSemRawNode<Atom>::pool[idx];
    return *static_cast<LifoSemNode<Handoff, Atom>*>(raw);
  }

  static uint32_t nodeToIdx(const LifoSemNode<Handoff, Atom>& node) {
    return LifoSemRawNode<Atom>::pool.locateElem(&node);
  }

  /// Either increments by n and returns 0, or pops a node and returns it.
  /// If n + the stripe's value overflows, then the stripe's value
  /// saturates silently at 2^32-1
  uint32_t incrOrPop(uint32_t n) {
    while (true) {
      assert(n > 0);

      auto head = head_.load(std::memory_order_acquire);
      if (head.isNodeIdx()) {
        auto& node = idxToNode(head.idx());
        if (head_.compare_exchange_strong(head, head.withPop(node.next))) {
          // successful pop
          return head.idx();
        }
      } else {
        auto after = head.withValueIncr(n);
        if (head_.compare_exchange_strong(head, after)) {
          // successful incr
          return 0;
        }
      }
      // retry
    }
  }

  /// Returns DECR if some amount was decremented, with that amount
  /// subtracted from n.  If n is 1 and this function returns DECR then n
  /// must be 0 afterward.  Returns PUSH if no value could be decremented
  /// and idx was pushed, or if idx was zero and no push was performed but
  /// a push would have been performed with a valid node.  Returns SHUTDOWN
  /// if the caller should have blocked but isShutdown().  If idx == 0,
  /// may return PUSH even after isShutdown() or may return SHUTDOWN
  WaitResult decrOrPush(uint32_t& n, uint32_t idx) {
    assert(n > 0);

    while (true) {
      auto head = head_.load(std::memory_order_acquire);

      if (!head.isNodeIdx() && head.value() > 0) {
        // decr
        auto delta = std::min(n, head.value());
        if (head_.compare_exchange_strong(head, head.withValueDecr(delta))) {
          n -= delta;
          return WaitResult::DECR;
        }
      } else {
        // push
        if (idx == 0) {
          return WaitResult::PUSH;
        }

        if (UNLIKELY(head.isShutdown())) {
          return WaitResult::SHUTDOWN;
        }

        auto& node = idxToNode(idx);
        node.next = head.isNodeIdx() ? head.idx() : 0;
        if (head_.compare_exchange_strong(head, head.withPush(idx))) {
          // push succeeded
          return WaitResult::PUSH;
        }
      }
    }
    // retry
  }
};

} // namespace detail

template <template<typename> class Atom, class BatonType>
struct LifoSemImpl : public detail::LifoSemBase<BatonType, Atom> {
  explicit LifoSemImpl(uint32_t v = 0)
    : detail::LifoSemBase<BatonType, Atom>(v) {}
};

} // namespace folly

#endif


text:
Copyright (c) 2009-2013 Bitcoin Developers
Copyright (c) 2014 Amigacoin Developers

Distributed under the MIT/X11 software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the [OpenSSL Toolkit](http://www.openssl.org/). This product includes
cryptographic software written by Eric Young ([eay@cryptsoft.com](mailto:eay@cryptsoft.com)), and UPnP software written by Thomas Bernard.

See readme-qt.rst for instructions on building Amigacoin-Qt, the
graphical user interface.

WINDOWS BUILD NOTES
===================

Compilers Supported
-------------------
TODO: What works?
Note: releases are cross-compiled using mingw running on Linux.

Dependencies
------------
Libraries you need to download separately and build:

                default path               download
OpenSSL         \openssl-1.0.1g-mgw        http://www.openssl.org/source/
Berkeley DB     \db-5.1.29.NC-mgw          http://www.oracle.com/technology/software/products/berkeley-db/index.html
Boost           \boost-1.55.0-mgw          http://www.boost.org/users/download/
miniupnpc       \miniupnpc-1.9-mgw         http://miniupnp.tuxfamily.org/files/

Their licenses:

	OpenSSL        Old BSD license with the problematic advertising requirement
	Berkeley DB    New BSD license with additional requirement that linked software must be free open source
	Boost          MIT-like license
	miniupnpc      New (3-clause) BSD license

Versions used in this release:

        OpenSSL      1.0.1g
	Berkeley DB  5.1.29.NC
	Boost        1.55.0
	miniupnpc    1.9

OpenSSL
-------
MSYS shell:

un-tar sources with MSYS 'tar xfz' to avoid issue with symlinks (OpenSSL ticket 2377)
change 'MAKE' env. variable from 'C:\MinGW32\bin\mingw32-make.exe' to '/c/MinGW32/bin/mingw32-make.exe'

        cd /c/openssl-1.0.1g
	./config
	make

Berkeley DB
-----------
MSYS shell:

	cd /c/db-5.1.29.NC/build_unix
	sh ../dist/configure --disable-replication --enable-mingw --enable-cxx
	make

Boost
-----
DOS prompt:

	cd \boost_1_55_0
	bootstrap.bat mingw
	b2 --build-type=complete --with-chrono --with-filesystem --with-program_options --with-system --with-thread toolset=gcc stage

MiniUPnPc
---------
UPnP support is optional, make with `USE_UPNP=` to disable it.

MSYS shell:

	cd /c/miniupnpc
	make -f Makefile.mingw
	mkdir miniupnpc
	cp *.h miniupnpc/

leveldb
-------
MSYS shell:

	cd /amigacoin/src/leveldb/
	export TARGET_OS=NATIVE_WINDOWS
	make libleveldb.a libmemenv.a

Amigacoin
---------
DOS prompt:

	cd \amigacoin\src
	mingw32-make -f makefile.mingw
	strip amigacoind.exe


text:
        <button class="btn btn-default" onclick="reload_table()"> Reload</button>

                    No
                    Tanggal Data Masuk
                    ND
                    SC
                    HD INPUTER
                    Tanggal Input
                    HD PS
                    Status PS
                    Tanggal PS
                    Eskalasi Kendala
                    Keterangan Tambahan
                    Action

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit SC

                <form action="#" id="form" class="form-horizontal">
                    <input type="hidden" value="" name="id"/>

                            ND

                                <input name="ND" class="form-control" type="text">

                            SC

                                <input name="sc" class="form-control" type="text">

                            Keterangan

                                <input name="keterangan" class="form-control" type="text">

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit PS

                <form action="#" id="formedit" class="form-horizontal">
                    <input type="hidden" value="" name="id"/>

                            ND

                                <input name="ND" class="form-control" type="text">

                            STATUS PS

                                <select name="ps" class="form-control">
                                    <option value="">Pilih Status PS</option>
                                    <?php
                                        foreach($select_status_ps as $object => $value) {
                                            $object = htmlspecialchars($object);
                                            echo '<option value="'. $object .'">'. $value .'</option>';
                                        }
                                    ?>
                                </select>

                            Keterangan

                                <input name="keterangan" class="form-control" type="text">

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Tambah Keterangan

                <form action="#" id="form3" class="form-horizontal">
                    <input type="hidden" value="" name="id"/>

                            ND

                                <input name="ND" class="form-control" type="text">

                            Keterangan

                                <input name="Keterangan" class="form-control" type="text">

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

DETAIL PELANGGAN

                <form action="#" id="form4" class="form-horizontal">
                    <input type="hidden" value="" name="id"/>

                            ND

                                <textarea name="ND" class="form-control" type="text"></textarea>

                            Nama Pelanggan

                                <textarea name="NAMA" class="form-control" type="text"></textarea>

                            STO

                                <textarea name="CAREA" class="form-control" type="text"></textarea>

                            RK

                                <textarea name="RK" class="form-control" type="text"></textarea>

                            DP

                                <textarea name="DP" class="form-control" type="text"> </textarea>

                </form>

                <button type="button" class="btn btn-danger" data-dismiss="modal">BACK</button>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Masukan Kendala

                <form action="#" id="form6" class="form-horizontal">
                    <input type="hidden" value="" name="id"/>

                            ND

                                <input name="ND" class="form-control" type="text">

                            Kendala

                                <select name="Kendala" class="form-control">
                                    <option value="">Pilih Kendala</option>
                                    <?php
                                        foreach($select_status as $object => $value) {
                                            $object = htmlspecialchars($object);
                                            echo '<option value="'. $object .'">'. $value .'</option>';
                                        }
                                    ?>
                                </select>

                            Keterangan

                                <input name="Keterangan" class="form-control" type="text">

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>


text:
package org.apache.pulsar.websocket.data;

import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * Represent results of publishing multiple messages.
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ProducerAcks {
    List<ProducerAck> messagePublishResults;

    // Version of schema used to encode messages.
    long schemaVersion;
}


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class DeleteRecords(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the DeleteRecords Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(DeleteRecords, self).__init__(temboo_session, '/Library/Zoho/CRM/DeleteRecords')

    def new_input_set(self):
        return DeleteRecordsInputSet()

    def _make_result_set(self, result, path):
        return DeleteRecordsResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return DeleteRecordsChoreographyExecution(session, exec_id, path)

class DeleteRecordsInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the DeleteRecords
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_AuthenticationToken(self, value):
        """
        Set the value of the AuthenticationToken input for this Choreo. ((required, string) A valid authentication token. Permanent authentication tokens can be generated by the GenerateAuthToken Choreo.)
        """
        super(DeleteRecordsInputSet, self)._set_input('AuthenticationToken', value)
    def set_ID(self, value):
        """
        Set the value of the ID input for this Choreo. ((required, integer) The ID for the record you want to delete)
        """
        super(DeleteRecordsInputSet, self)._set_input('ID', value)
    def set_Module(self, value):
        """
        Set the value of the Module input for this Choreo. ((optional, string) The Zoho module you want to access. Defaults to Leads.)
        """
        super(DeleteRecordsInputSet, self)._set_input('Module', value)
    def set_ResponseFormat(self, value):
        """
        Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid formats are: json and xml (the default).)
        """
        super(DeleteRecordsInputSet, self)._set_input('ResponseFormat', value)

class DeleteRecordsResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the DeleteRecords Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. (The response from Zoho. Format corresponds to the ResponseFormat input. Defaults to xml.)
        """
        return self._output.get('Response', None)

class DeleteRecordsChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return DeleteRecordsResultSet(response, path)