text:
class FdoArgumentDefinition : public FdoIDisposable
{
/// \cond DOXYGEN-IGNORE
protected:
    /// Constructs an instance of an FdoArgumentDefinition using the specified arguments.
    FdoArgumentDefinition(FdoString* name, FdoString* description, FdoDataType dataType);

    /// Constructs an instance of an FdoArgumentDefinition using the specified arguments.
    FdoArgumentDefinition(FdoString* name, FdoString* description, FdoPropertyType propertyType, FdoDataType dataType);

    /// Constructs an instance of an FdoArgumentDefinition with default properties.
    FdoArgumentDefinition();

    virtual ~FdoArgumentDefinition();

    virtual void Dispose();
/// \endcond

public:
    /// \brief
    /// Constructs an instance of an FdoArgumentDefinition using the specified arguments.
    ///
    /// \param name
    /// Input the name of the argument.
    /// \param description
    /// Input a brief description of the argument.
    /// \param dataType
    /// Input the type of argument.
    ///
    /// \return
    /// Returns FdoArgumentDefinition
    ///
    FDO_API static FdoArgumentDefinition* Create(FdoString* name, FdoString* description, FdoDataType dataType);

    /// \brief
    /// Constructs an instance of an FdoArgumentDefinition using the specified arguments.
    ///
    /// \param name
    /// Input the name of the argument.
    /// \param description
    /// Input a brief description of the argument.
    /// \param propertyType
    /// Input the property type of the argument
    /// \param dataType
    /// Input the data type of the argument;
    /// This is used only if the argument's property type is FdoPropertyType_DataProperty.
    ///
    /// \return
    /// Returns FdoArgumentDefinition
    ///
    FDO_API static FdoArgumentDefinition* Create(FdoString* name, FdoString* description, FdoPropertyType propertyType, FdoDataType dataType);

    /// \brief
    /// Gets the name of the argument.
    ///
    /// \return
    /// Returns the argument name
    ///
    FDO_API FdoString* GetName();

    /// \brief
    /// Gets a brief description of the argument.
    ///
    /// \return
    /// Returns the argument description
    ///
    FDO_API FdoString* GetDescription();

    /// \brief
    /// Gets the FdoDataType of the argument.
    ///
    /// \return
    /// Returns the property type of the argument
    ///
    FDO_API FdoPropertyType GetPropertyType();

    /// \brief
    /// Gets the FdoDataType of the argument.
    ///
    /// \return
    /// Returns the data type of the argument;
    /// This is valid only if the argument's property type is FdoPropertyType_DataProperty.
    ///
    FDO_API FdoDataType GetDataType();

protected:
    wchar_t*        m_name;
    wchar_t*        m_description;
    FdoPropertyType m_propertyType;
    FdoDataType     m_dataType;
};
#endif


