text:
#include "Keyboard.h"

#include <assert.h>

#include "../DinodeckLua.h"
#include "../LuaState.h"
#include "Button.h"

Reflect Keyboard::Meta("Keyboard", Keyboard::Bind);
static Keyboard* gKeyboard = NULL;

Keyboard::Keyboard()
{
    assert(gKeyboard == NULL);
    gKeyboard = this;
};

// Should be done once frame
void Keyboard::Update()
{
    for(int i = 0; i < KEY_LAST; i++ )
    {
        mButton[i].mJustPressed = false;
        mButton[i].mJustReleased = false;
    }
}

void Keyboard::OnKeyDownEvent(int key)
{
    assert(key < KEY_LAST);
    mButton[key].Update(true);
}

void Keyboard::OnKeyUpEvent(int key)
{
    assert(key < KEY_LAST);
    mButton[key].Update(false);
}

bool Keyboard::IsButtonHeld(int key) const
{
    assert(key < (int) KEY_LAST);
    return mButton[key].mIsDown;
}

bool Keyboard::IsButtonJustPressed(int key) const
{
    assert(key < (int) KEY_LAST);
    return mButton[key].mJustPressed;
}

bool Keyboard::IsButtonJustReleased(int key) const
{
    assert(key < (int) KEY_LAST);
    return mButton[key].mJustReleased;
}

static int lua_Keyboard_JustPressed(lua_State* state)
{
    int number = (int)luaL_checknumber(state, 1);
    number = std::max(0, std::min(number, ((int)KEY_LAST)));
    lua_pushboolean(state, gKeyboard->IsButtonJustPressed(number));
    return 1;
}

static int lua_Keyboard_JustReleased(lua_State* state)
{
    int number = (int)luaL_checknumber(state, 1);
    number = std::max(0, std::min(number, ((int)KEY_LAST)));
    lua_pushboolean(state, gKeyboard->IsButtonJustReleased(number));
    return 1;
}

static int lua_Keyboard_Held(lua_State* state)
{
    int number = (int)luaL_checknumber(state, 1);
    number = std::max(0, std::min(number, ((int)KEY_LAST)));
    lua_pushboolean(state, gKeyboard->IsButtonHeld(number));
    return 1;
}

static const struct luaL_reg luaBinding [] =
{
    {"JustPressed",     lua_Keyboard_JustPressed},
    {"JustReleased",    lua_Keyboard_JustReleased},
    {"Held",            lua_Keyboard_Held},
    {NULL, NULL}  /* sentinel */
};

void AddKeyToLuaGlobal(lua_State* state, const char* id, int value)
{
    lua_pushnumber(state, value);
    lua_setglobal(state, id);
}

void Keyboard::Bind(LuaState* state)
{
    state->Bind
    (
        Keyboard::Meta.Name(),
        luaBinding
    );

    lua_State* l = state->State();

    AddKeyToLuaGlobal(l, "KEY_BACKSPACE",   KEY_BACKSPACE);
    AddKeyToLuaGlobal(l, "KEY_TAB",         KEY_TAB);
    AddKeyToLuaGlobal(l, "KEY_CLEAR",       KEY_CLEAR);
    AddKeyToLuaGlobal(l, "KEY_RETURN",      KEY_RETURN);
    AddKeyToLuaGlobal(l, "KEY_PAUSE",       KEY_PAUSE);
    AddKeyToLuaGlobal(l, "KEY_ESCAPE",      KEY_ESCAPE);
    AddKeyToLuaGlobal(l, "KEY_SPACE",       KEY_SPACE);
    AddKeyToLuaGlobal(l, "KEY_EXCLAIM",     KEY_EXCLAIM);
    AddKeyToLuaGlobal(l, "KEY_QUOTEDBL",    KEY_QUOTEDBL);
    AddKeyToLuaGlobal(l, "KEY_HASH",        KEY_HASH);
    AddKeyToLuaGlobal(l, "KEY_DOLLAR",      KEY_DOLLAR);
    AddKeyToLuaGlobal(l, "KEY_AMPERSAND",   KEY_AMPERSAND);
    AddKeyToLuaGlobal(l, "KEY_QUOTE",       KEY_QUOTE);
    AddKeyToLuaGlobal(l, "KEY_LEFTPAREN",   KEY_LEFTPAREN);
    AddKeyToLuaGlobal(l, "KEY_RIGHTPAREN",  KEY_RIGHTPAREN);
    AddKeyToLuaGlobal(l, "KEY_ASTERISK",    KEY_ASTERISK);

    AddKeyToLuaGlobal(l, "KEY_A", KEY_A);
    AddKeyToLuaGlobal(l, "KEY_B", KEY_B);
    AddKeyToLuaGlobal(l, "KEY_C", KEY_C);
    AddKeyToLuaGlobal(l, "KEY_D", KEY_D);
    AddKeyToLuaGlobal(l, "KEY_E", KEY_E);
    AddKeyToLuaGlobal(l, "KEY_F", KEY_F);
    AddKeyToLuaGlobal(l, "KEY_G", KEY_G);
    AddKeyToLuaGlobal(l, "KEY_H", KEY_H);
    AddKeyToLuaGlobal(l, "KEY_I", KEY_I);
    AddKeyToLuaGlobal(l, "KEY_J", KEY_J);
    AddKeyToLuaGlobal(l, "KEY_K", KEY_K);
    AddKeyToLuaGlobal(l, "KEY_L", KEY_L);
    AddKeyToLuaGlobal(l, "KEY_M", KEY_M);
    AddKeyToLuaGlobal(l, "KEY_N", KEY_N);
    AddKeyToLuaGlobal(l, "KEY_O", KEY_O);
    AddKeyToLuaGlobal(l, "KEY_P", KEY_P);
    AddKeyToLuaGlobal(l, "KEY_Q", KEY_Q);
    AddKeyToLuaGlobal(l, "KEY_R", KEY_R);
    AddKeyToLuaGlobal(l, "KEY_S", KEY_S);
    AddKeyToLuaGlobal(l, "KEY_T", KEY_T);
    AddKeyToLuaGlobal(l, "KEY_U", KEY_U);
    AddKeyToLuaGlobal(l, "KEY_V", KEY_V);
    AddKeyToLuaGlobal(l, "KEY_W", KEY_W);
    AddKeyToLuaGlobal(l, "KEY_X", KEY_X);
    AddKeyToLuaGlobal(l, "KEY_Y", KEY_Y);
    AddKeyToLuaGlobal(l, "KEY_Z", KEY_Z);

    AddKeyToLuaGlobal(l, "KEY_0", KEY_0);
    AddKeyToLuaGlobal(l, "KEY_1", KEY_1);
    AddKeyToLuaGlobal(l, "KEY_2", KEY_2);
    AddKeyToLuaGlobal(l, "KEY_3", KEY_3);
    AddKeyToLuaGlobal(l, "KEY_4", KEY_4);
    AddKeyToLuaGlobal(l, "KEY_5", KEY_5);
    AddKeyToLuaGlobal(l, "KEY_6", KEY_6);
    AddKeyToLuaGlobal(l, "KEY_7", KEY_7);
    AddKeyToLuaGlobal(l, "KEY_8", KEY_8);
    AddKeyToLuaGlobal(l, "KEY_9", KEY_9);

    AddKeyToLuaGlobal(l, "KEY_UP",          KEY_UP);
    AddKeyToLuaGlobal(l, "KEY_DOWN",        KEY_DOWN);
    AddKeyToLuaGlobal(l, "KEY_RIGHT",       KEY_RIGHT);
    AddKeyToLuaGlobal(l, "KEY_LEFT",        KEY_LEFT);
    AddKeyToLuaGlobal(l, "KEY_INSERT",      KEY_INSERT);
    AddKeyToLuaGlobal(l, "KEY_HOME",        KEY_HOME);
    AddKeyToLuaGlobal(l, "KEY_END",         KEY_END);
    AddKeyToLuaGlobal(l, "KEY_PAGEUP",      KEY_PAGEUP);
    AddKeyToLuaGlobal(l, "KEY_PAGEDOWN",    KEY_PAGEDOWN);

    AddKeyToLuaGlobal(l, "KEY_RSHIFT",      KEY_RSHIFT);
    AddKeyToLuaGlobal(l, "KEY_LSHIFT",      KEY_LSHIFT);
    AddKeyToLuaGlobal(l, "KEY_RCTRL",       KEY_RCTRL);
    AddKeyToLuaGlobal(l, "KEY_LCTRL",       KEY_LCTRL);
    AddKeyToLuaGlobal(l, "KEY_RALT",        KEY_RALT);
    AddKeyToLuaGlobal(l, "KEY_LALT",        KEY_LALT);
}


text:
<!doctype html>
<meta charset="utf-8">
<link rel="icon" href="img/favicon.png">
<link rel="stylesheet" href="css/style.css">

<title>ESNES v1.0-alpha</title>

 <canvas id="canvas" width="256" height="240">

 </canvas>

<form method="post" enctype="multipart/form-data">

  ROM image:
  <input name="rom" type="file" accept=".nes" required>

 <fieldset name="graphics">
  <legend>Rendering</legend>

   Frame rate:
   <select name="fps">
    <option value="20.0329">20</option>
    <option value="30.0494">30</option>
    <option value="40.0658">40</option>
    <option value="50.0823">50</option>
    <option value="60.0988" selected>60</option>
   </select>
   fps

 </fieldset>

 <button>Start</button>
</form>

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

// SMP HEADER FILES ------
#include <smp/components/samplers/trajectory_bias.hpp>
#include <smp/components/distance_evaluators/kdtree.hpp>
#include <smp/components/extenders/single_integrator.hpp>
#include <smp/components/collision_checkers/standard.hpp>
#include <smp/components/multipurpose/minimum_time_reachability.hpp>

#include <smp/planners/rrtstar.hpp>

#include <smp/planner_utils/trajectory.hpp>

#include <smp/interfaces/libbot.hpp>

#include <smp/utils/branch_and_bound_euclidean.hpp>

// PARAMETERS TO THE PROBLEM ***********************************************************************************
// *
#define NUM_DIMENSIONS 15    // Change the number of dimensions from here. Scale it up to 30 - 50
                             //   dimensions to see the convergence of RRT* towards an optimal solution
                             //   in very high dimensional configuration spaces without employing any heuristics.

#define EXTENSION_LENGTH  30.0   // Maximum length of an extension. This parameter should ideally
                                 //   be equal longest straight line from the initial state to
                                 //   anywhere in the state space. In other words, this parameter
                                 //   should be "sqrt(d) L", where d is the dimensionality of space
                                 //   and L is the side length of a box containing the obstacle free space.
                                 //   __NOTE__: Smaller values of this parameter will lead to a good feasible
                                 //   solution very quickly, whilenot affecting the asymptotic optimality
                                 //   property of the RRT* algorithm.
// *
// *************************************************************************************************************

// SMP TYPE DEFINITIONS -------
using namespace smp;

// State, input, vertex_data, and edge_data definitions
typedef state_single_integrator<NUM_DIMENSIONS> state_t;
typedef input_single_integrator input_t;
typedef minimum_time_reachability_vertex_data vertex_data_t;
typedef minimum_time_reachability_edge_data edge_data_t;

// Create the typeparams structure
typedef struct _typeparams {
  typedef state_t state;
  typedef input_t input;
  typedef vertex_data_t vertex_data;
  typedef edge_data_t edge_data;
} typeparams;

// Define the trajectory type
typedef trajectory<typeparams> trajectory_t;

