text:
package org.jetbrains.plugins.github;

import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcsUtil.VcsUtil;
import git4idea.GitRevisionNumber;
import git4idea.GitUtil;
import git4idea.history.GitHistoryUtils;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import icons.GithubIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.github.util.GithubNotifications;
import org.jetbrains.plugins.github.util.GithubUrlUtil;
import org.jetbrains.plugins.github.util.GithubUtil;

import static org.jetbrains.plugins.github.util.GithubUtil.LOG;
import static org.jetbrains.plugins.github.util.GithubUtil.setVisibleEnabled;

/**
 * Created by IntelliJ IDEA.
 *
 * @author oleg
 * @date 12/10/10
 */
public class GithubOpenInBrowserAction extends DumbAwareAction {
  public static final String CANNOT_OPEN_IN_BROWSER = "Cannot open in browser";

  protected GithubOpenInBrowserAction() {
    super("Open on GitHub", "Open corresponding link in browser", GithubIcons.Github_icon);
  }

  @Override
  public void update(final AnActionEvent e) {
    Project project = e.getData(CommonDataKeys.PROJECT);
    VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
    if (project == null || project.isDefault() || virtualFile == null) {
      setVisibleEnabled(e, false, false);
      return;
    }
    GitRepositoryManager manager = GitUtil.getRepositoryManager(project);

    final GitRepository gitRepository = manager.getRepositoryForFile(virtualFile);
    if (gitRepository == null) {
      setVisibleEnabled(e, false, false);
      return;
    }

    if (!GithubUtil.isRepositoryOnGitHub(gitRepository)) {
      setVisibleEnabled(e, false, false);
      return;
    }

    ChangeListManager changeListManager = ChangeListManager.getInstance(project);
    if (changeListManager.isUnversioned(virtualFile)) {
      setVisibleEnabled(e, true, false);
      return;
    }

    Change change = changeListManager.getChange(virtualFile);
    if (change != null && change.getType() == Change.Type.NEW) {
      setVisibleEnabled(e, true, false);
      return;
    }

    setVisibleEnabled(e, true, true);
  }

  @Override
  public void actionPerformed(final AnActionEvent e) {
    final Project project = e.getData(CommonDataKeys.PROJECT);
    final VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
    final Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (virtualFile == null || project == null || project.isDisposed()) {
      return;
    }

    String urlToOpen = getGithubUrl(project, virtualFile, editor);
    if (urlToOpen != null) {
      BrowserUtil.browse(urlToOpen);
    }
  }

  @Nullable
  private static String getGithubUrl(@NotNull Project project, @NotNull VirtualFile virtualFile, @Nullable Editor editor) {
    GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
    final GitRepository repository = manager.getRepositoryForFile(virtualFile);
    if (repository == null) {
      StringBuilder details = new StringBuilder("file: " + virtualFile.getPresentableUrl() + "; Git repositories: ");
      for (GitRepository repo : manager.getRepositories()) {
        details.append(repo.getPresentableUrl()).append("; ");
      }
      GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "Can't find git repository", details.toString());
      return null;
    }

    final String githubRemoteUrl = GithubUtil.findGithubRemoteUrl(repository);
    if (githubRemoteUrl == null) {
      GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "Can't find github remote");
      return null;
    }

    String relativePath = VfsUtilCore.getRelativePath(virtualFile, repository.getRoot());
    if (relativePath == null) {
      GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "File is not under repository root",
                                    "Root: " + repository.getRoot().getPresentableUrl() + ", file: " + virtualFile.getPresentableUrl());
      return null;
    }

    String hash = getCurrentFileRevisionHash(project, virtualFile);
    if (hash != null) {
      return makeUrlToOpen(editor, relativePath, hash, githubRemoteUrl);
    }

    GithubNotifications.showError(project, CANNOT_OPEN_IN_BROWSER, "Can't get last revision.");
    return null;
  }

  @Nullable
  private static String makeUrlToOpen(@Nullable Editor editor,
                                      @NotNull String relativePath,
                                      @NotNull String branch,
                                      @NotNull String githubRemoteUrl) {
    final StringBuilder builder = new StringBuilder();
    final String githubRepoUrl = GithubUrlUtil.makeGithubRepoUrlFromRemoteUrl(githubRemoteUrl);
    if (githubRepoUrl == null) {
      return null;
    }
    if (StringUtil.isEmptyOrSpaces(relativePath)) {
      builder.append(githubRepoUrl).append("/tree/").append(branch);
    }
    else {
      builder.append(githubRepoUrl).append("/blob/").append(branch).append('/').append(relativePath);
    }

    if (editor != null && editor.getDocument().getLineCount() >= 1) {
      // lines are counted internally from 0, but from 1 on github
      SelectionModel selectionModel = editor.getSelectionModel();
      final int begin = editor.getDocument().getLineNumber(selectionModel.getSelectionStart()) + 1;
      final int selectionEnd = selectionModel.getSelectionEnd();
      int end = editor.getDocument().getLineNumber(selectionEnd) + 1;
      if (editor.getDocument().getLineStartOffset(end - 1) == selectionEnd) {
        end -= 1;
      }
      builder.append("#L").append(begin).append("-L").append(end);
    }

    return builder.toString();
  }

  @Nullable
  private static String getCurrentFileRevisionHash(@NotNull final Project project, @NotNull final VirtualFile file) {
    final Ref<GitRevisionNumber> ref = new Ref<GitRevisionNumber>();
    ProgressManager.getInstance().run(new Task.Modal(project, "Getting last revision", true) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          ref.set((GitRevisionNumber)GitHistoryUtils.getCurrentRevision(project, VcsUtil.getFilePath(file), "HEAD"));
        }
        catch (VcsException e) {
          LOG.warn(e);
        }
      }

      @Override
      public void onCancel() {
        throw new ProcessCanceledException();
      }
    });
    if (ref.isNull()) return null;
    return ref.get().getRev();
  }
}


text:
<title>Ajax Post Web Page Particle.io Photon </title>

Bryces sick meme page for all robotics #sick
 (formerly the Spark.io Core)

Device ID:<input id="myDeviceId" name="myCoreID" type=password size=50 placeholder="78dd12345678123456">

Get this from the core area when logged in

<input id="myFunctionName" name="myFunction"  type=hidden size=50 value="my-main" >

<form name="myForm" method="POST" id="myCoolForm" >

<input id="myParameter" name="params" type=text  style="display:none"     size=50 placeholder="d7-send-high">

Access Token:<input id="myToken" name="access_token" type=password size=50 placeholder="5622ce6bba702ef6bd3456d5ed26aaa4a28d7c9">

Get this from the settings area when logged into http://particle.io

</form>

<input type="button" value="Store the Photon's Token and ID locally!" onClick="{
   localStorage.setItem('myStoredText1', document.all.myToken.value)
   localStorage.setItem('myStoredText2', document.all.myDeviceId.value)
   alert( document.all.myToken.value + ' ' +document.all.myDeviceId.value + ' \nHas been stored')
}">

Photon servo control

    <input type="range" min="0" max="180" value="0" onchange="showValue(this.value)"/>
    0

<input type="button" value="d0-send-1" onClick="{
    sendToSpark('d0-send-1')
}">

<input type="button" value="d0-send-0" onClick="{
    sendToSpark('d0-send-0')
}">

<input type="button" value="d4-send-1" onClick="{
    sendToSpark('d4-send-1')
}">

<input type="button" value="d4-send-0" onClick="{
    sendToSpark('d4-send-0')
}">

<input type="button" value="d5-send-0" onClick="{
    sendToSpark('d5-send-0')
}">

   <input type="button" value="d5-send-1" onClick="{
    sendToSpark('d5-send-1')
}">

   <input type="button" value="d6-send-0" onClick="{
    sendToSpark('d6-send-0')
}">

   <input type="button" value="d6-send-1" onClick="{
    sendToSpark('d6-send-1')
}">

<input type="button" value="d7-send-1" onClick="{
    sendToSpark('d7-send-1')
}">

<input type="button" value="d7-send-0" onClick="{
    sendToSpark('d7-send-0')
}">

   <input type="button" value="CClockwise" onClick="{
    sendToSpark('d6-send-0')
    sendToSpark('d5-send-1')
}">

   <input type="button" value="Clockwise" onClick="{
    sendToSpark('d5-send-0')
    sendToSpark('d6-send-1')
}">

<input type="button" value="a1-read" onClick="{
    sendToSpark('a1-read')
}">

<input type="button" value="a4-send-0" onClick="{
    sendToSpark('a4-send-0')
}">

   <input type="button" value="a4-send-90" onClick="{
    sendToSpark('a4-send-90')
}">

   <input type="button" value="a4-send-180" onClick="{
    sendToSpark('a4-send-80')
}">

<input type="button" value="a4-send-255" onClick="{
    sendToSpark('a4-send-255')
}">

<input type="button" value="a0-read" onClick="{
    sendToSpark('a0-read')}">

<input type="button" value="d6-read" onClick="{
    sendToSpark('d6-read')
}">
<input type="button" value="d5-read" onClick="{
    sendToSpark('d5-read')
}">

   Note: PWM only on A4, A5 presently

 output here

<input type=button id="myToVolts" value="Convert Sensor reading into Volts" onclick="{
  var myTemp = parseFloat(getElementById('myDivId').innerHTML)
  document.all.myCalc1.value = (myTemp * 3.3 / 4095).toFixed(2);
}">
: <input type=text id="myCalc1" value=0 size=5>Volts

redpajama_set_name: RedPajamaGithub


text:
const Bool_t bAnaInfoMC     = kTRUE;
const Bool_t bIsInfoAOD     = kTRUE;
const Bool_t bIsPhysSel     = kFALSE;
const Bool_t bIsCentSel     = kFALSE;
const Bool_t bIsEvPnSel     = kFALSE;
const Bool_t bIsRespPID     = kTRUE;
const UInt_t wTriggerMask   = AliVEvent::kINT7;
const UInt_t wCollisionType = AliPicoHeaderCJ::kPA;

const TString sCentEsti     = "V0A";  // "V0M"; "V0A"; "V0C"
//=============================================================================

Bool_t AddTasksPicoV0Filter()
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if (bIsInfoAOD) {
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/train/AddAODHandler.C");
    AliAODInputHandler *aodIH = AddAODHandler();
  } else {
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/train/AddESDHandler.C");
    AliESDInputHandler *esdIH = AddESDHandler();
//  esdIH->SetReadFriends(kFALSE);
  }

  if (bAnaInfoMC && !bIsInfoAOD) {
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/train/AddMCHandler.C");
    AliMCEventHandler *mctEH = AddMCHandler(kFALSE);
  }

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/train/AddAODOutputHandler.C");
  AliAODHandler *aodH = AddAODOutputHandler();
  aodH->SetOutputFileName("AliAOD.PicoV0s.root");
  aodH->SetFillAOD(kTRUE);
  aodH->SetCreateNonStandardAOD();
  mgr->SetOutputEventHandler(aodH);
