text:
/* eslint-env browser */
/* globals jqUnit pageComponent */
(function (fluid, jqUnit, $) {
    "use strict";
    var gpii = fluid.registerNamespace("gpii");
    fluid.registerNamespace("gpii.tests.initBlock");

    gpii.tests.initBlock.runTests = function () {
        jqUnit.module("initBlock Helper Tests.");

        jqUnit.test("Verify the generated component.", function () {
            var expected = {
                "hasDataFromGrade": true,
                "req": {
                    "query": {
                        "myvar": "bar"
                    },
                    "params": {
                        "template": "initblock"
                    }
                },
                "json": {
                    "foo": "bar",
                    "baz": "quux",
                    "qux": "quux"
                },
                "myvar": "modelvariable",
                "markdown": "*this works*"
            };

            jqUnit.assertLeftHand("The component model should be as expected.", expected, pageComponent.requireRenderer.pageComponent.model);

            var viewportText = $(".initBlock-viewport").text().trim();
            jqUnit.assertEquals("The component's container should have been updated.", "The component has updated the body content.", viewportText);
        });
    };

    // A component definition that will be referenced from within the {{initBlock}} helper in our tests.
    fluid.defaults("gpii.tests.initBlock", {
        gradeNames: ["gpii.handlebars.templateAware"],
        template:   "initblock-viewport",
        selectors: {
            initial: ".initblock-viewport"
        },
        model: {
            hasDataFromGrade: true
        },
        invokers: {
            renderInitialMarkup: {
                func: "{that}.renderMarkup",
                args: [ "initial", "{that}.options.template", "{that}.model"]
            }
        },
        listeners: {
            "onMarkupRendered.runTests": {
                funcName: "gpii.tests.initBlock.runTests"
            }
        }
    });
})(fluid, jqUnit, jQuery);


text:
package org.jetbrains.plugins.gradle.service.notification;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.externalSystem.service.notification.NotificationData;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import javax.swing.event.HyperlinkEvent;

/**
 * @author Vladislav.Soroka
 * @since 4/1/14
 */
public class GotoSourceNotificationCallback extends NotificationListener.Adapter {
  public final static String ID = "goto_source";

  private final NotificationData myNotificationData;
  private final Project myProject;

  public GotoSourceNotificationCallback(NotificationData notificationData, Project project) {
    myNotificationData = notificationData;
    myProject = project;
  }

  @Override
  protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) {
    if (myNotificationData.getFilePath() == null) return;
    VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(myNotificationData.getFilePath());
    assert virtualFile != null;
    int line = myNotificationData.getLine() - 1;
    int column = myNotificationData.getColumn() - 1;

    final int guiLine = line < 0 ? -1 : line;
    final int guiColumn = column < 0 ? -1 : column + 1;
    new OpenFileDescriptor(myProject, virtualFile, guiLine, guiColumn).navigate(true);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.itracker.android.xmpp.archive;

import com.itracker.android.xmpp.AbstractProvider;
import com.itracker.android.xmpp.ProviderUtils;

import org.xmlpull.v1.XmlPullParser;

public abstract class AbstractModifiedProvider<T extends AbstractModified>
        extends AbstractProvider<T> {

    @Override
    protected T preProcess(XmlPullParser parser, T instance) {
        instance.setStart(ProviderUtils.parseDateTime(parser.getAttributeValue(
                null, AbstractModified.START_ATTRIBUTE)));
        instance.setStartString(parser.getAttributeValue(null,
                AbstractModified.START_ATTRIBUTE));
        instance.setVersion(ProviderUtils.parseInteger(parser
                .getAttributeValue(null, AbstractModified.VERSION_ATTRIBUTE)));
        instance.setWith(parser.getAttributeValue(null,
                AbstractModified.WITH_ATTRIBUTE));
        return super.preProcess(parser, instance);
    }

}


text:
@interface RSZoomImageToImageViewController : UIViewController

@end


text:
hnn
===

haskell neural network library

[![Build Status](https://secure.travis-ci.org/alpmestan/hnn.png?branch=master)](http://travis-ci.org/alpmestan/hnn)

You can find online documentation of approximately the latest version of this repo [here](http://alpmestan.com/hnn/) or [on hackage](http://hackage.haskell.org/package/hnn-0.2.0.0). See the _examples/_ directory to see how to use the library or the `AI.HNN.FF.Network` module for a tutorial.

Also, feel free to join _#haskell-math_ on irc.freenode.net if you have any question, or if you just want to chat about the library, some potential use you want to make of it, etc.

This library is written and maintained by Alp Mestanogullari <alpmestan@gmail.com> and Gatlin Johnson <rokenrol@gmail.com>.


text:
require_relative '../../test_helper'

class BranchWithConflictingFromRequirementsTest < StateMachinesTest
  def test_should_raise_an_exception
    exception = assert_raises(ArgumentError) { StateMachines::Branch.new(from: :parked, except_from: :parked) }
    assert_equal 'Conflicting keys: from, except_from', exception.message
  end
end


text:
@interface JCEventDetailViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate, JCEventEditViewControllerDelegate, JCPostCreateViewControllerDelegate>

@property (strong, nonatomic) PFObject *currentEvent;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *dateLabel;
@property (strong, nonatomic) IBOutlet UITextView *locationTextView;
@property (strong, nonatomic) IBOutlet UILabel *markerNum;

@property (weak, nonatomic) IBOutlet UITableView *postTableView;

@property (weak, nonatomic) IBOutlet UIButton *markBtn;
@property (strong, nonatomic) IBOutlet UIButton *moreBtn;
@property (strong, nonatomic) IBOutlet UIButton *detailBtn;

-(IBAction)markBtn:(id)sender;
-(IBAction)moreBtn:(id)sender;
-(IBAction)detailBtn:(id)sender;

@end


text:
/** @addtogroup AT32F403A_407_periph_driver
  * @{
  */

/** @defgroup USB
  * @brief USB driver modules
  * @{
  */

#include "at32f403a_407_conf.h"

#ifdef USB_MODULE_ENABLED

/** @defgroup USB_private_functions
  * @{
  */

/**
  * @brief usb packet buffer start address
  */
#define USB_ENDP_DESC_TABLE_OFFSET       0x40
uint32_t g_usb_packet_address = USB_PACKET_BUFFER_ADDRESS;
static uint16_t g_usb_offset_addr = USB_ENDP_DESC_TABLE_OFFSET;

/**
  * @brief  initialize usb peripheral controller register
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_dev_init(usbd_type *usbx)
{
  /* clear usb core reset */
  usbx->ctrl_bit.csrst = 0;

  /* clear usb interrupt status */
  usbx->intsts = 0;

  /* set usb packet buffer descirption table address */
  usbx->buftbl = USB_BUFFER_TABLE_ADDRESS;

  /* enable usb core and set device address to 0 */
  usbx->devaddr = 0x80;

  usb_interrupt_enable(usbx, USB_SOF_INT | USB_RST_INT | USB_SP_INT | USB_WK_INT | USB_TC_INT, TRUE);
}

/**
  * @brief  connect usb device
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_connect(usbd_type *usbx)
{
  /* enable usb phy */
  usbx->ctrl_bit.disusb = 0;

  /* Dp 1.5k pull-up enable */
  usbx->cfg_bit.puo = 0;
}

/**
  * @brief  disconnect usb device
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_disconnect(usbd_type *usbx)
{
  /* disable usb phy */
  usbx->ctrl_bit.disusb = TRUE;

  /* D+ 1.5k pull-up disable */
  usbx->cfg_bit.puo = TRUE;
}

/**
  * @brief  mapping usb packet buffer area
  *         two mapping intervals are available for packet buffer area,
  *         and are select by the usbbufs in the crm misc1 register.
  *         when usbbufs is 0,sram size is 512 bytes, packet buffer start
  *         address is 0x40006000.when usbbufs is 1, sram size is fixed to
  *         768~1280 bytes, and the  packet buffer start address is fixed to
  *         0x40007800,packet buffer size decided by whether can1 and can2 are
  *         enabled;when both can1 and can2 are disabled, usb packet buffer can be set to the
  *         maximum of 1280 bytes; when either can1 or can2 is enabled, usb packet buffer can be set to the
  *         maximum of 1024 bytes; when both CAN1 and CAN2 are enabled, usb packet buffer can be set to the
  *         maximum of 768 bytes.
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_usbbufs_enable(usbd_type *usbx, confirm_state state)
{
  if(state == TRUE)
  {
    /* enable usbbufs */
    g_usb_packet_address = USB_PACKET_BUFFER_ADDRESS_EX;
    CRM->misc1_bit.usbbufs = TRUE;
  }
  else
  {
    /* disable usbbufs */
    g_usb_packet_address = USB_PACKET_BUFFER_ADDRESS;
    CRM->misc1_bit.usbbufs = FALSE;
  }
}

/**
  * @brief  open usb endpoint
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @param  ept_info: endpoint information structure
  * @retval none
  */