// Define all planner component types
typedef sampler_trajectory_bias<typeparams,NUM_DIMENSIONS> sampler_t;
typedef distance_evaluator_kdtree<typeparams,NUM_DIMENSIONS> distance_evaluator_t;
typedef extender_single_integrator<typeparams,NUM_DIMENSIONS> extender_t;
typedef collision_checker_standard<typeparams,NUM_DIMENSIONS> collision_checker_t;
typedef minimum_time_reachability<typeparams,NUM_DIMENSIONS> min_time_reachability_t;

// Define all algorithm types
typedef rrtstar<typeparams>  rrtstar_t;

// Define utils
typedef branch_and_bound_euclidean<typeparams,NUM_DIMENSIONS> branch_and_bound_t;

// Define interface types
typedef interface_libbot<typeparams> interface_t;
typedef interface_libbot_environment environment_t;

void *pointer_to_sampler;

int wrapper_to_sampler_update_trajectory (trajectory_t *trajectory_in) {

  ((sampler_t*)(pointer_to_sampler))->update_trajectory (trajectory_in);

  return 1;
}

int
main () {

  // 1. CREATE PLANNING OBJECTS

  // 1.a Create the components
  sampler_t sampler;
  distance_evaluator_t distance_evaluator;
  extender_t extender;
  collision_checker_t collision_checker;
  min_time_reachability_t min_time_reachability;

  // 1.b Create the planner algorithm -- Note that the min_time_reachability variable acts both
  //                                       as a model checker and a cost evaluator.
  rrtstar_t planner (sampler, distance_evaluator, extender, collision_checker,
		     min_time_reachability, min_time_reachability);

  planner.parameters.set_phase (2);   // The phase parameter can be used to run the algorithm as an RRT,
                                      // See the documentation of the RRG algorithm for more information.

  planner.parameters.set_gamma (25.0);    // Set this parameter should be set at least to the side length of
                                          //   the (bounded) state space. E.g., if the state space is a box
                                          //   with side length L, then this parameter should be set to at
                                          //   least L for rapid and efficient convergence in trajectory space.
  planner.parameters.set_dimension (NUM_DIMENSIONS);
  planner.parameters.set_max_radius (EXTENSION_LENGTH);

  // 1.c Create the visualization interface
  interface_t interface;

  // 1.d Create the branch and bound utility
  branch_and_bound_t branch_and_bound;

  // 2. INITALIZE PLANNING OBJECTS

  // 2.a Initialize the sampler
  region<NUM_DIMENSIONS> sampler_support;
  for (int i = 0; i < NUM_DIMENSIONS; i++) {
    sampler_support.center[i] = 0.0;
    sampler_support.size[i] = 20.0;
  }
  sampler.set_support (sampler_support);
  pointer_to_sampler = &sampler;

  // 2.b Initialize the distance evaluator
  //     Nothing to initialize. One could change the kdtree weights.

  // 2.c Initialize the extender
  extender.set_max_length (EXTENSION_LENGTH);

  // 2.d Initialize the collision checker
  region<NUM_DIMENSIONS> obstacle_new;
  for (int i = 0; i < 2; i++) {
    obstacle_new.center[i] = 5.0;
    obstacle_new.size[i] = 5.0;
  }
  obstacle_new.center[1] = 4.0;
  for (int i = 2; i < NUM_DIMENSIONS; i++) {
    obstacle_new.center[i] = 0.0;
    obstacle_new.size[i] = 20.0;
  }
  collision_checker.add_obstacle (obstacle_new);

  for (int i = 0; i < 2; i++) {
    obstacle_new.center[i] = -5.0;
    obstacle_new.size[i] = 5.0;
  }
  collision_checker.add_obstacle (obstacle_new);

  obstacle_new.center[0] = 5.0;
  obstacle_new.center[1] = -5.0;
  for (int i = 0; i < 2; i++) {
    obstacle_new.size[i] = 5.0;
  }
  if (NUM_DIMENSIONS >=3 ) {
    obstacle_new.center[2] = 7.0;
    obstacle_new.size[2] = 5.0;
  }
  collision_checker.add_obstacle (obstacle_new);
  if (NUM_DIMENSIONS >=3 ) {
    obstacle_new.center[2] = -7.0;
    obstacle_new.size[2] = 5.0;
  }
  collision_checker.add_obstacle (obstacle_new);

  obstacle_new.center[0] = -5.0;
  obstacle_new.center[1] = 5.0;
  obstacle_new.size[0] = 10.0;
  obstacle_new.size[1] = 5.0;
  if (NUM_DIMENSIONS >=3 ) {
    obstacle_new.center[2] = 0.0;
    obstacle_new.size[2] = 10.0;
  }
  collision_checker.add_obstacle (obstacle_new);

  // 2.e Initialize the model checker (with minimum_time_reachability).
  region<NUM_DIMENSIONS> region_goal;
  for (int i = 0; i < 2; i++) {
    region_goal.center[i] = 8.0;
    region_goal.size[i] = 2.0;
  }
  for (int i = 2; i < NUM_DIMENSIONS; i++) {
    region_goal.center[i] = 0.0;
    region_goal.size[i] = 20.0;
  }
  min_time_reachability.set_goal_region (region_goal);

  // 2.e' Initialize the cost evaluator (with minimum_time_reachability).
  //    ---  Register a callback to the sampler class. The callback function is called
  //            whenevert the planner finds a better trajectory that reaches the goal region.
  min_time_reachability.register_new_update_function (&wrapper_to_sampler_update_trajectory);

  // 2.f Initialize the planner
  state_t *state_initial = new state_t;
  for (int i = 0; i < NUM_DIMENSIONS; i++) {
    state_initial->state_vars[i] = 0.0;
  }
  planner.initialize (state_initial);

  // 2.g Initialize the libbot interface.
  interface.set_planner (&planner);
  if (NUM_DIMENSIONS == 2)
    interface.visualize_2d();
  else
    interface.visualize_3d();

  // 2.h Initialize the branch and bound utility
  double bnb_goal_center[NUM_DIMENSIONS];
  for (int i = 0; i < 2; i++)
    bnb_goal_center[i] = 8.0;
  for (int i = 2; i < NUM_DIMENSIONS; i++)
    bnb_goal_center[i] = 0.0;
  branch_and_bound.set_planner (&planner);
  branch_and_bound.set_goal_region (region_goal);
  branch_and_bound.set_root_vertex (planner.get_root_vertex());

  // 3. PUBLISH THE ENVIRONMENT AS A MESAGE THROUGH THE INTERFACE
  environment_t environment;
  region<3> goal;
  goal.center[0] = 8.0;
  goal.center[1] = 8.0;
  goal.center[2] = 0.0;
  goal.size[0] = 2.0;
  goal.size[1] = 2.0;
  goal.size[2] = 20.0;
  environment.set_goal_region (goal);

  region<3> operating;
  operating.center[0] = 0.0;
  operating.center[1] = 0.0;
  operating.center[2] = 0.0;
  operating.size[0] = 20.0;
  operating.size[1] = 20.0;
  operating.size[2] = 20.0;
  environment.set_operating_region (operating);

  region<3> obstacle;
  obstacle.center[0] = 5.0;
  obstacle.center[1] = 4.0;
  obstacle.center[2] = 0.0;
  obstacle.size[0] = 5.0;
  obstacle.size[1] = 5.0;
  obstacle.size[2] = 20.0;
  environment.add_obstacle (obstacle);

  obstacle.center[0] = -5.0;
  obstacle.center[1] = -5.0;
  obstacle.center[2] = 0.0;
  obstacle.size[0] = 5.0;
  obstacle.size[1] = 5.0;
  obstacle.size[2] = 20.0;
  environment.add_obstacle (obstacle);

  obstacle.center[0] = 5.0;
  obstacle.center[1] = -5.0;
  obstacle.center[2] = 7.0;
  obstacle.size[0] = 5.0;
  obstacle.size[1] = 5.0;
  obstacle.size[2] = 5.0;
  environment.add_obstacle (obstacle);

  obstacle.center[0] = 5.0;
  obstacle.center[1] = -5.0;
  obstacle.center[2] = -7.0;
  obstacle.size[0] = 5.0;
  obstacle.size[1] = 5.0;
  obstacle.size[2] = 5.0;
  environment.add_obstacle (obstacle);

  obstacle.center[0] = -5.0;
  obstacle.center[1] = 5.0;
  obstacle.center[2] = 0.0;
  obstacle.size[0] = 10.0;
  obstacle.size[1] = 5.0;
  obstacle.size[2] = 10.0;
  environment.add_obstacle (obstacle);

  interface.publish_environment (environment);

  // 4. RUN THE PLANNER
  for (int i = 0; i < 20000; i++){

    planner.iteration ();

    if (i%1000 == 0){
      cout << "Iteration: " << i << " -- ball radius: " << planner.get_ball_radius_last () <<  endl;

      // Setup and run branch and bound
      double min_cost = min_time_reachability.get_best_cost ();
      if (min_cost > 0.1) {
      	branch_and_bound.set_upper_bound_cost (min_cost);
      	branch_and_bound.run_branch_and_bound ();
      }

      interface.publish_data ();
    }

  }

  // 5. PUBLISH THE RESULTS THROUGH THE LIBBOT INTERFACE
  interface.publish_data ();
  trajectory_t trajectory_final;
  min_time_reachability.get_solution (trajectory_final);
  interface.publish_trajectory (trajectory_final);

  return 1;

}


text:
package org.mitre.synthea.world.agents;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.mitre.synthea.helpers.Config;
import org.mitre.synthea.helpers.Utilities;
import org.mitre.synthea.modules.LifecycleModule;
import org.mitre.synthea.world.concepts.HealthRecord;
import org.mitre.synthea.world.concepts.VitalSign;
import org.mitre.synthea.world.concepts.HealthRecord.CarePlan;
import org.mitre.synthea.world.concepts.HealthRecord.Code;
import org.mitre.synthea.world.concepts.HealthRecord.Encounter;
import org.mitre.synthea.world.concepts.HealthRecord.Entry;
import org.mitre.synthea.world.concepts.HealthRecord.Medication;
import org.mitre.synthea.world.concepts.HealthRecord.Observation;
import org.mitre.synthea.world.concepts.HealthRecord.Procedure;
import org.mitre.synthea.world.geography.Location;

public class CommunityHealthWorker extends Provider {

	public static final String LUNG_CANCER_SCREENING = "Lung cancer screening";
	public static final String TOBACCO_SCREENING = "Tobacco screening";
	public static final String ALCOHOL_SCREENING = "Alcohol screening";
	public static final String OBESITY_SCREENING = "Obesity screening";
	public static final String BLOOD_PRESSURE_SCREENING = "Blood pressure screening";
	public static final String DIABETES_SCREENING = "Diabetes screening";
	public static final String COLORECTAL_CANCER_SCREENING = "Colorectal cancer screening";
	public static final String PREECLAMPSIA_SCREENING = "Preeclampsia screening";
	public static final String OSTEOPOROSIS_SCREENING = "Osteoporosis screening";

	public static final String ASPIRIN_MEDICATION = "Aspirin Medication";
	public static final String PREECLAMPSIA_ASPIRIN = "Preeclampsia aspirin";
	public static final String EXERCISE_PT_INJURY_SCREENING = "Fall prevention in older adults: Exercise or physical therapy";
	public static final String VITAMIN_D_INJURY_SCREENING = "Fall prevention in older adults: Vitamin D";
	public static final String DIET_PHYSICAL_ACTIVITY = "Diet and physical activity counseling";
	public static final String STATIN_MEDICATION = "Statin preventive medication";

	public static final String CITY = "city";
	public static final String DEPLOYMENT = "deployment";
	public static final String DEPLOYMENT_COMMUNITY = "community";
	public static final String DEPLOYMENT_EMERGENCY = "emergency";
	public static final String DEPLOYMENT_POSTDISCHARGE = "postdischarge";