//=============================================================================

  if (bIsPhysSel) {
    gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskPhysicsSelection.C");
    AliPhysicsSelectionTask *taskPhysSel = AddTaskPhysicsSelection(bAnaInfoMC);
  }

  if (bIsCentSel) {
    gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskCentrality.C");
    AliCentralitySelectionTask *taskCentSel = AddTaskCentrality(kTRUE, bIsAOD);
    if (wTriggerMask) taskCentSel->SelectCollisionCandidates(wTriggerMask);
    if (bAnaInfoMC)   taskCentSel->SetMCInput();
  }

  if (bIsEvPnSel) {
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
    AliEPSelectionTask *taskEventPlane = AddTaskEventplane();
    if (wTriggerMask) taskEventPlane->SelectCollisionCandidates(wTriggerMask);
    if (bAnaInfoMC)   taskEventPlane->SetUseMCRP();
  }

  if (bIsRespPID) {
    gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
    AliAnalysisTaskSE *taskRespPID = AddTaskPIDResponse(bAnaInfoMC, kTRUE,
                                                        kFALSE, 2,
                                                        kFALSE, "",
                                                        kTRUE, kTRUE,
                                                        2);
    if (wTriggerMask) taskRespPID->SelectCollisionCandidates(wTriggerMask);
  }
//=============================================================================

  AliAnalysisTaskSEPicoV0Maker *taskPicoV0Maker = new AliAnalysisTaskSEPicoV0Maker("AliAnalysisTaskSEPicoV0Maker", bAnaInfoMC);
  if (wTriggerMask) {
    taskPicoV0Maker->SetTriggerMask(wTriggerMask);
    taskPicoV0Maker->SelectCollisionCandidates(wTriggerMask);
  }

  taskPicoV0Maker->SetCollitionType(wCollisionType);
  taskPicoV0Maker->SetCentralityEstimator(sCentEsti.Data());
  taskPicoV0Maker->SetVertexContributorN(1);
//taskPicoV0Maker->SetRefitV0ESD();
//taskPicoV0Maker->SetSkipFastOnly();
//taskPicoV0Maker->SetDMPjetMC();

  mgr->AddTask(taskPicoV0Maker);
  mgr->ConnectInput(taskPicoV0Maker,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskPicoV0Maker, 1, mgr->CreateContainer("listPicoV0MakerEH",
                                                              TList::Class(),
                                                              AliAnalysisManager::kOutputContainer,
                                                              AliAnalysisManager::GetCommonFileName()));

  if (bAnaInfoMC) mgr->ConnectOutput(taskPicoV0Maker, 2, mgr->CreateContainer("listPicoV0MakerMC",
                                                                              TList::Class(),
                                                                              AliAnalysisManager::kOutputContainer,
                                                                              AliAnalysisManager::GetCommonFileName()));
//=============================================================================

  AliAnalysisTaskSEPicoV0Filter *taskPicoV0Filter = new AliAnalysisTaskSEPicoV0Filter("AliAnalysisTaskSEPicoV0Filter");
  if (wTriggerMask) taskPicoV0Filter->SelectCollisionCandidates(wTriggerMask);
  taskPicoV0Filter->SetAnaInfoMC(bAnaInfoMC);

  mgr->AddTask(taskPicoV0Filter);
  mgr->ConnectInput(taskPicoV0Filter, 0, mgr->GetCommonInputContainer());
//=============================================================================

/*if (bAnaInfoMC) {
    if (!bIsInfoAOD) {
      AliAnalysisTaskExtractPerformanceV0 *taskExtractV0 = new AliAnalysisTaskExtractPerformanceV0("AliAnalysisTaskExtractPerformanceV0");
      if (wTriggerMask) taskExtractV0->SelectCollisionCandidates(wTriggerMask);

      taskExtractV0->SetIsNuclear(kTRUE);
      taskExtractV0->SetINT7Trigger(kTRUE);
      taskExtractV0->SetUseOnTheFly(kFALSE);
      taskExtractV0->SetTakeAllTracks(kFALSE);
      taskExtractV0->SetpARapidityShift();
      taskExtractV0->SetCentralityEstimator(sCentEsti);
      taskExtractV0->SetLightWeightAnalysis(kFALSE);
      taskExtractV0->SetpAVertexSelection(kTRUE);
      taskExtractV0->SetSpecialExecution(kFALSE);
      taskExtractV0->SetSaveAssociatedOnly(kTRUE);
      taskExtractV0->SetSkipTrigger(kTRUE);
      taskExtractV0->SetDoNotCallTPCdEdx(kFALSE);
//    taskExtractV0->SetDiffractiveOnly(kTRUE);

      mgr->AddTask(taskExtractV0);
      mgr->ConnectInput(taskExtractV0,  0, mgr->GetCommonInputContainer());
      mgr->ConnectOutput(taskExtractV0, 1, mgr->CreateContainer("clistV0MC",
                                                                TList::Class(),
                                                                AliAnalysisManager::kOutputContainer,
                                                                AliAnalysisManager::GetCommonFileName()));

      AliAnalysisDataContainer *cV0Tree = mgr->CreateContainer("cTreeMC",
                                                               TTree::Class(),
                                                               AliAnalysisManager::kOutputContainer,
                                                               AliAnalysisManager::GetCommonFileName());
      cV0Tree->SetSpecialOutput();
      mgr->ConnectOutput(taskExtractV0, 2, cV0Tree);
    }
  } else {
    if (bIsInfoAOD) {
      AliAnalysisTaskExtractV0AOD *taskExtractV0 = new AliAnalysisTaskExtractV0AOD("AliAnalysisTaskExtractV0AOD");
      if (wTriggerMask) taskExtractV0->SelectCollisionCandidates(wTriggerMask);

      taskExtractV0->SetIsNuclear(kTRUE);
      taskExtractV0->SetIsLowEnergyPP(kFALSE);
      taskExtractV0->SetUseOnTheFly(kFALSE);
      taskExtractV0->SetTriggerMask("kINT7");

      mgr->AddTask(taskExtractV0);
      mgr->ConnectInput(taskExtractV0,  0, mgr->GetCommonInputContainer());
      mgr->ConnectOutput(taskExtractV0, 1, mgr->CreateContainer("cListV0",
                                                              TList::Class(),
                                                              AliAnalysisManager::kOutputContainer,
                                                              AliAnalysisManager::GetCommonFileName()));

      AliAnalysisDataContainer *cV0Tree = mgr->CreateContainer("cTree",
                                                               TTree::Class(),
                                                               AliAnalysisManager::kOutputContainer,
                                                               AliAnalysisManager::GetCommonFileName());
      cV0Tree->SetSpecialOutput();
      mgr->ConnectOutput(taskExtractV0, 2, cV0Tree);
    } else {
      AliAnalysisTaskExtractV0 *taskExtractV0 = new AliAnalysisTaskExtractV0("AliAnalysisTaskExtractV0");
      if (wTriggerMask) taskExtractV0->SelectCollisionCandidates(wTriggerMask);

      taskExtractV0->SetIsNuclear(kTRUE);
      taskExtractV0->SetINT7Trigger(kTRUE);
      taskExtractV0->SetUseOnTheFly(kFALSE);
      taskExtractV0->SetTakeAllTracks(kFALSE);
      taskExtractV0->SetCentralityEstimator(sCentEsti);
      taskExtractV0->SetLightWeightAnalysis(kFALSE);
      taskExtractV0->SetpAVertexSelection(kTRUE);
      taskExtractV0->SetSkipTrigger(kFALSE);
      taskExtractV0->SetTPCdEdxSelection(kFALSE);

      mgr->AddTask(taskExtractV0);
      mgr->ConnectInput(taskExtractV0,  0, mgr->GetCommonInputContainer());
      mgr->ConnectOutput(taskExtractV0, 1, mgr->CreateContainer("clistV0",
                                                                TList::Class(),
                                                                AliAnalysisManager::kOutputContainer,
                                                                AliAnalysisManager::GetCommonFileName()));

      AliAnalysisDataContainer *cV0Tree = mgr->CreateContainer("cTree",
                                                               TTree::Class(),
                                                               AliAnalysisManager::kOutputContainer,
                                                               AliAnalysisManager::GetCommonFileName());
      cV0Tree->SetSpecialOutput();
      mgr->ConnectOutput(taskExtractV0, 2, cV0Tree);
    }
  }*/

  return kFALSE;
}


text:
package com.github.kennycyb.uifactory.sample.components;

import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SpringLayout;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.kennycyb.uifactory.core.factory.SwingFactory;
import com.github.kennycyb.uifactory.core.factory.annotations.UiCursor;
import com.github.kennycyb.uifactory.core.factory.annotations.UiEnabled;
import com.github.kennycyb.uifactory.core.factory.annotations.UiIcon;
import com.github.kennycyb.uifactory.core.factory.annotations.UiLayout;
import com.github.kennycyb.uifactory.core.factory.annotations.UiText;
import com.github.kennycyb.uifactory.core.factory.annotations.UiToolTip;
import com.github.kennycyb.uifactory.core.factory.annotations.UiType;
import com.github.kennycyb.uifactory.core.factory.annotations.constraints.UiSpringGridConstraint;
import com.github.kennycyb.uifactory.core.factory.annotations.frame.UiFrameCloseOperation;
import com.github.kennycyb.uifactory.core.factory.annotations.frame.UiWindowPosition;
import com.github.kennycyb.uifactory.core.factory.enums.CursorType;
import com.github.kennycyb.uifactory.core.factory.enums.FrameCloseOperation;
import com.github.kennycyb.uifactory.core.factory.enums.WindowPosition;
import com.github.kennycyb.uifactory.sample.components.swing.CustomJButton;

/**
 *
 * @since 1.0
 */
@UiWindowPosition(WindowPosition.CENTER)
@UiText("Sample Button")
@UiLayout(SpringLayout.class)
@UiFrameCloseOperation(FrameCloseOperation.EXIT)
@UiSpringGridConstraint(cols = 2)
public class SampleButton extends JFrame {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unused")
	private static Logger LOGGER = LoggerFactory.getLogger(SampleButton.class);

	@UiText("Button with tooltip")
	JLabel label1;

	@UiToolTip("hello tooltip")
	@UiText("hello")
	JButton hello;

	@UiText("Button disabled")
	JLabel label2;

	@UiEnabled(false)
	@UiText("disabled")
	JButton disabled;

	@UiText("Button with icon only")
	JLabel label3;

	@UiIcon("iMac.icon")
	JButton iconButton;

	@UiText("Button with icon and text")
	JLabel label4;
	@UiText("iconWithText")
	@UiIcon("iMac.icon")
	JButton iconWithText;

	@UiText("Custom Button")
	JLabel label5;

	@UiType(CustomJButton.class)
	@UiText("custom button")
	@UiCursor(CursorType.HAND)
	JButton customButton;

	void onHello_actionPerformed(final ActionEvent e) {
		JOptionPane.showMessageDialog(this, "onHello_actionPerformed");
	}

	void onIconWithText_actionPerformed(final ActionEvent e) {
		JOptionPane.showMessageDialog(this, "onIconWithText_actionPerformed");
	}

	public static void main(final String[] args) {
		SwingFactory.create(SampleButton.class).setVisible(true);
	}
}


text:
import { expect } from 'chai';
import getRegionSettingsReducer, {
  getCountryCodeReducer,
  getAreaCodeReducer,
} from './getRegionSettingsReducer';
import getModuleStatusReducer from '../../lib/getModuleStatusReducer';
import actionTypes from './actionTypes';