text:
[ajaxMock](http://semanticsworks.com/) - A mock for jQuery AJAX
==================================================
It is inspired by [gist:1445906](https://gist.github.com/1445906) by cowboy.

How can you use it?
--------------------------------------

You can write your normal jQuery ajax code as usual. When you want to
mock your ajax call, import it ajaxMock.js into your page, and use the following code, and
your ajax call will be served by the mock. However, if there is no ajax setup match with an ajax
call, that ajax call be real ajax call, so you can mix mock ajax and real ajax together.

$.ajaxMock.on();

//for simple url mock use

$.ajaxMock.url( urlOrUrlRegEx, resultOrResultFunction);

//for full control use, or develop your own higher level api use

$.ajaxMock.setup(function match(mergedOptions, originalOptions) { return true;},
function result(mergedOptions, originalOptions) { return mockValue});

//if you want to throw away the previous setup, and start over.

$.ajaxMock.reset();

//when you want to switch real ajax

$.ajaxMock.off();

For more full usage details, see [test case](https://github.com/fredyang/ajaxMock/blob/master/test/test.js).

redpajama_set_name: RedPajamaGithub


text:
<claw version="2.0">
  <global type="root">
    <parameter key="translator" value="claw.wani.x2t.translator.ClawTranslator"/>
  </global>
  <sets>
    <set name="claw-external-set"/>
  </sets>
  <groups>
    <group name="add-print"/>
  </groups>
</claw>


text: A simple session management utility for NodeJs web applications


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

using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility;
using Microsoft.Practices.IoTJourney.ColdStorage.Logging;
using Xunit;

namespace Microsoft.Practices.IoTJourney.ColdStorage.Tests
{
    public class GivenAColdStorageEventSource
    {
        [Fact]
        public void CustomEventSourcePassesValidation()
        {
            EventSourceAnalyzer.InspectAll(ColdStorageEventSource.Log);
        }
    }
}


text: URL_BASE = 'https://daylight.luminoso.com/api/v5'


text:
package ch.ivyteam.test;

import static org.assertj.core.api.Assertions.assertThat;

import javax.inject.Named;

import org.junit.jupiter.api.Test;

import ch.ivyteam.ivy.bpm.engine.client.BpmClient;
import ch.ivyteam.ivy.bpm.engine.client.ExecutionResult;
import ch.ivyteam.ivy.bpm.engine.client.History;
import ch.ivyteam.ivy.bpm.engine.client.Workflow;
import ch.ivyteam.ivy.bpm.engine.client.element.BpmElement;
import ch.ivyteam.ivy.bpm.engine.client.element.BpmProcess;
import ch.ivyteam.ivy.bpm.exec.client.IvyProcessTest;
import ch.ivyteam.ivy.security.IUser;
import ch.ivyteam.ivy.workflow.CaseState;
import ch.ivyteam.ivy.workflow.TaskState;
import crm.Order;

@IvyProcessTest
public class TestInvoiceProcess
{
  /* The process under test */
  private static final BpmProcess INVOICE_PROCESS = BpmProcess.name("invoice");

  /* The process start elements */
  private static final BpmElement WRITE_INVOICE_START = INVOICE_PROCESS.elementName("writeInvoice.ivp");
  private static final BpmElement WRITE_INVOICE = INVOICE_PROCESS.elementName("write invoice");
  private static final BpmElement CHECK_ORDER_START = INVOICE_PROCESS.elementName("checkOrder.ivp");

  @Test
  void writeInvoice(BpmClient bpmClient)
  {
    /* Executing the write invoice process */
    ExecutionResult result = bpmClient
            .start()
            .process(WRITE_INVOICE_START)
            .execute();

    /* The execution should have ran exactly two elements; the RequestStart and UserTask */
    History history = result.history();
    assertThat(history.elementNames()).containsExactly("writeInvoice.ivp", "write invoice");

    /* The last executed task should be the RequestStart task */
    Workflow workflow = result.workflow();
    assertThat(workflow.executedTask().getName()).isEqualTo("start write invoice");

    /* Mock the UI part of the UserTask by setting the UI result */
    bpmClient.mock().uiOf(WRITE_INVOICE).with((params, results) -> results.set("total", 935));

    /* Drive the process further through the UserTask by telling the BpmClient hat it
     * should execute the next task with the role everybody */
    result = bpmClient
            .start()
            .anyActiveTask(result)
            .as().everybody()
            .execute();

    /* This time the execution should have ran until the end of the process */
    history = result.history();
    assertThat(history.elementNames()).containsExactly("write invoice", "end");

    /* Asserting the data of the last execution */
    Order orderData = result.data().last();
    assertThat(orderData.getTotal()).isEqualTo(935);

    /* The process is finished and therefore the workflow case should be done */
    workflow = result.workflow();
    assertThat(workflow.activeCase().getState()).isEqualTo(CaseState.DONE);
  }

  @Test
  void checkOrder(BpmClient bpmClient)
  {
    /* Mocking the return value of a html dialog */
    bpmClient.mock()
            .element(INVOICE_PROCESS.elementName("check order"))
            .with(Order.class, (in, out) -> out.setValid(Boolean.TRUE));

    ExecutionResult result = bpmClient
            .start()
            .process(CHECK_ORDER_START)
            .execute();

    /* Asserting the data of the last execution */
    Order orderData = result.data().last();
    assertThat(orderData.getValid()).isTrue();
  }

  @Test
  @SuppressWarnings("unused")
  void select(BpmClient bpmClient)
  {
    /* Selecting processes */
    BpmProcess byName = BpmProcess.name("invoice");
    BpmProcess byNameSelector = BpmProcess.name().startsWith("invo");

    /* Selecting process elements */
    BpmElement byEleName = INVOICE_PROCESS.elementName("write invoice");
    BpmElement byEleNameSelector = INVOICE_PROCESS.element().name().contains("write");
  }

  @Test
  @SuppressWarnings("unused")
  void as(BpmClient bpmClient)
  {
    /* Execution with the role everybody */
    ExecutionResult result = bpmClient.start()
            .process(WRITE_INVOICE_START)
            .as().everybody()
            .execute();

    /* Execution with a specific user */
    result = bpmClient.start()
            .process(WRITE_INVOICE_START)
            .as().user("James Bond")
            .execute();

    /* Execution by selecting a specific role */
    result = bpmClient.start()
            .process(WRITE_INVOICE_START)
            .as().role("Everybody")
            .execute();
  }

  @Test
  void start(BpmClient bpmClient)
  {
    bpmClient.mock().uiOf(WRITE_INVOICE).withNoAction();

    ExecutionResult result = bpmClient
            .start().process(WRITE_INVOICE_START)
            .execute();

    /* Execute any active task after the previous result */
    bpmClient.start().anyActiveTask(result).as().everybody().execute();

    result = bpmClient
            .start().process(WRITE_INVOICE_START)
            .execute();

    /* Execute the desired task */
    bpmClient.start().task(result.workflow().anyActiveTask()).as().everybody().execute();
  }

  @Test
  void workflow(BpmClient bpmClient, @Named("James Bond") IUser user)
  {
    BpmElement prepareShipmentStart = INVOICE_PROCESS.elementName("prepareShipment.ivp");

    ExecutionResult result = bpmClient
            .start().process(prepareShipmentStart)
            .as().user(user)
            .execute();

    /* Asserting case and task states */
    assertThat(result.workflow().activeCase().getState()).isEqualTo(CaseState.RUNNING);
    assertThat(result.workflow().executedTask().getState()).isEqualTo(TaskState.DONE);

    /* Asserting if any active tasks are present */
    assertThat(result.workflow().anyActiveTask()).isPresent();
    assertThat(result.workflow().activeTasks()).hasSize(1);
    assertThat(result.workflow().activeTask().name("prepare shipment")).isPresent();
    assertThat(result.workflow().activeTask().name().startsWith("prepare")).isPresent();

    /* Asserting the activator */
    assertThat(result.workflow().activeTask().activatorUser("James Bond")).isPresent();
    assertThat(result.workflow().activeTask().activator(user)).isPresent();

    /* Asserting the session user */
    assertThat(result.workflow().session().getSessionUserName()).isEqualTo("James Bond");
  }

  @Test
  void history(BpmClient bpmClient)
  {
    ExecutionResult result = bpmClient
            .start().process(WRITE_INVOICE_START)
            .execute();

    /* Assert that a specific element has been executed */
    assertThat(result.history().elements()).contains(WRITE_INVOICE_START);

    /* Assert that the elements with the given names have been executed */
    assertThat(result.history().elementNames()).contains("writeInvoice.ivp", "write invoice");
  }

  @Test
  void data(BpmClient bpmClient)
  {
    BpmElement writeInvoiceElement = INVOICE_PROCESS.elementName("write invoice");

    ExecutionResult result = bpmClient
            .start().process(WRITE_INVOICE_START)
            .execute();

    /* Process data at last executed element */
    assertThat(((Order)result.data().last()).getValid()).isFalse();

    /* Process data at elements last execution */
    assertThat(((Order)result.data().lastOnElement(writeInvoiceElement)).getValid()).isFalse();

    /* Process data for each execution of the element */
    assertThat(((Order)result.data().onElement(writeInvoiceElement).get(0)).getValid()).isFalse();

    /* Streaming over all executions of the process data */
    result.data().onElement(writeInvoiceElement)
            .stream()
            .map(data -> (Order)data)
            .forEach(data -> assertThat(data.getValid()).isFalse());
  }

  @Test
  void mock(BpmClient bpmClient)
  {
    /* Mocking an element that doesn't require nor return anything */
    bpmClient.mock()
            .element(INVOICE_PROCESS.elementName("check order"))
            .withNoAction();

    /* Mocking without prior setup */
    bpmClient.mock()
            .element(INVOICE_PROCESS.elementName("check order"))
            .with(Order.class, (in, out) -> out.setValid(Boolean.TRUE));

    /* Mocking by defining the data beforehand */
    Order myOrderData = new Order();
    myOrderData.setValid(Boolean.TRUE);

    bpmClient.mock()
            .element(INVOICE_PROCESS.elementName("check order"))
            .with(in -> myOrderData);

    /* Mocking only the UI part of the element */
    bpmClient.mock()
            .uiOf(INVOICE_PROCESS.elementName("check order"))
            .with((params, results) -> results.set("total", 935));
  }

}


text: CREATE DATABASE oaccdb WITH ENCODING='UTF8' CONNECTION LIMIT=-1;


text:
package org.radargun.reporting;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.CategoryItemLabelGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.StringTokenizer;

/**
 * Generates average and total throughput.  Used for parsing reports generated with a ClusterReportGenerator.
 *
 * @author Manik Surtani (manik@jboss.org)
 */
public class PutGetChartGenerator extends AbstractChartGen {
   private DefaultCategoryDataset putData, getData;
   private String chartExtension = ".png";
   private String putChartName = "PutChart", getChartName = "GetChart";
   private Log log = LogFactory.getLog(PutGetChartGenerator.class);
   private int nPuts = 0, nGets = 0;
   private int numFilesScanned = 0;

   public void generateChart() throws IOException {
      readData();

      String putChartNameToUse = filenamePrefix == null ? putChartName : filenamePrefix + "-" + putChartName;
      File chartFile;
      File root = null;
      if (outputDir == null) {
         chartFile = new File(putChartNameToUse + chartExtension);
      } else {
         root = new File(outputDir);
         if (!root.exists()) {
            if (root.mkdirs()) {
               log.warn("Could not create root dir : " + root.getAbsolutePath() + " This might result in reports not being generated");
            }
         }
         chartFile = new File(root, putChartNameToUse + chartExtension);
      }
      if (chartFile.exists()) {
         chartFile.renameTo(new File(putChartNameToUse + "." + System.currentTimeMillis() + chartExtension));
         chartFile = new File(putChartNameToUse + chartExtension);
      }

      ChartUtilities.saveChartAsPNG(chartFile, createChart("Report: Comparing Cache PUT (WRITE) performance", putData, nPuts / numFilesScanned), 800, 800);

      String getChartNameToUse = filenamePrefix == null ? getChartName : filenamePrefix + "-" + getChartName;
      chartFile = root == null ? new File(getChartNameToUse + chartExtension) : new File(root, getChartNameToUse + chartExtension);
      if (chartFile.exists()) {
         chartFile.renameTo(new File(getChartNameToUse + "." + System.currentTimeMillis() + chartExtension));
         chartFile = new File(getChartNameToUse + chartExtension);
      }

      ChartUtilities.saveChartAsPNG(chartFile, createChart("Report: Comparing Cache GET (READ) performance", getData, nGets / numFilesScanned), 800, 800);

      System.out.println("Charts saved as " + putChartNameToUse + " and " + getChartNameToUse);
   }

   private JFreeChart createChart(String title, DefaultCategoryDataset data, int numOperations) {
      JFreeChart chart = ChartFactory.createBarChart3D(title, "Cache operations performed (approx): " + NumberFormat.getIntegerInstance().format(numOperations), "Average time (" + MU + "-seconds)", data, PlotOrientation.VERTICAL, true, true, false);
      BarRenderer3D renderer = (BarRenderer3D) chart.getCategoryPlot().getRenderer();
      renderer.setBaseItemLabelsVisible(true);

      final NumberFormat fmt = NumberFormat.getNumberInstance();
      fmt.setMaximumFractionDigits(2);
      fmt.setMinimumFractionDigits(2);

      renderer.setBaseItemLabelGenerator(new CategoryItemLabelGenerator() {

         public String generateRowLabel(CategoryDataset categoryDataset, int i) {
            return null;
         }

         public String generateColumnLabel(CategoryDataset categoryDataset, int i) {
            return null;
         }

         public String generateLabel(CategoryDataset categoryDataset, int product, int operation) {
            String retval;
            try {
               retval = fmt.format(categoryDataset.getValue(product, operation)) + " " + MU + "s";
            }
            catch (Exception e) {
               e.printStackTrace();
               retval = e.toString();
            }
            return retval;
         }
      });

      chart.addSubtitle(getSubtitle());

      chart.setBorderVisible(true);
      chart.setAntiAlias(true);
      chart.setTextAntiAlias(true);
      chart.setBackgroundPaint(new Color(0x61, 0x9e, 0xa1));
      return chart;
   }

   private void readData() throws IOException {
      File file = new File(reportDirectory);
      if (!file.exists() || !file.isDirectory())
         throw new IllegalArgumentException("Report directory " + reportDirectory + " does not exist or is not a directory!");

      File[] files = getFilteredFiles(file);

      putData = new DefaultCategoryDataset();
      getData = new DefaultCategoryDataset();

      for (File f : files) {
         readData(f);
      }

      //sort(averageThroughput);
   }

   private void readData(File f) throws IOException {
      log.debug("Processing file " + f);
      //expected file format is: <product>_<config>_<size>.csv
      StringTokenizer tokenizer = new StringTokenizer(f.getName() + "_");
      String productName = tokenizer.nextToken() + "_" + tokenizer.nextToken();

      if (productName.indexOf(".xml") > 0) {
         productName = productName.substring(0, productName.indexOf(".xml"));
      }

      // now the contects of this file:

      String line = null;
      BufferedReader br = new BufferedReader(new FileReader(f));
      double avgPut = -1, avgGet = -1;
      Stats s = null;

      while ((line = br.readLine()) != null && s == null) {
         s = getAveragePutAndGet(line);
         log.debug("Read stats " + s);
         if (s != null) {
            avgPut = s.avgPut;
            avgGet = s.avgGet;
            nGets += s.numGets;
            nPuts += s.numPuts;
         }
      }

      br.close();

      putData.addValue(avgPut, productName, "PUT");
      getData.addValue(avgGet, productName, "GET");
      numFilesScanned++;
   }

   private Stats getAveragePutAndGet(String line) {
      // To be a valid line, the line should be comma delimited
      StringTokenizer strTokenizer = new StringTokenizer(line, ",");
      if (strTokenizer.countTokens() < 7) return null;

      // 8th token is avg put
      // 9th token is avg get
      for (int i = 0; i < 7; i++) strTokenizer.nextToken();

      String putStr = strTokenizer.nextToken();
      String getStr = strTokenizer.nextToken();

      // 20 and 21st tokens are the num puts and num gets performed.

      for (int i = 0; i < 10; i++) strTokenizer.nextToken();

      String nPutStr = strTokenizer.nextToken();
      String nGetStr = strTokenizer.nextToken();

      Stats s = new Stats();
      try {
         s.avgPut = Double.parseDouble(putStr) / 1000;
         s.avgGet = Double.parseDouble(getStr) / 1000;
         s.numPuts = Integer.parseInt(nPutStr);
         s.numGets = Integer.parseInt(nGetStr);
      }
      catch (NumberFormatException nfe) {
//         log.error("Unable to parse file properly!", nfe);
         return null;
      }
      return s;
   }

   private static class Stats {
      double avgPut, avgGet;
      int numPuts, numGets;

      public String toString() {
         return "Stats{" +
               "avgPut=" + avgPut +
               ", avgGet=" + avgGet +
               ", numPuts=" + numPuts +
               ", numGets=" + numGets +
               '}';
      }
   }

}


text:
package com.zm.json;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * Created by Administrator on 2017/3/15.
 */
public class JsonAnalysis {

    public static void main(String[] args){
        String json = "{aa:11,bb:{cc:{dd:22}},ee:{ff:'33',gg:44}}";

        if (json.length() - json.replace("{","").length() != json.length() - json.replace("}","").length()){
         throw new IllegalStateException("expression is error.");
        }
        Stack stack = new Stack();
//        Map result = new HashMap<>();
        analysis(stack, json);

//        System.out.println(":".equals(":"));
        System.out.println(stack);
//        System.out.println(stackParam.pop());
    }

    public static void analysis(Stack stack, String jsonString){

        for (int i = 0; i < jsonString.length(); i++) {

            if(jsonString.charAt(i) == '}'){
                doWithBrackets(stack);
            }else if (jsonString.charAt(i) == ',') {
                doWithBrackets(stack);
                stack.push(',');
            }else {
                stack.push(jsonString.charAt(i));
            }
        }
    }

    public static void doWithBrackets(Stack stack){
        StringBuilder key = new StringBuilder();
        StringBuilder value = new StringBuilder();
        Map mapValue = new HashMap<>();
        boolean isKey = false;

        while (stack.size()>0){
            Object item = stack.pop();
            boolean isMap = false;
            if (item instanceof Map){
                isMap = true;
            }else {
                item = item.toString();
            }
            if (!isKey && !item.equals(":")){
                if (isMap){
                    mapValue.putAll((Map) item);
                }else {

                    value.insert(0,item);
                }
            }else {
                if (!isKey){
                    isKey = true;
                    continue;
                }
                if ( !item.equals("{") && !item.equals(",")){
                    key.insert(0,item);
                }else {
                    break;
                }
            }
        }

        Map map = new HashMap<>();
        map.put(key,value.length()==0 ? mapValue : value);
        stack.push(map);

    }
}


text:
from __future__ import absolute_import

from google.appengine.ext import ndb

from api import fields
import config
import model
import util

class Config(model.Base, model.ConfigAuth):
  analytics_id = ndb.StringProperty(default='', verbose_name='Tracking ID')
  announcement_html = ndb.TextProperty(default='', verbose_name='Announcement HTML')
  announcement_type = ndb.StringProperty(default='info', choices=['info', 'warning', 'success', 'danger'])
  anonymous_recaptcha = ndb.BooleanProperty(default=False, verbose_name='Use reCAPTCHA in forms for unauthorized users')
  brand_name = ndb.StringProperty(default=config.APPLICATION_ID)
  check_unique_email = ndb.BooleanProperty(default=True, verbose_name='Check for uniqueness of the verified emails')
  email_authentication = ndb.BooleanProperty(default=False, verbose_name='Email authentication for sign in/sign up')
  feedback_email = ndb.StringProperty(default='')
  flask_secret_key = ndb.StringProperty(default=util.uuid())
  letsencrypt_challenge = ndb.StringProperty(default='', verbose_name=u'Let's Encrypt Challenge')
  letsencrypt_response = ndb.StringProperty(default='', verbose_name=u'Let's Encrypt Response')
  notify_on_new_user = ndb.BooleanProperty(default=True, verbose_name='Send an email notification when a user signs up')
  recaptcha_private_key = ndb.StringProperty(default='', verbose_name='Private Key')
  recaptcha_public_key = ndb.StringProperty(default='', verbose_name='Public Key')
  salt = ndb.StringProperty(default=util.uuid())
  verify_email = ndb.BooleanProperty(default=True, verbose_name='Verify user emails')

  @property
  def has_anonymous_recaptcha(self):
    return bool(self.anonymous_recaptcha and self.has_recaptcha)

  @property
  def has_email_authentication(self):
    return bool(self.email_authentication and self.feedback_email and self.verify_email)

  @property
  def has_recaptcha(self):
    return bool(self.recaptcha_private_key and self.recaptcha_public_key)

  @classmethod
  def get_master_db(cls):
    return cls.get_or_insert('master')

  FIELDS = {
    'analytics_id': fields.String,
    'announcement_html': fields.String,
    'announcement_type': fields.String,
    'anonymous_recaptcha': fields.Boolean,
    'brand_name': fields.String,
    'check_unique_email': fields.Boolean,
    'email_authentication': fields.Boolean,
    'feedback_email': fields.String,
    'flask_secret_key': fields.String,
    'letsencrypt_challenge': fields.String,
    'letsencrypt_response': fields.String,
    'notify_on_new_user': fields.Boolean,
    'recaptcha_private_key': fields.String,
    'recaptcha_public_key': fields.String,
    'salt': fields.String,
    'verify_email': fields.Boolean,
  }

  FIELDS.update(model.Base.FIELDS)
  FIELDS.update(model.ConfigAuth.FIELDS)


text:
package beaform.gui.main;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 * The new menu for the application.
 *
 * @author Steven Post
 *
 */
class NewMenu implements SubMenu {

	private final JMenu menu = new JMenu("New...");
	private final JMenuItem search = new JMenuItem("Search");

	/** The add item, which opens up the formula editor */
	private final JMenuItem add = new JMenuItem("Add");

	public NewMenu() {
		init();
	}

	private void init() {
		this.menu.add(this.search);
		this.search.addActionListener(new SearchGuiLaunchAction());

		this.menu.add(this.add);
		this.add.addActionListener(new FormulaEditorLaunchAction());
	}

	@Override
	public void attachToMenuBar(final JMenuBar menubar) {
		menubar.add(this.menu);
	}

}


text:
#include <WindowsConsoleControl.h>

#ifdef OS_WINDOWS

cc_Vector2 cc_getCursorPosition() {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		cc_Vector2 position = {0, 0};
		return position;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		cc_Vector2 position = {0, 0};
		return position;
	}

	cc_Vector2 position = {
		csbi.dwCursorPosition.X - csbi.srWindow.Left,
		csbi.dwCursorPosition.Y - csbi.srWindow.Top
	};
	return position;
}

cc_Vector2 cc_getCursorGlobalPosition() {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		cc_Vector2 position = {0, 0};
		return position;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		cc_Vector2 position = {0, 0};
		return position;
	}

	cc_Vector2 position = {
		csbi.dwCursorPosition.X,
		csbi.dwCursorPosition.Y
	};
	return position;
}

void cc_reverseColors() {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		return;
	}

	if(!SetConsoleTextAttribute(hStdOut, csbi.wAttributes | (WORD) COMMON_LVB_REVERSE_VIDEO)) {
		LOG_ERROR("SetConsoleTextAttribute failed (error %lu)", GetLastError());
		return;
	}
}

cc_type cc_getGlobalWidth() {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return 0;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		return 0;
	}

	return csbi.dwSize.X;
}

cc_type cc_getGlobalHeight() {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return 0;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		return 0;
	}

	return csbi.dwSize.Y;
}