	public static int cost = Integer.parseInt(Config.get("generate.chw.cost"));
	public static int budget = Integer.parseInt(Config.get("generate.chw.budget"));
	public static double community = Double.parseDouble(Config.get("generate.chw.community", "0.50"));
	public static double emergency = Double.parseDouble(Config.get("generate.chw.emergency", "0.25"));
	public static double postdischarge = Double.parseDouble(Config.get("generate.chw.postdischarge", "0.25"));

	public static int yearIntroduced = Integer.parseInt(Config.get("generate.chw.year_introduced"));

	public static Map<String,List<CommunityHealthWorker>> workers = generateWorkers();

	private CommunityHealthWorker(String deploymentType)
	{
		// don't allow anyone else to instantiate this

		attributes.put(CommunityHealthWorker.ALCOHOL_SCREENING, Boolean.parseBoolean(Config.get("chw.alcohol_screening")));
		attributes.put(CommunityHealthWorker.ASPIRIN_MEDICATION, Boolean.parseBoolean(Config.get("chw.aspirin_medication")));
		attributes.put(CommunityHealthWorker.BLOOD_PRESSURE_SCREENING, Boolean.parseBoolean(Config.get("chw.blood_pressure_screening")));
		attributes.put(CommunityHealthWorker.COLORECTAL_CANCER_SCREENING, Boolean.parseBoolean(Config.get("chw.colorectal_cancer_screening")));
		attributes.put(CommunityHealthWorker.DIABETES_SCREENING, Boolean.parseBoolean(Config.get("chw.diabetes_screening")));
		attributes.put(CommunityHealthWorker.DIET_PHYSICAL_ACTIVITY, Boolean.parseBoolean(Config.get("chw.diet_physical_activity")));
		attributes.put(CommunityHealthWorker.EXERCISE_PT_INJURY_SCREENING, Boolean.parseBoolean(Config.get("chw.exercise_pt_injury_screening")));
		attributes.put(CommunityHealthWorker.LUNG_CANCER_SCREENING, Boolean.parseBoolean(Config.get("chw.lung_cancer_screening")));
		attributes.put(CommunityHealthWorker.OBESITY_SCREENING, Boolean.parseBoolean(Config.get("chw.obesity_screening")));
		attributes.put(CommunityHealthWorker.OSTEOPOROSIS_SCREENING, Boolean.parseBoolean(Config.get("chw.osteoporosis_screening")));
		attributes.put(CommunityHealthWorker.PREECLAMPSIA_ASPIRIN, Boolean.parseBoolean(Config.get("chw.preeclampsia_aspirin")));
		attributes.put(CommunityHealthWorker.PREECLAMPSIA_SCREENING, Boolean.parseBoolean(Config.get("chw.preeclampsia_screening")));
		attributes.put(CommunityHealthWorker.STATIN_MEDICATION, Boolean.parseBoolean(Config.get("chw.statin_medication")));
		attributes.put(CommunityHealthWorker.TOBACCO_SCREENING, Boolean.parseBoolean(Config.get("chw.tobacco_screening")));
		attributes.put(CommunityHealthWorker.VITAMIN_D_INJURY_SCREENING, Boolean.parseBoolean(Config.get("chw.vitamin_d_injury_screening")));

		Location.assignCity(this);

		attributes.put(DEPLOYMENT, deploymentType);

		//resourceID so that it's the same as Provider.
		attributes.put("resourceID", UUID.randomUUID().toString());

		attributes.put("name", "CHW providing " + deploymentType + " services in " + attributes.get(CITY));
	}

	private static Map<String,List<CommunityHealthWorker>> generateWorkers() {
		Map<String,List<CommunityHealthWorker>> workers = new HashMap<String,List<CommunityHealthWorker>>();
		int numWorkers = budget / cost;
		int numWorkersGenerated = 0;
		CommunityHealthWorker worker;
		for(int i=0; i < Math.round(numWorkers * community); i++)
		{
			worker = new CommunityHealthWorker(DEPLOYMENT_COMMUNITY);
			String city = (String) worker.attributes.get(CITY);
			if(!workers.containsKey(city)) {
				workers.put(city, new ArrayList<CommunityHealthWorker>());
			}
			workers.get(city).add(worker);
			numWorkersGenerated++;
		}
		for(int i=0; i < Math.round(numWorkers * emergency); i++)
		{
			worker = new CommunityHealthWorker(DEPLOYMENT_EMERGENCY);
			String city = (String) worker.attributes.get(CITY);
			if(!workers.containsKey(city)) {
				workers.put(city, new ArrayList<CommunityHealthWorker>());
			}
			workers.get(city).add(worker);
			numWorkersGenerated++;
		}
		for(int i=numWorkersGenerated; i < numWorkers; i++)
		{
			worker = new CommunityHealthWorker(DEPLOYMENT_POSTDISCHARGE);
			String city = (String) worker.attributes.get(CITY);
			if(!workers.containsKey(city)) {
				workers.put(city, new ArrayList<CommunityHealthWorker>());
			}
			workers.get(city).add(worker);
		}

		return workers;
	}

	public static CommunityHealthWorker findNearbyCHW(Person person, long time, String deploymentType)
	{
		int year = Utilities.getYear(time);

		if (year < yearIntroduced)
		{
			// CHWs not introduced to the system yet
			return null;
		}

		CommunityHealthWorker worker = null;
		String city = (String) person.attributes.get(Person.CITY);

		double probability = 0.0;
		switch(deploymentType) {
		case DEPLOYMENT_COMMUNITY:
			if(workers.containsKey(city)) {
				probability = (double)(workers.get(city).size()) / (double)Location.getPopulation(city);
			}
			break;
		case DEPLOYMENT_EMERGENCY:
			probability = 0.9;
			break;
		case DEPLOYMENT_POSTDISCHARGE:
			probability = 0.9;
			break;
		}
		if(person.rand() < probability && workers.containsKey(city)) {
			List<CommunityHealthWorker> candidates = workers.get(city).stream()
					.filter(p -> p.attributes.get(DEPLOYMENT).equals(deploymentType))
					.collect(Collectors.toList());
			if(!candidates.isEmpty()) {
				worker = candidates.get((int)person.rand(0, candidates.size()-1));
			}
		}
		return worker;
	}

	/**
	 * Check whether this CHW offers the given service.
	 * @param service Service name
	 *
	 * @return true if the service is offered by this CHW
	 */
	public boolean offers(String service)
	{
		return (boolean) this.attributes.getOrDefault(service, false);
	}

	public void performEncounter(Person person, long time, String deploymentType)
	{
		// encounter class doesn't fit into the FHIR-prescribed set
		// so we use our own "community" encounter class
		Encounter enc = person.record.encounterStart(time, "community");
		enc.chw = this;
		// TODO - different codes based on different services offered?
		enc.codes.add( new Code("SNOMED-CT","389067005","Community health procedure") );

		this.incrementEncounters(deploymentType, Utilities.getYear(time));

		int chw_interventions = (int) person.attributes.getOrDefault(Person.CHW_INTERVENTION, 0);
		chw_interventions++;
		person.attributes.put(Person.CHW_INTERVENTION, chw_interventions);

		tobaccoScreening(person, time);
		alcoholScreening(person, time);
		lungCancerScreening(person, time);
		bloodPressureScreening(person, time);
		dietPhysicalActivityCounseling(person, time);
		obesityScreening(person, time);
		aspirinMedication(person, time);
		statinMedication(person, time);

		fallsPreventionExercise(person, time);
		fallsPreventionVitaminD(person, time);
		osteoporosisScreening(person, time);

		double adherence_chw_delta = Double.parseDouble( Config.get("lifecycle.aherence.chw_delta", "0.3"));
		double probability = (double) person.attributes.get(LifecycleModule.ADHERENCE_PROBABILITY);
		probability += (adherence_chw_delta);
		person.attributes.put(LifecycleModule.ADHERENCE_PROBABILITY, probability);

		enc.stop = time + TimeUnit.MINUTES.toMillis(35); // encounter lasts 35 minutes on avg
	}

	///////////////////////////
	// INDIVIDUAL SCREENINGS //
	///////////////////////////

	//TODO published studies and numbers to support impact of CHW on various conditions

	//The USPSTF recommends that clinicians ask all adults about tobacco use, advise them to stop using tobacco, and provide
	//behavioral interventions and U.S. Food and Drug Administration (FDA)–approved pharmacotherapy for cessation to adults who use tobacco.
	private void tobaccoScreening(Person person, long time)
	{
		int age = person.ageInYears(time);

		if(this.offers(TOBACCO_SCREENING) && age >= 18)
		{
			Procedure ct = person.record.procedure(time, "Tobacco usage screening (procedure)");

			ct.codes.add(new Code("SNOMED-CT","171209009","Tobacco usage screening (procedure)"));

			double quit_smoking_chw_delta = Double.parseDouble( Config.get("lifecycle.quit_smoking.chw_delta", "0.3"));
			double smoking_duration_factor_per_year = Double.parseDouble( Config.get("lifecycle.quit_smoking.smoking_duration_factor_per_year", "1.0"));
			double probability = (double) person.attributes.get(LifecycleModule.QUIT_SMOKING_PROBABILITY);
			int numberOfYearsSmoking = (int) person.ageInYears(time) - 15;
			probability += (quit_smoking_chw_delta / (smoking_duration_factor_per_year * numberOfYearsSmoking));
			person.attributes.put(LifecycleModule.QUIT_SMOKING_PROBABILITY, probability);

			if(person.attributes.containsKey("cardio_risk")){
				double cardioRisk = (double) person.attributes.get("cardio_risk");
				cardioRisk = cardioRisk / (4 + quit_smoking_chw_delta);
			    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk")){
				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + quit_smoking_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk")){
				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + quit_smoking_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points")){
				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}
		}
	}

	//The USPSTF recommends that clinicians screen adults age 18 years or older for alcohol misuse and provide persons engaged
	//in risky or hazardous drinking with brief behavioral counseling interventions to reduce alcohol misuse.
	private void alcoholScreening(Person person, long time)
	{
		int age = person.ageInYears(time);

		if(this.offers(ALCOHOL_SCREENING) && age >= 18)
		{
			Procedure ct = person.record.procedure(time, "Screening for alcohol abuse (procedure)");

			ct.codes.add(new Code("SNOMED-CT","713107002","Screening for alcohol abuse (procedure)"));

			double quit_alcoholism_chw_delta = Double.parseDouble( Config.get("lifecycle.quit_alcoholism.chw_delta", "0.3"));
			double alcoholism_duration_factor_per_year = Double.parseDouble( Config.get("lifecycle.quit_alcoholism.alcoholism_duration_factor_per_year", "1.0"));

			if(person.attributes.containsKey("cardio_risk")){
				double cardioRisk = (double) person.attributes.get("cardio_risk");
				cardioRisk = cardioRisk / (4 + quit_alcoholism_chw_delta);
			    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk")){
				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + quit_alcoholism_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk")){
				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + quit_alcoholism_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points")){
				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}

			if((boolean) person.attributes.getOrDefault(Person.ALCOHOLIC, false)){
				Procedure ct2 = person.record.procedure(time, "Alcoholism counseling (procedure)");

				ct2.codes.add(new Code("SNOMED-CT","24165007","Alcoholism counseling (procedure)"));

				double probability = (double) person.attributes.get(LifecycleModule.QUIT_ALCOHOLISM_PROBABILITY);
				int numberOfYearsAlcoholic = (int) person.ageInYears(time) - 25;
				probability += (quit_alcoholism_chw_delta / (alcoholism_duration_factor_per_year * numberOfYearsAlcoholic));
				person.attributes.put(LifecycleModule.QUIT_ALCOHOLISM_PROBABILITY, probability);

			}
		}
	}