describe('getCountryCodeReducer', () => {
  it('should be a function', () => {
    expect(getCountryCodeReducer).to.be.a('function');
  });
  it('should return a reducer', () => {
    expect(getCountryCodeReducer(actionTypes)).to.be.a('function');
  });
  describe('countryCodeReducer', () => {
    const reducer = getCountryCodeReducer(actionTypes);
    it('should have initial state of null', () => {
      expect(reducer(undefined, {})).to.be.null;
    });
    it('should return original state of actionTypes is not recognized', () => {
      const originalState = {};
      expect(reducer(originalState, { type: 'foo' })).to.equal(originalState);
    });
    it('should return action.countryCode on setData', () => {
      const countryCode = 'foo';
      expect(
        reducer(null, {
          type: actionTypes.setData,
          countryCode,
        }),
      ).to.equal(countryCode);
    });
    it('should return originalState on setData if action.countryCode is undefined', () => {
      expect(
        reducer('foo', {
          type: actionTypes.setData,
        }),
      ).to.equal('foo');
    });
  });
});

describe('getAreaCodeReducer', () => {
  it('should be a function', () => {
    expect(getAreaCodeReducer).to.be.a('function');
  });
  it('should return a reducer', () => {
    expect(getAreaCodeReducer(actionTypes)).to.be.a('function');
  });
  describe('areaCodeReducer', () => {
    const reducer = getAreaCodeReducer(actionTypes);
    it('should have initial state of ""', () => {
      expect(reducer(undefined, {})).to.equal('');
    });
    it('should return original state of actionTypes is not recognized', () => {
      const originalState = {};
      expect(reducer(originalState, { type: 'foo' })).to.equal(originalState);
    });
    it('should return action.areaCode on setData', () => {
      const areaCode = 'foo';
      expect(
        reducer(null, {
          type: actionTypes.setData,
          areaCode,
        }),
      ).to.equal(areaCode);
    });
    it('should return originalState on setData if action.areaCode is undefined', () => {
      expect(
        reducer('foo', {
          type: actionTypes.setData,
        }),
      ).to.equal('foo');
    });
  });
});

describe('getRegionSettingsReducer', () => {
  it('should be a function', () => {
    expect(getRegionSettingsReducer).to.be.a('function');
  });
  it('should return a reducer', () => {
    expect(getRegionSettingsReducer(actionTypes)).to.be.a('function');
  });
  describe('regionSettingsReducer', () => {
    const reducer = getRegionSettingsReducer(actionTypes);
    const statusReducer = getModuleStatusReducer(actionTypes);
    it('should be a combined reducer', () => {
      expect(reducer(undefined, {})).to.deep.equal({
        status: statusReducer(undefined, {}),
      });
    });
  });
});


text:
// [The "BSD licence"]
// Copyright (c) 2014-2015 Hannah von Reth <vonreth@kde.org>
// Copyright (c) 2009-2011 Yasuhiro Matsumoto
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  1. Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//  3. The name of the author may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef _TCP_H_
#define _TCP_H_

#ifdef _MSC_VER
#pragma warning( disable : 4996 4244 )
#define __attribute__(x)
#endif
void growl_tcp_write_raw(int sock, const unsigned char *data, const int data_length);
void growl_tcp_write_nl(int sock);
void growl_tcp_write(int sock , const char *const format , ...) __attribute__((format(printf, 2, 3)));
char *growl_tcp_read(int sock);
int growl_tcp_open(const char *server);
void growl_tcp_close(int sock);
int growl_tcp_datagram(const char *server , const unsigned char *data , const int data_length);

#endif /* _TCP_H_ */

/* vim:set et sw=2 ts=2 ai: */


text:
package org.apache.fluo.accumulo.util;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests ZookeeperUtil
 */
public class ZookeeperUtilTest {

  @Test
  public void testParseServersAndRoot() {
    Assert.assertEquals("localhost", ZookeeperUtil.parseServers("localhost/my/root"));
    Assert.assertEquals("host1,host2:2181", ZookeeperUtil.parseServers("host1,host2:2181/my/root"));
    Assert.assertEquals("localhost", ZookeeperUtil.parseServers("localhost"));

    Assert.assertEquals("/my/root", ZookeeperUtil.parseRoot("localhost/my/root"));
    Assert.assertEquals("/my/root/2", ZookeeperUtil.parseRoot("host1,host2:2181/my/root/2"));
    Assert.assertEquals("/my/root/3", ZookeeperUtil.parseRoot("host1,host2:2181/my/root/3    "));
    Assert.assertEquals("/", ZookeeperUtil.parseRoot("localhost"));
  }
}


text:
<?php

declare(strict_types=1);

namespace Leevel\Session;

use Leevel\Cache\File as CacheFile;

/**
 * session.file.
 */
class File extends Session implements ISession
{
    /**
     * 配置.
     */
    protected array $option = [
        'id'          => null,
        'name'        => null,
    ];

    /**
     * 构造函数.
     */
    public function __construct(CacheFile $cache, array $option = [])
    {
        $this->option = array_merge($this->option, $option);
        parent::__construct($cache);
    }
}


text:
import pytz
import logging
import cgi
from datetime import datetime, time, timedelta
from django.utils.translation import ugettext_noop
from django.utils.translation import ugettext as _
from corehq.apps.domain.models import Domain
from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin
from corehq.apps.reports.generic import GenericTabularReport
from corehq.apps.reports.datatables import (
    DataTablesColumn,
    DataTablesHeader,
    DTSortType,
)
from corehq.apps.reports.util import format_datatables_data
from custom.fri.models import FRISMSLog, PROFILE_DESC
from custom.fri.reports.filters import (InteractiveParticipantFilter,
    RiskProfileFilter, SurveyDateSelector)
from custom.fri.api import get_message_bank, add_metadata, get_date
from corehq.apps.sms.models import INCOMING, OUTGOING
from dimagi.utils.parsing import json_format_datetime
from casexml.apps.case.models import CommCareCase
from casexml.apps.case.xform import CaseDbCache
from corehq.apps.users.models import CouchUser, UserCache
from dimagi.utils.timezones import utils as tz_utils
from custom.fri.api import get_interactive_participants, get_valid_date_range
from django.core.urlresolvers import reverse
from corehq.apps.reports.dispatcher import CustomProjectReportDispatcher
from dateutil.parser import parse

RESPONSE_NOT_APPLICABLE = 1
NO_RESPONSE = 2

class FRIReport(CustomProjectReport, GenericTabularReport):
    _interactive_participants = None
    _domain_obj = None

    @property
    def timezone(self):
        return pytz.timezone(self.domain_obj.default_timezone)

    @property
    def domain_obj(self):
        if not self._domain_obj:
            self._domain_obj = Domain.get_by_name(self.domain, strict=True)
        return self._domain_obj

    @property
    def interactive_participants(self):
        if self._interactive_participants is None:
            self._interactive_participants = get_interactive_participants(self.domain)
        return self._interactive_participants

class MessageBankReport(FRIReport):
    name = ugettext_noop("Message Bank")
    slug = "fri_message_bank"
    description = ugettext_noop("Displays the message bank.")
    emailable = False
    fields = (
        "custom.fri.reports.filters.RiskProfileFilter",
    )
    report_template_path = "fri/message_bank.html"
    show_all_rows = True

    @property
    def template_context(self):
        result = {
            "is_previewer" : self.request.couch_user.is_previewer(),
        }
        return result

    @property
    def risk_profile(self):
        return RiskProfileFilter.get_value(self.request, self.domain)

    @property
    def headers(self):
        cols = [
            DataTablesColumn(_("Message Text")),
            DataTablesColumn(_("Risk Profile")),
        ]
        for case in self.interactive_participants:
            header_text = case.get_case_property("name_and_pid")
            cols.append(DataTablesColumn(header_text))
        header = DataTablesHeader(*cols)
        header.custom_sort = [[1, "asc"]]
        return header

    @property
    def rows(self):
        risk_profile = self.risk_profile
        result = []
        message_bank_messages = get_message_bank(self.domain, for_comparing=True)
        data = {}
        for case in self.interactive_participants:
            data[case._id] = self.get_participant_message_counts(message_bank_messages, case)

        for entry in message_bank_messages:
            msg_risk_profile = entry["message"].risk_profile
            if risk_profile and risk_profile != msg_risk_profile:
                continue
            msg_risk_profile_desc = None
            if msg_risk_profile:
                msg_risk_profile_desc = PROFILE_DESC.get(msg_risk_profile)
            msg_risk_profile_desc = msg_risk_profile_desc or "-"
            row = [
                self._fmt(entry["message"].message),
                self._fmt2(entry["message"].fri_id, msg_risk_profile_desc),
            ]
            for case in self.interactive_participants:
                row.append(self._fmt(data[case._id][entry["message"]._id]))
            result.append(row)
        return result

    def get_participant_messages(self, case):
        result = FRISMSLog.view("sms/by_recipient",
                                startkey=["CommCareCase", case._id, "SMSLog", OUTGOING],
                                endkey=["CommCareCase", case._id, "SMSLog", OUTGOING, {}],
                                reduce=False,
                                include_docs=True).all()
        return result

    def get_participant_message_counts(self, message_bank_messages, case):
        result = {}
        for entry in message_bank_messages:
            result[entry["message"]._id] = 0
        participant_messages = self.get_participant_messages(case)
        for sms in participant_messages:
            if sms.xforms_session_couch_id is None and sms.direction == OUTGOING:
                if not sms.fri_message_bank_lookup_completed:
                    add_metadata(sms, message_bank_messages)
                if sms.fri_message_bank_message_id in result:
                    result[sms.fri_message_bank_message_id] += 1
        return result

    def _fmt(self, val):
        return format_datatables_data(val, val)

    def _fmt2(self, val1, val2):
        val1 = cgi.escape(val1, True)
        val2 = cgi.escape(val2, True)
        return self.table_cell(val1, '%s%s' % (val1, val2))