void cc_setCursorGlobalPosition(const cc_Vector2 position) {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return;
	}

	COORD pos = {
		(short) position.x,
		(short) position.y
	};
	if(!SetConsoleCursorPosition(hStdOut, pos)) {
		LOG_ERROR("SetConsoleCursorPosition failed (error %lu)", GetLastError());
		return;
	}
}

cc_Vector2 cc_globalClamp(const cc_Vector2 position) {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return position;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		return position;
	}

	short maxX = (short) (csbi.dwSize.X - 1);
	short maxY = (short) (csbi.dwSize.Y - 1);
	cc_Vector2 result = {
		position.x < maxX ? (position.x < 0 ? 0 : position.x) : maxX,
		position.y < maxY ? (position.y < 0 ? 0 : position.y) : maxY
	};
	return result;
}

bool cc_globalContains(const cc_Vector2 position) {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return false;
	}

	CONSOLE_SCREEN_BUFFER_INFO csbi;
	if(!GetConsoleScreenBufferInfo(hStdOut, &csbi)) {
		LOG_ERROR("GetConsoleScreenBufferInfo failed (error %lu)", GetLastError());
		return false;
	}

	return position.x >= 0
	       && position.y >= 0
	       && position.x < csbi.dwSize.X
	       && position.y < csbi.dwSize.Y;
}

void cc_setCursorSize(unsigned int size) {
	HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
	if(hStdOut == INVALID_HANDLE_VALUE) {
		LOG_ERROR("GetStdHandle failed (error %lu)", GetLastError());
		return;
	}

	CONSOLE_CURSOR_INFO cci;
	if(!GetConsoleCursorInfo(hStdOut, &cci)) {
		LOG_ERROR("GetConsoleCursorInfo failed (error %lu)", GetLastError());
		return;
	}

	if(size < 100) {
		cci.dwSize = size;
	}
	else {
		cci.dwSize = 100;
	}

	if(!SetConsoleCursorInfo(hStdOut, &cci)) {
		LOG_ERROR("SetConsoleCursorInfo failed (error %lu)", GetLastError());
		return;
	}
}

#endif //OS_WINDOWS


text:
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from django.test import override_settings
from django.urls import reverse

from mock import patch

from contacts.models import Contact
from phone_numbers.models import PhoneNumber
from sms.models import SmsMessage
from voice.models import Call

from deterrence.models import Deterrent
from deterrence.models import DeterrenceCampaign
from deterrence.models import DeterrenceMessage

import deterrence.tasks

@override_settings(TWILIO_PHONE_NUMBER="+18881112222",
                   TWILIO_ACCOUNT_SID='ACxxxx',
                   TWILIO_AUTH_TOKEN='yyyyyyy',
                   GARFIELD_NUMBER_OF_DETERRENTS=1,
                   GARFIELD_DETERRENT_INTERVAL=300)