	// The USPSTF recommends annual screening for lung cancer with low-dose computed tomography
	// in adults ages 55 to 80 years who have a 30 pack-year smoking history and currently smoke
	// or have quit within the past 15 years.
	// Screening should be discontinued once a person has not smoked for 15 years or
	// develops a health problem that substantially limits life expectancy or the ability or willingness to have curative lung surgery.
	private void lungCancerScreening(Person person, long time)
	{
		int age = person.ageInYears(time);
		boolean isSmoker = (boolean) person.attributes.getOrDefault(Person.SMOKER, false);
		int quitSmokingAge = (int)person.attributes.getOrDefault(LifecycleModule.QUIT_SMOKING_AGE, 0);
		int yearsSinceQuitting = age - quitSmokingAge;

		// TODO: 30-year pack history
		if (this.offers(LUNG_CANCER_SCREENING) && age >= 55 && age <= 80 && (isSmoker || yearsSinceQuitting <= 15))
		{
			Procedure ct = person.record.procedure(time, "Low dose computed tomography of thorax (procedure)");

			ct.codes.add(new Code("SNOMED-CT","16334891000119106","Low dose computed tomography of thorax"));

			if((boolean) person.attributes.getOrDefault("lung_cancer", false))
			{
				person.attributes.put("probability_of_lung_cancer_treatment", 1.0); // screening caught lung cancer, send them to treatment
			}
		}
	}

	//The USPSTF recommends screening for high blood pressure in adults aged 18 years or older.
	//The USPSTF recommends obtaining measurements outside of the clinical setting for diagnostic
	//confirmation before starting treatment.
	private void bloodPressureScreening(Person person, long time){
		if (this.offers(BLOOD_PRESSURE_SCREENING)){
			//TODO metabolic syndrome module

			Procedure ct = person.record.procedure(time, "Blood pressure screening - first call (procedure)");

			ct.codes.add(new Code("SNOMED-CT","185665008","Blood pressure screening - first call (procedure)"));

			double blood_pressure_chw_delta = Double.parseDouble( Config.get("lifecycle.blood_pressure.chw_delta", "0.1"));

			if(person.attributes.containsKey("cardio_risk")){
				double cardioRisk = (double) person.attributes.get("cardio_risk");
				cardioRisk = cardioRisk / (4 + blood_pressure_chw_delta);
			    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk")){
				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + blood_pressure_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk")){
				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + blood_pressure_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points")){
				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}
		}
	}

	//The USPSTF recommends offering or referring adults who are overweight or obese and have
	//additional cardiovascular disease (CVD) risk factors to intensive behavioral counseling
	//interventions to promote a healthful diet and physical activity for CVD prevention.
	private void dietPhysicalActivityCounseling(Person person, long time){
		int age = person.ageInYears(time);

		if (this.offers(DIET_PHYSICAL_ACTIVITY) && age >=18 && person.getVitalSign(VitalSign.BMI) >= 25.0){
			//TODO metabolic syndrome module, colorectal cancer module

			// only for adults who have CVD risk factors
			// the exact threshold for CVD risk factors can be determined later

			double diet_physical_activity_chw_delta = Double.parseDouble( Config.get("lifecycle.diet_physical_activity.chw_delta", "0.1"));

			if(person.attributes.containsKey("cardio_risk")){
				if( person.attributes.get(Person.GENDER).equals("M") && (double)person.attributes.get("cardio_risk") > .0000002){
					Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)");
					ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)"));

					Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)");
					ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)"));

					double cardioRisk = (double) person.attributes.get("cardio_risk");
					cardioRisk = cardioRisk / (4 + diet_physical_activity_chw_delta);
				    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));

				}

				if( person.attributes.get(Person.GENDER).equals("F") && (double)person.attributes.get("cardio_risk") > .0000004){
					Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)");
					ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)"));

					Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)");
					ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)"));

					double cardioRisk = (double) person.attributes.get("cardio_risk");
					cardioRisk = cardioRisk / (4 + diet_physical_activity_chw_delta);
				    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));

				}
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk") && (double) person.attributes.get("atrial_fibrillation_risk") > .00000003){
				Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)");
				ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)"));

				Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)");
				ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)"));

				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + diet_physical_activity_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk") && (double)person.attributes.get("stroke_risk") > .00000003){
				Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)");
				ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)"));

				Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)");
				ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)"));

				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + diet_physical_activity_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points") && (int)person.attributes.get("stroke_points") > 3){
				Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)");
				ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)"));

				Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)");
				ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)"));

				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}
		}
	}

	//The USPSTF recommends screening all adults for obesity. Clinicians should offer or refer
	//patients with a body mass index of 30 kg/m2 or higher to intensive, multicomponent behavioral interventions.
	private void obesityScreening(Person person, long time){
		int age = person.ageInYears(time);

		if (this.offers(OBESITY_SCREENING) && age >= 18){
			//TODO metabolic syndrome module, diabetes

			Procedure ct = person.record.procedure(time, "Obesity screening (procedure)");

			ct.codes.add(new Code("SNOMED-CT","268551005","Obesity screening (procedure)"));

			double obesity_chw_delta = Double.parseDouble( Config.get("lifecycle.obesity_screening.chw_delta", "0.1"));

			if(person.attributes.containsKey("cardio_risk")){
				double cardioRisk = (double) person.attributes.get("cardio_risk");
				cardioRisk = cardioRisk / (4 + obesity_chw_delta);
			    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk")){
				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + obesity_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk")){
				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + obesity_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points")){
				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}

			if(person.getVitalSign(VitalSign.BMI) >= 30.0){
				//"Clinicians should offer or refer patients with a body mass index of 30 kg/m2 or higher to intensive, multicomponent behavioral interventions."(USPSTF)
				Procedure ct2 = person.record.procedure(time, "Obesity monitoring invitation (procedure)");

				ct2.codes.add(new Code("SNOMED-CT","310428009","Obesity monitoring invitation (procedure)"));
			}
		}
	}

	//The USPSTF recommends initiating low-dose aspirin use for the primary prevention of cardiovascular disease
	//and colorectal cancer in adults aged 50 to 59 years who have a 10% or greater 10-year cardiovascular risk,
	//are not at increased risk for bleeding, have a life expectancy of at least 10 years, and are willing to take low-dose aspirin daily for at least 10 years.
	private void aspirinMedication(Person person, long time){
		int age = person.ageInYears(time);

		// From QualityofLifeModule:
        // life expectancy equation derived from IHME GBD 2015 Reference Life Table
        // 6E-5x^3 - 0.0054x^2 - 0.8502x + 86.16
        // R^2 = 0.99978
		double lifeExpectancy = ((0.00006 * Math.pow(age, 3)) - (0.0054 * Math.pow(age, 2)) - (0.8502 * age) + 86.16);
		double tenYearStrokeRisk = (double) person.attributes.getOrDefault("cardio_risk", 0.0) * 3650;

		if(this.offers(ASPIRIN_MEDICATION) && age >= 50 && age < 60 && tenYearStrokeRisk >= .1 && lifeExpectancy >= 10){

			Procedure ct = person.record.procedure(time, "Administration of aspirin (procedure)");

			ct.codes.add(new Code("SNOMED-CT","431463004","Administration of aspirin (procedure)"));

			double aspirin_chw_delta = Double.parseDouble( Config.get("lifecycle.aspirin_medication.chw_delta", "0.1"));

			if(person.attributes.containsKey("cardio_risk")){
				double cardioRisk = (double) person.attributes.get("cardio_risk");
				cardioRisk = cardioRisk / (4 + aspirin_chw_delta);
			    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk")){
				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + aspirin_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk")){
				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + aspirin_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points")){
				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}
		}
	}

	//The USPSTF recommends that adults without a history of cardiovascular disease (CVD) (i.e., symptomatic coronary artery disease or ischemic stroke)
	//use a low- to moderate-dose statin for the prevention of CVD events and mortality when all of the following criteria are met:
	//1) they are ages 40 to 75 years; 2) they have 1 or more CVD risk factors (i.e., dyslipidemia, diabetes, hypertension, or smoking);
	//and 3) they have a calculated 10-year risk of a cardiovascular event of 10% or greater. Identification of dyslipidemia and calculation
	//of 10-year CVD event risk requires universal lipids screening in adults ages 40 to 75 years.
	private void statinMedication(Person person, long time){
		int age = person.ageInYears(time);

		double tenYearStrokeRisk = (double) person.attributes.getOrDefault("cardio_risk", 0.0) * 3650;

		boolean riskFactors = false;

		if((boolean) person.attributes.getOrDefault(Person.SMOKER, false) || ((boolean) person.attributes.getOrDefault("diabetes", false)) || ((boolean) person.attributes.getOrDefault("hypertension", false))){
			riskFactors = true;
		}

		//TODO check for history of CVD
		if(this.offers(STATIN_MEDICATION) && age >= 40 && age <= 75 && (riskFactors = true) && tenYearStrokeRisk >= .1){

			// TODO may need a better snomed code
			Procedure ct = person.record.procedure(time, "Over the counter statin therapy (procedure)");

			ct.codes.add(new Code("SNOMED-CT","414981001","Over the counter statin therapy (procedure)"));

			double statin_chw_delta = Double.parseDouble( Config.get("lifecycle.statin_medication.chw_delta", "0.1"));

			if(person.attributes.containsKey("cardio_risk")){
				double cardioRisk = (double) person.attributes.get("cardio_risk");
				cardioRisk = cardioRisk / (4 + statin_chw_delta);
			    person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("atrial_fibrillation_risk")){
				double af_risk = (double) person.attributes.get("atrial_fibrillation_risk");
				af_risk = af_risk / (4 + statin_chw_delta);
				person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_risk")){
				double stroke_risk = (double) person.attributes.get("stroke_risk");
				stroke_risk = stroke_risk / (4 + statin_chw_delta);
				person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650)));
			}

			if(person.attributes.containsKey("stroke_points")){
				int stroke_points = (int) person.attributes.get("stroke_points");
				stroke_points = stroke_points - 2;
				person.attributes.put("stroke_points", Math.max(0, stroke_points));
			}
		}
	}

	// The USPSTF recommends exercise or physical therapy to prevent falls
	// in community-dwelling adults age 65 years and older who are at increased risk for falls.
	private void fallsPreventionExercise(Person person, long time)
	{
		int age = person.ageInYears(time);
		if (this.offers(EXERCISE_PT_INJURY_SCREENING) && age > 65)
		{
			// TODO - implement fall risk using "Morse Fall Scale" - http://www.networkofcare.org/library/Morse%20Fall%20Scale.pdf
			// technically this refers to patients receiving care in acute situations, ie hospitals
			// 1. History of falling; immediate or within 3 months : No = 0, Yes = 25
			// 2. Secondary diagnosis : No = 0, Yes = 15
			// 3. Ambulatory aid : Bed rest/nurse assist = 0, Crutches/cane/walker = 15, Furniture = 30
			// 4. IV/Heparin Lock : No = 0, Yes = 20
			// 5. Gait/Transferring : Normal/bedrest/immobile = 0,  Weak = 10, Impaired = 20
			// 6. Mental status : Oriented to own ability = 0, Forgets limitations = 15

			// Risk Level | MFS Score | Action
			// -----------+-----------+-------
			// No Risk    | 0 - 24    | Basic Care
			// Low Risk   | 25 - 50   | Standard Fall Prevention Interventions
			// High Risk  | 51 - 135  | High Risk Fall Prevention Interventions
			// These #s may be tailored to specific patients or situations.

			int fallRisk = (int)person.rand(0, 60);

			if (fallRisk > 50)
			{
				CarePlan pt = person.record.careplanStart(time, "Physical therapy");
				pt.codes.add(new Code("SNOMED-CT", "91251008", "Physical therapy"));
			} else if (fallRisk > 40)
			{
				CarePlan exercise = person.record.careplanStart(time, "Physical activity target light exercise");
				exercise.codes.add(new Code("SNOMED-CT", "408580007", "Physical activity target light exercise"));
			}
		}
	}

	// The USPSTF recommends vitamin D supplementation to prevent falls
	// in community-dwelling adults age 65 years and older who are at increased risk for falls.
	private void fallsPreventionVitaminD(Person person, long time)
	{
		// https://www.uspreventiveservicestaskforce.org/Page/Document/RecommendationStatementFinal/falls-prevention-in-older-adults-counseling-and-preventive-medication#consider

		int age = person.ageInYears(time);
		if (this.offers(VITAMIN_D_INJURY_SCREENING) && age > 65)
		{
			// CHW interaction will decrease probability of injuries by g(x) % (this adds medication for vitamin D)

			// According to the Institute of Medicine, the recommended daily allowance for vitamin D
			// is 600 IU for adults aged 51 to 70 years and 800 IU for adults older than 70 years 7.
			// The AGS recommends 800 IU per day for persons at increased risk for falls.

			if (!person.record.medicationActive("Cholecalciferol 600 UNT"))
			{
				Medication vitD = person.record.medicationStart(time, "Cholecalciferol 600 UNT");
				vitD.codes.add(new Code("RxNorm", "994830", "Cholecalciferol 600 UNT"));
			}
		}
	}

	// The USPSTF recommends screening for osteoporosis in women age 65 years
	// and older and in younger women whose fracture risk is equal
	// to or greater than that of a 65-year-old white woman
	// who has no additional risk factors.
	private void osteoporosisScreening(Person person, long time)
	{
		// https://www.uspreventiveservicestaskforce.org/Page/Document/RecommendationStatementFinal/osteoporosis-screening
		int age = person.ageInYears(time);
		String gender = (String) person.attributes.get(Person.GENDER);
		boolean elevatedFractureRisk = (person.rand() < 0.05);
		// TODO - use FRAX instead of just guessing https://en.wikipedia.org/wiki/FRAX
		boolean alreadyDiagnosedOsteoporosis = person.record.conditionActive("Osteoporosis (disorder)");
		if (this.offers(OSTEOPOROSIS_SCREENING) && "F".equals(gender) && (age > 65 || elevatedFractureRisk) && !alreadyDiagnosedOsteoporosis)
		{
			// note that a lot of this already exists in the injuries & osteoporosis modules
			// TODO: ideally we would rework all 3 such that this CHW intervention would trigger an osteoporosis workup later
			// but this is the approach for now

			// bone density test
			Procedure proc = person.record.procedure(time, "Bone density scan (procedure)");
			proc.codes.add(new Code("SNOMED-CT","312681000","Bone density scan (procedure)"));

			boolean hasOsteoporosis = (boolean)person.attributes.getOrDefault("osteoporosis", false);

			double boneDensity;
			Observation obs;

			if (hasOsteoporosis)
			{
				boneDensity = person.rand(-3.8, -2.5);
				obs = person.record.observation(time, "DXA [T-score] Bone density", boneDensity);

				Entry condition = person.record.conditionStart(time, "osteoporosis");
				condition.codes.add(new Code("SNOMED-CT","64859006","Osteoporosis (disorder)"));
			} else
			{
				boneDensity = person.rand(-0.5, 0.5);
				obs = person.record.observation(time, "DXA [T-score] Bone density", boneDensity);
			}

			obs.codes.add(new Code("LOINC","38265-5","DXA [T-score] Bone density"));
		}
	}
}