class MessageReport(FRIReport, DatespanMixin):
    name = ugettext_noop('Message Report')
    slug = 'fri_message_report'
    fields = [
        DatespanMixin.datespan_field,
        "custom.fri.reports.fields.ShowOnlySurveyTraffic",
    ]
    exportable = True
    emailable = False

    @property
    def headers(self):
        header = DataTablesHeader(
            DataTablesColumn(_("Participant ID")),
            DataTablesColumn(_("Study Arm")),
            DataTablesColumn(_("Originator")),
            DataTablesColumn(_("Timestamp")),
            DataTablesColumn(_("Message Text")),
            DataTablesColumn(_("Message ID")),
            DataTablesColumn(_("Direction")),
        )
        header.custom_sort = [[1, "asc"],[0, "asc"],[3, "asc"]]
        return header

    def _case_name(self, contact, reverse=False):
        first_name = contact.get_case_property("first_name") or ""
        pid = contact.get_case_property("pid") or ""
        if first_name or pid:
            if reverse:
                return "%s %s" % (pid, first_name)
            else:
                return "%s %s" % (first_name, pid)
        else:
            return "-"

    def _user_name(self, contact):
        return contact.first_name or contact.raw_username

    def _participant_id(self, contact):
        if contact and contact.doc_type == "CommCareCase":
            return self._case_name(contact, True)
        else:
            return "-"

    def _originator(self, message, recipient, sender):
        if message.direction == INCOMING:
            if recipient:
                if recipient.doc_type == "CommCareCase":
                    return self._case_name(recipient)
                else:
                    return self._user_name(recipient)
            else:
                return "-"
        else:
            if sender:
                if sender.doc_type == "CommCareCase":
                    return self._case_name(sender)
                else:
                    return self._user_name(sender)
            else:
                return _("System")

    def show_only_survey_traffic(self):
        value = self.request.GET.get("show_only_survey_traffic", None)
        return value == "on"

    @property
    def rows(self):
        startdate = json_format_datetime(self.datespan.startdate_utc)
        enddate = json_format_datetime(self.datespan.enddate_utc)
        data = FRISMSLog.view("sms/by_domain",
                              startkey=[self.domain, "SMSLog", startdate],
                              endkey=[self.domain, "SMSLog", enddate],
                              include_docs=True,
                              reduce=False).all()
        result = []
        direction_map = {
            INCOMING: _("Incoming"),
            OUTGOING: _("Outgoing"),
        }
        message_bank_messages = get_message_bank(self.domain, for_comparing=True)

        case_cache = CaseDbCache(domain=self.domain, strip_history=False, deleted_ok=True)
        user_cache = UserCache()

        show_only_survey_traffic = self.show_only_survey_traffic()

        for message in data:
            if message.direction == OUTGOING and not message.processed:
                continue
            if show_only_survey_traffic and message.xforms_session_couch_id is None:
                continue
            # Add metadata from the message bank if it has not been added already
            if (message.direction == OUTGOING) and (not message.fri_message_bank_lookup_completed):
                add_metadata(message, message_bank_messages)

            if message.couch_recipient_doc_type == "CommCareCase":
                recipient = case_cache.get(message.couch_recipient)
            else:
                recipient = user_cache.get(message.couch_recipient)

            if message.chat_user_id:
                sender = user_cache.get(message.chat_user_id)
            else:
                sender = None

            study_arm = None
            if message.couch_recipient_doc_type == "CommCareCase":
                study_arm = case_cache.get(message.couch_recipient).get_case_property("study_arm")

            timestamp = tz_utils.adjust_datetime_to_timezone(message.date, pytz.utc.zone, self.domain_obj.default_timezone)
            result.append([
                self._fmt(self._participant_id(recipient)),
                self._fmt(study_arm or "-"),
                self._fmt(self._originator(message, recipient, sender)),
                self._fmt_timestamp(timestamp),
                self._fmt(message.text),
                self._fmt(message.fri_id or "-"),
                self._fmt(direction_map.get(message.direction,"-")),
            ])
        return result

    def _fmt(self, val):
        return format_datatables_data(val, val)

    def _fmt_timestamp(self, timestamp):
        return self.table_cell(
            timestamp,
            timestamp.strftime("%Y-%m-%d %H:%M:%S"),
        )

class PHEDashboardReport(FRIReport):
    name = ugettext_noop("PHE Dashboard")
    slug = "fri_phe_dashboard"
    description = ugettext_noop("Displays a list of active, arm A, participants.")
    emailable = False
    exportable = False
    report_template_path = "fri/phe_dashboard.html"
    hide_filters = True

    @property
    def template_context(self):
        result = {
            "fri_message_bank_url" : reverse(CustomProjectReportDispatcher.name(), args=[self.domain, MessageBankReport.slug]),
            "fri_chat_actions" : [self._open_chat_action(case._id) for case in self.interactive_participants],
        }
        return result

    @property
    def headers(self):
        return DataTablesHeader(
            DataTablesColumn(_("Participant")),
            DataTablesColumn(_("Last Day of PTS"), sort_type=DTSortType.NUMERIC),
            DataTablesColumn(_("Open Chat Window")),
        )

    @property
    def rows(self):
        result = []
        cases = self.interactive_participants
        for case in cases:
            start_date, end_date = get_valid_date_range(case)
            # end_date will never be None because of how we get_interactive_participants
            result.append([
                self._fmt(case.get_case_property("name_and_pid")),
                self._fmt_date(end_date),
                self._fmt_chat_link(case.get_id),
            ])
        return result

    def _fmt(self, val):
        return format_datatables_data(val, val)

    def _fmt_date(self, val):
        date_as_num = int(val.strftime("%Y%m%d"))
        return format_datatables_data(val.strftime("%m/%d/%Y"), date_as_num)

    def _fmt_chat_link(self, case_id):
        return self.table_cell(
            case_id,
            """%s""" % (self._open_chat_action(case_id), _("Open Chat Window")),
        )

    def _open_chat_action(self, case_id):
        url = reverse("sms_chat", args=[self.domain, case_id])
        return "window.open('%s', '_blank', 'location=no,menubar=no,scrollbars=no,status=no,toolbar=no,height=400,width=400');" % url

class SurveyResponsesReport(FRIReport):
    name = ugettext_noop("Survey Responses")
    slug = "fri_survey_responses"
    description = ugettext_noop("Shows information pertaining to survey responses.")
    emailable = False
    fields = [
        "custom.fri.reports.filters.SurveyDateSelector",
    ]

    @property
    def survey_report_date(self):
        return SurveyDateSelector.get_value(self.request, self.domain)

    @property
    def headers(self):
        cols = [
            DataTablesColumn(_("PID")),
            DataTablesColumn(_("Name")),
            DataTablesColumn(_("Arm")),
            DataTablesColumn(_("Week 1")),
            DataTablesColumn(_("Week 2")),
            DataTablesColumn(_("Week 3")),
            DataTablesColumn(_("Week 4")),
            DataTablesColumn(_("Week 5")),
            DataTablesColumn(_("Week 6")),
            DataTablesColumn(_("Week 7")),
            DataTablesColumn(_("Week 8")),
        ]
        header = DataTablesHeader(*cols)
        header.custom_sort = [[0, "asc"]]
        return header

    @property
    def rows(self):
        participants = self.get_participants()
        result = []
        for case in participants:
            pid = case.get_case_property("pid")
            study_arm = case.get_case_property("study_arm")
            registration_date = get_date(case, "start_date")
            first_name = case.get_case_property("first_name") or ""
            if registration_date is None:
                continue
            first_survey_date = self.get_first_tuesday(registration_date)
            row = [
                self._fmt(pid),
                self._fmt(first_name),
                self._fmt(study_arm),
            ]
            for i in range(8):
                next_survey_date = first_survey_date + timedelta(days=7*i)
                response = self.get_first_survey_response(case, next_survey_date)
                if response == RESPONSE_NOT_APPLICABLE:
                    row.append(self._fmt("-"))
                elif response == NO_RESPONSE:
                    row.append(self._fmt(_("No Response")))
                else:
                    response_timestamp = tz_utils.adjust_datetime_to_timezone(
                        response.date, pytz.utc.zone, self.domain_obj.default_timezone)
                    row.append(self._fmt_timestamp(response_timestamp))
            result.append(row)
        return result

    def get_first_tuesday(self, dt):
        while dt.weekday() != 1:
            dt = dt + timedelta(days=1)
        return dt

    def get_participants(self):
        result = CommCareCase.view("hqcase/types_by_domain",
                                   key=[self.domain, "participant"],
                                   include_docs=True,
                                   reduce=False).all()
        survey_report_date = parse(self.survey_report_date).date()

        def filter_function(case):
            registration_date = get_date(case, "start_date")
            if registration_date is None:
                return False
            first_tuesday = self.get_first_tuesday(registration_date)
            last_tuesday = first_tuesday + timedelta(days=49)
            return (survey_report_date >= first_tuesday and
                survey_report_date <= last_tuesday)

        result = filter(filter_function, result)
        return result

    def get_first_survey_response(self, case, dt):
        timestamp_start = datetime.combine(dt, time(20, 45))
        timestamp_start = tz_utils.adjust_datetime_to_timezone(
            timestamp_start, self.domain_obj.default_timezone, pytz.utc.zone)
        timestamp_start = timestamp_start.replace(tzinfo=None)
        timestamp_start = json_format_datetime(timestamp_start)

        timestamp_end = datetime.combine(dt + timedelta(days=1), time(11, 45))
        timestamp_end = tz_utils.adjust_datetime_to_timezone(
            timestamp_end, self.domain_obj.default_timezone, pytz.utc.zone)
        timestamp_end = timestamp_end.replace(tzinfo=None)
        if timestamp_end > datetime.utcnow():
            return RESPONSE_NOT_APPLICABLE
        timestamp_end = json_format_datetime(timestamp_end)

        all_inbound = FRISMSLog.view(
            "sms/by_recipient",
            startkey=["CommCareCase", case._id, "SMSLog", INCOMING, timestamp_start],
            endkey=["CommCareCase", case._id, "SMSLog", INCOMING, timestamp_end],
            reduce=False,
            include_docs=True
        ).all()

        survey_responses = filter(lambda s: s.xforms_session_couch_id is not None, all_inbound)
        if len(survey_responses) > 0:
            return survey_responses[0]
        else:
            return NO_RESPONSE

    def _fmt(self, val):
        return format_datatables_data(val, val)

    def _fmt_timestamp(self, timestamp):
        return self.table_cell(
            timestamp,
            timestamp.strftime("%Y-%m-%d %H:%M:%S"),
        )


text:
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>43.0</apiVersion>
    <label>CRLP_RollupContact_BTN</label>
    <description>Recalculate Contact Rollups Button</description>
</ApexPage>


text:
"""Defines utility methods for testing queues"""
import django.utils.timezone as timezone

import job.test.utils as job_test_utils
from job.execution.configuration.json.exe_config import ExecutionConfiguration
from queue.models import JobLoad, Queue
from node.resources.node_resources import NodeResources
from node.resources.resource import Cpus, Disk, Mem, Gpus

def create_job_load(job_type=None, measured=None, pending_count=0, queued_count=0, running_count=0):
    """Creates a job load model for unit testing

    :returns: The job load model
    :rtype: :class:`queue.models.JobLoad`
    """

    if not job_type:
        job_type = job_test_utils.create_seed_job_type()

    if not measured:
        measured = timezone.now()

    return JobLoad.objects.create(job_type=job_type, measured=measured, pending_count=pending_count,
                                  queued_count=queued_count, running_count=running_count,
                                  total_count=pending_count + queued_count + running_count)

def create_queue(job_type=None, priority=1, timeout=3600, resources=None, cpus_required=1.0, mem_required=512.0,
                 disk_in_required=200.0, disk_out_required=100.0, disk_total_required=300.0, gpus_required=0, queued=timezone.now()):
    """Creates a queue model for unit testing

    :param job_type: The job type
    :type job_type: :class:`job.models.JobType`
    :param priority: The priority
    :type priority: int
    :param timeout: The timeout
    :type timeout: int
    :param resources_required: The required resources
    :type resources_required: :class:`node.resources.node_resources.NodeResources`
    :param cpus_required: The number of CPUs required
    :type cpus_required: float
    :param mem_required: The memory required in MiB
    :type mem_required: float
    :param disk_in_required: The input disk space required in MiB
    :type disk_in_required: float
    :param disk_out_required: The output disk space required in MiB
    :type disk_out_required: float
    :param disk_total_required: The total disk space required in MiB
    :type disk_total_required: float
    :param gpus_required: The number of GPUs required
    :type gpus_required: float
    :param queued: The time the execution was queued
    :type queued: :class:`datetime.datetime`
    """

    job = job_test_utils.create_job(job_type=job_type, status='QUEUED')
    if not resources:
        resources = NodeResources([Cpus(cpus_required), Mem(mem_required), Disk(disk_total_required), Gpus(gpus_required)])

    return Queue.objects.create(job_type=job.job_type, job=job, exe_num=job.num_exes, priority=priority,
                                timeout=timeout, input_file_size=disk_in_required,
                                interface=job.get_job_interface().get_dict(),
                                configuration=ExecutionConfiguration().get_dict(),
                                resources=resources.get_json().get_dict(), queued=queued)