class DeterrenceCampaignTestCase(TestCase):
    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    @patch('contacts.tasks.lookup_contact.apply_async')
    def setUp(self, mock_lookup, mock_check_campaign):
        self.contact_a = \
            Contact.objects.create(phone_number="+15556667777",
                                   whitepages_first_name="John")
        self.contact_b = Contact.objects.create(phone_number="+15556667778")
        self.contact_c = Contact.objects.create(phone_number="+15556667779")

        self.phone_number = PhoneNumber.objects.create(sid="PNxxx",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675309",
                                                       formatted="(555) "
                                                                 "867-5309",
                                                       friendly_name="Stuff.",
                                                       number_type="ADV",
                                                       country_code="1")

        self.det_number = PhoneNumber.objects.create(sid="PNyyy",
                                                     account_sid="ACxxx",
                                                     service_sid="SExxx",
                                                     url="http://exmple.com",
                                                     e164="+15558675310",
                                                     formatted="(555) "
                                                               "867-5310",
                                                     friendly_name="Stuff.",
                                                     number_type="DET",
                                                     country_code="1")

        self.contact_a.related_phone_numbers.add(self.phone_number)
        self.contact_b.related_phone_numbers.add(self.phone_number)
        self.contact_c.related_phone_numbers.add(self.phone_number)

        image = SimpleUploadedFile(name="example_image.png",
                                   content=open("./deterrence/tests/assets/"
                                                "example_image.png",
                                                "rb").read(),
                                   content_type="image/png")

        self.deterrent = Deterrent.objects.create(image=image,
                                                  body="A message from "
                                                       "Garfield.",
                                                  personalize=True)
        self.deterrence_campaign = \
            DeterrenceCampaign.objects \
            .create(related_deterrent=self.deterrent)

        self.deterrence_campaign.related_contacts.add(self.contact_a)
        self.deterrence_campaign.related_contacts.add(self.contact_b)
        self.deterrence_campaign.related_contacts.add(self.contact_c)

        self.message = {"From": "+15556667777",
                        "To": "+15558675309",
                        "Body": "Test."}

    @patch('deterrence.tasks.send_deterrence.apply_async')
    def test_send_deterrence_campaign(self, mock_send):
        deterrence.tasks.send_deterrence_campaign("http://example.com")

        self.assertEqual(3,
                         mock_send.call_count)

        campaign = DeterrenceCampaign.objects.latest('date_created')
        self.assertFalse(campaign.date_sent is None)

    @patch('deterrence.tasks.send_deterrence.apply_async')
    def test_send_deterrence_do_not_deter(self, mock_send):
        self.contact_a.do_not_deter = True
        self.contact_a.save()

        deterrence.tasks.send_deterrence_campaign("http://example.com")

        self.assertEqual(2, mock_send.call_count)
        self.assertFalse(self.phone_number.contact_set.all()[0].deterred)

        campaign = DeterrenceCampaign.objects.latest('date_created')
        self.assertFalse(campaign.date_sent is None)

    @patch('deterrence.tasks.send_deterrence.apply_async')
    def test_send_deterrence_arrested(self, mock_send):
        self.contact_a.arrested = True
        self.contact_a.save()

        deterrence.tasks.send_deterrence_campaign("http://example.com")

        self.assertEqual(2, mock_send.call_count)
        self.assertFalse(self.phone_number.contact_set.all()[0].deterred)

        campaign = DeterrenceCampaign.objects.latest('date_created')
        self.assertFalse(campaign.date_sent is None)

    @patch('deterrence.tasks.send_deterrence.apply_async')
    def test_send_deterrence_recruiter(self, mock_send):
        self.contact_a.recruiter = True
        self.contact_a.save()

        deterrence.tasks.send_deterrence_campaign("http://example.com")

        self.assertEqual(2, mock_send.call_count)
        self.assertFalse(self.phone_number.contact_set.all()[0].deterred)

        campaign = DeterrenceCampaign.objects.latest('date_created')
        self.assertFalse(campaign.date_sent is None)

class DeterrenceTestCase(TestCase):
    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    @patch('contacts.tasks.lookup_contact.apply_async')
    def setUp(self, mock_lookup, mock_check_campaign):
        self.contact_a = Contact.objects.create(phone_number="+15556667777")
        self.contact_b = Contact.objects.create(phone_number="+15556667778")
        self.contact_c = Contact.objects.create(phone_number="+15556667779")

        self.phone_number = PhoneNumber.objects.create(sid="PNxxx",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675309",
                                                       formatted="(555) "
                                                                 "867-5309",
                                                       friendly_name="Stuff.",
                                                       number_type="ADV",
                                                       country_code="1")

        self.det_number = PhoneNumber.objects.create(sid="PNyyy",
                                                     account_sid="ACxxx",
                                                     service_sid="SExxx",
                                                     url="http://exmple.com",
                                                     e164="+15558675310",
                                                     formatted="(555) "
                                                               "867-5310",
                                                     friendly_name="Stuff.",
                                                     number_type="DET",
                                                     country_code="1")

        self.contact_a.related_phone_numbers.add(self.phone_number)
        self.contact_b.related_phone_numbers.add(self.phone_number)
        self.contact_c.related_phone_numbers.add(self.phone_number)

        image = SimpleUploadedFile(name="example_image.png",
                                   content=open("./deterrence/tests/assets/"
                                                "example_image.png",
                                                "rb").read(),
                                   content_type="image/png")

        self.deterrent = Deterrent.objects.create(image=image,
                                                  body="A message from "
                                                       "Garfield.",
                                                  personalize=True)
        self.deterrence_campaign = \
            DeterrenceCampaign.objects \
            .create(related_deterrent=self.deterrent)

        self.deterrence_campaign.related_contacts.add(self.contact_a)
        self.deterrence_campaign.related_contacts.add(self.contact_b)
        self.deterrence_campaign.related_contacts.add(self.contact_c)

        self.message = {"From": "+15556667777",
                        "To": "+15558675309",
                        "Body": "Test."}

    @patch('deterrence.tasks.send_sms_message')
    def test_send_deterrence(self, mock_send):
        mock_send.side_effect = [{'MessageSid': 'MMxxx',
                                  'Body': 'A message from Garfield.',
                                  'Status': 'queued'}]

        deterrence.tasks.send_deterrence("http://example.com",
                                         self.deterrence_campaign.id,
                                         self.contact_a.id)

        mock_send.assert_called_once_with(
            from_="+15558675310",
            to="+15556667777",
            body="A message from Garfield.",
            media_url="http://example.com/"
                      "{0}".format(self.deterrent.image.url),
            status_callback="http://example.com"
                            "{0}".format(reverse('deterrence:deterrence'
                                                 '_message_status_callback')))
        self.assertEqual(1,
                         len(DeterrenceMessage.objects.all()))
        contact = Contact.objects.get(pk=self.contact_a.id)
        self.assertTrue(contact.deterred)
        self.assertEqual(1,
                         contact.deterrents_received)

    @patch('deterrence.tasks.send_sms_message')
    def test_send_deterrence_first_name(self, mock_send):
        mock_send.side_effect = [{'MessageSid': 'MMxxx',
                                  'Body': 'John, a message from Garfield.',
                                  'Status': 'queued'}]

        self.contact_a.whitepages_first_name = "John"
        self.contact_a.save()

        deterrence.tasks.send_deterrence("http://example.com",
                                         self.deterrence_campaign.id,
                                         self.contact_a.id)

        mock_send.assert_called_once_with(
            from_="+15558675310",
            to="+15556667777",
            body="John, a message from Garfield.",
            media_url="http://example.com/"
                      "{0}".format(self.deterrent.image.url),
            status_callback="http://example.com"
                            "{0}".format(reverse('deterrence:deterrence'
                                                 '_message_status_callback')))
        self.assertEqual(1,
                         len(DeterrenceMessage.objects.all()))
        contact = Contact.objects.get(pk=self.contact_a.id)
        self.assertTrue(contact.deterred)

    @patch('deterrence.tasks.send_sms_message')
    def test_send_deterrence_no_personalize(self, mock_send):
        mock_send.side_effect = [{'MessageSid': 'MMxxx',
                                  'Body': 'A message from Garfield.',
                                  'Status': 'queued'}]

        self.contact_a.whitepages_first_name = "John"
        self.contact_a.save()

        self.deterrent.personalize = False
        self.deterrent.save()

        deterrence.tasks.send_deterrence("http://example.com",
                                         self.deterrence_campaign.id,
                                         self.contact_a.id)

        mock_send.assert_called_once_with(
            from_="+15558675310",
            to="+15556667777",
            body="A message from Garfield.",
            media_url="http://example.com/"
                      "{0}".format(self.deterrent.image.url),
            status_callback="http://example.com"
                            "{0}".format(reverse('deterrence:deterrence'
                                                 '_message_status_callback')))
        self.assertEqual(1,
                         len(DeterrenceMessage.objects.all()))
        contact = Contact.objects.get(pk=self.contact_a.id)
        self.assertTrue(contact.deterred)

    def test_send_deterrence_do_not_deter(self):
        self.contact_a.do_not_deter = True
        self.contact_a.save()

        result = \
            deterrence.tasks.send_deterrence("http://example.com",
                                             self.deterrence_campaign.id,
                                             self.contact_a.id)

        self.assertFalse(result)
        self.assertFalse(self.contact_a.deterred)

    def test_send_deterrence_arrested(self):
        self.contact_a.arrested = True
        self.contact_a.save()

        result = \
            deterrence.tasks.send_deterrence("http://example.com",
                                             self.deterrence_campaign.id,
                                             self.contact_a.id)

        self.assertFalse(result)
        self.assertFalse(self.contact_a.deterred)

    def test_send_deterrence_recruiter(self):
        self.contact_a.recruiter = True
        self.contact_a.save()

        result = \
            deterrence.tasks.send_deterrence("http://example.com",
                                             self.deterrence_campaign.id,
                                             self.contact_a.id)

        self.assertFalse(result)
        self.assertFalse(self.contact_a.deterred)

@override_settings(GARFIELD_NUMBER_OF_DETERRENTS=1,
                   GARFIELD_DETERRENT_INTERVAL=300)