text:
import sys, traceback
import os
import re
import sqlite3
import distutils.core
import cv2
import numpy as np
import argparse
import string
import plantcv as pcv
import visualize_plantcv_results as avr

### Parse command-line arguments
def options():
  parser = argparse.ArgumentParser(description="Sitching and Ordering Image Slices")
  parser.add_argument("-d", "--database", help="Database to query.", required=True)
  parser.add_argument("-o", "--outdir", help="Output directory for image files.", required=True)
  #parser.add_argument("-D", "--debug", help="Turn on debug, prints intermediate images.", action="store_true")
  args = parser.parse_args()
  return args

### Main pipeline
def main():
  # Get options
  args = options()

  img_file_dir =avr.d3_color_output(args.database,args.outdir,'Dp1AA','vis','vis_sv','rgb','on','off','yes','yes','all')
  #img_file_dir='/home/mgehan/LemnaTec/out_folder/slice_figs_and_images_04-21-2014_16:59:07/'
  #avr.cat_fig(args.outdir,img_file_dir)

if __name__ == '__main__':
  main()


text:
<?php
/* @var $this \Sil\DevPortal\controllers\ApiController */
/* @var $invitedDomainsDataProvider CDataProvider */
/* @var $api \Sil\DevPortal\models\Api */

// Set up the breadcrumbs.
$this->breadcrumbs += array(
    'APIs' => array('api/'),
    $api->display_name => array('/api/details/', 'code' => $api->code),
    'Invited Domains',
);

$this->pageTitle = 'Invited Domains';
$this->pageSubtitle = 'Domains that have been granted permission to see this API';
?>
<?php if ($api->isPubliclyVisible()): ?>

        <button type="button" class="close" data-dismiss="alert">×</button>
        Note
        This is a publicly visible API, so no invitations are necessary.

<?php endif; ?>

        <?php

        $this->widget('bootstrap.widgets.TbGridView', array(
            'type' => 'striped hover',
            'dataProvider' => $invitedDomainsDataProvider,
            'template' => '{items}{pager}',
            'columns' => array(
                array(
                    'name' => 'domain',
                    'header' => 'Domain',
                ),
                array(
                    'name' => 'created',
                    'header' => 'Invited',
                    'value' => 'Utils::getShortDateTime($data->created)'
                ),
                array(
                    'name' => 'invited_by_user_id',
                    'header' => 'Invited By',
                    'value' => 'is_null($data->invitedByUser) ? '
                    . '(UNKNOWN) : '
                    . 'sprintf('
                    .   '"%s (%s)",'
                    .   '$data->invitedByUser->email,'
                    .   '$data->invitedByUser->getDisplayName()'
                    . ');'
                ),
                array(
                    'class' => 'ActionLinksColumn',
                    'htmlOptions' => array('style' => 'text-align: right'),
                    'links' => array(
                        array(
                            'icon' => 'remove',
                            'text' => 'Uninvite',
                            'urlPattern' => '/api/cancel-domain-invitation/:api_visibility_domain_id',
                        ),
                    ),
                ),
            ),
        ));

        ?>


text:
namespace DbExam.Models
{
    public enum RelationshipType
    {
        MortalEnemies,
        RegularEnemies,
        DoNotLikeEachOther,
        Teammates,
        Friends,
        RomanticallyInvolved,
        Indifferent,
        NotRelatedAtAll
    }
}


text:
package org.codinjutsu.tools.nosql.commons.view.action;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAware;
import org.codinjutsu.tools.nosql.NoSqlExplorerPanel;
import org.codinjutsu.tools.nosql.commons.utils.GuiUtils;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class RefreshServerAction extends AnAction implements DumbAware {

    private static final Icon CONNECT_ICON = GuiUtils.loadIcon("connector.png", "connector_dark.png");
    private static final Icon REFRESH_ICON = AllIcons.Actions.Refresh;
    private static final String REFRESH_TEXT = "Refresh this server";
    private static final String CONNECT_TEXT = "Connect to this server";

    private final NoSqlExplorerPanel noSqlExplorerPanel;

    public RefreshServerAction(NoSqlExplorerPanel noSqlExplorerPanel) {
        super(REFRESH_TEXT);
        this.noSqlExplorerPanel = noSqlExplorerPanel;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
        noSqlExplorerPanel.reloadServerConfiguration(noSqlExplorerPanel.getSelectedServerNode(), true);
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        DefaultMutableTreeNode selectedServerNode = noSqlExplorerPanel.getSelectedServerNode();
        event.getPresentation().setVisible(selectedServerNode != null);
        if (selectedServerNode == null) {
            return;
        }
        boolean isConnected = selectedServerNode.getChildCount() > 0;
        event.getPresentation().setIcon(isConnected ? REFRESH_ICON : CONNECT_ICON);
        event.getPresentation().setText(isConnected ? REFRESH_TEXT : CONNECT_TEXT);
    }
}


text:
declare module "simple-dom" {
  import { Simple } from "@glimmer/interfaces";
  export interface Document extends Simple.Document {}
}


text:
import { afterCreateEventHandler } from "../utils/events";
import { startRendering, jsx } from "../utils/rendering";
import Application from "./Application";
import { getLocale, setLocale } from "../utils/locale";

// locales exposed through the UI
const locales = new Set<string>([
  "en",
  "en-US",
  "en-GB",
  "fr-FR",
  "fr-CA",
  "es",
  "es-ES",
  "es-MX",
]);

setLocale("en-US");

//Renders the application content
function render() {
  return (
    <calcite-shell dir="ltr" theme="light">

Translation

        <calcite-tip
          style="display: flex; flex-direction: column; width: 380px;"
          heading="Options"
          nonDismissible
        >
          {renderLocaleSelect()}
        </calcite-tip>

          <calcite-tip heading="Result" nonDismissible>

 new Application({ container: el })}>

          </calcite-tip>

    </calcite-shell>
  );
}

function renderLocaleSelect() {
  return (
    <calcite-label key="locale">
      Locale
      <calcite-select
        scale="s"
        afterCreate={afterCreateEventHandler(
          "calciteSelectChange",
          (event: any) => {
            setLocale(event.target.selectedOption.value);
          }
        )}
      >
        {Array.from(locales, (locale) => (
          <calcite-option
            label={locale}
            value={locale}
            selected={getLocale() === locale}
          ></calcite-option>
        ))}
      </calcite-select>
    </calcite-label>
  );
}

startRendering(document.body, render);


text:
#undef DEBUG

#include <linux/export.h>
#include <linux/threads.h>
#include <linux/kernel_stat.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/timex.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <linux/seq_file.h>
#include <linux/cpumask.h>
#include <linux/profile.h>
#include <linux/bitops.h>
#include <linux/list.h>
#include <linux/radix-tree.h>
#include <linux/mutex.h>
#include <linux/bootmem.h>
#include <linux/pci.h>
#include <linux/debugfs.h>
#include <linux/of.h>
#include <linux/of_irq.h>

#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/irq.h>
#include <asm/cache.h>
#include <asm/prom.h>
#include <asm/ptrace.h>
#include <asm/machdep.h>
#include <asm/udbg.h>
#include <asm/smp.h>
#include <asm/debug.h>

#ifdef CONFIG_PPC64
#include <asm/paca.h>
#include <asm/firmware.h>
#include <asm/lv1call.h>
#endif
#define CREATE_TRACE_POINTS
#include <asm/trace.h>

DEFINE_PER_CPU_SHARED_ALIGNED(irq_cpustat_t, irq_stat);
EXPORT_PER_CPU_SYMBOL(irq_stat);

int __irq_offset_value;

#ifdef CONFIG_PPC32
EXPORT_SYMBOL(__irq_offset_value);
atomic_t ppc_n_lost_interrupts;

#ifdef CONFIG_TAU_INT
extern int tau_initialized;
extern int tau_interrupts(int);
#endif
#endif /* CONFIG_PPC32 */

#ifdef CONFIG_PPC64

int distribute_irqs = 1;

static inline notrace unsigned long get_irq_happened(void)
{
	unsigned long happened;

	__asm__ __volatile__("lbz %0,%1(13)"
	: "=r" (happened) : "i" (offsetof(struct paca_struct, irq_happened)));

	return happened;
}