text:
<?php

namespace User\Model;

use Zend\Db\TableGateway\TableGateway;

class UserTable
{
	protected $tableGateway;

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}
	public function fetchAll(){

        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

	public function getUser($id){
		$id = (int) $id;
		$rowset = $this->tableGateway->select(array('id' => $id));
		$row = $rowset->current();
		if(!$row){
			throw new \Exception("Could Not find row $id");
		}
		return $row;
	}

	public function saveUser(User $user)
	{

		$data = array(
			'fname' => $user->fname,
			'mname' => $user->mname,
			'lname' => $user->lname,
			'email' => $user->email,
			'role' => (int)$user->role,
			'username' => $user->username,
			'secret' => $user->secret,
			'status' => (int)$user->status,
		);
		$id = intval($user->id);
		if($id == 0){
			$this->tableGateway->insert($data);
		}
		else {
			if($this->getUser($id)){
				$this->tableGateway->update($data,array('id' => $id));
			}
			else{
				throw new \Exception('User id does not exist');
			}
		}
	}
	public function deleteUser($id)
	{
		$this->tableGateway->delete(array('id' => (int) $id));
	}
}


text:
CHANGELOG for 3.0.x
===================

This changelog references the relevant changes (bug and security fixes) done
in 3.0 minor versions.

To get the diff for a specific change, go to
https://github.com/FriendsOfSymfony/FOSElasticaBundle/commit/XXX where XXX is
the commit hash. To get the diff between two versions, go to
https://github.com/FriendsOfSymfony/FOSElasticaBundle/compare/v3.0.0...v3.0.1

To generate a changelog summary since the last version, run
`git log --no-merges --oneline v3.0.0...3.0.x`

* 3.0.0-ALPHA6

 * Moved `is_indexable_callback` from the listener properties to a type property called
   `indexable_callback` which is run when both populating and listening for object
   changes.
 * AbstractProvider constructor change: Second argument is now an `IndexableInterface`
   instance.
 * Annotation @Search moved to FOS\ElasticaBundle\Annotation\Search with FOS\ElasticaBundle\Configuration\Search deprecated
 * Deprecated FOS\ElasticaBundle\Client in favour of FOS\ElasticaBundle\Elastica\Client
 * Deprecated FOS\ElasticaBundle\DynamicIndex in favour of FOS\ElasticaBundle\Elastica\Index
 * Deprecated FOS\ElasticaBundle\IndexManager in favour of FOS\ElasticaBundle\Index\IndexManager
 * Deprecated FOS\ElasticaBundle\Resetter in favour of FOS\ElasticaBundle\Index\Resetter

* 3.0.0-ALPHA5 (2014-05-23)

 * Doctrine Provider speed up by disabling persistence logging while populating documents

* 3.0.0-ALPHA4 (2014-04-10)

 * Indexes are now capable of logging errors with Elastica
 * Fixed deferred indexing of deleted documents
 * Resetting an index will now create it even if it doesn't exist
 * Bulk upserting of documents is now supported when populating

* 3.0.0-ALPHA3 (2014-04-01)

 * a9c4c93: Logger is now only enabled in debug mode by default
 * #463: allowing hot swappable reindexing
 * #415: BC BREAK: document indexing occurs in postFlush rather than the pre* events previously.
 * 7d13823: Dropped (broken) support for Symfony <2.3
 * #496: Added support for HTTP headers
 * #528: FOSElasticaBundle will disable Doctrine logging when populating for a large increase in speed

* 3.0.0-ALPHA2 (2014-03-17)

 * 41bf07e: Renamed the `no-stop-on-error` option in PopulateCommand to `ignore-errors`
 * 418b9d7: Fixed validation of url configuration
 * 726892c: Ignore TypeMissingException when resetting a single type. This allows to create new types without having to recreate the whole index.
 * 7f53bad Add support for include_in_{parent,root} for nested and objects


text:
package org.pmiops.workbench.exceptions;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.pmiops.workbench.model.ErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ExceptionAdvice {
  private static final Logger log = Logger.getLogger(ExceptionAdvice.class.getName());

  @ExceptionHandler({HttpMessageNotReadableException.class})
  public ResponseEntity<?> messageNotReadableError(Exception e) {
    log.log(Level.INFO, "failed to parse HTTP request message, returning 400", e);
    return ResponseEntity.status(HttpStatus.BAD_REQUEST)
        .body(
            WorkbenchException.errorResponse("failed to parse valid JSON request message")
                .statusCode(HttpStatus.BAD_REQUEST.value()));
  }

  @ExceptionHandler({Exception.class})
  public ResponseEntity<?> serverError(Exception e) {
    final int statusCode;
    // if exception class has an HTTP status associated with it, grab it
    if (e.getClass().getAnnotation(ResponseStatus.class) != null) {
      statusCode = e.getClass().getAnnotation(ResponseStatus.class).value().value();
    } else {
      statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
    }

    ErrorResponse errorResponse = WorkbenchException.errorResponse().statusCode(statusCode);

    // Only include Exception details on Workbench errors.
    if (e instanceof WorkbenchException) {
      errorResponse.setErrorClassName(e.getClass().getName());
      ErrorResponse thrownErrorResponse = ((WorkbenchException) e).getErrorResponse();
      if (thrownErrorResponse != null) {
        errorResponse
            .message(thrownErrorResponse.getMessage())
            .errorCode(thrownErrorResponse.getErrorCode())
            .parameters(thrownErrorResponse.getParameters());
      }
    }

    // only log error if it's a server error
    if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR.value()) {
      final String logMessage =
          String.format("ErrorId %s: %s", errorResponse.getErrorUniqueId(), e.getClass().getName());
      log.log(Level.SEVERE, logMessage, e);
    }

    return ResponseEntity.status(statusCode).body(errorResponse);
  }
}


text:
static const char kAllButtonTargetsKey;

@interface _MARUIButtonTarget : NSObject

@property (nonatomic, copy) void (^block)(id sender);

- (id)initWithBlock:(void (^)(id sender))block;

- (void)invoke:(id)sender;

@end

@implementation _MARUIButtonTarget

- (id)initWithBlock:(void (^)(id sender))block{
    self = [super init];
    if (self) {
        _block = [block copy];
    }
    return self;
}

- (void)invoke:(id)sender {
    if (_block) _block(sender);
}

@end

static char * mar_button_sounddic_key;

@implementation UIButton (MAREX)

- (void)mar_addActionBlock:(void (^)(id))block forState:(UIControlEvents)event
{
    if (!block) return;
    _MARUIButtonTarget *target = [[_MARUIButtonTarget alloc] initWithBlock:block];
    [self addTarget:target action:@selector(invoke:) forControlEvents:event];
    NSMutableArray *targets = [self _mar_allButtonTargets];
    [targets addObject:target];
}

- (void)mar_removeAllActionBlocks
{
    NSMutableArray *targets = [self _mar_allButtonTargets];
    [targets enumerateObjectsUsingBlock:^(id  _Nonnull target, NSUInteger idx, BOOL * _Nonnull stop) {
        [self removeTarget:target action:@selector(invoke:) forControlEvents:UIControlEventAllEvents];
    }];
    [targets removeAllObjects];
}

- (NSMutableArray *)_mar_allButtonTargets
{
    NSMutableArray *targets = objc_getAssociatedObject(self, &kAllButtonTargetsKey);
    if (!targets) {
        targets = [NSMutableArray arrayWithCapacity:7];
        objc_setAssociatedObject(self, &kAllButtonTargetsKey, targets, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return targets;
}

- (void)mar_setSoundID:(MARAudioID)audioID forState:(UIControlEvents)event
{
    NSMutableDictionary *soundDic = [self mar_soundDic];
    NSString *key = [NSString stringWithFormat:@"%ld", (long)event];
    MARSystemSound *sound = [soundDic objectForKey:key];
    if (sound) {
        [self removeTarget:sound action:@selector(play) forControlEvents:event];
        [soundDic removeAllObjects];
    }
    sound = [MARSystemSound new];
    sound.audioID = audioID;
    [soundDic setObject:sound forKey:key];
    [self addTarget:sound action:@selector(play) forControlEvents:event];
}

- (void)mar_setLocalSoundURL:(NSURL *)soundURL forState:(UIControlEvents)event
{
    NSMutableDictionary *soundDic = [self mar_soundDic];
    NSString *key = [NSString stringWithFormat:@"%ld", (long)event];
    MARSystemSound *sound = [soundDic objectForKey:key];
    if (sound) {
        [self removeTarget:sound action:@selector(play) forControlEvents:event];
        [soundDic removeAllObjects];
    }
    sound = [MARSystemSound new];
    sound.soundURL = soundURL;
    [soundDic setObject:sound forKey:key];
    [self addTarget:sound action:@selector(play) forControlEvents:event];
}

- (NSMutableDictionary *)mar_soundDic
{
    NSMutableDictionary *soundDic = [self mar_getAssociatedValueForKey:mar_button_sounddic_key];
    if (!soundDic) {
        soundDic = [NSMutableDictionary dictionaryWithCapacity:7];
        [self mar_setAssociateValue:soundDic withKey:mar_button_sounddic_key];
    }
    return soundDic;
}

@end


text:
package org.openflow.protocol.statistics;

import java.nio.ByteBuffer;

/**
 * Represents an ofp_port_stats_request structure
 * @author David Erickson (daviderickson@cs.stanford.edu)
 */
public class OFPortStatisticsRequest implements OFStatistics {
    protected short portNumber;

    /**
     * @return the portNumber
     */
    public short getPortNumber() {
        return portNumber;
    }

    /**
     * @param portNumber the portNumber to set
     */
    public void setPortNumber(short portNumber) {
        this.portNumber = portNumber;
    }

    public int getLength() {
        return 8;
    }

    public void readFrom(ByteBuffer data) {
        this.portNumber = data.getShort();
        data.getShort(); // pad
        data.getInt(); // pad
    }

    public void writeTo(ByteBuffer data) {
        data.putShort(this.portNumber);
        data.putShort((short) 0); // pad
        data.putInt(0); // pad
    }

    public int hashCode() {
        final int prime = 433;
        int result = 1;
        result = prime * result + portNumber;
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof OFPortStatisticsRequest)) {
            return false;
        }
        OFPortStatisticsRequest other = (OFPortStatisticsRequest) obj;
        if (portNumber != other.portNumber) {
            return false;
        }
        return true;
    }
}


text:
package com.streamsets.pipeline.destination.aerospike;

import com.streamsets.pipeline.api.ConfigDef;
import com.streamsets.pipeline.api.ValueChooserModel;

public class BinMappingConfig {
  @ConfigDef(
      required = true,
      type = ConfigDef.Type.STRING,
      label = "Bin",
      description = "Expression to get bin name",
      displayPosition = 20
  )
  public String binExpr;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.STRING,
      label = "Value",
      description = "Expression to get value",
      defaultValue="${record:attribute('/val')}",
      displayPosition = 30
  )
  public String valueExpr;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue="STRING",
      label = "Partition Value Type",
      description="Partition column's value type",
      displayPosition = 20
  )
  @ValueChooserModel(DataTypeChooserValues.class)
  public DataType valueType = DataType.STRING;

  public BinMappingConfig() {
  }
}