void usb_ept_open(usbd_type *usbx, usb_ept_info *ept_info)
{
  uint16_t type = 0;

  /* set endpoint address */
  USB_SET_EPT_ADDRESS(ept_info->eptn, ept_info->ept_address);

  /* select endpoint transfer type */
  if(ept_info->trans_type == EPT_CONTROL_TYPE)
  {
    type = USB_EPT_CONTROL;
  }
  else if(ept_info->trans_type == EPT_BULK_TYPE)
  {
    type = USB_EPT_BULK;
  }
  else if(ept_info->trans_type == EPT_INT_TYPE)
  {
    type = USB_EPT_INT;
  }
  else if(ept_info->trans_type == EPT_ISO_TYPE)
  {
    type = USB_EPT_ISO;
    ept_info->is_double_buffer = TRUE;
  }

  /* configure endpoint transfer type (control, bulk, interrupt, isochronous) */
  USB_SET_TRANS_TYPE(ept_info->eptn, type);

  /* endpoint is in transfer */
  if(ept_info->inout == DATA_TRANS_IN)
  {
      if(ept_info->is_double_buffer == 0)
      {
        /* set in endpoint tx offset address */
        USB_SET_TX_ADDRESS(ept_info->eptn, ept_info->tx_addr);

        /* clear in endpoint data toggle */
        USB_CLEAR_TXDTS(ept_info->eptn);

        /* set endpoint transmission status: nak */
        USB_SET_TXSTS(ept_info->eptn, USB_TX_NAK);
      }
      else
      {
        /* set double buffer endpoint*/
        USB_SET_EPT_DOUBLE_BUFFER(ept_info->eptn);

        /* set in endpoint offset address0 and address1 */
        USB_SET_DOUBLE_BUFF0_ADDRESS(ept_info->eptn, ept_info->tx_addr);
        USB_SET_DOUBLE_BUFF1_ADDRESS(ept_info->eptn, ept_info->rx_addr);

        /* clear in and out data toggle */
        USB_CLEAR_TXDTS(ept_info->eptn);
        USB_CLEAR_RXDTS(ept_info->eptn);

        /* toggle rx data toggle flag */
        USB_TOGGLE_RXDTS(ept_info->eptn);

        /* set endpoint reception status: disable */
        USB_SET_RXSTS(ept_info->eptn, USB_RX_DISABLE);

        /* set endpoint transmision status: nak */
        USB_SET_TXSTS(ept_info->eptn, USB_TX_NAK);
      }
  }
  else
  {
    if(ept_info->is_double_buffer == 0)
    {
      /* set out endpoint rx offset address */
      USB_SET_RX_ADDRESS(ept_info->eptn, ept_info->rx_addr);

      /* clear out endpoint data toggle */
      USB_CLEAR_RXDTS(ept_info->eptn);

      /* set out endpoint max reception buffer size */
      USB_SET_RXLEN(ept_info->eptn, ept_info->maxpacket);

      /* set endpoint reception status: valid */
      USB_SET_RXSTS(ept_info->eptn, USB_RX_VALID);
    }
    else
    {
      /* set double buffer endpoint */
      USB_SET_EPT_DOUBLE_BUFFER(ept_info->eptn);

      /* set out endpoint offset address0 and address1 */
      USB_SET_DOUBLE_BUFF0_ADDRESS(ept_info->eptn, ept_info->tx_addr);
      USB_SET_DOUBLE_BUFF1_ADDRESS(ept_info->eptn, ept_info->rx_addr);

      /* set out endpoint max reception buffer size */
      USB_SET_EPT_DOUBLE_BUF0_LEN(ept_info->eptn, ept_info->maxpacket, DATA_TRANS_OUT);
      USB_SET_EPT_DOUBLE_BUF1_LEN(ept_info->eptn, ept_info->maxpacket, DATA_TRANS_OUT);

      /* clear in and out data toggle */
      USB_CLEAR_TXDTS(ept_info->eptn);
      USB_CLEAR_RXDTS(ept_info->eptn);

      /* toggle tx data toggle flag */
      USB_TOGGLE_TXDTS(ept_info->eptn);

      /* set endpoint reception status: valid */
      USB_SET_RXSTS(ept_info->eptn, USB_RX_VALID);

      /* set endpoint transmision status: disable */
      USB_SET_TXSTS(ept_info->eptn, USB_TX_DISABLE);
    }
  }
}

/**
  * @brief  close usb endpoint
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @param  ept_info: endpoint information structure
  * @retval none
  */
void usb_ept_close(usbd_type *usbx, usb_ept_info *ept_info)
{
  if(ept_info->is_double_buffer == 0)
  {
    if(ept_info->inout == DATA_TRANS_IN)
    {
      /*clear tx data toggle */
      USB_CLEAR_TXDTS(ept_info->eptn);

      /* set tx status: disable */
      USB_SET_TXSTS(ept_info->eptn, USB_TX_DISABLE);
    }
    else
    {
      /*clear rx data toggle */
      USB_CLEAR_RXDTS(ept_info->eptn);

      /* set rx status: disable */
      USB_SET_RXSTS(ept_info->eptn, USB_RX_DISABLE);

    }
  }
  else
  {
    /* double buffer */

    /*clear rx and tx data toggle */
    USB_CLEAR_TXDTS(ept_info->eptn);
    USB_CLEAR_RXDTS(ept_info->eptn);

    if(ept_info->inout == DATA_TRANS_IN)
    {
      /* toggle tx */
      USB_TOGGLE_TXDTS(ept_info->eptn);

      /* set tx and rx status: disable */
      USB_SET_TXSTS(ept_info->eptn, USB_TX_DISABLE);
      USB_SET_RXSTS(ept_info->eptn, USB_RX_DISABLE);
    }
    else
    {
      /* toggle rx */
      USB_TOGGLE_RXDTS(ept_info->eptn);

      /* set tx and rx status: disable */
      USB_SET_TXSTS(ept_info->eptn, USB_TX_DISABLE);
      USB_SET_RXSTS(ept_info->eptn, USB_RX_DISABLE);
    }
  }
}

/**
  * @brief  write data from user memory to usb buffer
  * @param  pusr_buf: point to user buffer
  * @param  offset_addr: endpoint tx offset address
  * @param  nbytes: number of bytes data write to usb buffer
  * @retval none
  */
void usb_write_packet(uint8_t *pusr_buf, uint16_t offset_addr, uint16_t nbytes)
{
  /* endpoint tx buffer address */
  __IO uint16_t *d_addr = (__IO uint16_t *)(offset_addr * 2 + g_usb_packet_address);

  uint32_t nhbytes = (nbytes + 1) >> 1;
  uint32_t n_index;
  uint16_t *pbuf = (uint16_t *)pusr_buf;
  for(n_index = 0; n_index < nhbytes; n_index ++)
  {
#if defined (__ICCARM__) && (__VER__ < 7000000)
    *d_addr++  = *(__packed uint16_t *)pbuf;
#else
    *d_addr++ = __UNALIGNED_UINT16_READ(pbuf);
#endif
    d_addr ++;
    pbuf ++;
  }
}

/**
  * @brief  read data from usb buffer to user buffer
  * @param  pusr_buf: point to user buffer
  * @param  offset_addr: endpoint rx offset address
  * @param  nbytes: number of bytes data write to usb buffer
  * @retval none
  */
void usb_read_packet(uint8_t *pusr_buf, uint16_t offset_addr, uint16_t nbytes)
{
  __IO uint16_t *s_addr = (__IO uint16_t *)(offset_addr * 2 + g_usb_packet_address);
  uint32_t nhbytes = (nbytes + 1) >> 1;
  uint32_t n_index;
  uint16_t *pbuf = (uint16_t *)pusr_buf;
  for(n_index = 0; n_index < nhbytes; n_index ++)
  {
#if defined (__ICCARM__) && (__VER__ < 7000000)
    *(__packed uint16_t *)pbuf = *(__IO uint16_t *)s_addr ++;
#else
    __UNALIGNED_UINT16_WRITE(pbuf, *(__IO uint16_t *)s_addr ++);
#endif
    s_addr ++;
    pbuf ++;
  }
}

/**
  * @brief  usb interrupt enable
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @param  interrupt:
  *         this parameter can be any combination of the following values:
  *         - USB_LSOF_INT
  *         - USB_SOF_INT
  *         - USB_RST_INT
  *         - USB_SP_INT
  *         - USB_WK_INT
  *         - USB_BE_INT
  *         - USB_UCFOR_INT
  *         - USB_TC_INT
  * @param  new_state (TRUE or FALSE)
  * @retval none
  */
void usb_interrupt_enable(usbd_type *usbx, uint16_t interrupt, confirm_state new_state)
{
  if(new_state == TRUE)
  {
    usbx->ctrl |= interrupt;
  }
  else
  {
    usbx->ctrl &= ~interrupt;
  }
}

/**
  * @brief  set the host assignment address
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @param  address: host assignment address
  * @retval none
  */
void usb_set_address(usbd_type *usbx, uint8_t address)
{
  usbx->devaddr_bit.addr = address;
  usbx->devaddr_bit.cen = TRUE;
}

/**
  * @brief  set endpoint tx or rx status to stall
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @param  ept_info: endpoint information structure
  * @retval none
  */
void usb_ept_stall(usbd_type *usbx, usb_ept_info *ept_info)
{
  if(ept_info->inout == DATA_TRANS_IN)
  {
    USB_SET_TXSTS(ept_info->eptn, USB_TX_STALL)
  }
  else
  {
    USB_SET_RXSTS(ept_info->eptn, USB_RX_STALL)
  }
}