class DeterrenceTestCaseMultipleNumbers(TestCase):
    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    @patch('contacts.tasks.lookup_contact.apply_async')
    def setUp(self, mock_lookup, mock_check_campaign):
        self.contact_a = Contact.objects.create(phone_number="+15556667777")
        self.contact_b = Contact.objects.create(phone_number="+15556667778")
        self.contact_c = Contact.objects.create(phone_number="+15556667779")

        self.phone_number = PhoneNumber.objects.create(sid="PNxxx",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675309",
                                                       formatted="(555) "
                                                                 "867-5308",
                                                       friendly_name="Stuff.",
                                                       number_type="ADV",
                                                       country_code="1")

        self.det_number_1 = PhoneNumber.objects.create(sid="PNxxx",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675309",
                                                       formatted="(555) "
                                                                 "867-5309",
                                                       friendly_name="Stuff.",
                                                       number_type="DET",
                                                       country_code="1")

        self.det_number_2 = PhoneNumber.objects.create(sid="PNyyy",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675310",
                                                       formatted="(555) "
                                                                 "867-5310",
                                                       friendly_name="Stuff.",
                                                       number_type="DET",
                                                       country_code="1")

        self.det_number_3 = PhoneNumber.objects.create(sid="PNzzz",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675311",
                                                       formatted="(555) "
                                                                 "867-5311",
                                                       friendly_name="BURNED.",
                                                       number_type="DET",
                                                       burned=True,
                                                       country_code="1")

        self.contact_a.related_phone_numbers.add(self.phone_number)
        self.contact_b.related_phone_numbers.add(self.phone_number)

        image = SimpleUploadedFile(name="example_image.png",
                                   content=open("./deterrence/tests/assets/"
                                                "example_image.png",
                                                "rb").read(),
                                   content_type="image/png")

        self.deterrent = Deterrent.objects.create(image=image,
                                                  body="A message from "
                                                       "Garfield.")
        self.deterrence_campaign = \
            DeterrenceCampaign.objects \
            .create(related_deterrent=self.deterrent)

        self.deterrence_campaign.related_contacts.add(self.contact_a)
        self.deterrence_campaign.related_contacts.add(self.contact_b)
        self.deterrence_campaign.related_contacts.add(self.contact_c)

        self.contact_c.related_phone_numbers.add(self.phone_number)

        self.message = {"From": "+15556667777",
                        "To": "+15558675309",
                        "Body": "Test."}

    @patch('deterrence.tasks.send_deterrence.apply_async')
    def test_send_deterrence_campaign(self, mock_send):
        deterrence.tasks.send_deterrence_campaign("http://example.com")

        self.assertEqual(3, mock_send.call_count)
        for call in mock_send.call_args_list:
            args, kwargs = call
            self.assertEqual(kwargs['args'][1],
                             self.deterrence_campaign.id)

    @override_settings(GARFIELD_NUMBER_OF_DETERRENTS=3)
    @patch('deterrence.tasks.send_deterrence.apply_async')
    def test_send_deterrence_campaign_multiple_deterrents(self, mock_send):
        deterrence.tasks.send_deterrence_campaign("http://example.com")

        self.assertEqual(9, mock_send.call_count)

    def test_unused_deterrence_phone_number(self):
        test_1 = \
            deterrence.tasks \
            .get_unused_deterrence_phone_number(self.contact_a)

        DeterrenceMessage.objects \
            .create(sid="MMxxx",
                    body="A message to you, Rudy.",
                    status="delivered",
                    related_deterrent=self.deterrent,
                    related_phone_number=self.det_number_2,
                    related_campaign=self.deterrence_campaign,
                    related_contact=self.contact_a)

        test_2 = \
            deterrence.tasks \
            .get_unused_deterrence_phone_number(self.contact_a)

        self.assertEqual(test_1, self.det_number_2)
        self.assertEqual(test_2, self.det_number_1)

    def test_unused_deterrence_phone_number_overload(self):
        test_1 = \
            deterrence.tasks \
            .get_unused_deterrence_phone_number(self.contact_a)

        DeterrenceMessage.objects \
            .create(sid="MMxxx",
                    body="A message to you, Rudy.",
                    status="delivered",
                    related_deterrent=self.deterrent,
                    related_phone_number=self.det_number_2,
                    related_campaign=self.deterrence_campaign,
                    related_contact=self.contact_a)

        test_2 = \
            deterrence.tasks \
            .get_unused_deterrence_phone_number(self.contact_a)

        DeterrenceMessage.objects \
            .create(sid="MMxxx",
                    body="A message to you, Rudy.",
                    status="delivered",
                    related_deterrent=self.deterrent,
                    related_phone_number=self.det_number_1,
                    related_campaign=self.deterrence_campaign,
                    related_contact=self.contact_a)

        test_3 = \
            deterrence.tasks \
            .get_unused_deterrence_phone_number(self.contact_a)

        self.assertEqual(test_1, self.det_number_2)
        self.assertEqual(test_2, self.det_number_1)
        self.assertEqual(test_3, self.det_number_2)

class DeterrenceCheckCampaignTestCase(TestCase):
    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    @patch('contacts.tasks.lookup_contact.apply_async')
    def setUp(self, mock_lookup, mock_check_campaign):
        self.contact_a = Contact.objects.create(phone_number="+15556667777")
        self.contact_b = Contact.objects.create(phone_number="+15556667778")
        self.contact_c = Contact.objects.create(phone_number="+15556667779")

        self.phone_number = PhoneNumber.objects.create(sid="PNxxx",
                                                       account_sid="ACxxx",
                                                       service_sid="SExxx",
                                                       url="http://exmple.com",
                                                       e164="+15558675309",
                                                       formatted="(555) "
                                                                 "867-5309",
                                                       friendly_name="Stuff.",
                                                       number_type="ADV",
                                                       country_code="1")

        self.det_number = PhoneNumber.objects.create(sid="PNyyy",
                                                     account_sid="ACxxx",
                                                     service_sid="SExxx",
                                                     url="http://exmple.com",
                                                     e164="+15558675310",
                                                     formatted="(555) "
                                                               "867-5310",
                                                     friendly_name="Stuff.",
                                                     number_type="DET",
                                                     country_code="1")

        self.contact_a.related_phone_numbers.add(self.phone_number)
        self.contact_b.related_phone_numbers.add(self.phone_number)
        self.contact_c.related_phone_numbers.add(self.phone_number)

        image = SimpleUploadedFile(name="example_image.png",
                                   content=open("./deterrence/tests/assets/"
                                                "example_image.png",
                                                "rb").read(),
                                   content_type="image/png")

        self.deterrent = Deterrent.objects.create(image=image,
                                                  body="A message from "
                                                       "Garfield.")
        self.deterrence_campaign = \
            DeterrenceCampaign.objects \
            .create(related_deterrent=self.deterrent)

        self.message = {"From": "+15556667777",
                        "To": "+15558675309",
                        "Body": "Test."}

    def test_check_campaign_for_contact(self):
        test = deterrence.tasks.check_campaign_for_contact(self.contact_a.id)

        campaign = \
            DeterrenceCampaign.objects.get(pk=self.deterrence_campaign.id)

        self.assertFalse(test)
        self.assertEqual(1,
                         len(DeterrenceCampaign.objects.all()))
        self.assertEqual(campaign.related_contacts.all()[0],
                         self.contact_a)

    def test_check_campaign_for_contact_already_present(self):
        self.deterrence_campaign.related_contacts.add(self.contact_b)
        self.deterrence_campaign.save()

        test = deterrence.tasks.check_campaign_for_contact(self.contact_a.id)

        self.assertFalse(test)

        second_test = \
            deterrence.tasks.check_campaign_for_contact(self.contact_b.id)

        campaign = \
            DeterrenceCampaign.objects.get(pk=self.deterrence_campaign.id)

        self.assertTrue(second_test)
        self.assertEqual(2,
                         len(campaign.related_contacts.all()))

    def test_check_campaign_for_contact_campaign_does_not_exist(self):
        self.deterrence_campaign.delete()

        test = deterrence.tasks.check_campaign_for_contact(self.contact_a.id)

        campaigns = DeterrenceCampaign.objects.all()

        self.assertFalse(test)
        self.assertEqual(1,
                         len(campaigns))
        self.assertEqual(campaigns[0].related_contacts.all()[0],
                         self.contact_a)

    def test_check_campaign_for_contact_multiple_attempts(self):
        self.deterrence_campaign.related_contacts.add(self.contact_a)

        deterrence.tasks.check_campaign_for_contact(self.contact_a.id)
        deterrence.tasks.check_campaign_for_contact(self.contact_a.id)
        deterrence.tasks.check_campaign_for_contact(self.contact_a.id)

        campaigns = DeterrenceCampaign.objects.all()

        self.assertEqual(1,
                         len(campaigns))
        self.assertEqual(1,
                         len(campaigns[0].related_contacts.all()))
        self.assertEqual(campaigns[0].related_contacts.all()[0],
                         self.contact_a)

    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    def test_only_add_to_campaign_if_sms_advertising_number(self,
                                                            mock_check):
        SmsMessage.objects.create(to_number="+15558675310",
                                  from_number="+15556667777",
                                  body="Test.",
                                  related_contact=self.contact_a,
                                  related_phone_number=self.det_number)

        self.assertFalse(mock_check.called)

    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    def test_only_add_to_campaign_if_call_advertising_number(self,
                                                             mock_check):
        Call.objects.create(to_number="+15558675310",
                            from_number="+15556667777",
                            related_contact=self.contact_a,
                            related_phone_number=self.det_number)

        self.assertFalse(mock_check.called)

    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    def test_add_to_campaign_if_call_advertising_number(self,
                                                        mock_check):
        Call.objects.create(to_number="+15558675309",
                            from_number="+15556667777",
                            related_contact=self.contact_a,
                            related_phone_number=self.phone_number)

        self.assertTrue(mock_check.called)

class DeterrenceMessageStatusCallbackTestCase(TestCase):
    @patch('deterrence.tasks.check_campaign_for_contact.apply_async')
    @patch('contacts.tasks.lookup_contact.apply_async')
    def setUp(self, mock_lookup, mock_check_campaign):
        self.contact_a = Contact.objects.create(phone_number="+15556667777")

        self.det_number = PhoneNumber.objects.create(sid="PNyyy",
                                                     account_sid="ACxxx",
                                                     service_sid="SExxx",
                                                     url="http://exmple.com",
                                                     e164="+15558675310",
                                                     formatted="(555) "
                                                               "867-5310",
                                                     friendly_name="Stuff.",
                                                     number_type="DET",
                                                     country_code="1")

        image = SimpleUploadedFile(name="example_image.png",
                                   content=open("./deterrence/tests/assets/"
                                                "example_image.png",
                                                "rb").read(),
                                   content_type="image/png")

        self.deterrent = Deterrent.objects.create(image=image,
                                                  body="A message from "
                                                       "Garfield.")
        self.deterrence_campaign = \
            DeterrenceCampaign.objects \
            .create(related_deterrent=self.deterrent)

        self.deterrence_message = \
            DeterrenceMessage.objects \
            .create(sid="MMxxxx",
                    body="A message to you, Rudy.",
                    status="queued",
                    related_phone_number=self.det_number,
                    related_campaign=self.deterrence_campaign,
                    related_contact=self.contact_a,
                    related_deterrent=self.deterrent)

    def test_handle_deterrence_message_status_callback(self):
        deterrence.tasks \
            .handle_deterrence_message_status_callback("MMxxxx",
                                                       "delivered")
        message = DeterrenceMessage.objects.get(sid="MMxxxx")
        self.assertEqual("delivered",
                         message.status)


text:
package org.apache.druid.query.topn.types;

import org.apache.druid.query.aggregation.Aggregator;
import org.apache.druid.query.dimension.ColumnSelectorStrategy;
import org.apache.druid.query.topn.HeapBasedTopNAlgorithm;
import org.apache.druid.query.topn.TopNParams;
import org.apache.druid.query.topn.TopNQuery;
import org.apache.druid.query.topn.TopNResultBuilder;
import org.apache.druid.segment.ColumnValueSelector;
import org.apache.druid.segment.Cursor;
import org.apache.druid.segment.StorageAdapter;

import javax.annotation.Nullable;

/**
 * This {@link ColumnSelectorStrategy} is used by all {@link org.apache.druid.query.topn.TopNAlgorithm} to provide
 * selector value cardinality to {@link TopNParams} (perhaps unecessarily, but that is another matter), but is primarily
 * used by {@link HeapBasedTopNAlgorithm} to serve as its value aggregates store.
 *
 * Given a query, column value selector, and cursor to process, the aggregates store is populated by calling
 * {@link #scanAndAggregate} and can be applied to {@link TopNResultBuilder} through {@link #updateResults}.
 */