static inline notrace void set_soft_enabled(unsigned long enable)
{
	__asm__ __volatile__("stb %0,%1(13)"
	: : "r" (enable), "i" (offsetof(struct paca_struct, soft_enabled)));
}

static inline notrace int decrementer_check_overflow(void)
{
 	u64 now = get_tb_or_rtc();
 	u64 *next_tb = &__get_cpu_var(decrementers_next_tb);

	if (now >= *next_tb)
		set_dec(1);
	return now >= *next_tb;
}

/* This is called whenever we are re-enabling interrupts
 * and returns either 0 (nothing to do) or 500/900 if there's
 * either an EE or a DEC to generate.
 *
 * This is called in two contexts: From arch_local_irq_restore()
 * before soft-enabling interrupts, and from the exception exit
 * path when returning from an interrupt from a soft-disabled to
 * a soft enabled context. In both case we have interrupts hard
 * disabled.
 *
 * We take care of only clearing the bits we handled in the
 * PACA irq_happened field since we can only re-emit one at a
 * time and we don't want to "lose" one.
 */
notrace unsigned int __check_irq_replay(void)
{
	/*
	 * We use local_paca rather than get_paca() to avoid all
	 * the debug_smp_processor_id() business in this low level
	 * function
	 */
	unsigned char happened = local_paca->irq_happened;

	/* Clear bit 0 which we wouldn't clear otherwise */
	local_paca->irq_happened &= ~PACA_IRQ_HARD_DIS;

	/*
	 * Force the delivery of pending soft-disabled interrupts on PS3.
	 * Any HV call will have this side effect.
	 */
	if (firmware_has_feature(FW_FEATURE_PS3_LV1)) {
		u64 tmp, tmp2;
		lv1_get_version_info(&tmp, &tmp2);
	}

	/*
	 * We may have missed a decrementer interrupt. We check the
	 * decrementer itself rather than the paca irq_happened field
	 * in case we also had a rollover while hard disabled
	 */
	local_paca->irq_happened &= ~PACA_IRQ_DEC;
	if ((happened & PACA_IRQ_DEC) || decrementer_check_overflow())
		return 0x900;

	/* Finally check if an external interrupt happened */
	local_paca->irq_happened &= ~PACA_IRQ_EE;
	if (happened & PACA_IRQ_EE)
		return 0x500;

#ifdef CONFIG_PPC_BOOK3E
	/* Finally check if an EPR external interrupt happened
	 * this bit is typically set if we need to handle another
	 * "edge" interrupt from within the MPIC "EPR" handler
	 */
	local_paca->irq_happened &= ~PACA_IRQ_EE_EDGE;
	if (happened & PACA_IRQ_EE_EDGE)
		return 0x500;

	local_paca->irq_happened &= ~PACA_IRQ_DBELL;
	if (happened & PACA_IRQ_DBELL)
		return 0x280;
#endif /* CONFIG_PPC_BOOK3E */

	/* There should be nothing left ! */
	BUG_ON(local_paca->irq_happened != 0);

	return 0;
}

notrace void arch_local_irq_restore(unsigned long en)
{
	unsigned char irq_happened;
	unsigned int replay;

	/* Write the new soft-enabled value */
	set_soft_enabled(en);
	if (!en)
		return;
	/*
	 * From this point onward, we can take interrupts, preempt,
	 * etc... unless we got hard-disabled. We check if an event
	 * happened. If none happened, we know we can just return.
	 *
	 * We may have preempted before the check below, in which case
	 * we are checking the "new" CPU instead of the old one. This
	 * is only a problem if an event happened on the "old" CPU.
	 *
	 * External interrupt events will have caused interrupts to
	 * be hard-disabled, so there is no problem, we
	 * cannot have preempted.
	 */
	irq_happened = get_irq_happened();
	if (!irq_happened)
		return;

	/*
	 * We need to hard disable to get a trusted value from
	 * __check_irq_replay(). We also need to soft-disable
	 * again to avoid warnings in there due to the use of
	 * per-cpu variables.
	 *
	 * We know that if the value in irq_happened is exactly 0x01
	 * then we are already hard disabled (there are other less
	 * common cases that we'll ignore for now), so we skip the
	 * (expensive) mtmsrd.
	 */
	if (unlikely(irq_happened != PACA_IRQ_HARD_DIS))
		__hard_irq_disable();
#ifdef CONFIG_TRACE_IRQFLAGS
	else {
		/*
		 * We should already be hard disabled here. We had bugs
		 * where that wasn't the case so let's dbl check it and
		 * warn if we are wrong. Only do that when IRQ tracing
		 * is enabled as mfmsr() can be costly.
		 */
		if (WARN_ON(mfmsr() & MSR_EE))
			__hard_irq_disable();
	}
#endif /* CONFIG_TRACE_IRQFLAG */

	set_soft_enabled(0);

	/*
	 * Check if anything needs to be re-emitted. We haven't
	 * soft-enabled yet to avoid warnings in decrementer_check_overflow
	 * accessing per-cpu variables
	 */
	replay = __check_irq_replay();

	/* We can soft-enable now */
	set_soft_enabled(1);

	/*
	 * And replay if we have to. This will return with interrupts
	 * hard-enabled.
	 */
	if (replay) {
		__replay_interrupt(replay);
		return;
	}

	/* Finally, let's ensure we are hard enabled */
	__hard_irq_enable();
}
EXPORT_SYMBOL(arch_local_irq_restore);

/*
 * This is specifically called by assembly code to re-enable interrupts
 * if they are currently disabled. This is typically called before
 * schedule() or do_signal() when returning to userspace. We do it
 * in C to avoid the burden of dealing with lockdep etc...
 *
 * NOTE: This is called with interrupts hard disabled but not marked
 * as such in paca->irq_happened, so we need to resync this.
 */
void notrace restore_interrupts(void)
{
	if (irqs_disabled()) {
		local_paca->irq_happened |= PACA_IRQ_HARD_DIS;
		local_irq_enable();
	} else
		__hard_irq_enable();
}

/*
 * This is a helper to use when about to go into idle low-power
 * when the latter has the side effect of re-enabling interrupts
 * (such as calling H_CEDE under pHyp).
 *
 * You call this function with interrupts soft-disabled (this is
 * already the case when ppc_md.power_save is called). The function
 * will return whether to enter power save or just return.
 *
 * In the former case, it will have notified lockdep of interrupts
 * being re-enabled and generally sanitized the lazy irq state,
 * and in the latter case it will leave with interrupts hard
 * disabled and marked as such, so the local_irq_enable() call
 * in cpu_idle() will properly re-enable everything.
 */
bool prep_irq_for_idle(void)
{
	/*
	 * First we need to hard disable to ensure no interrupt
	 * occurs before we effectively enter the low power state
	 */
	hard_irq_disable();

	/*
	 * If anything happened while we were soft-disabled,
	 * we return now and do not enter the low power state.
	 */
	if (lazy_irq_pending())
		return false;

	/* Tell lockdep we are about to re-enable */
	trace_hardirqs_on();

	/*
	 * Mark interrupts as soft-enabled and clear the
	 * PACA_IRQ_HARD_DIS from the pending mask since we
	 * are about to hard enable as well as a side effect
	 * of entering the low power state.
	 */
	local_paca->irq_happened &= ~PACA_IRQ_HARD_DIS;
	local_paca->soft_enabled = 1;

	/* Tell the caller to enter the low power state */
	return true;
}

#endif /* CONFIG_PPC64 */

int arch_show_interrupts(struct seq_file *p, int prec)
{
	int j;

#if defined(CONFIG_PPC32) && defined(CONFIG_TAU_INT)
	if (tau_initialized) {
		seq_printf(p, "%*s: ", prec, "TAU");
		for_each_online_cpu(j)
			seq_printf(p, "%10u ", tau_interrupts(j));
		seq_puts(p, "  PowerPC             Thermal Assist (cpu temp)\n");
	}
#endif /* CONFIG_PPC32 && CONFIG_TAU_INT */

	seq_printf(p, "%*s: ", prec, "LOC");
	for_each_online_cpu(j)
		seq_printf(p, "%10u ", per_cpu(irq_stat, j).timer_irqs);
        seq_printf(p, "  Local timer interrupts\n");

	seq_printf(p, "%*s: ", prec, "SPU");
	for_each_online_cpu(j)
		seq_printf(p, "%10u ", per_cpu(irq_stat, j).spurious_irqs);
	seq_printf(p, "  Spurious interrupts\n");

	seq_printf(p, "%*s: ", prec, "CNT");
	for_each_online_cpu(j)
		seq_printf(p, "%10u ", per_cpu(irq_stat, j).pmu_irqs);
	seq_printf(p, "  Performance monitoring interrupts\n");

	seq_printf(p, "%*s: ", prec, "MCE");
	for_each_online_cpu(j)
		seq_printf(p, "%10u ", per_cpu(irq_stat, j).mce_exceptions);
	seq_printf(p, "  Machine check exceptions\n");

	return 0;
}

/*
 * /proc/stat helpers
 */
u64 arch_irq_stat_cpu(unsigned int cpu)
{
	u64 sum = per_cpu(irq_stat, cpu).timer_irqs;

	sum += per_cpu(irq_stat, cpu).pmu_irqs;
	sum += per_cpu(irq_stat, cpu).mce_exceptions;
	sum += per_cpu(irq_stat, cpu).spurious_irqs;

	return sum;
}

#ifdef CONFIG_HOTPLUG_CPU
void migrate_irqs(void)
{
	struct irq_desc *desc;
	unsigned int irq;
	static int warned;
	cpumask_var_t mask;
	const struct cpumask *map = cpu_online_mask;

	alloc_cpumask_var(&mask, GFP_KERNEL);

	for_each_irq_desc(irq, desc) {
		struct irq_data *data;
		struct irq_chip *chip;

		data = irq_desc_get_irq_data(desc);
		if (irqd_is_per_cpu(data))
			continue;

		chip = irq_data_get_irq_chip(data);

		cpumask_and(mask, data->affinity, map);
		if (cpumask_any(mask) >= nr_cpu_ids) {
			printk("Breaking affinity for irq %i\n", irq);
			cpumask_copy(mask, map);
		}
		if (chip->irq_set_affinity)
			chip->irq_set_affinity(data, mask, true);
		else if (desc->action && !(warned++))
			printk("Cannot set affinity for irq %i\n", irq);
	}

	free_cpumask_var(mask);

	local_irq_enable();
	mdelay(1);
	local_irq_disable();
}
#endif

static inline void handle_one_irq(unsigned int irq)
{
	struct thread_info *curtp, *irqtp;
	unsigned long saved_sp_limit;
	struct irq_desc *desc;

	desc = irq_to_desc(irq);
	if (!desc)
		return;

	/* Switch to the irq stack to handle this */
	curtp = current_thread_info();
	irqtp = hardirq_ctx[smp_processor_id()];

	if (curtp == irqtp) {
		/* We're already on the irq stack, just handle it */
		desc->handle_irq(irq, desc);
		return;
	}

	saved_sp_limit = current->thread.ksp_limit;

	irqtp->task = curtp->task;
	irqtp->flags = 0;

	/* Copy the softirq bits in preempt_count so that the
	 * softirq checks work in the hardirq context. */
	irqtp->preempt_count = (irqtp->preempt_count & ~SOFTIRQ_MASK) |
			       (curtp->preempt_count & SOFTIRQ_MASK);

	current->thread.ksp_limit = (unsigned long)irqtp +
		_ALIGN_UP(sizeof(struct thread_info), 16);

	call_handle_irq(irq, desc, irqtp, desc->handle_irq);
	current->thread.ksp_limit = saved_sp_limit;
	irqtp->task = NULL;

	/* Set any flag that may have been set on the
	 * alternate stack
	 */
	if (irqtp->flags)
		set_bits(irqtp->flags, &curtp->flags);
}