/**
  * @brief  usb device enter suspend mode
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_enter_suspend(usbd_type *usbx)
{
  usbx->ctrl_bit.ssp = TRUE;
  usbx->ctrl_bit.lpm = TRUE;
}

/**
  * @brief  usb device exit suspend mode
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_exit_suspend(usbd_type *usbx)
{
  usbx->ctrl_bit.ssp = FALSE;
  usbx->ctrl_bit.lpm = FALSE;
}

/**
  * @brief  usb remote wakeup set
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_remote_wkup_set(usbd_type *usbx)
{
   usbx->ctrl_bit.gresume = TRUE;
}

/**
  * @brief  usb remote wakeup clear
  * @param  usbx: to select the usb peripheral.
  *         parameter as following values: USB
  * @retval none
  */
void usb_remote_wkup_clear(usbd_type *usbx)
{
  usbx->ctrl_bit.gresume = FALSE;
}

/**
  * @brief  usb auto malloc endpoint buffer
  * @param  mapacket: endpoint support max packet size
  * @retval none
  */
uint16_t usb_buffer_malloc(uint16_t maxpacket)
{
  uint16_t offset = g_usb_offset_addr;
  g_usb_offset_addr += maxpacket;
  return offset;
}

/**
  * @brief  free usb endpoint buffer
  * @param  none
  * @retval none
  */
void usb_buffer_free(void)
{
  g_usb_offset_addr = USB_ENDP_DESC_TABLE_OFFSET;
}

/**
  * @brief  get flag of usb.
  * @param  usbx: select the usb peripheral
  * @param  flag: select the usb flag
  *         this parameter can be one of the following values:
  *         - USB_INOUT_FLAG
  *         - USB_LSOF_FLAG
  *         - USB_SOF_FLAG
  *         - USB_RST_FLAG
  *         - USB_SP_FLAG
  *         - USB_WK_FLAG
  *         - USB_BE_FLAG
  *         - USB_UCFOR_FLAG
  *         - USB_TC_FLAG
  * @retval none
  */
flag_status usb_flag_get(usbd_type *usbx, uint16_t flag)
{
  flag_status status = RESET;

  if((usbx->intsts & flag) == RESET)
  {
    status = RESET;
  }
  else
  {
    status = SET;
  }
  return status;
}

/**
  * @brief  clear flag of usb.
  * @param  usbx: select the usb peripheral
  * @param  flag: select the usb flag
  *         this parameter can be one of the following values:
  *         - USB_INOUT_FLAG
  *         - USB_LSOF_FLAG
  *         - USB_SOF_FLAG
  *         - USB_RST_FLAG
  *         - USB_SP_FLAG
  *         - USB_WK_FLAG
  *         - USB_BE_FLAG
  *         - USB_UCFOR_FLAG
  *         - USB_TC_FLAG
  * @retval none
  */
void usb_flag_clear(usbd_type *usbx, uint16_t flag)
{
  usbx->intsts = ~flag;
}

/**
  * @}
  */

#endif

/**
  * @}
  */

/**
  * @}
  */


text:
"""
Runs Coverity Prevent on a build of Chromium.

This script should be run in a Visual Studio Command Prompt, so that the
INCLUDE, LIB, and PATH environment variables are set properly for Visual
Studio.

Usage examples:
  coverity.py
  coverity.py --dry-run
  coverity.py --target=debug
  %comspec% /c ""C:\Program Files\Microsoft Visual Studio 8\VC\vcvarsall.bat"
      x86 && C:\Python24\python.exe C:\coverity.py"

For a full list of options, pass the '--help' switch.

See http://support.microsoft.com/kb/308569 for running this script as a
Scheduled Task on Windows XP.

"""

import optparse
import os
import subprocess
import sys
import time

# TODO(wtc): Change these constants to command-line flags, particularly the
# ones that are paths.  Set default values for the flags.

CHROMIUM_SOURCE_DIR = 'E:\\chromium.latest'

# Relative to CHROMIUM_SOURCE_DIR.
CHROMIUM_SOLUTION_FILE = 'src\\chrome\\chrome.sln'

# Relative to CHROMIUM_SOURCE_DIR.
CHROMIUM_SOLUTION_DIR = 'src\\chrome'

COVERITY_BIN_DIR = 'C:\\coverity\\prevent-mingw-4.4.0\\bin'

COVERITY_INTERMEDIATE_DIR = 'C:\\coverity\\cvbuild\\cr_int'

COVERITY_DATABASE_DIR = 'C:\\coverity\\cvbuild\\db'

COVERITY_ANALYZE_OPTIONS = ('--cxx --security --concurrency '
                            '--enable ATOMICITY '
                            '--enable MISSING_LOCK '
                            '--enable DELETE_VOID '
                            '--checker-option PASS_BY_VALUE:size_threshold:16 '
                            '--checker-option '
                            'USE_AFTER_FREE:allow_simple_use:false '
                            '--enable-constraint-fpp '
                            '--enable-callgraph-metrics')

COVERITY_PRODUCT = 'Chromium'

COVERITY_USER = 'admin'

# Relative to CHROMIUM_SOURCE_DIR.  Contains the pid of this script.
LOCK_FILE = 'coverity.lock'

def _RunCommand(cmd, dry_run, shell=False):
  """Runs the command if dry_run is false, otherwise just prints the command."""
  print cmd
  # TODO(wtc): Check the return value of subprocess.call, which is the return
  # value of the command.
  if not dry_run:
    subprocess.call(cmd, shell=shell)

def main(options, args):
  """Runs all the selected tests for the given build type and target."""
  # Create the lock file to prevent another instance of this script from
  # running.
  lock_filename = '%s\\%s' % (CHROMIUM_SOURCE_DIR, LOCK_FILE)
  try:
    lock_file = os.open(lock_filename,
                        os.O_CREAT | os.O_EXCL | os.O_TRUNC | os.O_RDWR)
  except OSError, err:
    print 'Failed to open lock file:\n  ' + str(err)
    return 1

  # Write the pid of this script (the python.exe process) to the lock file.
  os.write(lock_file, str(os.getpid()))

  options.target = options.target.title()

  start_time = time.time()

  print 'Change directory to ' + CHROMIUM_SOURCE_DIR
  os.chdir(CHROMIUM_SOURCE_DIR)

  cmd = 'gclient sync'
  _RunCommand(cmd, options.dry_run, shell=True)
  print 'Elapsed time: %ds' % (time.time() - start_time)

  # Do a clean build.  Remove the build output directory first.
  # TODO(wtc): Consider using Python's rmtree function in the shutil module,
  # or the RemoveDirectory function in
  # trunk/tools/buildbot/scripts/common/chromium_utils.py.
  cmd = 'rmdir /s /q %s\\%s\\%s' % (CHROMIUM_SOURCE_DIR,
                                    CHROMIUM_SOLUTION_DIR, options.target)
  _RunCommand(cmd, options.dry_run, shell=True)
  print 'Elapsed time: %ds' % (time.time() - start_time)

  cmd = '%s\\cov-build.exe --dir %s devenv.com %s\\%s /build %s' % (
      COVERITY_BIN_DIR, COVERITY_INTERMEDIATE_DIR, CHROMIUM_SOURCE_DIR,
      CHROMIUM_SOLUTION_FILE, options.target)
  _RunCommand(cmd, options.dry_run)
  print 'Elapsed time: %ds' % (time.time() - start_time)

  cmd = '%s\\cov-analyze.exe --dir %s %s' % (COVERITY_BIN_DIR,
                                             COVERITY_INTERMEDIATE_DIR,
                                             COVERITY_ANALYZE_OPTIONS)
  _RunCommand(cmd, options.dry_run)
  print 'Elapsed time: %ds' % (time.time() - start_time)

  cmd = ('%s\\cov-commit-defects.exe --dir %s --datadir %s --product %s '
         '--user %s') % (COVERITY_BIN_DIR, COVERITY_INTERMEDIATE_DIR,
                         COVERITY_DATABASE_DIR, COVERITY_PRODUCT,
                         COVERITY_USER)
  _RunCommand(cmd, options.dry_run)

  print 'Total time: %ds' % (time.time() - start_time)

  os.close(lock_file)
  os.remove(lock_filename)

  return 0

if '__main__' == __name__:
  option_parser = optparse.OptionParser()
  option_parser.add_option('', '--dry-run', action='store_true', default=False,
                           help='print but don\'t run the commands')
  option_parser.add_option('', '--target', default='Release',
                           help='build target (Debug or Release)')
  options, args = option_parser.parse_args()

  result = main(options, args)
  sys.exit(result)


text:
package com.logginghub.utils.data;

public class DataStructureBuilder {

    public static DataStructureBuilder start() {
        return new DataStructureBuilder();
    }

}