public interface TopNColumnAggregatesProcessor<ValueSelectorType> extends ColumnSelectorStrategy
{
  /**
   * Get value cardinality of underlying {@link ColumnValueSelector}
   */
  int getCardinality(ValueSelectorType selector);

  /**
   * Used by {@link HeapBasedTopNAlgorithm}.
   *
   * Create an Aggregator[][] using {@link org.apache.druid.query.topn.BaseTopNAlgorithm.AggregatorArrayProvider} and
   * the given parameters.
   *
   * As the Aggregator[][] is used as an integer-based lookup, this method is only applicable for dimension types
   * that use integer row values, e.g. string columns where the value cardinality is known.
   *
   * A dimension type that does not have integer values should return null.
   *
   * @param query          The TopN query being served
   * @param params         Parameters for the TopN query being served
   * @param storageAdapter Column storage adapter, to provide information about the column that can be used for
   *                       query optimization, e.g. whether dimension values are sorted or not
   *
   * @return an Aggregator[][] for integer-valued dimensions, null otherwise
   */
  @Nullable
  Aggregator[][] getRowSelector(TopNQuery query, TopNParams params, StorageAdapter storageAdapter);

  /**
   * Used by {@link HeapBasedTopNAlgorithm}. The contract of this method requires calling {@link #initAggregateStore()}
   * prior to calling this method.
   *
   * Iterate through the {@link Cursor}, reading the current row from a dimension value selector, and for each row
   * value:
   *  1. Retrieve the Aggregator[] for the row value from rowSelector (fast integer lookup), usable if value cardinality
   *     is known, or from aggregatesStore (slower map).
   *
   *  2. If the rowSelector/aggregatesStore did not have an entry for a particular row value, this function
   *     should retrieve the current Aggregator[] using
   *     {@link org.apache.druid.query.topn.BaseTopNAlgorithm#makeAggregators} and the provided cursor and query,
   *     storing them in rowSelector/aggregatesStore
   *
   * 3. Call {@link Aggregator#aggregate()} on each of the aggregators.
   *
   * If a dimension type doesn't have integer values, it should ignore rowSelector and use the aggregatesStore map only.
   *
   * @param query           The TopN query being served.
   * @param selector        Dimension value selector
   * @param cursor          Cursor for the segment being queried
   * @param rowSelector     Integer lookup containing aggregators
   *
   * @return the number of processed rows (after postFilters are applied inside the cursor being processed)
   */
  long scanAndAggregate(
      TopNQuery query,
      ValueSelectorType selector,
      Cursor cursor,
      Aggregator[][] rowSelector
  );

  /**
   * Used by {@link HeapBasedTopNAlgorithm}.
   *
   * Read entries from the aggregates store, adding the keys and associated values to the resultBuilder, applying the
   * valueTransformer to the keys if present
   *
   * @param resultBuilder   TopN result builder
   */
  void updateResults(TopNResultBuilder resultBuilder);

  /**
   * Initializes the underlying aggregates store to something nice and seleector type appropriate
   */
  void initAggregateStore();

  /**
   * Closes all on heap {@link Aggregator} associated with the aggregates processor
   */
  void closeAggregators();
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>LevelCollection Constructor (ICollection)</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            log4net SDK Documentation - Microsoft .NET Framework 4.0

LevelCollection Constructor (ICollection)

 Initializes a new instance of the LevelCollection class that contains elements copied from the specified Level collection.

        [Visual Basic]

Overloads Public Sub New( _
   ByVal col As ICollection _
)