text:
module NUSBotgram
  module DataTypes
    # Telegram InlineKeyboardButton data type
    #
    # @attr [String] text Label text on the button
    # @attr [String] url Optional. HTTP url to be opened when button is pressed
    # @attr [String] callback_data Optional. Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
    # @attr [String] switch_inline_query Optional. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot's username will be inserted.
    #
    # See more at https://core.telegram.org/bots/api#inlinekeyboardbutton
    class InlineKeyboardButton < NUSBotgram::DataTypes::Base
      attribute :text, String
      attribute :url, String
      attribute :callback_data, String
      attribute :switch_inline_query, String
    end
  end
end


text:
package google

import (
	"encoding/base64"
	"fmt"
	"log"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
	"google.golang.org/api/cloudkms/v1"
)

func TestAccKmsSecret_basic(t *testing.T) {
	// Nested tests confuse VCR
	skipIfVcr(t)
	t.Parallel()

	projectOrg := getTestOrgFromEnv(t)
	projectBillingAccount := getTestBillingAccountFromEnv(t)

	projectId := "tf-test-" + randString(t, 10)
	keyRingName := fmt.Sprintf("tf-test-%s", randString(t, 10))
	cryptoKeyName := fmt.Sprintf("tf-test-%s", randString(t, 10))

	plaintext := fmt.Sprintf("secret-%s", randString(t, 10))
	aad := "plainaad"

	// The first test creates resources needed to encrypt plaintext and produce ciphertext
	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testGoogleKmsCryptoKey_basic(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName),
				Check: func(s *terraform.State) error {
					ciphertext, cryptoKeyId, err := testAccEncryptSecretDataWithCryptoKey(t, s, "google_kms_crypto_key.crypto_key", plaintext, "")

					if err != nil {
						return err
					}

					// The second test asserts that the data source has the correct plaintext, given the created ciphertext
					vcrTest(t, resource.TestCase{
						PreCheck:  func() { testAccPreCheck(t) },
						Providers: testAccProviders,
						Steps: []resource.TestStep{
							{
								Config: testGoogleKmsSecret_datasource(cryptoKeyId.terraformId(), ciphertext),
								Check:  resource.TestCheckResourceAttr("data.google_kms_secret.acceptance", "plaintext", plaintext),
							},
						},
					})

					return nil
				},
			},
			// With AAD
			{
				Config: testGoogleKmsCryptoKey_basic(projectId, projectOrg, projectBillingAccount, keyRingName, cryptoKeyName),
				Check: func(s *terraform.State) error {
					ciphertext, cryptoKeyId, err := testAccEncryptSecretDataWithCryptoKey(t, s, "google_kms_crypto_key.crypto_key", plaintext, aad)

					if err != nil {
						return err
					}

					// The second test asserts that the data source has the correct plaintext, given the created ciphertext
					vcrTest(t, resource.TestCase{
						PreCheck:  func() { testAccPreCheck(t) },
						Providers: testAccProviders,
						Steps: []resource.TestStep{
							{
								Config: testGoogleKmsSecret_aadDatasource(cryptoKeyId.terraformId(), ciphertext, base64.StdEncoding.EncodeToString([]byte(aad))),
								Check:  resource.TestCheckResourceAttr("data.google_kms_secret.acceptance", "plaintext", plaintext),
							},
						},
					})

					return nil
				},
			},
		},
	})
}

func testAccEncryptSecretDataWithCryptoKey(t *testing.T, s *terraform.State, cryptoKeyResourceName, plaintext, aad string) (string, *kmsCryptoKeyId, error) {
	config := googleProviderConfig(t)

	rs, ok := s.RootModule().Resources[cryptoKeyResourceName]
	if !ok {
		return "", nil, fmt.Errorf("Resource not found: %s", cryptoKeyResourceName)
	}

	cryptoKeyId, err := parseKmsCryptoKeyId(rs.Primary.Attributes["id"], config)

	if err != nil {
		return "", nil, err
	}

	kmsEncryptRequest := &cloudkms.EncryptRequest{
		Plaintext: base64.StdEncoding.EncodeToString([]byte(plaintext)),
	}

	if aad != "" {
		kmsEncryptRequest.AdditionalAuthenticatedData = base64.StdEncoding.EncodeToString([]byte(aad))
	}

	encryptResponse, err := config.NewKmsClient(config.userAgent).Projects.Locations.KeyRings.CryptoKeys.Encrypt(cryptoKeyId.cryptoKeyId(), kmsEncryptRequest).Do()

	if err != nil {
		return "", nil, fmt.Errorf("Error encrypting plaintext: %s", err)
	}

	log.Printf("[INFO] Successfully encrypted plaintext and got ciphertext: %s", encryptResponse.Ciphertext)

	return encryptResponse.Ciphertext, cryptoKeyId, nil
}

func testGoogleKmsSecret_datasource(cryptoKeyTerraformId, ciphertext string) string {
	return fmt.Sprintf(`
data "google_kms_secret" "acceptance" {
  crypto_key = "%s"
  ciphertext = "%s"
}
`, cryptoKeyTerraformId, ciphertext)
}

func testGoogleKmsSecret_aadDatasource(cryptoKeyTerraformId, ciphertext, aad string) string {
	return fmt.Sprintf(`
data "google_kms_secret" "acceptance" {
  crypto_key                    = "%s"
  ciphertext                    = "%s"
  additional_authenticated_data = "%s"
}
`, cryptoKeyTerraformId, ciphertext, aad)
}


text:
  Servoz est
       un village
       localisé dans le département de Haute-Savoie en Rhône-Alpes. Elle totalisait 895 habitants en 2008.

La ville compte de multiples  aménagements, elle propose entre autres un terrain de tennis, un équipement de roller/skate et deux boucles de randonnée.

La localité dispose concernant l'enseignement de un collège.
Concernant les moins de 6 ans, la ville est équipée de une école primaire.
Servoz est équipée des  équipements éducatifs facilitant une bonne prise en charge des jeunes.
Si vous avez un projet de faire une acquisition à Servoz, il est intéressant d' évaluer la notoriété des équipements éducatifs

À proximité de Servoz sont situées les villes de
Domancy à 9 km, 1 771 habitants,
Chamonix-Mont-Blanc à 8 km, 9 195 habitants,
Saint-Gervais-les-Bains localisée à 5 km, 5 594 habitants,
Passy à 6 km, 11 234 habitants,
 entre autres. De plus, Servoz est située à seulement 20 km de Cluses.

À Servoz, le prix moyen à l'achat d'un appartement s'évalue à 5 167 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 6 251 € du m². À la location la valeur moyenne se situe à 10,43 € du m² mensuel.

Le parc de logements, à Servoz, se décomposait en 2011 en 248 appartements et 440 maisons soit
 un marché relativement équilibré.

Si vous envisagez de demenager à Servoz, vous pourrez facilement trouver une maison à acheter.


text:
Modernizr.addTest('backgroundcliptext', function(){

  var div = document.createElement('div');
  div.style.cssText = Modernizr._prefixes.join('background-clip:text;');
  return !!div.style.cssText.replace(/\s/g,'').length;

});


text:
typedef void(^lzButtonBlock)(UIButton* button);
@interface LZBaseViewController : UIViewController

@property (nonatomic,strong)UIButton *leftButon;
@property (nonatomic,strong)UIButton *rightButton;
@property (nonatomic,strong)UILabel *customTitleLabel;

@property (nonatomic,copy)NSString *flog;

- (void)lzSetNavigationTitle:(NSString*)title;
- (void)lzSetLeftButtonWithTitle:(NSString*)title
                   selectedImage:(NSString*)selectImageName
                     normalImage:(NSString*)normalImage
                     actionBlock:(lzButtonBlock)block;

- (void)lzSetRightButtonWithTitle:(NSString*)title
                    selectedImage:(NSString*)selectImageName
                      normalImage:(NSString*)normalImage
                      actionBlock:(lzButtonBlock)block;

- (void)lzHiddenNavigationBar:(BOOL)hidden;
@end


text:
using Orleans;
using System.Threading.Tasks;
using UnitTests.GrainInterfaces;

namespace UnitTests.Grains
{
    public class NullStateGrain : Grain<NullableState>, INullStateGrain
    {
        public async Task SetStateAndDeactivate(NullableState state)
        {
            this.State = state;
            await WriteStateAsync();
            DeactivateOnIdle();
        }

        public Task<NullableState> GetState()
        {
            return Task.FromResult(this.State);
        }
    }
}


text:
shrinkypic
==========

A pyside/python interface for several ImageMagick picture manipulation affects.

SHRINKYPIC INSTALLATION

Open a terminal and perform the following steps.

1) Pull from repository with:

    hg clone http://hg.palaso.org/shrinkypic ~/Projects/shrinkypic

2) Install required packages:

    sudo apt-get install python-pyside imagemagick pngnq

3) Install ShrinkyPic with:

    cd ~/Projects/shrinkypic
    ./setup.py build
    sudo ./setup.py install

4) Start ShinkyPic with:

    shrinkypic


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

module Capricious

  describe LogNormal do
    LOGNORMAL_SAMPLE_COUNT = 50000

    def generate_samples(policy, mean, variance, count=LOGNORMAL_SAMPLE_COUNT)
      # identify mu and sigmasq so that log-normal will have requested mean and variance
      # http://en.wikipedia.org/wiki/Log-normal_distribution
      sigmasq = Math.log(1.0 + (variance / (mean**2)))
      mu = Math.log(mean) - 0.5*sigmasq
      @randomvar = Capricious::LogNormal.new(mu, sigmasq, nil, policy, true)
      count.times {@randomvar.next}
    end

    [MWC5].each do |policy|
      [[2.5,1.5], [10.0,3.5]].each do |mean, variance|

        it "should, given policy #{policy.name}, generate log-normally-distributed numbers with a mean of #{mean} and a variance of #{variance}, as judged by mean estimates" do
          generate_samples(policy, mean, variance)
          @randomvar.aggregate.mean.should be_close(@randomvar.expected_mean, 0.02 * mean)
          @randomvar.aggregate.stddev.should be_close(Math.sqrt(@randomvar.expected_variance), 0.02 * Math.sqrt(variance))
          @randomvar.aggregate.variance.should be_close(@randomvar.expected_variance, 0.02 * variance)
        end

      end

      it "should, given policy #{policy.name}, generate the same sequence given the same seed" do
        @randomvar = Normal.new(1.0, 1.5, nil, policy, false)
        @randomvar2 = Normal.new(1.0, 1.5, nil, policy, false)
        (LOGNORMAL_SAMPLE_COUNT/10).times { @randomvar2.next.should == @randomvar.next }
      end

    end
  end
end


text:
namespace hana = boost::hana;

int main() {
    BOOST_HANA_CONSTANT_CHECK(
        BOOST_HANA_STRING("abcdef") == BOOST_HANA_STRING("abcdef")
    );

    BOOST_HANA_CONSTANT_CHECK(
        BOOST_HANA_STRING("abcdef") != BOOST_HANA_STRING("abef")
    );
}


text:
package quickfix;

/**
 * Applications can throw this exception to abort the sending or resending
 * of a message.
 */
public class DoNotSend extends Exception {

    public DoNotSend() {
        super();
    }
}


text:
var path = require('path')
var autoprefixer = require('autoprefixer')