text:
define(['core/boilerplate', 'conf/background'],
	function(Boilerplate, Conf) {
		var Background = function() {

			this.init = function(parent, args) {
				// Initialize Background
				if (args.hasOwnProperty('transform'))
					this.transform = args.transform;

				if (args.hasOwnProperty('img'))
					this.img = args.img;
			}
		}

		Background.prototype = {
			name : "Background", // Define name of the model
			update : function() {
				// Update Background each frame
				this.transform.position.x -= Boilerplate.getManager("Background").speed;

				if (this.transform.position.x <= -Boilerplate.scene.width)
					this.transform.position.x = Boilerplate.scene.width;
			},
			render : function() {
				// Render Background on scene
				var scale = Boilerplate.scene.scale(this.transform);

				var x = this.transform.position.x,
					y = this.transform.position.y;

				Boilerplate.scene.ctx.drawImage(
					this.img.data,
					this.transform.position.x,
					0
				);

				Boilerplate.scene.ctx.restore();
			}
		}

		return Background;
	}
);


text:
package com.synthform.colombo.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

/**
 * Created by riccardobusetti on 27/06/16.
 */

public class AppStatus {

    static Context context;
    private static AppStatus instance = new AppStatus();
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static AppStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;

        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }
}


text:
Neurosynth is a Python package for large-scale synthesis of functional neuroimaging data.

## Code status