        [C#]

public LevelCollection(
   ICollection col
);

Parameters

          col

The Level collection whose elements are copied to the new list.

See Also

        LevelCollection Class | log4net.Core Namespace | LevelCollection Constructor Overload List

          Copyright 2004-2011 The Apache Software Foundation.


text:
module ResourceManagement

  # This class describes a pre-defined package containing quotas for multiple resources.
  class Package
    attr_reader :key

    def initialize(key, quotas_by_service)
      @key = key
      @quotas = quotas_by_service
    end

    def self.all
      PACKAGES
    end

    def self.find(key)
      PACKAGES.find { |pkg| pkg.key == key }
    end

    def quota(service_type, resource_name)
      @quotas[service_type.to_sym].try { |q| q[resource_name.to_sym] } || 0
    end

    # Returns whether this resource should be shown by default on the package comparison table.
    def self.significant?(service_type, resource_name)
      SIGNIFICANT_RESOURCES.include?("#{service_type.to_s}/#{resource_name.to_s}")
    end

    PACKAGES = [
      # NOTE: when adding new packages, please also add the human-readable name to plugins/resource_management/config/locales/en.yml
      new('P', {
        compute: {
          cores:     10,
          instances: 5,
          ram:       8 << 10, # 8 * 2^10 MiB = 8 GiB
        },
        network: {
          floating_ips:  2,
          networks:      1,
          subnets:       1,
          ports:         500,
          rbac_policies: 5,
          routers:       1,
          security_group_rules: 100,
          security_groups:      20,
        },
        dns: {
          recordsets: 5,
        },
        :'object-store' => {
          capacity: 1 << 30, # 2^30 bytes = 1 GiB
        },
        volumev2: {
          capacity:  16, # GiB
          snapshots: 2,
          volumes:   2,
        },
      }),
    ]

    SIGNIFICANT_RESOURCES = [
      'compute/cores',
      'compute/ram',
      'network/floating_ips',
      'network/networks',
      'object-store/capacity',
      'volumev2/capacity',
    ]
  end

end


text:
<?xml version='1.0'?>
<!DOCTYPE PISI SYSTEM 'http://www.pardus.org.tr/projeler/pisi/pisi-spec.dtd'>
<PISI>
    <Source>
        <Name>silicon-empire</Name>
        <Homepage>http://getsilicon.org/</Homepage>
        <Packager>
            <Name>Alexey Ivanov</Name>
            <Email>alexey.ivanes@gmail.com</Email>
        </Packager>
        <License>GPLv3</License>
        <Icon>silicon-empire</Icon>
        <IsA>app:gui</IsA>
        <PartOf>hardware.optical</PartOf>
        <Summary>Silicon is set of OpenSource tools to manage and organize your optical discs like CDs, DVDs and Blu-rays. </Summary>
        <Description>Silicon target is made optical discs managing easy.</Description>
        <Archive sha1sum="ab0208b4947ec3f120f6d3998bf489c3a3f41188" type="targz">http://getsilicon.org/download/silicon_1.7.3_src.tar.gz</Archive>
        <BuildDependencies>
            <Dependency>qt-devel</Dependency>
            <Dependency>taglib-devel</Dependency>
            <Dependency>phonon-devel</Dependency>
            <Dependency>fuse-devel</Dependency>
        </BuildDependencies>
        <Patches>
            <Patch level="1">make.patch</Patch>
	  </Patches>
    </Source>
    <Package>
        <Name>silicon-empire</Name>
        <RuntimeDependencies>
            <Dependency>qt</Dependency>
            <Dependency>taglib</Dependency>
            <Dependency>phonon</Dependency>
            <Dependency>fuse</Dependency>
        </RuntimeDependencies>
        <Files>
            <Path fileType="executable">/usr/bin</Path>
            <Path fileType="library">/usr/lib</Path>
            <Path fileType="header">/usr/include</Path>
            <Path fileType="data">/usr/share</Path>
        </Files>
    </Package>
    <History>
        <Update release="3">
            <Date>2011-06-18</Date>
            <Version>1.7.3</Version>
            <Comment>Version update.</Comment>
            <Name>Alexey Ivanov</Name>
            <Email>alexey.ivanes@gmail.com</Email>
        </Update>
        <Update release="2">
            <Date>2011-05-31</Date>
            <Version>1.7.2</Version>
            <Comment>Not working</Comment>
            <Name>Alexey Ivanov</Name>
            <Email>alexey.ivanes@gmail.com</Email>
        </Update>
        <Update release="1">
            <Date>2011-03-22</Date>
            <Version>1.7.0</Version>
            <Comment>First release</Comment>
            <Name>Alexey Ivanov</Name>
            <Email>alexey.ivanes@gmail.com</Email>
        </Update>
    </History>
</PISI>


text:
'use strict';

var createWhitelist = require('./lib/create-whitelist');
var cloneWithWhitelist = require('./lib/clone-ast');

function createCloneFunction (options) {
    return cloneWithWhitelist(createWhitelist(options));
}

var espurify = createCloneFunction();
espurify.customize = createCloneFunction;
espurify.cloneWithWhitelist = cloneWithWhitelist;
module.exports = espurify;


text:
// ReSharper disable All

namespace OpenTl.Schema
{
	using System;
	using System.Collections;
	using System.Text;

	using OpenTl.Schema;
	using OpenTl.Schema.Serialization.Attributes;

	[Serialize(0xf9d27a5a)]
	public sealed class TUpdateInlineBotCallbackQuery : IUpdate
	{
       [SerializationOrder(0)]
       public BitArray Flags {get; set;}

       [SerializationOrder(1)]
       public long QueryId {get; set;}

       [SerializationOrder(2)]
       public int UserId {get; set;}

       [SerializationOrder(3)]
       public OpenTl.Schema.IInputBotInlineMessageID MsgId {get; set;}

       [SerializationOrder(4)]
       public long ChatInstance {get; set;}

       [SerializationOrder(5)]
       [CanSerialize("Flags", 0)]
       public byte[] Data {get; set;}

       /// <summary>Binary representation for the 'GameShortName' property</summary>
       [SerializationOrder(6)]
       [CanSerialize("Flags", 1)]
       public byte[] GameShortNameAsBinary { get => _GameShortNameAsBinary; set { _GameShortName = Encoding.UTF8.GetString(value); _GameShortNameAsBinary = value; }}
       private byte[] _GameShortNameAsBinary;
       private string _GameShortName;
       public string GameShortName { get => _GameShortName; set { GameShortNameAsBinary = Encoding.UTF8.GetBytes(value); _GameShortName = value; }}

	}
}


text:
module Specs
  def self.sleep_and_wait_until(timeout = 10)
    t1 = Time.now.to_f
    ::Timeout.timeout(timeout) do
      loop until yield
    end

    diff = Time.now.to_f - t1
    STDERR.puts "wait took a bit long: #{diff} seconds" if diff > 0.4
  rescue Timeout::Error
    t2 = Time.now.to_f
    raise "Timeout after: #{t2 - t1} seconds"
  end
end


text:
.class Landroid/service/voice/VoiceInteractionSession$4;
.super Ljava/lang/Object;
.source "VoiceInteractionSession.java"

# interfaces
.implements Landroid/view/ViewTreeObserver$OnPreDrawListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/service/voice/VoiceInteractionSession;->doShow(Landroid/os/Bundle;ILcom/android/internal/app/IVoiceInteractionSessionShowCallback;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/service/voice/VoiceInteractionSession;

.field final synthetic val$showCallback:Lcom/android/internal/app/IVoiceInteractionSessionShowCallback;

# direct methods
.method constructor <init>(Landroid/service/voice/VoiceInteractionSession;Lcom/android/internal/app/IVoiceInteractionSessionShowCallback;)V
    .locals 0
    .param p1, "this$0"    # Landroid/service/voice/VoiceInteractionSession;
    .param p2, "val$showCallback"    # Lcom/android/internal/app/IVoiceInteractionSessionShowCallback;

    .prologue
    .line 990
    iput-object p1, p0, Landroid/service/voice/VoiceInteractionSession$4;->this$0:Landroid/service/voice/VoiceInteractionSession;

    iput-object p2, p0, Landroid/service/voice/VoiceInteractionSession$4;->val$showCallback:Lcom/android/internal/app/IVoiceInteractionSessionShowCallback;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onPreDraw()Z
    .locals 3

    .prologue
    .line 993
    iget-object v1, p0, Landroid/service/voice/VoiceInteractionSession$4;->this$0:Landroid/service/voice/VoiceInteractionSession;

    iget-object v1, v1, Landroid/service/voice/VoiceInteractionSession;->mRootView:Landroid/view/View;

    invoke-virtual {v1}, Landroid/view/View;->getViewTreeObserver()Landroid/view/ViewTreeObserver;

    move-result-object v1

    invoke-virtual {v1, p0}, Landroid/view/ViewTreeObserver;->removeOnPreDrawListener(Landroid/view/ViewTreeObserver$OnPreDrawListener;)V

    .line 995
    :try_start_0
    iget-object v1, p0, Landroid/service/voice/VoiceInteractionSession$4;->val$showCallback:Lcom/android/internal/app/IVoiceInteractionSessionShowCallback;

    invoke-interface {v1}, Lcom/android/internal/app/IVoiceInteractionSessionShowCallback;->onShown()V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    .line 999
    :goto_0
    const/4 v1, 0x1

    return v1

    .line 996
    :catch_0
    move-exception v0

    .line 997
    .local v0, "e":Landroid/os/RemoteException;
    const-string/jumbo v1, "VoiceInteractionSession"

    const-string/jumbo v2, "Error calling onShown"

    invoke-static {v1, v2, v0}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_0
.end method


text:
title: Multitouch
description: Tracks multitouch input.
category: input
---

# Multitouch

Tracks multitouch input and outputs a list of active touches, plus scale and rotation delta between the first two touch points.

For single-point input, generally [pointer](/api/pointer) is more appropriate as it provides a simple, cross-platform interface.

<TOC />

## Import

```javascript
import { multitouch } from 'popmotion';
```

## Usage

```typescript
multitouch({
  preventDefault?: boolean = true,
  scale?: number,
  rotate?: number
})
```

```javascript
multitouch().start(({ touches, scale, rotate }) => {
  touches.forEach(({ x, y }) => console.log(x, y))
});
```

`multitouch` provides:

- `touches: { x: number, y: number }[]`: An array of `x`/`y` coordinates representing each active finger.
- `scale: number`: The distance between the first two fingers since `start`, represented as a multiplier of the original distance. `scale` starts from `1.0`, or the initially provided `scale`.
- `rotate: number`: The angle rotation of the first two fingers as a delta of the original rotation. `rotate` starts from `0.0`, or the initially provided `rotate`.

### Commonly-used properties

If you often use, for instance, `rotate`, you can easily create a new action that returns only that value:

```javascript
const touchRotation = (initialRotate = 0) => multitouch({ rotate: initialRotate })
  .pipe(({ rotate }) => rotate);

touchRotation(45).start((rotate) => console.log(rotate));
```

## Props

- `preventDefault?: boolean = true`
- `scale?: number = 1.0`
- `rotate?: number = 0.0`

## Methods

### Action methods

`multitouch()` returns:

- `filter((v: any) => boolean)`: Returns a new action that filters out values when the provided function returns `false`.
- `pipe(...funcs: Array<(v) => v)`: Returns a new action that will run `update` values through this sequence of functions.
- `start(update | { update, complete })`: Starts the action and returns a subscription.
- `while((v: any) => boolean)`: Returns a new action that will `complete` when the provided function returns `false`.

### Subscription methods

`multitouch().start()` returns:

- `stop(): void`

## Example

<CodePen id="LOBjxQ" />


text:
title: "Tip of the Week #49: Argument-Dependent Lookup"
layout: tips
sidenav: side-nav-tips.html
published: true
permalink: tips/49
type: markdown
order: "049"
---

Originally posted as totw/49 on 2013-07-14

*"...whatever disappearing trail of its legalistic argle-bargle one chooses to
follow..." --Antonin Scalia, [U.S. v Windsor dissenting opinion](http://www.supremecourt.gov/opinions/12pdf/12-307_6j37.pdf)*

## Overview

A function call expression such as `func(a,b,c)`, in which the function is named
without the `::` scope operator, is called unqualified. When C++ code refers to
a function by an unqualified name, the compiler performs a search for a matching
function declaration. What is surprising to some people (and different from
other languages) is that in addition to the caller's lexical scope, the set of
search scopes is augmented by namespaces associated with the function argument
types. This additional lookup is called *Argument-Dependent Lookup* (ADL). It's
definitely happening in your code, so you'll be much better off with a basic
understanding of how it works.

## Name Lookup Basics

A function call must be mapped to a single function definition by the compiler.
This matching is done in two independent serial processing stages. First, *name
lookup* applies some scope searching rules to produce a set of overloads
matching the name of the function. Then *overload resolution* takes those
overloads produced by that name lookup and tries to choose a best match for the
arguments given at the call site. Keep this distinction in mind. Name lookup
comes first, and it doesn't try to make any determination as to whether a
function is a good match or not. It doesn't even consider the argument count. It
just searches scopes for a function name. Overload resolution is a complex topic
in its own right, but it's not our focus right now. Just know that it's a
separate processing stage that gets its inputs from name lookup.

When an unqualified function call is encountered, several independent search
sequences can occur for that function name, each attempting to match the name to
a set of overloads. The most obvious search is the outward search starting from
the lexical scope of the call site:

```c++
namespace b {
void func();
namespace internal {
void test() { func(); } // ok: finds b::func().
} // b::internal
} // b
```

This name lookup has nothing to do with ADL yet (`func()` has no arguments). It
is simply a search outward from the site of the function call, proceeding
outward from local function scope (if applicable), to class scope, enclosing
class scope, and base classes (if applicable), then to namespace scope, and out
into enclosing namespaces, and finally the global `::` namespace.

As name lookup progresses through a sequence of increasingly widening scopes,
the process stops as soon as any function with the target name is found, whether
or not that function's arguments are compatible with the arguments supplied by
the call site. When a scope is encountered containing at least one function
declaration with the target name, the overloads in that scope become the result
of that name lookup.

This is illustrated in the example below:

```c++
namespace b {
void func(const string&);  // b::func
namespace internal {
void func(int);  // b::internal::func
namespace deep {
void test() {
  string s("hello");
  func(s);  // error: finds only b::internal::func(int).
}
}  // b::internal::deep
}  // b::internal
}  // b
```

It's tempting but incorrect to think a `func(s)` expression will overlook the
obviously bad match of `b::internal::func(int)`, and continue looking to the
next outward enclosing scope to find `b::func(const string&)`. However, name
lookup doesn't consider argument types. It finds something called `func` and
stops in `b::internal`, leaving the evaluation of "obviously bad" to the
overload resolution phase. The `b::func(const string&)` function is never even
seen by overload resolution.

An important implication of the scoped search order is that overloads in a scope
appearing earlier in the search order will hide overloads from later scopes.

## Argument-Dependent Lookup (ADL)

If a function call passes arguments, a few more parallel name lookups are
launched. These extra lookups consider each associated namespace of each of the
function call's arguments. Unlike lexical scope name lookup, these argument-
dependent lookups do not proceed to enclosing scopes.

Results of lexical scope name lookup and all ADLs are merged together, to form
the final set of function overloads.

## The Simple Case

Consider the following code:

```c++
namespace aspace {
struct A {};
void func(const A&);  // found by ADL name lookup on 'a'.
}  // namespace aspace

namespace bspace {
void func(int);  // found by lexical scope name lookup
void test() {
  aspace::A a;
  func(a);  // aspace::func(const aspace::A&)
}
}  // namespace bspace
```

Two name lookups are launched to resolve the call to `func(a)`. The lexical
scope name lookup starts in the local function scope of `bspace::test()`. It
finds no `func` there and proceeds to the scope of namespace `bspace`, in which
it finds `func(int)` and stops. The other name lookup, which is due to ADL,
starts in the namespace associated with the argument `a`. In this case, that's
only namespace `aspace`. That lookup finds `aspace::func(const aspace::A&)` and
stops. Overload resolution therefore receives two candidates. These are
'bspace::func(int)' from lexical name lookup, and 'aspace::func(const
aspace::A&)' from the single ADL lookup. In overload resolution, the `func(a)`
call resolves to `aspace::func(const aspace::A&)`. The `bspace::func(int)`
overload is not a good match for the argument type and so it is rejected by
overload resolution.

The lexical name search and each of the additional ADL-triggered name searches
can be considered to occur in parallel, with each returning a set of candidate
function overloads. The results of all such searches are thrown in a bag and
they compete via overload resolution to determine the best match. If there's a
tie for best match, the compiler issues an ambiguity error; "There can be only
one." If no overload is a good match, that's an error too. So more precisely,
"there must be exactly one", which doesn't sound as cool in a movie trailer.

## Type-Associated Namespaces

The previous example was the simple case, but a more sophisticated type can have
many namespaces associated with it. The set of namespaces associated with a type
includes any namespace of any type that appears as a part of the argument type's
full name, including its template parameter types. It also includes the
namespaces of direct and indirect base classes. For example, a single argument
that expands to the type `a::A<b::B, c::internal::C*>` will produce searches
beginning in the `a`, `b` and `c::internal` namespaces (and any other namespaces
associated with the constituent types `a::A`, `b::B`, or `c::internal::C`), each
looking for the called function name. The following example shows a few of these
effects:

```c++
namespace aspace {
struct A {};
template <typename T> struct AGeneric {};
void func(const A&);
template <typename T> void find_me(const T&);
}  // namespace aspace

namespace bspace {
typedef aspace::A AliasForA;
struct B : aspace::A {};
template <typename T> struct BGeneric {};
void test() {
  // ok: base class namespace searched.
  func(B());
  // ok: template parameter namespace searched.
  find_me(BGeneric<aspace::A>());
  // ok: template namespace searched.
  find_me(aspace::AGeneric<int>());
}
}  // namespace bspace
```

## Tips

With the fundamental name lookup mechanism fresh in your mind, consider the
following tips which may help you when you are working with real C++ code.

## Type Aliases

Sometimes determining the set of namespaces associated with a type will take a
bit of detective work. `typedef` and using declarations can introduce aliases
for a type. In those cases the aliases are fully resolved and expanded to their
source types before the list of namespaces to search are chosen. This is one way
in which `typedef` and using declarations can be a bit misleading, because they
can lead you to make incorrect predictions about which namespaces will be
searched by ADL. This is demonstrated below:

```c++
namespace cspace {
// ok: note that this searches aspace, not bspace.
void test() {
  func(bspace::AliasForA());
}
}  // namespace cspace
```

## Caveat Iterator

Be careful with iterators. You don't really know with what namespaces they are
associated, so don't rely on ADL for resolving function calls involving
iterators. They might just be pointers to the elements, or they might be in some
namespace private to the implementation that has nothing to do with the
container's namespace.

```c++
namespace d {
int test() {
  std::vector<int> vec(a);
  // maybe this compiles, maybe not!
  return count(vec.begin(), vec.end(), 0);
}
}  // namespace d
```

The above code has a dependency on whether `std::vector<int>::iterator` is
`int*` (which is possible) or some type in a namespace that has a count overload
(like `std::count()`). It's possible that this will work on some platforms and not
others, or that it will work in debug builds with instrumented iterators, but
not in optimized builds. It's better to just qualify the function name. If you
want to call `std::count()`, spell it that way.

## Overloaded Operators

An operator (e.g. `+` or `<<`) can be thought of as a kind of function name,
e.g. `operator+(a,b)` or `operator<<(a,b)`, and are also unqualified. One of the
most important uses of ADL is the search for `operator<<` used during logging.
Usually we see something like `std::cout << obj;` for some `obj`, let's say of
type `O::Obj`. This statement is like an unqualified function call of the form
`operator<<(std::ostream&, const O::Obj&)`, which will find overloads in the
`std` namespace from the `std::ostream` parameter, the `O` namespace from the
`O::Obj` parameter, and of course any overloads picked up from the lexical scope
search from the call site.

It's important to place such operators in the same namespace as the user-defined
type they're meant to operate upon: in this case within namespace `O`. If the
`operator<<` is placed in an outer namespace like `::` (the global namespace),
that operator will work for a while until someone quite innocently places an
unrelated `operator<<` in namespace 'O' for some other type. It takes a bit of
discipline but saves a lot of confusion later to follow the simple rule of
defining all operators and other associated nonmember functions next to the
type's definition in the same namespace.

## Fundamental Types

Note that the fundamental types (e.g. `int`, `double`, etc) are not associated
with the global namespace. They are associated with no namespace. They do not
contribute any namespaces to ADL. Pointer and array types are associated with
their pointee or element types.

## Refactoring Gotchas

Refactorings that change the types of arguments to an unqualified function call
can affect which, if any, overloads are considered. Just moving a type into a
namespace and leaving behind a typedef in the old namespace for compatibility
doesn't help, and really just makes the problem harder to diagnose. Be careful
when moving types to new namespaces.

Similarly, moving a function to a new namespace and leaving behind a `using`
declaration might mean that unqualified calls won't find it anymore. Sadly, they
might still compile by finding a different function you didn't intend them to
find. Be careful when moving functions to new namespaces.

## Final Thought

Relatively few programmers understand the exact rules and corner cases involved
with function lookups. The language spec contains 13 pages of rules about what
exactly goes into a name search, including special cases, details about friend
functions, and enclosing class scopes to keep your head spinning for years.
Despite all this complexity, if you keep the basic idea of parallel name
searches in mind, you'll be on solid footing for understanding how your function
calls and operators are resolving. You will now be able to see how seemingly
remote declarations end up being chosen when you invoke functions or operators.
And you'll be a little better able to diagnose puzzling build errors like
ambiguities or name-hiding effects when they happen.


text:
package com.massive.deliveries.test.di.module;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.massive.deliveries.test.BuildConfig;
import com.massive.deliveries.test.data.network.ApiHelper;
import com.massive.deliveries.test.data.network.model.Deliveries;
import com.massive.deliveries.test.di.ActivityContext;
import com.massive.deliveries.test.di.PerActivity;
import com.massive.deliveries.test.ui.delivery.DeliveryIPresenter;
import com.massive.deliveries.test.ui.delivery.DeliveryIView;
import com.massive.deliveries.test.ui.delivery.DeliveryPresenter;
import com.massive.deliveries.test.ui.login.LoginIPresenter;
import com.massive.deliveries.test.ui.login.LoginIView;
import com.massive.deliveries.test.ui.login.LoginPresenter;
import com.massive.deliveries.test.ui.main.MainAdapter;
import com.massive.deliveries.test.ui.main.MainIPresenter;
import com.massive.deliveries.test.ui.main.MainIView;
import com.massive.deliveries.test.ui.main.MainPresenter;
import com.massive.deliveries.test.ui.splash.SplashIPresenter;
import com.massive.deliveries.test.ui.splash.SplashIView;
import com.massive.deliveries.test.ui.splash.SplashPresenter;
import com.massive.deliveries.test.utils.rx.AppSchedulerProvider;
import com.massive.deliveries.test.utils.rx.SchedulerProvider;

import java.util.ArrayList;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import io.reactivex.disposables.CompositeDisposable;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *  Creaated by Balwinder on   26/08/17.
 */

@Module
public class ActivityModule {

    private AppCompatActivity mActivity;

    public ActivityModule(AppCompatActivity activity) {
        this.mActivity = activity;
    }

    @Provides
    @ActivityContext
    Context provideContext() {
        return mActivity;
    }

    @Provides
    AppCompatActivity provideActivity() {
        return mActivity;
    }

    @Provides
    CompositeDisposable provideCompositeDisposable() {
        return new CompositeDisposable();
    }

    @Provides
    SchedulerProvider provideSchedulerProvider() {
        return new AppSchedulerProvider();
    }

    @Provides
    @PerActivity
    SplashIPresenter<SplashIView> provideSplashPresenter(
            SplashPresenter<SplashIView> presenter) {
        return presenter;
    }

    @Provides
    DeliveryIPresenter<DeliveryIView> provideAboutPresenter(
            DeliveryPresenter<DeliveryIView> presenter) {
        return presenter;
    }

    @Provides
    @PerActivity
    LoginIPresenter<LoginIView> provideLoginPresenter(
            LoginPresenter<LoginIView> presenter) {
        return presenter;
    }

    @Provides
    @PerActivity
    MainIPresenter<MainIView> provideMainPresenter(
            MainPresenter<MainIView> presenter) {
        return presenter;
    }

    @Provides
    @PerActivity
    MainAdapter provideMainAdapter() {
        return new MainAdapter(new ArrayList<Deliveries>() , mActivity);
    }

    @Provides
    LinearLayoutManager provideLinearLayoutManager(AppCompatActivity activity) {
        return new LinearLayoutManager(activity);
    }

    @Provides
    @Singleton
    ApiHelper provideApiHelper()
    {
        return    new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(ApiHelper.class);
    }

}


text: The `<body>` tag defines the body of the document, which contains all of its content.


text:
package com.ecollege.lunit.fixture;

import com.ecollege.lunit.command.CommandException;
import com.ecollege.lunit.command.ExternalCommand;

/**
 * Executes a command as if from the command line. However, note that since this
 * class utilizes Runtime.exec(), redirects, etc. (e.g. cat > test.out) will not
 * work. ExternalCommandFixture executes a single executable program or script.
 * If redirect is desired, simply create a script that does redirection
 * internally.
 *
 * @author toddf
 * @since Sep 15, 2008
 */
public class ExternalCommandFixture
implements TestFixture
{
	// SECTION: INSTANCE VARIABLES

	private ExternalCommand setupCommand;
	private ExternalCommand teardownCommand;

	// SECTION: CONSTRUCTOR

	public ExternalCommandFixture()
	{
		super();
		setupCommand = new ExternalCommand();
		teardownCommand = new ExternalCommand();
	}

	// SECTION: ACCESSORS/MUTATORS

	public String getSetupCommand()
	{
		return setupCommand.getCommand();
	}

	public boolean hasSetupCommand()
	{
		return setupCommand.hasCommand();
	}

	public void setSetupCommand(String command)
	{
		setupCommand.setCommand(command);
	}

	public boolean shouldValidateExitValue()
	{
		return (setupCommand.shouldValidateExitValue() || teardownCommand
		    .shouldValidateExitValue());
	}

	public void setValidateExitValue(boolean value)
	{
		setupCommand.setValidateExitValue(value);
		teardownCommand.setValidateExitValue(value);
	}

	public String getTeardownCommand()
	{
		return teardownCommand.getCommand();
	}

	public boolean hasTeardownCommand()
	{
		return teardownCommand.hasCommand();
	}

	public void setTeardownCommand(String command)
	{
		teardownCommand.setCommand(command);
	}

	// SECTION: TEST FIXTURE

	@Override
	public void setup() throws Exception
	{
		if (hasSetupCommand())
		{
			try
			{
				setupCommand.execute();
			}
			catch (CommandException e)
			{
				throw new FixtureException("Setup Failed: " + getSetupCommand(), e);
			}
		}
	}

	@Override
	public void teardown() throws Exception
	{
		if (hasTeardownCommand())
		{
			try
			{
				teardownCommand.execute();
			}
			catch (CommandException e)
			{
				throw new FixtureException("Teardown Failed: " + getTeardownCommand(), e);
			}
		}
	}
}