var ENV = process.env.NODE_ENV || 'development'
var DEV_SERVER_PORT = 8080
var PROXY = {
  '/api': {
    target: 'http://localhost:3000',
    pathRewrite: {'^/api': '/api'}
  }
}

module.exports = {
  context: path.join(__dirname, '/client'),
  entry: {
    main: './main',
    another: './another'
  },
  output: require('./.webpack/output')(ENV),
  devServer: require('./.webpack/devServer')(ENV, DEV_SERVER_PORT, PROXY),
  plugins: require('./.webpack/plugins')(ENV),
  module: require('./.webpack/loaders')(ENV),
  resolve: {
    extensions: ['', '.js', '.ts', '.jsx']
  },
  postcss: [
    autoprefixer({
      browsers: ['last 2 version']
    })
  ],
  progress: true,
  compress: true
}


text:
package com.google.gwt.dev.util.xml;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Retains parsed information about a particular schema clas.
 */
public class HandlerClassInfo {
  private static final HandlerMethod[] EMPTY_ARRAY_HANDLERMETHOD = new HandlerMethod[0];
  private static Map<Class<?>,HandlerClassInfo> sClassInfoMap =
    new HashMap<Class<?>,HandlerClassInfo>();

  public static synchronized HandlerClassInfo getClassInfo(Class<?> c) {
    if (sClassInfoMap.containsKey(c)) {
      return sClassInfoMap.get(c);
    } else {
      throw new RuntimeException("The schema class '" + c.getName()
          + "' should have been registered prior to parsing");
    }
  }

  public static synchronized void registerClass(Class<?> c) {
    if (sClassInfoMap.containsKey(c)) {
      return;
    }

    // Put a guard null in so that recursive registration of the same
    // class won't die.
    //
    sClassInfoMap.put(c, null);
    HandlerClassInfo classInfo = createClassInfo(c);
    sClassInfoMap.put(c, classInfo);
  }

  private static HandlerClassInfo createClassInfo(Class<?> c) {
    Map<String,HandlerMethod> namedHandlerMethods = new HashMap<String,HandlerMethod>();
    try {
      loadClassInfoRecursive(namedHandlerMethods, c);
    } catch (Exception e) {
      throw new RuntimeException("Unable to use class '" + c.getName()
          + "' as a handler", e);
    }
    HandlerClassInfo classInfo = new HandlerClassInfo(namedHandlerMethods);
    return classInfo;
  }

  private static void loadClassInfoRecursive(Map<String,HandlerMethod> namedHandlerMethods,
      Class<?> c) {
    if (!Schema.class.isAssignableFrom(c)) {
      // Have gone up as far as we can go.
      //
      return;
    }

    Method[] methods = c.getDeclaredMethods();
    for (int i = 0, n = methods.length; i < n; ++i) {
      Method method = methods[i];
      HandlerMethod handlerMethod = HandlerMethod.tryCreate(method);
      if (handlerMethod != null) {
        // Put in the map, but only if that method isn't already there.
        // (Allows inheritance where most-derived class wins).
        //
        String name = method.getName();
        if (!namedHandlerMethods.containsKey(name)) {
          namedHandlerMethods.put(name, handlerMethod);
        }
      }
    }

    // Recurse into superclass.
    //
    Class<?> superclass = c.getSuperclass();
    if (superclass != null) {
      loadClassInfoRecursive(namedHandlerMethods, superclass);
    }
  }

  private final Map<String,HandlerMethod> namedHandlerMethods;

  // Nobody else can create one.
  private HandlerClassInfo(Map<String,HandlerMethod> namedHandlerMethods) {
    this.namedHandlerMethods = namedHandlerMethods;
  }

  public HandlerMethod getEndMethod(String localName) {
    String methodName = "__" + localName.replace('-', '_');
    return namedHandlerMethods.get(methodName + "_end");
  }

  public HandlerMethod[] getHandlerMethods() {
    return namedHandlerMethods.values().toArray(EMPTY_ARRAY_HANDLERMETHOD);
  }

  public HandlerMethod getStartMethod(String localName) {
    String methodName = "__" + localName.replace('-', '_');
    return namedHandlerMethods.get(methodName + "_begin");
  }

  public HandlerMethod getTextMethod() {
    return namedHandlerMethods.get("__text");
  }
}


text:
layout: post
title: "PackageMaker could not copy unreadable files"
published: true
---

I was getting a bizarre error with Apple's PackageMaker

    % /Developer/usr/bin/packagemaker --filter "\.DS_Store" --root-volume-only --domain system --verbose --no-relocate -l "/" --target 10.5 --id com.codeography.program.pkg --resources build/Release/Package/resources --scripts build/Release/Package/scripts --title "Program Name 2.1.10" --version 2.1.10 --root build/Release/Package/root --out installer.pkg
    Preverifying root
      Preverifying root
      Checking bundle identifiers
      Checking package configuration
      Checking contents
      Loading contents
      Applying Recommended Permissions
      Checking for ZeroLink
    Preverifying Program Name 2.1.10
      Preverifying Program Name 2.1.10
    Building root
      Building root
      Copying Scripts
      Copying unreadable files to temporary location
        ERROR: Could not copy unreadable files.
      Renaming package files

After hours of searching I found that I had a vim swap file that wasn't world readable. And when I change the owner of the files that I need to package to be root, my user no longer had read permissions. Finding this was pretty easy using the `find` command.

    % find . \! -perm -444
    installer/config/.Info.plist.swp

Deleted that file and everything worked.


text:
exports.buildFormatHash = function(modelName, locals, response) {
  var formatHash, renderHTML, renderJSON, renderXML;
  renderHTML = function() {
    return response.render("" + modelName + "/show.html.eco", locals);
  };
  renderJSON = function() {
    return response.render("" + modelName + "/show.json.eco", locals);
  };
  renderXML = function() {
    return response.render("" + modelName + "/show.xml.eco", locals);
  };
  formatHash = {
    'text/html': renderHTML,
    'application/json': renderJSON,
    'application/fhir+json': renderJSON,
    'application/xml': renderXML,
    'application/fhit+xml': renderXML
  };
  return formatHash;
};


text:
#ifndef           POLYBLK_H
#define           POLYBLK_H

#include          "rect.h"
#include          "points.h"
#include          "scrollview.h"
#include          "elst.h"

#include          "hpddef.h"     //must be last (handpd.dll)

enum POLY_TYPE
{
  POLY_TEXT,                     // Text region
  POLY_PAGE,                     // Page block
  POLY_X                         // Don't care
};

class DLLSYM POLY_BLOCK          //poly block
{

  public:
    POLY_BLOCK() {
    }                            //empty constructor
    POLY_BLOCK(  //simple constructor
               ICOORDELT_LIST *points,
               POLY_TYPE t);
    ~POLY_BLOCK () {
    }                            //destructor

    TBOX *bounding_box() {  // access function
      return &box;
    }

    ICOORDELT_LIST *points() {  // access function
      return &vertices;
    }

    void compute_bb();

    POLY_TYPE isA() {
      return type;
    }

    void rotate(  //rotate it
                FCOORD rotation);
    void move(                //move it
              ICOORD shift);  //vector

    void plot(ScrollView* window, ScrollView::Color colour, inT32 num);

    void fill(ScrollView* window, ScrollView::Color colour);

    BOOL8 contains(  // is poly inside poly
                   POLY_BLOCK *poly);

    BOOL8 overlap(  // do polys overlap
                  POLY_BLOCK *poly);

    inT16 winding_number(                         // get winding number
                         const ICOORD &test_pt);  // around this point

    void prep_serialise() {
      vertices.prep_serialise ();
    }

    void dump(FILE *f) {
      vertices.dump (f);
    }

    void de_dump(FILE *f) {
      vertices.de_dump (f);
    }

                                 //convert to ascii
    make_serialise (POLY_BLOCK) void serialise_asc (
      FILE * f);
    void de_serialise_asc(  //convert from ascii
                          FILE *f);

  private:
    ICOORDELT_LIST vertices;     // vertices
    TBOX box;                     // bounding box
    POLY_TYPE type;              // Page block or
    // text region
};

class DLLSYM PB_LINE_IT          //line iterator
{
  public:
    PB_LINE_IT(  //constructor
               POLY_BLOCK *blkptr) {
      block = blkptr;
    }

    NEWDELETE2 (PB_LINE_IT) void set_to_block (POLY_BLOCK * blkptr) {
      block = blkptr;
    }

    ICOORDELT_LIST *get_line(inT16 y);

  private:
    POLY_BLOCK * block;
};
#endif


text:
package com.rackspacecloud.blueflood.outputs.serializers;

import com.rackspacecloud.blueflood.exceptions.SerializationException;
import com.rackspacecloud.blueflood.outputs.formats.MetricData;
import com.rackspacecloud.blueflood.types.Locator;
import com.rackspacecloud.blueflood.utils.Util;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

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

public class BatchedMetricsJSONOutputSerializer extends JSONBasicRollupsOutputSerializer
        implements BatchedMetricsOutputSerializer<JSONObject> {

    @Override
    public JSONObject transformRollupData(Map<Locator, MetricData> metricData, Set<MetricStat> filterStats)
            throws SerializationException {
        final JSONObject globalJSON = new JSONObject();
        final JSONArray metricsArray = new JSONArray();

        for (Map.Entry<Locator, MetricData> one : metricData.entrySet()) {
            final JSONObject singleMetricJSON = new JSONObject();
            singleMetricJSON.put("metric", one.getKey().getMetricName());
            singleMetricJSON.put("unit", one.getValue().getUnit() == null ? Util.UNKNOWN : one.getValue().getUnit());
            singleMetricJSON.put("type", one.getValue().getType());
            Set<MetricStat> oneFilterStats = fixFilterStats(one.getValue(), filterStats);
            JSONArray values = transformDataToJSONArray(one.getValue(), oneFilterStats);
            singleMetricJSON.put("data", values);
            metricsArray.add(singleMetricJSON);
        }

        globalJSON.put("metrics", metricsArray);
        return globalJSON;
    }
}


text: I wasn't born to follow and I'm not sure if I was born to lead, but what I'm certain is that I was born to fight my way through life and win.


text:
package net.dempsy.vfs.gz;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import net.dempsy.vfs.CompressedFileSystem;

public class GzFileSystem extends CompressedFileSystem {

    private final static String[] SCHEMES = {"gz"};

    @Override
    public String[] supportedSchemes() {
        return SCHEMES;
    }

    @Override
    protected InputStream wrap(final InputStream is) throws IOException {
        return new GZIPInputStream(is);
    }

    @Override
    protected OutputStream wrap(final OutputStream os) throws IOException {
        return new GZIPOutputStream(os);
    }
}


text:
#ifndef INNER_PRODUCT_CIRCUIT_H
#define INNER_PRODUCT_CIRCUIT_H

#include "libgarble/garble.h"
#include "libgarble/circuit_builder.h"

/* Creates a circuit that finds the inner product modulo p between the first and second half of the input wires (each vectors of n/len numbers, with len bits each), and put the output on the output wires (also a vector of n/len len-bit numbers). Assumes that the inputs are reduced modulo p.
*/

void innerProductCircuit(garble_circuit *circuit, garble_context *garblingContext,
                  int n, int offset, int* inputs, int* outputs, int len, int p);