static inline void check_stack_overflow(void)
{
#ifdef CONFIG_DEBUG_STACKOVERFLOW
	long sp;

	sp = __get_SP() & (THREAD_SIZE-1);

	/* check for stack overflow: is there less than 2KB free? */
	if (unlikely(sp < (sizeof(struct thread_info) + 2048))) {
		printk("do_IRQ: stack overflow: %ld\n",
			sp - sizeof(struct thread_info));
		dump_stack();
	}
#endif
}

void do_IRQ(struct pt_regs *regs)
{
	struct pt_regs *old_regs = set_irq_regs(regs);
	unsigned int irq;

	trace_irq_entry(regs);

	irq_enter();

	check_stack_overflow();

	/*
	 * Query the platform PIC for the interrupt & ack it.
	 *
	 * This will typically lower the interrupt line to the CPU
	 */
	irq = ppc_md.get_irq();

	/* We can hard enable interrupts now */
	may_hard_irq_enable();

	/* And finally process it */
	if (irq != NO_IRQ)
		handle_one_irq(irq);
	else
		__get_cpu_var(irq_stat).spurious_irqs++;

	irq_exit();
	set_irq_regs(old_regs);

	trace_irq_exit(regs);
}

void __init init_IRQ(void)
{
	if (ppc_md.init_IRQ)
		ppc_md.init_IRQ();

	exc_lvl_ctx_init();

	irq_ctx_init();
}

#if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
struct thread_info   *critirq_ctx[NR_CPUS] __read_mostly;
struct thread_info    *dbgirq_ctx[NR_CPUS] __read_mostly;
struct thread_info *mcheckirq_ctx[NR_CPUS] __read_mostly;

void exc_lvl_ctx_init(void)
{
	struct thread_info *tp;
	int i, cpu_nr;

	for_each_possible_cpu(i) {
#ifdef CONFIG_PPC64
		cpu_nr = i;
#else
		cpu_nr = get_hard_smp_processor_id(i);
#endif
		memset((void *)critirq_ctx[cpu_nr], 0, THREAD_SIZE);
		tp = critirq_ctx[cpu_nr];
		tp->cpu = cpu_nr;
		tp->preempt_count = 0;

#ifdef CONFIG_BOOKE
		memset((void *)dbgirq_ctx[cpu_nr], 0, THREAD_SIZE);
		tp = dbgirq_ctx[cpu_nr];
		tp->cpu = cpu_nr;
		tp->preempt_count = 0;

		memset((void *)mcheckirq_ctx[cpu_nr], 0, THREAD_SIZE);
		tp = mcheckirq_ctx[cpu_nr];
		tp->cpu = cpu_nr;
		tp->preempt_count = HARDIRQ_OFFSET;
#endif
	}
}
#endif

struct thread_info *softirq_ctx[NR_CPUS] __read_mostly;
struct thread_info *hardirq_ctx[NR_CPUS] __read_mostly;

void irq_ctx_init(void)
{
	struct thread_info *tp;
	int i;

	for_each_possible_cpu(i) {
		memset((void *)softirq_ctx[i], 0, THREAD_SIZE);
		tp = softirq_ctx[i];
		tp->cpu = i;
		tp->preempt_count = 0;

		memset((void *)hardirq_ctx[i], 0, THREAD_SIZE);
		tp = hardirq_ctx[i];
		tp->cpu = i;
		tp->preempt_count = HARDIRQ_OFFSET;
	}
}

static inline void do_softirq_onstack(void)
{
	struct thread_info *curtp, *irqtp;
	unsigned long saved_sp_limit = current->thread.ksp_limit;

	curtp = current_thread_info();
	irqtp = softirq_ctx[smp_processor_id()];
	irqtp->task = curtp->task;
	irqtp->flags = 0;
	current->thread.ksp_limit = (unsigned long)irqtp +
				    _ALIGN_UP(sizeof(struct thread_info), 16);
	call_do_softirq(irqtp);
	current->thread.ksp_limit = saved_sp_limit;
	irqtp->task = NULL;

	/* Set any flag that may have been set on the
	 * alternate stack
	 */
	if (irqtp->flags)
		set_bits(irqtp->flags, &curtp->flags);
}

void do_softirq(void)
{
	unsigned long flags;

	if (in_interrupt())
		return;

	local_irq_save(flags);

	if (local_softirq_pending())
		do_softirq_onstack();

	local_irq_restore(flags);
}

irq_hw_number_t virq_to_hw(unsigned int virq)
{
	struct irq_data *irq_data = irq_get_irq_data(virq);
	return WARN_ON(!irq_data) ? 0 : irq_data->hwirq;
}
EXPORT_SYMBOL_GPL(virq_to_hw);

#ifdef CONFIG_SMP
int irq_choose_cpu(const struct cpumask *mask)
{
	int cpuid;

	if (cpumask_equal(mask, cpu_all_mask)) {
		static int irq_rover;
		static DEFINE_RAW_SPINLOCK(irq_rover_lock);
		unsigned long flags;

		/* Round-robin distribution... */
do_round_robin:
		raw_spin_lock_irqsave(&irq_rover_lock, flags);

		irq_rover = cpumask_next(irq_rover, cpu_online_mask);
		if (irq_rover >= nr_cpu_ids)
			irq_rover = cpumask_first(cpu_online_mask);

		cpuid = irq_rover;

		raw_spin_unlock_irqrestore(&irq_rover_lock, flags);
	} else {
		cpuid = cpumask_first_and(mask, cpu_online_mask);
		if (cpuid >= nr_cpu_ids)
			goto do_round_robin;
	}

	return get_hard_smp_processor_id(cpuid);
}
#else
int irq_choose_cpu(const struct cpumask *mask)
{
	return hard_smp_processor_id();
}
#endif

int arch_early_irq_init(void)
{
	return 0;
}

#ifdef CONFIG_PPC64
static int __init setup_noirqdistrib(char *str)
{
	distribute_irqs = 0;
	return 1;
}

__setup("noirqdistrib", setup_noirqdistrib);
#endif /* CONFIG_PPC64 */


text:
using System;
using System.Text;
using NUnit.Framework;
using Vestris.VMWareLibUnitTests;
using Vestris.VMWareLib;
using Vestris.VMWareLib.Tools.Windows;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace Vestris.VMWareToolsUnitTests.Windows
{
    [TestFixture]
    public class ShellUnitTests : VMWareUnitTest
    {
        [Test]
        public void TestRunCommandStdOutInGuest()
        {
            foreach (VMWareVirtualMachine virtualMachine in _test.PoweredVirtualMachines)
            {
                Shell guestShell = new Shell(virtualMachine);
                string guid = Guid.NewGuid().ToString();
                StringBuilder commands = new StringBuilder();
                commands.AppendLine(string.Format("echo {0}", guid));
                Shell.ShellOutput output = guestShell.RunCommandInGuest(commands.ToString());
                Assert.AreEqual(guid, output.StdOut.Trim());
                Assert.IsTrue(string.IsNullOrEmpty(output.StdErr));
            }
        }

        [Test]
        public void TestRunCommandStdOutStdErrInGuest()
        {
            foreach (VMWareVirtualMachine virtualMachine in _test.PoweredVirtualMachines)
            {
                Shell guestShell = new Shell(virtualMachine);
                string guid = Guid.NewGuid().ToString();
                StringBuilder commands = new StringBuilder();
                commands.AppendLine(string.Format("echo {0}", guid));
                commands.AppendLine(string.Format("echo {0} 1>&2", guid));
                Shell.ShellOutput output = guestShell.RunCommandInGuest(commands.ToString());
                Console.WriteLine(output.StdOut);
                Console.WriteLine(output.StdErr);
                Assert.AreEqual(guid, output.StdOut.Trim());
                Assert.AreEqual(guid, output.StdErr.Trim());
            }
        }

        [Test]
        public void TestGetEnvironmentVariables()
        {
            foreach (VMWareVirtualMachine virtualMachine in _test.PoweredVirtualMachines)
            {
                Shell guestShell = new Shell(virtualMachine);
                Dictionary<string, string> guestEnvironmentVariables = guestShell.GetEnvironmentVariables();
                Dictionary<string, string>.Enumerator guestEnumerator = guestEnvironmentVariables.GetEnumerator();
                while (guestEnumerator.MoveNext())
                {
                    Console.WriteLine(string.Format("{0}: {1}",
                        guestEnumerator.Current.Key, guestEnumerator.Current.Value));
                }
                Assert.IsTrue(guestEnvironmentVariables.ContainsKey("Path"));
                Assert.IsTrue(guestEnvironmentVariables.ContainsKey("USERPROFILE"));
            }
        }
    }
}


text:
package it.redhat.hacep.playground.console;

import it.redhat.hacep.HACEP;
import it.redhat.hacep.playground.console.commands.ConsoleCommand;
import it.redhat.hacep.playground.console.support.ConsoleCommandComparator;
import it.redhat.hacep.playground.console.support.ConsoleCommandNotFoundException;
import it.redhat.hacep.playground.console.support.IllegalParametersException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;

public class TextUI implements UI {

    private final static Logger LOGGER = LoggerFactory.getLogger(TextUI.class);

    @Inject
    private HACEP hacep;

    @Inject
    private Instance<ConsoleCommand> commands;

    private final BufferedReader in;
    private final PrintStream out;

    public TextUI() {
        this.in = new BufferedReader(new InputStreamReader(System.in));
        this.out = System.out;
    }

    @Override
    public void start() throws IOException {
        hacep.start();
        boolean keepRunning = true;
        while (keepRunning) {
            out.print("> ");
            out.flush();
            String line = in.readLine();
            if (line == null) {
                break;
            }
            keepRunning = processLine(line);
        }
    }

    private boolean processLine(String line) {
        Scanner scanner = new Scanner(line);
        try {
            String name = scanner.next();
            findByName(name)
                    .orElseThrow(() -> new ConsoleCommandNotFoundException(name))
                    .execute(this, scanner);
        } catch (NoSuchElementException e) {
            out.println("> ");
        } catch (IllegalParametersException | ConsoleCommandNotFoundException e) {
            println(e.getMessage());
        }
        return true;
    }

    @Override
    public void print(Object message) {
        out.print(message);
    }

    @Override
    public void println(Object message) {
        out.println(message);
    }

    @Override
    public void print(String message) {
        out.print(message);
    }

    @Override
    public void println(String message) {
        out.println(message);
    }

    @Override
    public void println() {
        out.println();
    }

    @Override
    public void printUsage() {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Start print usage");
        }
        StreamSupport.stream(commands.spliterator(), true)
                .sorted(new ConsoleCommandComparator())
                .forEachOrdered(c -> {
                    c.usage(this);
                    println();
                    println();
                });
    }

    public Optional<ConsoleCommand> findByName(String name) {
        return StreamSupport.stream(commands.spliterator(), false)
                .filter(c -> Pattern.compile(c.command()).matcher(name).matches())
                .findFirst();
    }

    @Override
    public UI register(ConsoleCommand cmd) {
        throw new IllegalStateException();
    }
}


text:
@implementation DCSearchRequest

@end


text:
#include "quadrature/angular/gauss_legendre.h"

#include "test_helpers/test_helper_functions.h"
#include "test_helpers/gmock_wrapper.h"