* [![tests status](https://secure.travis-ci.org/neurosynth/neurosynth.png?branch=master)](https://travis-ci.org/neurosynth/neurosynth) travis-ci.org (master branch)

* [![Coverage Status](https://coveralls.io/repos/neurosynth/neurosynth/badge.png?branch=master)](https://coveralls.io/r/neurosynth/neurosynth?branch=master)

## Installation

Dependencies:

* NumPy/SciPy
* pandas
* NiBabel
* [ply](http://www.dabeaz.com/ply/)
* scikit-learn

We recommend installing the core scientific packages (NumPy, SciPy, pandas, sklearn) via a distribution like [https://store.continuum.io/cshop/anaconda/](Anaconda), which will keep clutter and conflicts to a minimum. The other packages can be installed with pip using the requirements file:

	> pip install -r requirements.txt

Or by name:

	> pip install nibabel ply

Assuming you have those packages in working order, the easiest way to install Neurosynth is from the command line with pip:

	> pip install neurosynth

Alternatively, if you want the latest development version, you can install directly from the github repo:

	> pip install git+https://github.com/neurosynth/neurosynth.git

Depending on your operating system, you may need superuser privileges (prefix the above line with 'sudo').

That's it! You should now be ready to roll.

## Documentation

Documentation, including a [full API reference](http://neurosynth.readthedocs.org/en/latest/reference.html), is available [here](http://neurosynth.readthedocs.org/en/latest/)(caution: work in progress).

## Usage

Running analyses in Neurosynth is pretty straightforward. We're working on a user manual; in the meantime, you can take a look at the code in the /examples directory for an illustration of some common uses cases (some of the examples are in IPython Notebook format; you can view these online by entering the URL of the raw example on github into the online [IPython Notebook Viewer](http://nbviewer.ipython.org)--for example [this tutorial](http://nbviewer.ipython.org/urls/raw.github.com/neurosynth/neurosynth/master/examples/neurosynth_demo.ipynb) provides a nice overview). The rest of this Quickstart guide just covers the bare minimum.

The NeuroSynth dataset resides in a separate submodule located [here](http://github.com/neurosynth/neurosynth-data). Probably the easiest way to get the most recent data though is from within the Neurosynth package itself:

	import neurosynth as ns
	ns.dataset.download(path='.', unpack=True)

...which should download the latest database files and save them to the current directory. Alternatively, you can manually download the data files from the [neurosynth-data repository](http://github.com/neurosynth/neurosynth-data). The latest dataset is always stored in current_data.tar.gz in the root folder. Older datasets are also available in the archive folder.

The dataset archive (current_data.tar.gz) contains 2 files: database.txt and features.txt. These contain the activations and meta-analysis tags for Neurosynth, respectively.

Once you have the data in place, you can generate a new Dataset instance from the database.txt file:

	> from neurosynth.base.dataset import Dataset
	> dataset = Dataset('data/database.txt')

This should take several minutes to process. Note that this is a memory-intensive operation, and may be very slow on machines with less than 8 GB of RAM.

Once initialized, the Dataset instance contains activation data from nearly 10,000 published neuroimaging articles. But it doesn't yet have any features attached to those data, so let's add some:

	> dataset.add_features('data/features.txt')

Now our Dataset has both activation data and some features we can use to manipulate the data with. In this case, the features are just term-based tags--i.e., words that occur in the abstracts of the articles from which the dataset is drawn (for details, see this [Nature Methods] paper, or the Neurosynth website).

We can now do various kinds of analyses with the data. For example, we can use the features we just added to perform automated large-scale meta-analyses. Let's see what features we have:

	> dataset.get_feature_names()
	['phonetic', 'associative', 'cues', 'visually', ... ]

We can use these features--either in isolation or in combination--to select articles for inclusion in a meta-analysis. For example, suppose we want to run a meta-analysis of emotion studies. We could operationally define a study of emotion as one in which the authors used words starting with 'emo' with high frequency:

	> ids = dataset.get_studies(features='emo*', frequency_threshold=0.001)

Here we're asking for a list of IDs of all studies that use words starting with 'emo' (e.g.,'emotion', 'emotional', 'emotionally', etc.) at a frequency of 1 in 1,000 words or greater (in other words, if an article has 5,000 words of text, it will only be included in our set if it uses words starting with 'emo' at least 5 times).

	> len(ids)
	639

The resulting set includes 639 studies.

Once we've got a set of studies we're happy with, we can run a simple meta-analysis, prefixing all output files with the string 'emotion' to distinguish them from other analyses we might run:

	> from neurosynth.analysis import meta
	> ma = meta.MetaAnalysis(dataset, ids)
	> ma.save_results('some_directory/emotion')

You should now have a set of Nifti-format brain images on your drive that display various meta-analytic results. The image names are somewhat cryptic; see the Documentation for details. It's important to note that the meta-analysis routines currently implemented in Neurosynth aren't very sophisticated; they're designed primarily for efficiency (most analyses should take just a few seconds), and take multiple shortcuts as compared to other packages like ALE or MKDA. But with that caveat in mind (and one that will hopefully be remedied in the near future), Neurosynth gives you a streamlined and quick way of running large-scale meta-analyses of fMRI data.

## Getting help

For a more comprehensive set of examples, see [this tutorial](http://nbviewer.ipython.org/urls/raw.github.com/neurosynth/neurosynth/master/examples/neurosynth_demo.ipynb)--also included in IPython Notebook form in the examples/ folder (along with several other simpler examples).

For bugs or feature requests, please [create a new issue](https://github.com/neurosynth/neurosynth/issues/new). If you run into problems installing or using the software, try posting to the [Neurosynth Google group](https://groups.google.com/forum/#!forum/neurosynthlist) or email [Tal Yarkoni](mailto:tyarkoni@gmail.com).


text:
import {Node} from 'forestry';
import bodec from 'bodec';
import {nodeIsDirectory} from '../lib/mode';

var DATE_PROPERTIES = ['atime', 'mtime', 'ctime', 'birthtime'];

function deserializeData(data) {
  var data = Object.assign({}, data);
  if (data.stat) {
    data.stat = Object.assign({}, data.stat);
    DATE_PROPERTIES.forEach(function(time) {
      if (data.stat.hasOwnProperty(time)) data.stat[time] = new Date(data.stat[time]);
    })
  }
  if (data.contents) data.contents = bodec.fromRaw(data.contents)
  return data;
}

function createNode(dataNode) {
  var data = deserializeData(dataNode.data);
  if (!nodeIsDirectory(dataNode)) return new Node(data)

  let node = new Node(data);
  dataNode.children.forEach(childDataNode => node.addChild(createNode(childDataNode)));
  return node
}

export default function __loadTree(dataNode) {
  let fs = this;
  fs.rootNode = createNode(dataNode);
}


text:
namespace Microsoft.Azure.Management.Compute.Fluent.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Describes scaling information of a sku.
    /// </summary>
    public partial class VirtualMachineScaleSetSkuCapacity
    {
        /// <summary>
        /// Initializes a new instance of the VirtualMachineScaleSetSkuCapacity
        /// class.
        /// </summary>
        public VirtualMachineScaleSetSkuCapacity()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the VirtualMachineScaleSetSkuCapacity
        /// class.
        /// </summary>
        /// <param name="minimum">The minimum capacity.</param>
        /// <param name="maximum">The maximum capacity that can be set.</param>
        /// <param name="defaultCapacity">The default capacity.</param>
        /// <param name="scaleType">The scale type applicable to the sku.
        /// Possible values include: 'Automatic', 'None'</param>
        public VirtualMachineScaleSetSkuCapacity(long? minimum = default(long?), long? maximum = default(long?), long? defaultCapacity = default(long?), VirtualMachineScaleSetSkuScaleType? scaleType = default(VirtualMachineScaleSetSkuScaleType?))
        {
            Minimum = minimum;
            Maximum = maximum;
            DefaultCapacity = defaultCapacity;
            ScaleType = scaleType;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets the minimum capacity.
        /// </summary>
        [JsonProperty(PropertyName = "minimum")]
        public long? Minimum { get; private set; }

        /// <summary>
        /// Gets the maximum capacity that can be set.
        /// </summary>
        [JsonProperty(PropertyName = "maximum")]
        public long? Maximum { get; private set; }

        /// <summary>
        /// Gets the default capacity.
        /// </summary>
        [JsonProperty(PropertyName = "defaultCapacity")]
        public long? DefaultCapacity { get; private set; }

        /// <summary>
        /// Gets the scale type applicable to the sku. Possible values include:
        /// 'Automatic', 'None'
        /// </summary>
        [JsonProperty(PropertyName = "scaleType")]
        public VirtualMachineScaleSetSkuScaleType? ScaleType { get; private set; }

    }
}


text:
package ch.pantas.billsplitter.dataaccess.rowmapper;

import android.content.ContentValues;
import android.database.Cursor;
import android.test.suitebuilder.annotation.SmallTest;

import com.google.inject.Inject;

import java.util.UUID;

import ch.pantas.billsplitter.framework.BaseMockitoInstrumentationTest;
import ch.pantas.billsplitter.model.Event;
import ch.pantas.billsplitter.model.SupportedCurrency;

import static ch.pantas.billsplitter.dataaccess.db.BillSplitterDatabaseOpenHelper.EventTable.CURRENCY;
import static ch.pantas.billsplitter.dataaccess.db.BillSplitterDatabaseOpenHelper.EventTable.ID;
import static ch.pantas.billsplitter.dataaccess.db.BillSplitterDatabaseOpenHelper.EventTable.NAME;
import static ch.pantas.billsplitter.dataaccess.db.BillSplitterDatabaseOpenHelper.EventTable.OWNER;
import static ch.pantas.billsplitter.model.SupportedCurrency.CHF;
import static java.util.UUID.randomUUID;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class EventRowMapperTest extends BaseMockitoInstrumentationTest {

    @Inject
    private EventRowMapper mapper;

    @SmallTest
    public void testMapThrowsNullPointerExceptionIfNoCursorProvided() {
        try {
            mapper.map(null);
            fail("No exception has been thrown");
        } catch (NullPointerException e) {
            assertNotNull(e);
        }
    }

    @SmallTest
    public void testMapCorrectlyMapsCursor() {
        // Given
        String id = randomUUID().toString();
        String name = "Event 1";
        SupportedCurrency currency = CHF;
        String owner = randomUUID().toString();
        Cursor cursor = createEventCursor(id, name, currency, owner);

        // When
        Event event = mapper.map(cursor);

        // Then
        assertNotNull(event);
        assertEquals(id, event.getId().toString());
        assertEquals(name, event.getName().toString());
        assertEquals(currency, event.getCurrency());
        assertEquals(owner, event.getOwnerId().toString());
    }

    @SmallTest
    public void testValuesThrowsNullPointerExceptionIfNoEventProvided() {
        try {
            mapper.getValues(null);
            fail("No exception has been thrown");
        } catch (NullPointerException e) {
            assertNotNull(e);
        }
    }

    @SmallTest
    public void testValuesReturnsCorrectValues() {
        // Given
        UUID id = randomUUID();
        String name = "Event 1";
        SupportedCurrency currency = CHF;
        UUID owner = randomUUID();
        Event event = new Event(id, name, CHF, owner);

        // When
        ContentValues values = mapper.getValues(event);

        // Then
        assertEquals(id.toString(), values.getAsString(ID));
        assertEquals(name, values.getAsString(NAME));
        assertEquals(currency.toString(), values.getAsString(CURRENCY));
        assertEquals(owner.toString(), values.getAsString(OWNER));
    }

    @SmallTest
    public void testValuesDoesNotReturnIdIfIdIsNull() {
        // Given
        String name = "Event 1";
        Event event = new Event(name, CHF, randomUUID());

        // When
        ContentValues values = mapper.getValues(event);

        // Then
        assertFalse(values.containsKey(ID));
    }

    private Cursor createEventCursor(String id, String name, SupportedCurrency currency, String owner) {
        Cursor c = mock(Cursor.class);
        when(c.getColumnIndex(ID)).thenReturn(0);
        when(c.getString(0)).thenReturn(id);
        when(c.getColumnIndex(NAME)).thenReturn(1);
        when(c.getString(1)).thenReturn(name);
        when(c.getColumnIndex(CURRENCY)).thenReturn(2);
        when(c.getString(2)).thenReturn(currency.toString());
        when(c.getColumnIndex(OWNER)).thenReturn(3);
        when(c.getString(3)).thenReturn(owner);

        return c;
    }
}


text:
previewmd
=========
# What is it?
PreviewMD is a tiny command-line utility to preview markdown files on a local machine. You can use it instead of the web-based github editor. I like it because it fits into my development toolkit (Sublime+iTerm) and lets me organize my thoughts better to have a "clean" commit.

Once installed, you can point previewmd at a markdown file. It starts a web server and watches for changes to the file; Changes automatically refresh the page.

# Install
Installation requires the Go utilities (http://golang.org/doc/install)

`> go install github.com/etherealmachine/previewmd`
# Use
Point it at the file you want to preview.

	> previewmd -f <markdown file>
	Preview file at http://localhost:8080


text:
module Fog
  module Compute
    class Cloudstack
      class Job < Fog::Model
        identity  :id,              :aliases => 'jobid'
        attribute :user_id,         :aliases => 'userid'
        attribute :account_id,      :aliases => 'accountid'
        attribute :cmd
        attribute :job_status,      :aliases => 'jobstatus',     :type => :integer
        attribute :job_result_type, :aliases => 'jobresulttype'
        attribute :job_result_code, :aliases => 'jobresultcode', :type => :integer
        attribute :job_proc_status, :aliases => 'jobprocstatus', :type => :integer

        attribute :created_at,      :aliases => 'created',       :type => :time
        attribute :job_result,      :aliases => 'jobresult'

        def reload
          requires :id
          merge_attributes(service.query_async_job_result('jobid' => self.id)['queryasyncjobresultresponse'])
        end

        def ready?
          self.job_status != 0
        end

        def successful?
          self.job_result_code == 0
        end

        # so dirty
        def result
          if successful? && model = Fog::Compute::Cloudstack.constants.find{|c| c.to_s.downcase == self.job_result.keys.first.to_s}.to_s
            collection = model.gsub(/.[A-Z]/){|w| "#{w[0,1]}_#{w[1,1].downcase}"}.downcase + "s" # cheap underscorize, assume simple pluralization
            service.send(collection).new(self.job_result.values.first)
          else self.job_result
          end
        end

        def save
          raise Fog::Errors::Error.new('Creating a job is not supported')
        end

        def destroy
          raise Fog::Errors::Error.new('Destroying a job is not supported')
        end

      end # Job
    end # Cloudstack
  end # Compute
end # Fog


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<!--
  Copyright 2016 Goldman Sachs.
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
  -->

<MithraObject objectType="transactional">
    <PackageName>com.gs.fw.common.mithra.test.domain</PackageName>
    <ClassName>DbsTestEntity</ClassName>
    <DefaultTable>DBS_ENTITY</DefaultTable>

    <Attribute name="id"            javaType="int"      columnName="DBS_ENTITY_ID"   primaryKey="true" primaryKeyGeneratorStrategy="Max"/>
    <Attribute name="name"          javaType="String"   columnName="NAME" />
    <Attribute name="description"   javaType="String"   columnName="DESCRIPTION"/>
    <Attribute name="groupId"       javaType="long"     columnName="DBS_GROUP_ID"/>
    <Attribute name="accountId"     javaType="String"   columnName="ACCOUNT"/>
    <Index name="byName" unique="true">name</Index>
</MithraObject>


text:
package programmersguide.workingwithbarcode.barcodeadvancedfeatures.setstartandstopsymbolsofcodabarbarcode.java;

import com.aspose.barcode.*;

public class SetStartandStopSymbolsofCodabarBarcode
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = "src/programmersguide/workingwithbarcode/barcodeadvancedfeatures/setstartandstopsymbolsofcodabarbarcode/data/";

        // Create instance of BarCodeBuilder, specify codetext and symbology in the constructor
        BarCodeBuilder builder = new BarCodeBuilder("$ 123:50", Symbology.Codabar);

        // Set the codabar start symbol to A
        builder.setCodabarStartSymbol(CodabarSymbol.A);

        // Set the codabar stop symbol to D
        builder.setCodabarStopSymbol(CodabarSymbol.D);

        // Save the image to disk in PNG format
        builder.save(dataDir + "barcode.out.png");

        // Print message
        System.out.println("Barcode image generated successfully.");
    }
}


text:
<?php

/* AngeAngeBundle:Utilisateur:edit.html.twig */
class __TwigTemplate_1e0d78114e3d559d8fc31776b8b10e23 extends Twig_Template
{
    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
Utilisateur edit

<form action=\"";
        // line 3
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("utilisateur_update", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
        echo "\" method=\"post\" ";
        echo $this->env->getExtension('form')->renderEnctype($this->getContext($context, "edit_form"));
        echo ">
    ";
        // line 4
        echo $this->env->getExtension('form')->renderWidget($this->getContext($context, "edit_form"));
        echo "

        <button type=\"submit\">Edit</button>

</form>

        env, $this->env->getExtension('routing')->getPath("utilisateur"), "html", null, true);
        echo "\">
            Back to the list

        <form action=\"";
        // line 17
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("utilisateur_delete", array("id" => $this->getAttribute($this->getContext($context, "entity"), "id"))), "html", null, true);
        echo "\" method=\"post\">
            ";
        // line 18
        echo $this->env->getExtension('form')->renderWidget($this->getContext($context, "delete_form"));
        echo "
            <button type=\"submit\">Delete</button>
        </form>

";
    }

    public function getTemplateName()
    {
        return "AngeAngeBundle:Utilisateur:edit.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }
}


text:
require 'action_mailer'

module Errorkit
  class ErrorsMailer < ActionMailer::Base
    before_action :append_view_paths

    helper_method :error, :limit

    self.mailer_name = 'errors'

    def error_notification(error_id)
      @error = Error.find(error_id)

      mail(:to => mailer_recipients,
           :from => mailer_sender,
           :subject => mailer_subject) do |format|
        format.html { render "#{mailer_name}/error_notification" }
      end
    end

    protected

    def error
      @error
    end

    def limit(hash)
      hash.each do |k, v|
        if v.is_a?(Hash)
          limit(v)
        else
          hash[k] = v[0..1024] + "..." if v.length > 1024
        end
      end
    end

    def mailer_recipients
      Errorkit.config.mailer_recipients
    end

    def mailer_sender
      Errorkit.config.mailer_sender
    end

    def mailer_subject
      message = error.message
      message = message[0..27] + '...' if message.length > 30

      "[#{error.environment || 'Error'}] #{error.exception}: #{message}"
    end

    def append_view_paths
      append_view_path Pathname.new(File.expand_path('../../../', __FILE__)).join('lib', 'generators', 'errorkit', 'templates', 'app', 'views')
    end
  end
end


text:
package org.schoellerfamily.gedbrowser.security.exception;

/**
 * @author Dick Schoeller
 */
public final class ExceptionResponse {
    /**
     * The error code.
     */
    private final String errorCode;

    /**
     * A descriptive message.
     */
    private final String errorMessage;

    /**
     * Constructor.
     *
     * @param errorCode the error code
     * @param errorMessage the error message
     */
    public ExceptionResponse(final String errorCode,
            final String errorMessage) {
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    /**
     * @return the error code
     */
    public String getErrorCode() {
        return errorCode;
    }

    /**
     * @return the error messaged
     */
    public String getErrorMessage() {
        return errorMessage;
    }
}


text:
package com.google.cloud.managed.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(value = "/info")
public class GaeInfoServlet extends HttpServlet {

  private static final long serialVersionUID = -3598229312089602597L;

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.setContentType("text");
    PrintWriter out = resp.getWriter();

    ClassLoader cl = getClass().getClassLoader();
    out.append("CLASS LOADER:\n\n");
    out.append("Name: ").append(cl != null ? cl.getClass().getName() : null).append('\n');
    if (cl instanceof URLClassLoader) {
      URLClassLoader urlCl = (URLClassLoader) cl;
      out.append("Urls: ").append('\n');
      for (URL url : urlCl.getURLs()) {
        out.append(url.toString()).append('\n');
      }
    }

    out.append("\nENVIRONMENT VARIABLES:\n\n");
    Map<String, String> envVars = System.getenv();
    for (Map.Entry<String, String> entry : envVars.entrySet()) {
      out.append(entry.getKey()).append("=").append(entry.getValue()).append('\n');
    }

    out.append("\n\nSYSTEM PROPERTIES:\n\n");
    System.getProperties().list(out);

    out.close();
  }
}


text:
package com.nostra13.universalimageloader.cache.memory.impl;

import android.graphics.Bitmap;
import com.nostra13.universalimageloader.cache.memory.MemoryCache;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class LimitedAgeMemoryCache
    implements MemoryCache
{

    private final MemoryCache a;
    private final long b;
    private final Map c = Collections.synchronizedMap(new HashMap());

    public LimitedAgeMemoryCache(MemoryCache memorycache, long l)
    {
        a = memorycache;
        b = 1000L * l;
    }

    public void clear()
    {
        a.clear();
        c.clear();
    }

    public Bitmap get(String s)
    {
        Long long1 = (Long)c.get(s);
        if (long1 != null && System.currentTimeMillis() - long1.longValue() > b)
        {
            a.remove(s);
            c.remove(s);
        }
        return (Bitmap)a.get(s);
    }

    public volatile Object get(Object obj)
    {
        return get((String)obj);
    }

    public Collection keys()
    {
        return a.keys();
    }

    public volatile boolean put(Object obj, Object obj1)
    {
        return put((String)obj, (Bitmap)obj1);
    }

    public boolean put(String s, Bitmap bitmap)
    {
        boolean flag = a.put(s, bitmap);
        if (flag)
        {
            c.put(s, Long.valueOf(System.currentTimeMillis()));
        }
        return flag;
    }

    public volatile void remove(Object obj)
    {
        remove((String)obj);
    }

    public void remove(String s)
    {
        a.remove(s);
        c.remove(s);
    }
}


text:
namespace GekkoAssembler.GekkoInstructions
{
    public class MultiplyLowImmediateInstruction : GekkoInstruction
    {
        public override int ByteCode
            => (((((7 << 5) | RegisterDestination) << 5) | RegisterA) << 16) | (SIMM & 0xFFFF);

        public int RegisterDestination { get; }
        public int RegisterA { get; }
        public int SIMM { get; }

        public MultiplyLowImmediateInstruction(int address, int registerDestination, int registerA, int simm) : base(address)
        {
            RegisterDestination = registerDestination;
            RegisterA = registerA;
            SIMM = simm;
        }
    }
}


text:
//
// TreeViewBackend.cs
//
// Author:
//       Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Shapes;

using Xwt.Backends;
using Xwt.WPFBackend.Utilities;
using System.Windows;
using SWC=System.Windows.Controls;
using System.Windows.Controls;

namespace Xwt.WPFBackend
{
	public class TreeViewBackend
		: WidgetBackend, ITreeViewBackend
	{
		private static readonly ResourceDictionary TreeResourceDictionary;
		static TreeViewBackend()
		{
			Uri uri = new Uri ("pack://application:,,,/Xwt.WPF;component/XWT.WPFBackend/TreeView.xaml");
			TreeResourceDictionary = (ResourceDictionary)XamlReader.Load (System.Windows.Application.GetResourceStream (uri).Stream);
		}

		public TreeViewBackend ()
		{
			Tree = new ExTreeView();
			Tree.Resources.MergedDictionaries.Add (TreeResourceDictionary);
			Tree.ItemTemplate = new HierarchicalDataTemplate { ItemsSource = new Binding ("Children") };
			Tree.SetValue (VirtualizingStackPanel.IsVirtualizingProperty, true);
		}

		public ScrollViewer ScrollViewer {
			get {
				Decorator border = System.Windows.Media.VisualTreeHelper.GetChild(Tree, 0) as Decorator;
				if (border != null)
					return border.Child as ScrollViewer;
				else
					return null;
			}
		}

		public TreePosition CurrentEventRow { get; set;  }

		public ScrollPolicy VerticalScrollPolicy {
			get { return ScrollViewer.GetVerticalScrollBarVisibility (Tree).ToXwtScrollPolicy (); }
			set { ScrollViewer.SetVerticalScrollBarVisibility (Tree, value.ToWpfScrollBarVisibility ()); }
		}

		public ScrollPolicy HorizontalScrollPolicy {
			get { return ScrollViewer.GetHorizontalScrollBarVisibility (Tree).ToXwtScrollPolicy (); }
			set { ScrollViewer.SetHorizontalScrollBarVisibility (Tree, value.ToWpfScrollBarVisibility ()); }
		}

		public IScrollControlBackend CreateVerticalScrollControl()
		{
			return new ScrollControlBackend(ScrollViewer, true);
		}

		public IScrollControlBackend CreateHorizontalScrollControl()
		{
			return new ScrollControlBackend(ScrollViewer, false);
		}

		public TreePosition[] SelectedRows {
			get { return Tree.SelectedItems.Cast<TreePosition> ().ToArray (); }
		}

		public TreePosition FocusedRow {
			get {
				if (Tree.FocusedItem != null)
					return Tree.FocusedItem.DataContext as TreePosition;
				return null;
			}
			set {
				ExTreeViewItem item = GetVisibleTreeItem (value);
				Tree.FocusedItem = item;
			}
		}

		private bool headersVisible = true;
		public bool HeadersVisible {
			get { return this.headersVisible; }
			set
			{
				this.headersVisible = value;
				if (value) {
					if (Tree.View.ColumnHeaderContainerStyle != null)
						Tree.View.ColumnHeaderContainerStyle.Setters.Remove (HideHeaderSetter);
				} else {
					if (Tree.View.ColumnHeaderContainerStyle == null)
						Tree.View.ColumnHeaderContainerStyle = new Style();

				    Tree.View.ColumnHeaderContainerStyle.Setters.Add (HideHeaderSetter);
				}
			}
		}

		GridLines gridLinesVisible;
		public GridLines GridLinesVisible {
			get {
				return gridLinesVisible;
			}
			set {
				gridLinesVisible = value;
			}
		}

		public void SelectRow (TreePosition pos)
		{
			Tree.SelectedItems.Add (pos);
		}

		public void UnselectRow (TreePosition pos)
		{
			Tree.SelectedItems.Remove (pos);
		}

		public bool IsRowSelected (TreePosition row)
		{
			return Tree.SelectedItems.Contains (row);
		}

		public bool IsRowExpanded (TreePosition row)
		{
			return ((TreeStoreNode) row).IsExpanded;
		}

		public void ExpandToRow (TreePosition pos)
		{
			TreeStoreNode parent = ((TreeStoreNode) pos).Parent;
			if (parent != null)
			    parent.IsExpanded = true;
		}

		public void ExpandRow (TreePosition row, bool expandChildren)
		{
			TreeStoreNode node = ((TreeStoreNode) row);
			node.IsExpanded = true;

			if (expandChildren) {
			    foreach (TreeStoreNode childNode in node.Children)
			        childNode.IsExpanded = true;
			}
		}

		public void CollapseRow (TreePosition row)
		{
			((TreeStoreNode) row).IsExpanded = false;
		}

		public void ScrollToRow (TreePosition pos)
		{
			ExTreeViewItem item = GetVisibleTreeItem (pos);
			if (item != null)
				item.BringIntoView ();
		}

		public void SetSelectionMode (SelectionMode mode)
		{
			Tree.SelectionMode = (mode == SelectionMode.Single)
			                     	? SWC.SelectionMode.Single
			                     	: SWC.SelectionMode.Extended;
		}

		public void SelectAll ()
		{
			Tree.SelectAllExpanded();
		}

		public void UnselectAll ()
		{
			Tree.UnselectAll();
		}

		public void SetSource (ITreeDataSource source, IBackend sourceBackend)
		{
			Tree.ItemsSource = (TreeStoreBackend) sourceBackend;
		}

		public object AddColumn (ListViewColumn column)
		{
			var col = new GridViewColumn ();

			UpdateColumn (column, col, ListViewColumnChange.Title);

			Tree.View.Columns.Add (col);

			UpdateColumn (column, col, ListViewColumnChange.Cells);

			return col;
		}

		public void UpdateColumn (ListViewColumn column, object handle, ListViewColumnChange change)
		{
			var col = ((GridViewColumn) handle);
			switch (change) {
			case ListViewColumnChange.Title:
				col.Header = column.Title;
				break;

			case ListViewColumnChange.Cells:
                var cellTemplate = CellUtil.CreateBoundColumnTemplate(Context, Frontend, column.Views);

				col.CellTemplate = new DataTemplate { VisualTree = cellTemplate };

				int index = Tree.View.Columns.IndexOf (col);
				if (index == 0) {
					var dockFactory = CreateExpanderDock ();
					dockFactory.AppendChild (cellTemplate);

					col.CellTemplate.VisualTree = dockFactory;
				}

				break;
			case ListViewColumnChange.Alignment:
				var style = new Style(typeof(GridViewColumnHeader));
				style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, Util.ToWpfHorizontalAlignment(column.Alignment)));
				col.HeaderContainerStyle = style;
				break;
			}
		}

		public void RemoveColumn (ListViewColumn column, object handle)
		{
			Tree.View.Columns.Remove ((GridViewColumn) handle);
		}

		private RowDropPosition dropPosition;
		private ExTreeViewItem dropTarget;
		private Adorner dropAdorner;
		public bool GetDropTargetRow (double x, double y, out RowDropPosition pos, out TreePosition nodePosition)
		{
			nodePosition = null;
			this.dropPosition = pos = RowDropPosition.Into;

			var result = VisualTreeHelper.HitTest (Tree, new System.Windows.Point (x, y)) as PointHitTestResult;

			var element = (result != null) ? result.VisualHit as FrameworkElement : null;
			while (element != null) {
				if (element is ExTreeViewItem)
					break;
				if (element is ExTreeView) // We can't succeed past this point
					return false;

				element = VisualTreeHelper.GetParent (element) as FrameworkElement;
			}

			this.dropTarget = (ExTreeViewItem)element;

			if (element == null)
				return false;

			var point = ((UIElement)result.VisualHit).TranslatePoint (result.PointHit, element);

			double edge = element.ActualHeight * 0.15;
			if (point.Y <= edge)
				this.dropPosition = pos = RowDropPosition.Before;
			else if (point.Y >= element.ActualHeight - edge)
				this.dropPosition = pos = RowDropPosition.After;

			nodePosition = element.DataContext as TreeStoreNode;
			return true;
		}

		public override void EnableEvent (object eventId)
		{
			base.EnableEvent (eventId);
			if (eventId is TableViewEvent) {
				switch ((TableViewEvent)eventId) {
				case TableViewEvent.SelectionChanged:
					Tree.SelectedItemsChanged += OnSelectedItemsChanged;
					break;
				}
			}
		}

		public override void DisableEvent (object eventId)
		{
			base.DisableEvent (eventId);
			if (eventId is TableViewEvent) {
				switch ((TableViewEvent)eventId) {
				case TableViewEvent.SelectionChanged:
					Tree.SelectedItemsChanged -= OnSelectedItemsChanged;
					break;
				}
			}
		}

		protected ExTreeView Tree {
			get { return (ExTreeView)Widget; }
			set { Widget = value; }
		}

		protected ITreeViewEventSink TreeViewEventSink {
			get { return (ITreeViewEventSink)EventSink; }
		}

		protected override double DefaultNaturalHeight {
			get { return -1; }
		}

		protected override double DefaultNaturalWidth {
			get { return -1; }
		}

		public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
		{
			return Size.Zero;
		}

		private void OnSelectedItemsChanged (object sender, EventArgs e)
		{
			Context.InvokeUserCode (TreeViewEventSink.OnSelectionChanged);
		}

		protected override void OnDragOver (object sender, DragOverEventArgs e)
		{
			AdornerLayer layer = AdornerLayer.GetAdornerLayer (Widget);
			if (this.dropAdorner != null)
			    layer.Remove (this.dropAdorner);

			base.OnDragOver (sender, e);

			if (this.dropTarget != null)
			    layer.Add (this.dropAdorner = new TreeViewDropAdorner (this.dropTarget, this.dropPosition));
		}

		protected override void OnDragLeave (object sender, EventArgs e)
		{
			base.OnDragLeave (sender, e);

			if (this.dropAdorner != null)
				AdornerLayer.GetAdornerLayer (Widget).Remove (this.dropAdorner);
		}

		protected override void OnDragFinished (object sender, DragFinishedEventArgs e)
		{
			base.OnDragFinished (sender, e);

			if (this.dropAdorner != null)
				AdornerLayer.GetAdornerLayer (Widget).Remove (this.dropAdorner);
		}

		private ExTreeViewItem GetVisibleTreeItem (TreePosition pos, Action<ExTreeViewItem> walk = null)
		{
			Tree.UpdateLayout();
			Stack<TreeStoreNode> nodes = new Stack<TreeStoreNode> ();

			TreeStoreNode node = (TreeStoreNode) pos;
			do {
				nodes.Push (node);
				node = node.Parent;
			} while (node != null);

			ExTreeViewItem treeItem = null;
			ItemContainerGenerator g = Tree.ItemContainerGenerator;
			while (nodes.Count > 0) {
				node = nodes.Pop ();
				treeItem = (ExTreeViewItem) g.ContainerFromItem (node);
				if (treeItem == null)
					continue;

				treeItem.UpdateLayout ();
				g = treeItem.ItemContainerGenerator;

				if (walk != null)
					walk (treeItem);
			}

			return treeItem;
		}

		private FrameworkElementFactory CreateExpanderDock ()
		{
			var dockFactory = new FrameworkElementFactory (typeof (DockPanel));

			var source = new RelativeSource (RelativeSourceMode.FindAncestor, typeof (ExTreeViewItem), 1);

			Style expanderStyle = new Style (typeof (SWC.Primitives.ToggleButton));
			expanderStyle.Setters.Add (new Setter (UIElement.FocusableProperty, false));
			expanderStyle.Setters.Add (new Setter (FrameworkElement.WidthProperty, 19d));
			expanderStyle.Setters.Add (new Setter (FrameworkElement.HeightProperty, 13d));

			var expanderTemplate = new ControlTemplate (typeof (SWC.Primitives.ToggleButton));

			var outerBorderFactory = new FrameworkElementFactory (typeof (Border));
			outerBorderFactory.SetValue (FrameworkElement.WidthProperty, 19d);
			outerBorderFactory.SetValue (FrameworkElement.HeightProperty, 13d);
			outerBorderFactory.SetValue (Control.BackgroundProperty, Brushes.Transparent);
			outerBorderFactory.SetBinding (UIElement.VisibilityProperty,
				new Binding ("HasItems") { RelativeSource = source, Converter = BoolVisibilityConverter });

			var innerBorderFactory = new FrameworkElementFactory (typeof (Border));
			innerBorderFactory.SetValue (FrameworkElement.WidthProperty, 9d);
			innerBorderFactory.SetValue (FrameworkElement.HeightProperty, 9d);
			innerBorderFactory.SetValue (Control.BorderThicknessProperty, new Thickness (1));
			innerBorderFactory.SetValue (Control.BorderBrushProperty, new SolidColorBrush (Color.FromRgb (120, 152, 181)));
			innerBorderFactory.SetValue (Border.CornerRadiusProperty, new CornerRadius (1));
			innerBorderFactory.SetValue (UIElement.SnapsToDevicePixelsProperty, true);

			innerBorderFactory.SetValue (Control.BackgroundProperty, ExpanderBackgroundBrush);

			var pathFactory = new FrameworkElementFactory (typeof (Path));
			pathFactory.SetValue (FrameworkElement.MarginProperty, new Thickness (1));
			pathFactory.SetValue (Shape.FillProperty, Brushes.Black);
			pathFactory.SetBinding (Path.DataProperty,
				new Binding ("IsChecked") {
					RelativeSource = new RelativeSource (RelativeSourceMode.FindAncestor, typeof (SWC.Primitives.ToggleButton), 1),
					Converter = BooleanGeometryConverter
			});

			innerBorderFactory.AppendChild (pathFactory);
			outerBorderFactory.AppendChild (innerBorderFactory);

			expanderTemplate.VisualTree = outerBorderFactory;

			expanderStyle.Setters.Add (new Setter (Control.TemplateProperty, expanderTemplate));

			var toggleFactory = new FrameworkElementFactory (typeof (SWC.Primitives.ToggleButton));
			toggleFactory.SetValue (FrameworkElement.StyleProperty, expanderStyle);
			toggleFactory.SetBinding (FrameworkElement.MarginProperty,
				new Binding ("Level") { RelativeSource = source, Converter = LevelConverter });
			toggleFactory.SetBinding (SWC.Primitives.ToggleButton.IsCheckedProperty,
				new Binding ("IsExpanded") { RelativeSource = source });
			toggleFactory.SetValue (SWC.Primitives.ButtonBase.ClickModeProperty, ClickMode.Press);

			dockFactory.AppendChild (toggleFactory);
			return dockFactory;
		}

		private static readonly LevelToIndentConverter LevelConverter = new LevelToIndentConverter();
		private static readonly BooleanToVisibilityConverter BoolVisibilityConverter = new BooleanToVisibilityConverter();

		private static readonly LinearGradientBrush ExpanderBackgroundBrush = new LinearGradientBrush {
			StartPoint = new System.Windows.Point (0, 0),
			EndPoint = new System.Windows.Point (1, 1),
			GradientStops = new GradientStopCollection {
				new GradientStop (Colors.White, 0.2),
				new GradientStop (Color.FromRgb (192, 183, 166), 1)
			}
		};

		private static readonly Geometry Plus = Geometry.Parse ("M 0 2 L 0 3 L 2 3 L 2 5 L 3 5 L 3 3 L 5 3 L 5 2 L 3 2 L 3 0 L 2 0 L 2 2 Z");
		private static readonly Geometry Minus = Geometry.Parse ("M 0 2 L 0 3 L 5 3 L 5 2 Z");

		private static readonly BooleanToValueConverter BooleanGeometryConverter =
			new BooleanToValueConverter { TrueValue = Minus, FalseValue = Plus };

		private static readonly Setter HideHeaderSetter = new Setter (UIElement.VisibilityProperty, Visibility.Collapsed);
	}
}


text:
'''
 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

 For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 x 53 = 49714.

 What is the total of all the name scores in the file?
 '''

def worth(name):
	return sum(ord(letter) - ord('A') + 1 for letter in name)
def solve():
 names = open('pythran/tests/euler/names22.txt').read().replace('"', '').split(',')
 names.sort()

 return sum((i+1) * worth(names[i]) for i in range(0, len(names)))


text:
'use strict';
import fsExtra from 'fs-extra';
import path from 'path';
import stream from 'stream';
import sinon from 'sinon';
import nock from 'nock';

import {getLogger} from '@/lib/util/logger';
import * as wrapperHelpers from '@/lib/commandWrappers/helpers';
import {ProgressStream} from '@/lib/util/progress';
import {BackendConfig} from '@/types';
import {Compression} from '@/lib/commandWrappers/tarWrapper';

export function fakeBackendConfig(alias: string): BackendConfig {
    return {
        alias,
        options: {},
        backend: {
            pull: () => createNodeModules(),
            push: () => Promise.resolve(),
            validateOptions: () => Promise.resolve(),
        }
    }
}

export function createNodeModules(): Promise<void> {
    return fsExtra.ensureDir(path.join(process.cwd(), 'node_modules'))
        .then(() => fsExtra.writeFile(
            path.join(process.cwd(), 'node_modules', 'foobar'),
            'deadbeef'
        ));
}

export function notifyAssert(assertion: () => void, done: (e?: Error) => void) {
    try {
        assertion();
        done();
    } catch (e) {
        done(e);
    }
}

export function checkMockResult(mocks: sinon.SinonMock[], done: (e?: Error) => void, error?: Error) {
    if (error && error.name === 'ExpectationError') {
        return done(error);
    }

    try {
        mocks.map(mock => mock.verify());
    } catch (error) {
        return done(error);
    }

    done();
}

export function checkNock(scopes: nock.Scope[], done: (err?: Error) => void) {
    try {
        scopes.map(scope => scope.done());
    } catch (error) {
        return done(error);
    }

    done();
}

// This class is used as `generic error`,
// if we want to test error propagation
export class AnError extends Error {}

// Simulate AWSError
export class AWSError extends Error {
    statusCode?: number;
    code: string;
    constructor(_message: string, code: string, _statusCode?: number) {
        super();
        this.message = 'The specified key does not exist.';
        this.statusCode = 404;
        this.code = 'NoSuchKey';
        this.name = code;
    }
}

// A stream to simulate download error
export class FailingStream extends stream.Readable {
    turn: number;
    failError: Error;
    constructor(failError = new AnError('read error')) {
        super();
        this.turn = 0;
        this.failError = failError;
    }
    _read() {
        if (this.turn < 5) {
            this.turn++;
            setImmediate(() => {
                this.push('wertyuiopasdfghjk');
            });
        } else {
            this.emit('error', this.failError);
            this.push(null);
        }
    }
}

export class SuccessfulStream extends stream.Readable {
    turn: number;

    constructor() {
        super();
        this.turn = 0;
    }

    _read() {
        if (this.turn < 5) {
            this.turn++;
            setImmediate(() => {
                this.push('wertyuiopasdfghjk');
            });
        } else {
            this.push(null);
        }
    }
}

export class DevNullStream extends stream.Writable {
    _write(_chunk: any, _encoding: string, callback: () => void) {
        callback();
    }
}

export function fakeExtractArchiveFromStream(stream: NodeJS.ReadableStream): Promise<string> {
    const allchunks: string[] = [];
    let interval: NodeJS.Timeout;
    return new Promise(resolve => {
        stream.read();
        interval = setInterval(() => {
            const chunk = stream.read();
            if (chunk === null) {
                clearInterval(interval);
                return resolve(allchunks.join());
            } else {
                allchunks.push(chunk.toString());
            }
        }, 10);
    });
}

export function fakeCreateStreamArchive(_inputPaths: string[], _compressionType: Compression, _params: {}): {
    stream: NodeJS.ReadableStream, promise: Promise<string>
} {
    return {
        stream: new SuccessfulStream(),
        promise: Promise.resolve(''),
    };
}

export function mockGetOutput(sandbox: sinon.SinonSandbox) {
    sandbox.stub(wrapperHelpers, 'getOutput').callsFake((executable, args) => {
        const commandName = `[${executable} ${args.join(' ')}]`;

        console.error(`${commandName} is being executed! Looks lile someone doesn't mock the env properly`);
        return Promise.reject(new Error('waaat'));
    });
}

export function makeFakeBackendToolsProvider() {
    return {
        getLogger() {
            return getLogger();
        },

        getProgressStream(label?: string, total?: number) {
            return new ProgressStream({}, label || 'wat', {}, total);
        },
    };
}


text:
command_line="$(python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' ${HONGGFUZZ_PATH})"
command_line+=("--workspace=${FUZZER_OUTPUT_ROOT}")

if [[ -n "${FUZZER_SEED_CORPUS_DIR}" ]]; then
    command_line+=("--input=${FUZZER_SEED_CORPUS_DIR}")
    command_line+=("--output=${FUZZER_OUTPUT_CORPUS_DIR}")
else
    command_line+=("--input=${FUZZER_OUTPUT_CORPUS_DIR}")
fi
if (( FUZZER_IS_REGRESSION )); then
    # Dry-run-only mode - see https://github.com/google/honggfuzz/issues/296.
    command_line+=("--mutations_per_run=0")
    command_line+=("--verifier")
    # Make the output more suitable for debugging.
    command_line+=("--verbose")
    command_line+=("--keep_output")
fi

command_line+=("--crashdir=${FUZZER_ARTIFACTS_DIR}")

if [[ "${FUZZER_TIMEOUT_SECS}" -gt 0 ]]; then
    command_line+=("--run_time=${FUZZER_TIMEOUT_SECS}")
fi

if [[ -n "${FUZZER_DICTIONARY_PATH}" ]]; then
    command_line+=("--dict=${FUZZER_DICTIONARY_PATH}")
fi
command_line+=("--" "${FUZZER_BINARY}")

exec "${command_line[@]}" "$@"