/* Creates a circuit that finds the inner product over GF2N between the first and second half of the input wires (each vectors of n/len numbers, with len bits each), and put the output on the output wires (also a vector of n/len len-bit numbers). This also takes the irreducible polynomial for the representation of GF2N used.
*/

void innerProductGF2NCircuit(garble_circuit *circuit, garble_context *garblingContext,
                  int n, int* inputs, int* outputs, int len, int *irredPoly);

/* Creates a circuit that finds the inner product modulo 2^32 (ie, for 32-bit numbers) between the first and second half of the input wires (each vectors of n/len numbers, with len bits each), and put the output on the output wires (also a vector of n/len len-bit numbers).
*/

void innerProductCircuit32(garble_circuit *circuit, garble_context *garblingContext,
                  int n, int* inputs, int* outputs);

#endif


text:
def lambda_handler(event, context):
    name = event.get('name')
    print timeit.default_timer()
    return "hello %s"%name


text:
BitRun API is a project that provides ability to execute code snippets
written in various languages (Ruby, Pythong, Node, PHP, Go, ...). Under the hood
it used Docker to run the code and provides process and filesystem isolation. API
service is written in Go and could be easily installed on the server and only
requires Docker to run.

## Reference

To execute the code you must provide filename and content.

```
POST https://bit.run/api/v1/run
```

Parameters:

- `filename` - Name of the file to run. This is needed to determine the language. Required.
- `content` - Code to execute. Required.

Example:

```bash
curl \
  -i \
  -X POST "https://bit.run/api/v1/run" \
  -d "filename=test.rb&content=puts 'Hello World'"
```

Output:

```
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 13
X-Run-Command: ruby test.rb
X-Run-Duration: 261.752379ms
X-Run-Exitcode: 0

Hello World
```

If request is successful, API will respond with plaintext of the executed command.
Extra meta data will be included in the headers:

- `X-Run-Command`  - full command that was executed
- `X-Run-Duration` - how long it took to process the request (not to run the code)
- `X-Run-Exitcode` - exit code of executed command

Each run is limited by 10 seconds. If your code runs longer than 10s API will
respond with 400 and provide error message:

```json
{
  "error": "Operation timed out after 10s"
}
```

### Command override

By default, bitrun will execute code snippet with a default command. For example,
ruby snippet will use the following command: "ruby main.rb". To override the command,
you can specify `command` parameter when making an API call:

```bash
curl \
  -i \
  -X POST "https://bit.run/api/v1/run" \
  -d "filename=test.rb&content=puts 'Hello World'&command=ruby -v"
```

Response:

```
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 59
X-Run-Command: ruby test.rb
X-Run-Duration: 126.436286ms
X-Run-Exitcode: 0

ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]
```

### Supported languages

To check which languages are currently supported, make a call:

```
GET https://bit.run/api/v1/config
```

Response will include supported languages along with commands used to run scripts:

```json
{
  ".rb": {
    "image": "ruby:2.2",
    "command": "ruby %s",
    "format": "text/plain"
  },
  ".py": {
    "image": "python:2.7",
    "command": "python %s",
    "format": "text/plain"
  },
  ".php": {
    "image": "php:5.6",
    "command": "php %s",
    "format": "text/plain"
  }
}
```

## License

MIT


text:
<!DOCTYPE html>

<meta name="google-site-verification" content="5nSBbBmcaGsk2iAbW9GKCfvnwqVdClgqJsGNQPTGth8" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Tulevik Solutions LLP">
    <meta name="author" content="ashok parmar & team">

    <title>Tulevik Solutions LLP</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">

	<link rel="stylesheet" href="vendor/font-awesome-4.7.0/css/font-awesome.css">

    <link href="css/new-age.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>

                        Who We Are

                        What We Do

                        Product

                        Contact

Who We Are

As a team we are focused on the success of our customers by delivering high quality, dependable and consistent results. Our ability to adapt to our customers processes is core to our business and the key to the achievement of our customer's satisfaction.

What We Do

We come along side your organization and act like an extension of your business to help you delivery your services in an extremely efficient and cost effective way. We can easily mould our idea into your process or help you define a new process to ensure timely delivery with consistent quality.

Even if you have a unique and specialized service we can help you to convert into IT services. Our team has the ability to learn even the most complex processes and convert it to application process with mobility. Our team will work tirelessly until you are completely satisfied.

Web Development

Web development broadly refers to the tasks associated with developing websites for hosting via intranet or Internet.

Mobility

Mobility is the trend toward a shift in work habits, with more employees working out of the office and using mobile devices and cloud services to perform business tasks.

Custom Web API

A web service/API is any piece of software that makes itself available over the internet and uses a standardized XML/JSON messaging system. Web Services using SOAP, REST, and JSON

WAMP/LAMP

WAMP is for windows operating system. LAMP is for Linux operating system.
Full form of WAMP is Windows, Apache, MySQL and PHP & LAMP is Linux, Apache, MySQL and PHP.

MEAN stack/NodeJs

The term MEAN stack refers to a collection of JavaScript based technologies used to develop web applications. MEAN is an acronym for MongoDB, ExpressJS, AngularJS and Node.js.

WordPress

Create your stunning website WordPress.com powers beautiful websites for businesses, professionals, and bloggers.

AWS

Amazon Web Services (AWS) is a comprehensive, evolving cloud computing platform provided by Amazon.com.

Heroku

Heroku is a cloud platform that lets companies build, deliver, monitor and scale apps — we're the fastest way to go from idea to URL, bypassing all those infrastructure headaches.

DigitalOcean

DigitalOcean is a cloud infrastructure provider focused on simplifying web infrastructure for software developers.

Our Product

Feedback Analyzer

Invoice Management

Assessment Master

Bill Analyzer & Audit

 Feedback Analyzer

Benefits

Direct Engagement to customer and Employee

Reputation Management

Stay Ahead of the Curve

Accountability

Who can & where it use

Department Wise Surveys

Management/Owners

Regional and Branch

Sales & Marketing

Canteens

Housekeeping

Human Resources

Features

Feedback campaigning with template

Define start & End Date for Feedback

Live Dashboard

Google Analytics

 Invoice Management

Benefits

Tracking of PO/SO/Invoice/ Delivery Challan

Client Management

Product Management

Send invoices to clients by email

Printable invoice in PDF/HTML format

Payment Monitoring and Alerts

Tracking pending payment/Invoice

Who can & where it use

Small Organization/Company

 Assessment Master

Benefits

Employee Self Assessment

Increase productivity in organization

Remote area accessibility using offline

Staff capabilities check and planning

Accountability

Who can & where it use

Corporate

Small organization/Company

Educational Institute

Professional Institute

Features

Offline and online availability

Live Dashboard

Instant Result

Analytics

 Bill Analyzer & Audit

Benefits

Eliminate Manual Work

Overall bill cost reduction

Analyze & Ensuring correct rates are applied from carrier

Analyse call rates between carriers if using multiple

Reducing non-essential calls – Directory Basis

Optimization on bill plan

Savings of monthly Bills

Savings on Process time

Who can & where it use

Features

PDF & Excel based process

Dynamic Template based Input

Multiple Template carrier wise

Analytics based on historical data

Export on PDF, XLS, JSON, CSV

Integration API – On request

              <form class="form-horizontal" action="" method="post">
              <fieldset>
                <legend class="text-left">Contact us</legend>

              </fieldset>
              </form>

                 India - Navi Mumbai

                 Email : contact@tuleviksolutions.com

© 2017 Tulevik Solutions LLP. All Rights Reserved.

                    Privacy

                    Terms

                    FAQ


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var di_1 = require('angular2/src/core/di');
var xhr_1 = require('angular2/src/core/compiler/xhr');
var client_message_broker_1 = require('angular2/src/web_workers/shared/client_message_broker');
var messaging_api_1 = require('angular2/src/web_workers/shared/messaging_api');
/**
 * Implementation of compiler/xhr that relays XHR requests to the UI side where they are sent
 * and the result is proxied back to the worker
 */
var WebWorkerXHRImpl = (function (_super) {
    __extends(WebWorkerXHRImpl, _super);
    function WebWorkerXHRImpl(messageBrokerFactory) {
        _super.call(this);
        this._messageBroker = messageBrokerFactory.createMessageBroker(messaging_api_1.XHR_CHANNEL);
    }
    WebWorkerXHRImpl.prototype.get = function (url) {
        var fnArgs = [new client_message_broker_1.FnArg(url, null)];
        var args = new client_message_broker_1.UiArguments("get", fnArgs);
        return this._messageBroker.runOnService(args, String);
    };
    WebWorkerXHRImpl = __decorate([
        di_1.Injectable(),
        __metadata('design:paramtypes', [client_message_broker_1.ClientMessageBrokerFactory])
    ], WebWorkerXHRImpl);
    return WebWorkerXHRImpl;
})(xhr_1.XHR);
exports.WebWorkerXHRImpl = WebWorkerXHRImpl;
//# sourceMappingURL=xhr_impl.js.map


text:
package com.mansonheart.moxysandbox.ui.fragment;

/**
 * Created by alexandr on 02.01.17.
 */

public class Dummy {
}


text:
import {combineReducers} from 'redux';
import {connectRouter} from 'connected-react-router';

import device from './app/DeviceReducer';
import navMenu from './app/NavMenuReducer';
import loadComponent from './app/LoadComponentReducer';

export default history => combineReducers({

    router: connectRouter(history),

    device,
    navMenu,
    loadComponent

});


text:
layout:     post
title:      Jammin
subtitle:   takka tung tung
date:       2012-02-14
author:     "Manfred Neustifter"
header-img: "img/Jammin/hearts.jpg"
---

Valentine's Day 2012. My love life probably couldn't have been any more complicated, but thats a different story. On this night we played for the lovers at Bond University.

Thats me I was on the congo drum... takka tung tung.

I wore the big hat incase I messed up, if needed I could hang my head in shame and nobody would see me. It would be my only refuge. This was the first time I'd played in front of a crowd. I dusted a jug of beer before we got started. I only agreed because there was 4 of us and we had never played together, and what was there to loose?

"Don's Tavern" Bond University, Gold Coast - Australia

Turns out there was nothing to worry about. We had chemistry, it was a great show. Everyone had a blast.

I got that congo drum 10 years earlier, circa 2002. At the time I was living in Madang Cres, Runaway Bay, on the northern end of the Gold Coast. My neighbour was a cool little old Balinese guy. Sometimes he would play his drums out on the porch which overlooked our ground floor flat, only obscured by a few tropical trees and foliage. Now and then he'd invite me up, eventually I picked up the Indonesian style drum rhythms. I bought a drum from one of his friend's who sold them at the markets, but I hardly ever used it, except when we had house parties at our place. It was more an ornamental item than anything.

Then my friend Johan who had been getting a few paid gigs suddenly had his drummer pull out late from a scheduled show. He asked if I would fill in. I was reluctant. Playing at Little Beans wasn't rehearsed or planned. This time it would be just the 2 of us, not enough other instruments to just blend in, nowhere to hide. And this venue, it usually got pretty crowded, full of the young people in our neighbourhood, faces we'd see again. Anyway, I tucked into some liquid courage and eased into the show.

"LittleBeans" Nobby Beach, Gold Coast - Australia

For the first hour I played pretty lightly and let Johan lead on his guitar with his singing. Then I warmed up, and it was really fun. We had a beer breaks between every song, I got louder and playing with more confidence with every beer. Good times.