namespace  {

using namespace bart;

/* Constructor test for quadrature::angular::GaussLegendre class */
class QuadratureAngularGaussLegendreConstructorTest : public ::testing::Test {
 public:
  // Test parameters
  const int n_points = 4; // number of quadrature points
};

// Constructor given a valid number of points should not throw
TEST_F(QuadratureAngularGaussLegendreConstructorTest, Constructor) {
  EXPECT_NO_THROW(quadrature::angular::GaussLegendre test_quadrature(n_points));
}

// Constructor given an invalid number of points should throw
TEST_F(QuadratureAngularGaussLegendreConstructorTest, ConstructorBadNPoints) {
  auto bad_n_points = test_helpers::RandomVector(5, -5, 0);
  bad_n_points.push_back(0);
  for (const int n_points : bad_n_points) {
    EXPECT_ANY_THROW({
      quadrature::angular::GaussLegendre test_quadrature(n_points);
                     });
  }
}

/* Tests for the quadrature::angular::GaussLegendre class. */
class QuadratureAngularGaussLegendreTest
    : public QuadratureAngularGaussLegendreConstructorTest {
 public:
  QuadratureAngularGaussLegendreTest() : test_quadrature_(n_points) {}

  // Object to be tested
  quadrature::angular::GaussLegendre test_quadrature_;
};

// Order getter should return number of points
TEST_F(QuadratureAngularGaussLegendreTest, Order) {
  EXPECT_EQ(n_points, test_quadrature_.order());
}

/* Generate set should return a set of points and weights that exactly
 * integrate a spherical harmonic (Y_1_1) is used here */
TEST_F(QuadratureAngularGaussLegendreTest, GenerateSet) {
  auto set = test_quadrature_.GenerateSet();
  EXPECT_EQ(set.size(), n_points);

  // Generate negative x points to integrate over -1, 1
  for (auto point_pair : set) {
    point_pair.first.get().at(0) *= -1;
    set.push_back(point_pair);
  }

  double sum{0.0};

  // Y l = 1, m = 1
  auto legendre = [](const double point) {
    return 0.25 * 3 / M_PI * point * point;
  };

  for (const auto point_pair : set) {
    const auto point = point_pair.first.get().at(0);
    const auto weight = point_pair.second.get();
    sum += weight * legendre(point);
  }
  EXPECT_NEAR(1.0, sum, 1e-5);
}

} // namespace


text:
<?php

defined('PHPFOX') or exit('NO DICE!');

?>
<form method="post" action="{url link='admincp.core.currency.add'}">
{if $bIsEdit}

<input type="hidden" name="id" value="{$aForms.currency_id}" />

{/if}

		{phrase var='admincp.currency_details'}

			{phrase var='admincp.currency_id'}:

			<input type="text" name="val[currency_id]" value="{value type='input' id='currency_id'}" size="5" maxlength="3" />

			{phrase var='admincp.symbol'}:

			<input type="text" name="val[symbol]" value="{value type='input' id='symbol'}" size="5" maxlength="10" />

			{phrase var='admincp.phrase'}:

			{if $bIsEdit}
			{module name='language.admincp.form' type='text' id='phrase_var' var_name=$aForms.phrase_var}
			{else}
			{module name='language.admincp.form' type='text' id='phrase_var'}
			{/if}

			{phrase var='admincp.is_active'}:

				<input type="radio" name="val[is_active]" value="1" {value type='radio' id='is_active' default='1' selected='true'}/> {phrase var='admincp.yes'}
				<input type="radio" name="val[is_active]" value="0" {value type='radio' id='is_active' default='0'}/> {phrase var='admincp.no'}

		<input type="submit" value="{phrase var='admincp.submit'}" class="button" />

</form>


text:
package org.oseraf.bullseye.store.impl.blueprints

import com.tinkerpop.blueprints._
import org.oseraf.bullseye.store._

import scala.collection.JavaConversions._

/**
 * Created by nhamblet.
 */
trait BlueprintsPlugin {
  val graph: Graph
}

trait BlueprintsVertexIteratorPlugin
  extends BlueprintsPlugin
     with EntityIterationPlugin {
  override def entities: Iterable[EntityStore.ID] =
    graph.getVertices.map(v => v.getId.toString)
}

trait BlueprintsEdgeIteratorPlugin
  extends BlueprintsPlugin
     with RelationshipIterationPlugin {
  override def relationships: Iterable[EntityStore.ID] =
    graph.getEdges.map(e => e.getId.toString)
}

trait BlueprintsNeighborhoodPlugin
  extends BlueprintsPlugin
     with NeighborhoodPlugin {
  override def neighborhood(entityId: EntityStore.ID) =
    graph.getVertex(entityId).getEdges(Direction.BOTH).map(e => e.getId.toString)
}

class BlueprintsGraphStore(val graph: Graph)
  extends EntityStore
    with AttributeBasedSearchAvailableOptionsPlugin
    with BlueprintsNeighborhoodPlugin
    with BlueprintsVertexIteratorPlugin
    with BlueprintsEdgeIteratorPlugin
    with SplicePlugin
    with BruteForceAttributeBasedNaivelyFuzzySearchPlugin
{
  override val store = this

  override def entity(id: EntityStore.ID) =
    new BlueprintsEntity(graph.getVertex(id))

  override def relationship(id: EntityStore.ID) =
    new BlueprintsRelationship(graph.getEdge(id))

  override def addEntity(id: EntityStore.ID, entity: Entity) = {
    val vertex = graph.addVertex(id)
    copyAttributes(entity, vertex)
    true
  }

  override def addRelationship(id: EntityStore.ID, relationship: Relationship) = {
    relationship.connecting().toList match {
      case List(sourceId, targetId) =>
        val source = graph.getVertex(sourceId)
        val target = graph.getVertex(targetId)
        val label = relationship.attribute(BlueprintsGraphStore.RELATIONSHIP_LABEL_SOURCE_ATTRIBUTE, BlueprintsGraphStore.DEFAULT_EDGE_LABEL)
        val edge = graph.addEdge(id, source, target, label)
        copyAttributes(relationship, edge)
        true
      case _ =>
        false
    }
  }

  override def entityExists(id: EntityStore.ID) =
    graph.getVertex(id) != null

  override def relationshipExists(id: EntityStore.ID) =
    graph.getEdge(id) != null

  override def removeEntity(id: EntityStore.ID) = {
    graph.removeVertex(graph.getVertex(id))
    true
  }

  override def removeRelationship(id: EntityStore.ID) = {
    graph.removeEdge(graph.getEdge(id))
    true
  }

  override def updateEntity(id: EntityStore.ID, entity: Entity) = {
    val vertex = graph.getVertex(id)
    vertex.getPropertyKeys.foreach(key => vertex.removeProperty[String](key))
    copyAttributes(entity, vertex)
    true
  }

  override def updateRelationship(id: EntityStore.ID, relationship: Relationship) = {
    val edge = graph.getEdge(id)
    edge.getPropertyKeys.foreach(key => edge.removeProperty[String](key))
    copyAttributes(relationship, edge)
    true
  }

  lazy val searchableAttributes: Iterable[(AttributeContainer.KEY, String)] =
    graph.getVertices
      .foldLeft(Set[String]()) { case (attrs, vertex) => attrs ++ vertex.getPropertyKeys }
      .map(key => (key, StringUtils.toDisplayName(key)))
      .toSeq ++ Seq((AttributeBasedSearch.FAKE_ID_ATTRIBUTE_KEY, "ID"))

  private def copyAttributes(container: AttributeContainer, element: Element) =
    container.attributes.foreach(p => element.setProperty(p._1, p._2))
}

object BlueprintsGraphStore {
  final val DEFAULT_EDGE_LABEL = ""
  final val RELATIONSHIP_LABEL_SOURCE_ATTRIBUTE = "OSERAF:store/blueprints/edge/label"

  def apply(graph: Graph) = {
    new BlueprintsGraphStore(graph)
  }
}

class BlueprintsAttributeContainer(el: Element)
  extends AttributeContainer
{
  override def attribute(key: AttributeContainer.KEY) =
    el.getProperty[AttributeContainer.VALUE](key)

  override var attributes =
    el.getPropertyKeys.map(k => k -> el.getProperty[AttributeContainer.VALUE](k)).toMap
}

class BlueprintsEntity(vertex: Vertex)
  extends BlueprintsAttributeContainer(vertex)
     with Entity

class BlueprintsRelationship(edge: Edge)
  extends BlueprintsAttributeContainer(edge)
     with BinaryRelationship {

  override def from =
    edge.getVertex(Direction.OUT).getId.toString

  override def to =
    edge.getVertex(Direction.IN).getId.toString

  override def isDirected =
    true
}

class IndexedBlueprintsGraphStore(g:Graph) extends BlueprintsGraphStore(g) with IndexedBlueprintsFuzzyVertexSearchPlugin


text:
"use strict";

(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(["foo"], factory);
  } else if (typeof exports !== "undefined") {
    factory(require("foo"));
  } else {
    var mod = {
      exports: {}
    };
    factory(global.foo);
    global.actual = mod.exports;
  }
})(this, function (_foo) {
  var foo = babelHelpers.interopRequireWildcard(_foo);
  foo;
});


text:
package com.set.servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String UPLOAD_DIRECTORY = "images/news";

	private static final int MEMORY_TRESHHOLD = 1024 * 1024 * 3; //3mb
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		if (!ServletFileUpload.isMultipartContent(request)) {
			PrintWriter writer = response.getWriter();
			writer.println("Error uploading files!");
			//writer.flush();
			return;
		}

		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(MEMORY_TRESHHOLD);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

	}
}


text:
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Prompt</title>
</head>

<body>
	<script>
		prompt("What is your name?");
	</script>

	<p>This program just keeps popping up prompts. It is both useless and annoying, but it shows you how to use prompt.
	</p>
</body>

</html>


text:
from pyramid.httpexceptions import (
    HTTPNotModified,
    HTTPPreconditionFailed,
)
from .interfaces import CONNECTION

def etag_tid(view_callable):
    def wrapped(context, request):
        result = view_callable(context, request)
        conn = request.registry[CONNECTION]
        embedded = (conn.get_by_uuid(uuid) for uuid in sorted(request._embedded_uuids))
        uuid_tid = ((item.uuid, item.tid) for item in embedded)
        request.response.etag = '&'.join('%s=%s' % (u, t) for u, t in uuid_tid)
        cache_control = request.response.cache_control
        cache_control.private = True
        cache_control.max_age = 0
        cache_control.must_revalidate = True
        return result

    return wrapped

def if_match_tid(view_callable):
    """ ETag conditional PUT/PATCH support

    Returns 412 Precondition Failed when etag does not match.
    """
    def wrapped(context, request):
        if_match = str(request.if_match)
        if if_match == '*':
            return view_callable(context, request)
        uuid_tid = (v.split('=', 1) for v in if_match.strip('"').split('&'))
        conn = request.registry[CONNECTION]
        mismatching = (
            conn.get_by_uuid(uuid).tid != tid
            for uuid, tid in uuid_tid)
        if any(mismatching):
            raise HTTPPreconditionFailed("The resource has changed.")
        return view_callable(context, request)

    return wrapped

def etag_app_version(view_callable):
    def wrapped(context, request):
        etag = request.registry.settings['snovault.app_version']
        if etag in request.if_none_match:
            raise HTTPNotModified()
        result = view_callable(context, request)
        request.response.etag = etag
        return result

    return wrapped

def etag_app_version_effective_principals(view_callable):
    def wrapped(context, request):
        app_version = request.registry.settings['snovault.app_version']
        etag = app_version + ' ' + ' '.join(sorted(request.effective_principals))
        if etag in request.if_none_match:
            raise HTTPNotModified()
        result = view_callable(context, request)
        request.response.etag = etag
        cache_control = request.response.cache_control
        cache_control.private = True
        cache_control.max_age = 0
        cache_control.must_revalidate = True
        return result

    return wrapped