text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Summary extends MY_Controller {

	public $data = array();

	function __construct()
	{
		parent:: __construct();
		$this->data	=	array_merge($this->data,$this->load_libraries(array('material','custom','select2','tablecloth')));
		$this->session->unset_userdata('partner_filter');
		$this->load->module('charts/summaries');
	}

	public function index()
	{
		$this->data['content_view'] = 'summary/summary_view';
		// echo "<pre>";print_r($this->data);die();
		$this -> template($this->data);
	}

	public function heivalidation()
	{
		$this->data['content_view'] = 'summary/hei_validation_view';
		$this->template($this->data);
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Youhosting service management
 */
namespace Box\Mod\Serviceyouhosting\Api;

class Guest extends \Api_Abstract
{
    /**
     * Youhosting webhooks listener
     *
     * @return bool
     *
     * @throws \Exception
     */
    public function webhook($data)
    {
        $this->di['logger']->info('YouHosting WebHook: ' . print_r($data, 1));

        $config = $this->di['mod_config']('serviceyouhosting');

        if (isset($config['yh_ips'])) {
            $allowed_ips = explode(PHP_EOL, $config['yh_ips']);
            array_walk($allowed_ips, create_function('&$val', '$val = trim($val);'));
        } else {
            $allowed_ips = array(
                '212.1.209.2',
            );
        }

        if (!in_array($this->di['request']->getClientAddress(), $allowed_ips)) {
            throw new \Exception('IP not allowed');
        }

        if (!isset($data['yh_event'])) {
            throw new \Exception('Event name is missing');
        }

        $account_id = isset($data['yh_account_id']) ? $data['yh_account_id'] : null;
        $client_id  = isset($data['yh_client_id']) ? $data['yh_client_id'] : null;

        $service      = $this->getService();
        $orderService = $this->di['mod_service']('order');

        switch ($data['yh_event']) {
            case 'CREATE_ACCOUNT':
                $bb_order_id = $service->isYHAccountImported($account_id);
                if (!$bb_order_id) {
                    $account = $service->getApi()->call('Account.get', array('id' => $account_id));
                    $service->importYouhostingAccount($account);

                    $this->di['logger']->info('Imported YouHosting account. Invoked by WebHook');
                }

                break;

            case 'SUSPEND_ACCOUNT':
                $bb_order_id = $service->isYHAccountImported($account_id);
                $order       = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
                if ($order->status == 'active') {
                    $orderService->suspendFromOrder($order, 'Auto-Suspend');
                    $this->di['logger']->info('Suspended YouHosting account. Invoked by WebHook');
                }
                break;

            case 'UNSUSPEND_ACCOUNT':
                $bb_order_id = $service->isYHAccountImported($account_id);
                $order       = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
                if ($order->status == 'suspended') {
                    $orderService->unsuspendFromOrder($order);
                    $this->di['logger']->info('Unsuspended YouHosting account. Invoked by WebHook');
                }
                break;

            case 'REMOVE_ACCOUNT':
                $bb_order_id = $service->isYHAccountImported($account_id);
                $order       = $this->di['db']->getExistingModelById('ClientOrder', $data['order_id'], 'Order not found');
                if ($order->status == 'active') {
                    $orderService->cancelFromOrder($order, 'Auto-Suspend');
                    $this->di['logger']->info('Canceled YouHosting account. Invoked by WebHook');
                }
                break;

            default:
                break;
        }

        return true;
    }

    /**
     * Return master_domains
     *
     * @return array
     */
    public function master_domains($data)
    {
        $key = 'settings_subdomains';

        $cache = $this->di['cache'];
        if ($cache->exists($key)) {
            return $cache->get($key);
        }

        try {
            $result = $this->getService()->getApi()->call('Settings.subdomains');
            $cache->set($key, $result);
        } catch (\Exception $e) {
            error_log($e->getMessage());
            $result = array();
        }

        return $result;
    }
}


text:
ActiveRecord::Schema.define(:version => 20110520212834) do

  create_table "services", :force => true do |t|
    t.integer  "user_id"
    t.string   "provider"
    t.string   "uid"
    t.string   "uname"
    t.string   "uemail"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.text     "token"
    t.text     "token_secret"
    t.text     "token_refresh"
  end

  create_table "sessions", :force => true do |t|
    t.string   "session_id", :null => false
    t.text     "data"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "sessions", ["session_id"], :name => "index_sessions_on_session_id"
  add_index "sessions", ["updated_at"], :name => "index_sessions_on_updated_at"

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
var boot = require('../../browser.js')
    , mdm = boot("/boot")
    , lazynode = require("lazynode")
    , uuid = require("node-uuid")

var remote = lazynode.connect({
    createStream: createStream
    , methods: ["time"]
})

setInterval(function () {
    remote.time(function (t) {
        console.log('time = ' + t)
    })
}, 1000)

function createStream() {
    return mdm.createStream("upnode-" + uuid())
}


text:
package com.qmetry.qaf.automation.data;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptException;

import org.json.JSONObject;

import com.qmetry.qaf.automation.core.AutomationError;
import com.qmetry.qaf.automation.ui.annotations.UiElement;
import com.qmetry.qaf.automation.ui.annotations.UiElement.Type;
import com.qmetry.qaf.automation.ui.webdriver.QAFExtendedWebElement;
import com.qmetry.qaf.automation.util.ClassUtil;
import com.qmetry.qaf.automation.util.JSONUtil;
import com.qmetry.qaf.automation.util.StringUtil;

/**
 * Base class to create FormDatabean which is kind of Data-bean specifically
 * design to interact with UI forms. You can map bean properties with UI form
 * fields by providing {@link UiElement} annotation with property and fill/fetch
 * data to/from UI form.
 *
 * @see UiElement
 * @author Chirag Jayswal.
 */
public class BaseFormDataBean extends BaseDataBean {
	transient private Field[] allFields;
	transient protected final ElementInteractor interactor;

	public BaseFormDataBean() {
		interactor = new ElementInteractor();
	}

	/**
	 * it will fill up UI form fields given in argument with the property value
	 * one by one in order provided by {@link UiElement#order()}. If no argument
	 * if provided then it will fill all fields except read-only. To provide
	 * property specific custom implementation create filler method just like
	 * setter with Object as argument. For example if bean property is "
	 * String foo" then the filler method would be
	 * fillFoo(){}.
	 *
	 * @see UiElement
	 * @param fieldLocs
	 *            optional field locators
	 */
	public void fillUiElements(String... fieldLocs) {
		List<String> includeLst = null;
		if ((fieldLocs != null) && (fieldLocs.length > 0)) {
			includeLst = Arrays.asList(fieldLocs);
		}
		for (Field field : getFields()) {
			if (field.isAnnotationPresent(UiElement.class)
					&& ((includeLst == null) || includeLst.contains(field.getName())
							|| includeLst.contains(field.getAnnotation(UiElement.class).fieldLoc()))) {
				fillUiData(field);
			}
		}
	}

	public void fillUiRequiredElements() {
		for (Field field : getFields()) {
			if ((field.isAnnotationPresent(UiElement.class) && field.getAnnotation(UiElement.class).required())) {
				fillUiData(field);
			}
		}
	}

	final public void fetchUiElements(String... fieldLocs) {
		Field[] flds = getFields();// this.getClass().getDeclaredFields();
		List<String> includeLst = null;
		if ((fieldLocs != null) && (fieldLocs.length > 0)) {
			includeLst = Arrays.asList(fieldLocs);
		}
		for (Field fld : flds) {
			fld.setAccessible(true);
			if (!Modifier.isFinal(fld.getModifiers()) && fld.isAnnotationPresent(UiElement.class)) {
				UiElement map = fld.getAnnotation(UiElement.class);
				if ((includeLst == null) || includeLst.contains(fld.getName()) || includeLst.contains(map.fieldLoc())) {
					Object val = fetchUiData(fld);
					setField(fld, String.valueOf(val));
				}
			}
		}
	}

	final public boolean verifyUiElements(String... fieldmapnames) {
		Field[] flds = this.getClass().getDeclaredFields();
		List<String> includeLst = null;
		boolean outcome = true;
		if ((fieldmapnames != null) && (fieldmapnames.length > 0)) {
			includeLst = Arrays.asList(fieldmapnames);
		}
		for (Field fld : flds) {
			fld.setAccessible(true);
			if (fld.isAnnotationPresent(UiElement.class)) {
				UiElement map = fld.getAnnotation(UiElement.class);
				String mapName = StringUtil.isNotBlank(map.viewLoc()) ? map.viewLoc() : fld.getName();
				if ((includeLst == null) || includeLst.contains(mapName)) {
					outcome = outcome && verifyUiData(fld);
				}
			}
		}
		return outcome;
	}

	final public boolean verifyUiVaules(String... fieldmapnames) {
		Field[] flds = this.getClass().getDeclaredFields();
		List<String> includeLst = null;
		boolean outcome = true;
		if ((fieldmapnames != null) && (fieldmapnames.length > 0)) {
			includeLst = Arrays.asList(fieldmapnames);
		}
		for (Field fld : flds) {
			fld.setAccessible(true);
			if (fld.isAnnotationPresent(UiElement.class)) {
				UiElement map = fld.getAnnotation(UiElement.class);
				String mapName = StringUtil.isNotBlank(map.viewLoc()) ? map.viewLoc() : fld.getName();
				if ((includeLst == null) || includeLst.contains(mapName)) {
					outcome = outcome && verifyUiData(fld);
				}
			}
		}
		return outcome;
	}

	final public <T> boolean setBeanData(String propNameOrMapping, T data) {
		Field fld = getField(propNameOrMapping);
		try {
			setField(fld, String.valueOf(data));
			return true;
		} catch (Exception e) {
			logger.error("Error while geting field " + fld.getName() + "  data", e);
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	final public <T> T getBeanData(String propNameOrMapping) {
		Field fld = getField(propNameOrMapping);
		try {
			fld.setAccessible(true);
			return (T) fld.get(this);
		} catch (Exception e) {
			logger.error("Error while geting field " + fld.getName() + "  data", e);
		}
		return null;
	}

	/**
	 * finds bean property with given name or filedLoc or viewLoc
	 *
	 * @param nameOrLoc
	 * @return field or throws runtime exception.
	 */
	protected Field getField(String nameOrLoc) {
		Field[] flds = getFields();// this.getClass().getDeclaredFields();

		for (Field fld : flds) {
			if (fld.getName().equalsIgnoreCase(nameOrLoc)) {
				return fld;
			}
			UiElement element = fld.getAnnotation(UiElement.class);
			if ((null != element) && (element.fieldLoc().equalsIgnoreCase(nameOrLoc)
					|| element.viewLoc().equalsIgnoreCase(nameOrLoc))) {
				return fld;
			}
		}
		throw new RuntimeException("No property found to map with " + nameOrLoc);
	}

	protected String getMappedFieldLoc(Field fld) {
		if (fld.isAnnotationPresent(UiElement.class)) {
			UiElement map = fld.getAnnotation(UiElement.class);

			return map.fieldLoc();
		}
		return "";
	}

	protected String getMappedViewLoc(Field fld) {
		if (fld.isAnnotationPresent(UiElement.class)) {
			UiElement map = fld.getAnnotation(UiElement.class);
			return map.viewLoc();
		}
		return "";
	}

	protected boolean checkParent(String parent, String depVal) {
		String parentval = String.valueOf((Object)getBeanData(parent));
		if (depVal.equalsIgnoreCase(parentval) || resolveExpr(depVal)) {
			return true;
		}
		return false;
	}

	/**
	 * returns ordered fields array. Order can be defined by
	 * {@link UiElement#order()}
	 */
	@Override
	protected Field[] getFields() {
		if (null == allFields) {
			allFields = ClassUtil.getAllFields(this.getClass(), BaseFormDataBean.class);
			Arrays.sort(allFields, new FieldsComparator());
		}
		return allFields;
	}

	private static boolean isExpr(String str) {
		Pattern p = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);
		Matcher m = p.matcher(str);
		return m.find();
	}

	private Boolean resolveExpr(String strExpr) {
		// the pattern we want to search for
		Pattern p = Pattern.compile("\\$\\{(\\w+)\\}", Pattern.MULTILINE);
		Matcher m = p.matcher(strExpr);
		logger.info("Evaluating expr: " + strExpr);

		// print all the matches that we find
		while (m.find()) {
			String param = m.group(1);
			Object paramVal = getBeanData(m.group(1));
			logger.info("parameter " + param + ": " + paramVal);
			strExpr = strExpr.replaceAll("\\$\\{" + param + "\\}", String.valueOf(paramVal));
		}
		try {
			return (Boolean)StringUtil.eval(strExpr, toMap());
		} catch (ScriptException e) {
			logger.error("Unable to evaluate dependency condition: " + strExpr, e);
			throw new AutomationError("Unable to evaluate dependency condition: " + strExpr, e);
		}
	}

	private Object fetchUiData(Field field) {
		try {
			Method m = this.getClass().getDeclaredMethod("fetch" + StringUtil.getTitleCase(field.getName()));
			m.setAccessible(true);
			logger.debug("invoking custom fetch method for field " + field.getName());
			return m.invoke(this);

		} catch (Exception e) {
		}
		UiElement map = field.getAnnotation(UiElement.class);
		if ((null == map)) {
			return null;
		}
		Type type = map.fieldType();
		String loc = map.fieldLoc();
		Class<? extends QAFExtendedWebElement> eleClass = map.elementClass();

		return interactor.fetchValue(loc, type,eleClass);
	}

	private void fillUiData(Field fld) {
		UiElement params = fld.getAnnotation(UiElement.class);
		if ((null == params) || params.readonly()) {
			return;
		}
		Type type = params.fieldType();
		String loc = params.fieldLoc();
		String val = params.defaultValue();
		String depends = params.dependsOnField();
		String depVal = params.dependingValue();
		Class<? extends QAFExtendedWebElement> eleClass = params.elementClass();

		try {
			fld.setAccessible(true);
			Object o = fld.get(this);
			logger.debug("value " + o + " for" + fld.getName());

			val = (null == o ? null : String.valueOf(o));
		} catch (NullPointerException e) {
			val = null;
		} catch (Exception e) {
			logger.error("Unable to get data from bean for " + fld.getName(), e);

		}

		if ((val != null)
				&& (StringUtil.isBlank(depends) || StringUtil.isBlank(depVal) || checkParent(depends, depVal))) {
			try {
				Method m = ClassUtil.getMethod(this.getClass(), "fill" + StringUtil.getTitleCase(fld.getName()));
				m.setAccessible(true);
				logger.debug("invoking custom fill method for field " + fld.getName());

				m.invoke(this);

			} catch (NoSuchMethodException nse) {
				interactor.fillValue(loc, val, type, eleClass);
			} catch (Exception e) {
				logger.error("Unable to invoke custom fill method for field " + fld.getName(), e);
				throw new AutomationError("Unable to invoke custom fill method for field " + fld.getName(), e);
			}
		}
	}

	private boolean verifyUiData(Field fld) {
		UiElement map = fld.getAnnotation(UiElement.class);
		Type type = map.fieldType();
		String loc = map.fieldLoc();
		String depends = map.dependsOnField();
		String depVal = map.dependingValue();
		Class<? extends QAFExtendedWebElement> eleClass = map.elementClass();

		try {
			if (StringUtil.isBlank(depends) || checkParent(depends, depVal)) {
				return interactor.verifyValue(loc, String.valueOf(getBeanData(loc)), type,eleClass);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			return false;
		}
		// Skipped so just return success
		return true;

	}

	private class FieldsComparator implements Comparator<Field> {

		@Override
		public int compare(Field o1, Field o2) {
			return getOrder(o1) - getOrder(o2);
		}

		private int getOrder(Field f) {
			return f.isAnnotationPresent(UiElement.class) ? f.getAnnotation(UiElement.class).order()
					: Integer.MAX_VALUE;
		}

	}

}


text:
<!DOCTYPE html>

  <title>Pong!</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <link href="../pong.css" media="screen, print" rel="stylesheet" type="text/css" />

This is Pong!

Full Game

game runner - Part 1

bouncing ball - Part 2

game loop - Part 3

collision detection - Part 4

computer AI - Part 5

        The classic game loop starts with a menu, waits for a user to start the game, runs
        the game until there is a winner, or the user abandons it, and then goes back to the menu.

        Here we have hooked up keyboard events to allow the user to move the paddles up and
        down, start a 1 or 2 player game, and abandon the game in progress.

        Press 1 for a single player game.

        Press 2 for a double player game.

        Press 0 to watch the computer play itself.

        Player 1 moves using the Q and A keys.

        Player 2 moves using the P and L keys.

        Esc can be used to abandon a game.

        NOTE: The paddles will be innefective until we implement collision detection in the next section.

  <canvas id="game">

      Sorry, this example cannot be run because your browser does not support the <canvas> element

  </canvas>


text:
param(
    [string]$project,
    [string]$target,
    [string]$configuration,
    [string]$clean,
    [string]$outputDir,
    [string]$msbuildLocation,
    [string]$msbuildArguments,
    [string]$jdkVersion,
    [string]$jdkArchitecture
)

Write-Verbose "Entering script XamarinAndroid.ps1"
Write-Verbose "project = $project"
Write-Verbose "target = $target"
Write-Verbose "configuration = $configuration"
Write-Verbose "clean = $clean"
Write-Verbose "outputDir = $outputDir"
Write-Verbose "msbuildLocation = $msbuildLocation"
Write-Verbose "msbuildArguments = $msbuildArguments"
Write-Verbose "jdkVersion = $jdkVersion"
Write-Verbose "jdkArchitecture = $jdkArchitecture"

# Import the Task.Common and Task.Internal dll that has all the cmdlets we need for Build
import-module "Microsoft.TeamFoundation.DistributedTask.Task.Internal"
import-module "Microsoft.TeamFoundation.DistributedTask.Task.Common"

if (!$project)
{
    throw "project parameter not set on script"
}

# check for project pattern
if ($project.Contains("*") -or $project.Contains("?"))
{
    Write-Verbose "Pattern found in solution parameter. Calling Find-Files."
    Write-Verbose "Find-Files -SearchPattern $project"
    $projectFiles = Find-Files -SearchPattern $project
    Write-Verbose "projectFiles = $projectFiles"
}
else
{
    Write-Verbose "No Pattern found in project parameter."
    $projectFiles = ,$project
}

if (!$projectFiles)
{
    throw "No project with search pattern '$project' was found."
}

$args = $msbuildArguments;

if ($configuration)
{
    Write-Verbose "adding configuration: $configuration"
    $args = "$args /p:configuration=$configuration"
}

if ($clean.ToLower() -eq 'true')
{
    Write-Verbose "adding /t:clean"
    $args = "$args /t:clean"
}

if ($target)
{
    Write-Verbose "adding target: $target"
    $args = "$args /t:$target"
}

# Always build the APK file
Write-Verbose "adding target: PackageForAndroid"
$args = "$args /t:PackageForAndroid"

if ($outputDir)
{
    Write-Verbose "adding OutputPath: $outputDir"
    $args = "$args /p:OutputPath=""$outputDir"""
}

if ($jdkVersion -and $jdkVersion -ne "default")
{
    $jdkPath = Get-JavaDevelopmentKitPath -Version $jdkVersion -Arch $jdkArchitecture
    if (!$jdkPath)
    {
        throw "Could not find JDK $jdkVersion $jdkArchitecture, please make sure the selected JDK is installed properly"
    }

    Write-Verbose "adding JavaSdkDirectory: $jdkPath"
    $args = "$args /p:JavaSdkDirectory=`"$jdkPath`""
}

Write-Verbose "args = $args"

# build each project file
$exitCode = 0;
foreach ($pf in $projectFiles)
{
    try {
        Invoke-MSBuild $pf -LogFile "$pf.log" -ToolLocation $msBuildLocation -CommandLineArgs $args
    }
    catch [System.Exception] {
        Write-Error $error[0]
        $exitCode = 1
    }
}

if ($exitCode -ne 0) {
    Write-Error "See https://go.microsoft.com/fwlink/?LinkId=760847"
}

Write-Verbose "Leaving script XamarinAndroid.ps1"


text:
/** Define the Upvote database model/association
 * @exports Upvote
 * @param  {object} sequelize - sequelize
 * @param  {object} DataTypes - sequelize Datatypes
 * @return {object} The Upvote model
 */
export default (sequelize, DataTypes) => {
  const Upvote = sequelize.define('Upvote', {
    recipeId: {
      type: DataTypes.INTEGER,
      references: {
        model: 'Recipes',
        key: 'id',
        as: 'recipeId',
      }
    },
    userId: {
      type: DataTypes.INTEGER,
      references: {
        model: 'Users',
        key: 'id',
        as: 'userId',
      }
    }
  });
  Upvote.associate = (models) => {
    Upvote.belongsTo(models.Recipe, {
      foreignKey: 'recipeId',
      onDelete: 'CASCADE'
    });
    Upvote.belongsTo(models.User, {
      foreignKey: 'userId',
      onDelete: 'CASCADE'
    });
  };
  return Upvote;
};


text:
import express, { Router } from "express";
// @ts-ignore
import { HttpError } from "express-err";
import type { TransactionOrKnex } from "objection";

import { job as buildJob } from "@argos-ci/build";
import { raw, transaction } from "@argos-ci/database";
import type { Repository } from "@argos-ci/database/models";
import { Build, File, Screenshot } from "@argos-ci/database/models";

import { SHA256_REGEX_STR } from "../../../constants.js";
import { repoAuth } from "../../../middlewares/repoAuth.js";
import { validate } from "../../../middlewares/validate.js";
import { asyncHandler } from "../../../util.js";
import { getUnknownScreenshotKeys } from "./util.js";

const router = Router();
export default router;

const validateRoute = validate({
  params: {
    type: "object",
    required: ["buildId"],
    properties: {
      buildId: {
        type: "integer",
      },
    },
  },
  body: {
    type: "object",
    required: ["screenshots"],
    properties: {
      screenshots: {
        type: "array",
        uniqueItems: true,
        items: {
          type: "object",
          required: ["key", "name"],
          properties: {
            key: {
              type: "string",
              pattern: SHA256_REGEX_STR,
            },
            name: {
              type: "string",
            },
          },
        },
      },
      parallel: {
        type: "boolean",
        nullable: true,
      },
      parallelTotal: {
        type: "integer",
        minimum: 1,
        nullable: true,
      },
    },
  },
});

type UpdateRequest = express.Request<
  {
    buildId?: string;
  },
  Record<string, never>,
  {
    commit: string;
    screenshots: {
      key: string;
      name: string;
    }[];
    parallel?: boolean;
    parallelTotal?: number;
  }
> & { authRepository?: Repository };

// It stucks the build, so for now we can't do it, but we should
// ---
// const checkAllScreenshotKeysExist = async (unknownKeys) => {
//   const s3 = getS3();
//   const screenshotsBucket = config.get("s3.screenshotsBucket");
//   const exists = await Promise.all(
//     unknownKeys.map((key) =>
//       checkIfExists({
//         s3,
//         Key: key,
//         Bucket: screenshotsBucket,
//       })
//     )
//   );
//   const missingKeys = unknownKeys.filter((_key, index) => !exists[index]);
//   if (missingKeys.length > 0) {
//     throw new HttpError(
//       400,
//       `Missing screenshots for keys: ${missingKeys.join(", ")}`
//     );
//   }
// };

const insertFilesAndScreenshots = async ({
  req,
  build,
  unknownKeys,
  trx,
}: {
  req: UpdateRequest;
  build: Build;
  unknownKeys: string[];
  trx?: TransactionOrKnex;
}) => {
  await transaction(trx, async (trx) => {
    // Insert unknown files
    await File.query(trx)
      .insert(unknownKeys.map((key) => ({ key })))
      .onConflict("key")
      .ignore();

    // Retrieve all screenshot files
    const screenshots = req.body.screenshots;
    const screenshotKeys = screenshots.map((screenshot) => screenshot.key);
    const files = await File.query(trx).whereIn("key", screenshotKeys);

    // Insert screenshots
    await Screenshot.query(trx).insert(
      screenshots.map((screenshot) => {
        const file = files.find((f) => f.key === screenshot.key);
        if (!file) {
          throw new Error(`File not found for key ${screenshot.key}`);
        }
        return {
          screenshotBucketId: build.compareScreenshotBucket!.id,
          name: screenshot.name,
          s3Id: screenshot.key,
          fileId: file.id,
        };
      })
    );
  });
};

const handleUpdateParallel = async ({
  req,
  build,
  unknownKeys,
}: {
  req: UpdateRequest;
  build: Build;
  unknownKeys: string[];
}) => {
  if (!req.body.parallelTotal) {
    throw new HttpError(
      400,
      "`parallelTotal` is required when `parallel` is `true`"
    );
  }

  const parallelTotal = Number(req.body.parallelTotal);

  if (build.totalBatch && build.totalBatch !== parallelTotal) {
    throw new HttpError(400, "`parallelTotal` must be the same on every batch");
  }

  const complete = await transaction(async (trx) => {
    await insertFilesAndScreenshots({ req, build, unknownKeys, trx });

    await Build.query(trx)
      .findById(build.id)
      .patch({
        batchCount: raw('"batchCount" + 1'),
        totalBatch: parallelTotal,
      });

    if (parallelTotal === build.batchCount! + 1) {
      await build
        .$relatedQuery("compareScreenshotBucket", trx)
        .patch({ complete: true });
      return true;
    }

    return false;
  });

  if (complete) {
    await buildJob.push(build.id);
  }
};

const handleUpdateSingle = async ({
  req,
  build,
  unknownKeys,
}: {
  req: UpdateRequest;
  build: Build;
  unknownKeys: string[];
}) => {
  await transaction(async (trx) => {
    await insertFilesAndScreenshots({ req, build, unknownKeys, trx });

    await build
      .compareScreenshotBucket!.$query(trx)
      .patchAndFetch({ complete: true });
  });
  await buildJob.push(build.id);
};

router.put(
  "/builds/:buildId",
  repoAuth,
  // Temporary increase the limit
  // we should find a way to split the upload in several requests
  express.json({ limit: "1mb" }),
  validateRoute,
  asyncHandler(async (req: UpdateRequest, res) => {
    const buildId = Number(req.params["buildId"]);

    const build = await Build.query()
      .findById(buildId)
      .withGraphFetched("compareScreenshotBucket");

    if (!build) {
      throw new HttpError(404, "Build not found");
    }

    if (!build.compareScreenshotBucket) {
      throw new HttpError(
        500,
        "Could not find compareScreenshotBucket for build"
      );
    }

    if (build.compareScreenshotBucket.complete) {
      throw new HttpError(409, "Build is already finalized");
    }

    if (build.repositoryId !== req.authRepository!.id) {
      throw new HttpError(403, "Build does not belong to repository");
    }

    const screenshots = req.body.screenshots;
    const screenshotKeys = screenshots.map((screenshot) => screenshot.key);
    const unknownKeys = await getUnknownScreenshotKeys(screenshotKeys);
    // await checkAllScreenshotKeysExist(unknownKeys);

    const ctx = { req, build, unknownKeys };
    if (req.body.parallel) {
      await handleUpdateParallel(ctx);
    } else {
      await handleUpdateSingle(ctx);
    }

    const buildUrl = await build.getUrl();

    res.send({ build: { id: build.id, url: buildUrl } });
  })
);


text:
NAMESPACE_BEGIN(monoco)

class connection
  : public std::enable_shared_from_this<connection>
{
public:
  connection(const connection&) = delete;
  connection& operator=(const connection&) = delete;

	explicit connection(boost::asio::ip::tcp::socket socket,
						connection_manager<connection>& manager, request_handler& handler):
		_socket(std::move(socket)),
		_manager(manager),
		_req_handler(handler)
		{
		}

  void start()
  {
	  read();
  }

  void stop()
  {
	  _socket.close();
  }

private:
  void read()
  {
	  _request.args.clear();
	  _reply.headers.clear();
	  auto self(shared_from_this());

	  _socket.async_read_some(boost::asio::buffer(_buffer),
							  [this, self](boost::system::error_code ec, std::size_t bytes_transferred)
							  {
								  if (!ec)
								  {
									  request_parser::result_type result;
									  std::tie(result, std::ignore) = _req_parser.parse(
										  _request, _buffer.data(), _buffer.data() + bytes_transferred);

									  if (result == request_parser::good)
									  {
										  _req_handler.handle_request(_request, _reply);
										  write();
									  }
									  else
									  {
										  read();
									  }
								  }
								  else if (ec == boost::asio::error::eof)
								  {
									  _manager.stop(shared_from_this());
								  }
							  });
  }

   void write()
  {
	  auto self(shared_from_this());
	  boost::asio::async_write(_socket, _reply.to_buffers(),
							   [this, self](boost::system::error_code ec, std::size_t)
							   {
								   if (!ec)
									   read();
							   });

  }

	boost::asio::ip::tcp::socket _socket;

	connection_manager<connection>& _manager;

	request_handler _req_handler;

	std::array<char, 8192> _buffer;

	request _request;

	request_parser _req_parser;

	reply _reply;
};

typedef std::shared_ptr<connection> connection_ptr;

NAMESPACE_END(monoco)

#endif


text:
require 'spec_helper'

describe "admin_expense_types/edit" do
  before(:each) do
    @expense_type = assign(:expense_type, stub_model(Admin::ExpenseType,
      :expense_type => "MyString"
    ))
  end

  it "renders the edit expense_type form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form", :action => admin_expense_types_path(@expense_type), :method => "post" do
      assert_select "input#expense_type_expense_type", :name => "expense_type[expense_type]"
    end
  end
end


text:
Project = require('../../models/models').Project;

function handleError(res, reason, message, code) {
    console.log("ERROR: " + reason);
    res.status(code || 500).json({"error": message});
}

module.exports = {
    collection:{
        doGet:function(req, res){
            Project.find(function (err, projects) {
                if (err) {
                    handleError(res, err.message, "Failed to get the project.");
                } else {
                    res.status(200).json(projects);
                }
            });
        },
        doPost:function (req, res) {
            var project = new Project(req.body);
            project.save(function (err) {
                if (err) {
                    handleError(res, err.message, "Failed to create new project.");
                } else {
                    res.status(201).location('/api/projects/' + project.id).json(project);
                }
            });
        }
    }
};


text:
<multicounter style="height:300px" class="container" ng-class="{'positive': targetValue && trendPositive, 'negative': targetValue && !trendPositive}">

{{displayNames[0]}}

            <value>{{counterValues[0] | customNumbers : shortens[0] : decimals[0]}} {{suffixes[0]}}</value>
            <counter-target ng-if="targetValue">({{targetValues[0] | customNumbers[0]}})</counter-target>

{{displayNames[1]}}

            <value>{{counterValues[1] | customNumbers : shortens[1] : decimals[1]}} {{suffixes[1]}}</value>
            <counter-target ng-if="targetValue">({{targetValues[1] | customNumbers[1]}})</counter-target>

{{displayNames[2]}}

            <value>{{counterValues[2] | customNumbers : shortens[2] : decimals[2]}} {{suffixes[2]}}</value>
            <counter-target ng-if="targetValue">({{targetValues[2] | customNumbers[2]}})</counter-target>

{{displayNames[3]}}

            <value>{{counterValues[3] | customNumbers : shortens[3] : decimals[3]}} {{suffixes[3]}}</value>
            <counter-target ng-if="targetValue">({{targetValues[3] | customNumbers[3]}})</counter-target>

</multicounter>


text:
renderer
========

A Rendering API for javascript objects.


text:
package at.tugraz.sss.serv.datatype.enums;

import java.util.*;

public enum SSCircleRightE{

  all,
  read,
  edit;

  public static List<SSCircleRightE> get(final List<String> values){

    final List<SSCircleRightE> result = new ArrayList<>();

    for(String value : values){
      result.add(get(value));
    }

    return result;
  }

  public static SSCircleRightE get(final String value){
    return SSCircleRightE.valueOf(value);
  }

  private SSCircleRightE(){/* Do nothing because of only JSON Jackson needs this */ }
}


text:
<?php

namespace Drupal\search_api\Form;

use Drupal\Core\Entity\EntityConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\Error;
use Drupal\search_api\SearchApiException;

/**
 * Defines a confirm form for reindexing an index.
 */
class IndexReindexConfirmForm extends EntityConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this->t('Are you sure you want to reindex the search index %name?', ['%name' => $this->entity->label()]);
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->t('Indexed data will remain on the search server until all items have been reindexed. Searches on this index will continue to yield results. This action cannot be undone.');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return new Url('entity.search_api_index.canonical', ['search_api_index' => $this->entity->id()]);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\search_api\IndexInterface $index */
    $index = $this->getEntity();

    try {
      $index->reindex();
      drupal_set_message($this->t('The search index %name was successfully reindexed.', ['%name' => $index->label()]));
    }
    catch (SearchApiException $e) {
      drupal_set_message($this->t('Failed to reindex items for the search index %name.', ['%name' => $index->label()]), 'error');
      $message = '%type while trying to reindex items on index %name: @message in %function (line %line of %file)';
      $variables = [
        '%name' => $index->label(),
      ];
      $variables += Error::decodeException($e);
      $this->getLogger('search_api')->error($message, $variables);
    }

    $form_state->setRedirect('entity.search_api_index.canonical', ['search_api_index' => $index->id()]);
  }

}


text: Brisket TemplateAdapter for using handlebars templates


text:
package com.ctrip.hermes.consumer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.unidal.lookup.annotation.Inject;
import org.unidal.lookup.annotation.Named;
import org.unidal.tuple.Pair;

import com.ctrip.hermes.consumer.api.BaseMessageListener;
import com.ctrip.hermes.consumer.api.Consumer;
import com.ctrip.hermes.consumer.api.MessageListener;
import com.ctrip.hermes.consumer.api.MessageListenerConfig;
import com.ctrip.hermes.consumer.api.OffsetStorage;
import com.ctrip.hermes.consumer.api.PullConsumerConfig;
import com.ctrip.hermes.consumer.api.PullConsumerHolder;
import com.ctrip.hermes.consumer.engine.CompositeSubscribeHandle;
import com.ctrip.hermes.consumer.engine.Engine;
import com.ctrip.hermes.consumer.engine.SubscribeHandle;
import com.ctrip.hermes.consumer.engine.Subscriber;
import com.ctrip.hermes.consumer.engine.ack.AckManager;
import com.ctrip.hermes.consumer.engine.config.ConsumerConfig;
import com.ctrip.hermes.consumer.pull.DefaultPullConsumerHolder;
import com.ctrip.hermes.core.bo.Offset;
import com.ctrip.hermes.core.meta.MetaService;
import com.ctrip.hermes.core.utils.PlexusComponentLocator;
import com.ctrip.hermes.meta.entity.Topic;

@Named(type = com.ctrip.hermes.consumer.api.Consumer.class)
public class DefaultConsumer extends Consumer {

	private static final MessageListenerConfig DEFAULT_MESSAGE_LISTENER_CONFIG = new MessageListenerConfig();

	@Inject
	private Engine m_engine;

	@Inject
	private MetaService m_metaService;

	@Inject
	private ConsumerConfig m_config;

	private ConsumerHolder start(String topicPattern, String groupId, MessageListener<?> listener,
	      MessageListenerConfig listenerConfig, ConsumerType consumerType) {
		return start(topicPattern, groupId, listener, listenerConfig, consumerType, null);
	}

	private ConsumerHolder start(String topicPattern, String groupId, MessageListener<?> listener,
	      MessageListenerConfig listenerConfig, ConsumerType consumerType, OffsetStorage offsetStorage) {
		return start(topicPattern, groupId, listener, listenerConfig, consumerType, offsetStorage, null);
	}

	private ConsumerHolder start(String topicPattern, String groupId, MessageListener<?> listener,
	      MessageListenerConfig listenerConfig, ConsumerType consumerType, OffsetStorage offsetStorage,
	      Class<?> messageClazz) {
		if (listener instanceof BaseMessageListener) {
			((BaseMessageListener<?>) listener).setGroupId(groupId);
		}
		SubscribeHandle subscribeHandle = m_engine.start(new Subscriber(topicPattern, groupId, listener, listenerConfig,
		      consumerType, offsetStorage, messageClazz));

		return new DefaultConsumerHolder(subscribeHandle);
	}

	@Override
	public ConsumerHolder start(String topic, String groupId, MessageListener<?> listener) {
		return start(topic, groupId, listener, DEFAULT_MESSAGE_LISTENER_CONFIG);
	}

	@Override
	public ConsumerHolder start(String topic, String groupId, MessageListener<?> listener, MessageListenerConfig config) {
		ConsumerType type = config.isStrictlyOrdering() ? ConsumerType.STRICTLY_ORDERING : ConsumerType.DEFAULT;
		return start(topic, groupId, listener, config, type);
	}

	public static class DefaultConsumerHolder implements ConsumerHolder {

		private SubscribeHandle m_subscribeHandle;

		public DefaultConsumerHolder(SubscribeHandle subscribeHandle) {
			m_subscribeHandle = subscribeHandle;
		}

		public boolean isConsuming() {
			if (m_subscribeHandle instanceof CompositeSubscribeHandle) {
				return ((CompositeSubscribeHandle) m_subscribeHandle).getChildHandleList().size() > 0;
			}
			return false;
		}

		@Override
		public void close() {
			m_subscribeHandle.close();
		}

	}

	@Override
	public Offset getOffsetByTime(String topicName, int partition, long time) {
		Topic topic = m_metaService.findTopicByName(topicName);
		if (topic == null || topic.findPartition(partition) == null) {
			throw new IllegalArgumentException(String.format("Topic [%s] or partition [%s] not found.", topicName,
			      partition));
		}
		return m_metaService.findMessageOffsetByTime(topicName, partition, time);
	}

	@Override
	public Map<Integer, Offset> getOffsetByTime(String topicName, long time) {
		Topic topic = m_metaService.findTopicByName(topicName);
		if (topic == null) {
			throw new IllegalArgumentException(String.format("Topic [%s] not found.", topicName));
		}

		return m_metaService.findMessageOffsetByTime(topicName, time);
	}

	private Topic validateTopicAndConsumerGroup(String topicName, String groupId) {
		Topic topic = m_metaService.findTopicByName(topicName);

		if (topic == null) {
			throw new IllegalArgumentException("Topic not found: " + topicName);
		}
		if (topic.findConsumerGroup(groupId) == null) {
			throw new IllegalArgumentException("Consumer group not found: " + groupId);
		}
		return topic;
	}

	@Override
	public <T> PullConsumerHolder<T> openPullConsumer(String topicName, String groupId, Class<T> messageClass,
	      PullConsumerConfig config) {
		return openPullConsumer(topicName, groupId, -1L, messageClass, config);
	}

	public <T> PullConsumerHolder<T> openPullConsumer(String topicName, String groupId, final long startTimeMillis,
	      Class<T> messageClass, PullConsumerConfig config) {

		ensureSingleTopic(topicName);

		Topic topic = validateTopicAndConsumerGroup(topicName, groupId);

		OffsetStorage offsetStorage = null;

		if (startTimeMillis > 0) {
			offsetStorage = new OffsetStorage() {
				ConcurrentMap<Pair<String, Integer>, Offset> m_offsets = new ConcurrentHashMap<>();

				@Override
				public Offset queryLatestOffset(String topic, int partition) {
					Pair<String, Integer> key = new Pair<String, Integer>(topic, partition);
					Offset offset = m_offsets.get(key);
					if (offset != null) {
						return offset;
					} else {
						return getOffsetByTime(topic, partition, startTimeMillis);
					}
				}

				@Override
				public void updatePulledOffset(String topic, int partition, Offset offset) {
					Pair<String, Integer> key = new Pair<String, Integer>(topic, partition);
					Offset existingOffset = m_offsets.get(key);
					if (existingOffset == null) {
						m_offsets.putIfAbsent(key, new Offset(0L, 0L, null));
						existingOffset = m_offsets.get(key);
					}
					synchronized (this) {
						if (existingOffset.getPriorityOffset() < offset.getPriorityOffset()) {
							existingOffset.setPriorityOffset(offset.getPriorityOffset());
						}
						if (existingOffset.getNonPriorityOffset() < offset.getNonPriorityOffset()) {
							existingOffset.setNonPriorityOffset(offset.getNonPriorityOffset());
						}
					}
				}
			};
		}

		DefaultPullConsumerHolder<T> holder = new DefaultPullConsumerHolder<T>(topicName, groupId, topic.getPartitions()
		      .size(), config, PlexusComponentLocator.lookup(AckManager.class), offsetStorage, m_config);

		MessageListenerConfig listenerConfig = new MessageListenerConfig();

		ConsumerHolder consumerHolder = start(topicName, groupId, holder, listenerConfig, ConsumerType.PULL,
		      offsetStorage, messageClass);
		holder.setConsumerHolder(consumerHolder);

		return holder;
	}

	private void ensureSingleTopic(String topicName) {
		if (topicName != null && (topicName.indexOf("*") >= 0 || topicName.indexOf("#") >= 0)) {
			throw new IllegalArgumentException("Pull consumer can not use topic pattern: " + topicName);
		}

	}
}


text:
@class NSString;

@interface EmoticonMd5Object : MMObject <PBCoding>
{
    unsigned int m_status;
    NSString *m_md5;
    NSString *m_cdnUrl;
    NSString *m_designerId;
    NSString *m_thumbImgUrl;
    NSString *m_encryptUrl;
    NSString *m_aesKey;
    NSString *m_productId;
}

+ (unsigned int)StatusValueFailed;
+ (unsigned int)StatusValueComplete;
+ (unsigned int)StatusValueUnComplete;
+ (void)initialize;
@property(retain, nonatomic) NSString *m_productId; // @synthesize m_productId;
@property(retain, nonatomic) NSString *m_aesKey; // @synthesize m_aesKey;
@property(retain, nonatomic) NSString *m_encryptUrl; // @synthesize m_encryptUrl;
@property(retain, nonatomic) NSString *m_thumbImgUrl; // @synthesize m_thumbImgUrl;
@property(retain, nonatomic) NSString *m_designerId; // @synthesize m_designerId;
@property(retain, nonatomic) NSString *m_cdnUrl; // @synthesize m_cdnUrl;
@property(nonatomic) unsigned int m_status; // @synthesize m_status;
@property(retain, nonatomic) NSString *m_md5; // @synthesize m_md5;
- (void).cxx_destruct;
@property(readonly, copy) NSString *description;
- (id)init;
- (void)dealloc;
- (const map_0e718273 *)getValueTagIndexMap;
- (id)getValueTypeTable;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
//	File name: CoreEntries.h
//	Description: Component externals declaration.

#ifndef COREENTRIES_H__BUILDERELEMENTS__INCLUDED_
#define COREENTRIES_H__BUILDERELEMENTS__INCLUDED_

#include "../BuilderElements.h"

BUILDERELEMENTS_FUNC_DECLARE result			DllGetClassObject(REFCLSID rCLSID, REFIID rIID, void** ppObject);
BUILDERELEMENTS_FUNC_DECLARE result			CanUnloadNow();

BUILDERELEMENTS_FUNC_DECLARE void			GetComponentName(String& rComponentName);
BUILDERELEMENTS_FUNC_DECLARE void			GetComponentVersion(String& rComponentVersion);

#endif // !COREENTRIES_H__BUILDERELEMENTS__INCLUDED_


text:
.. _developing_packages:

Developing packages
===================

This section shows how to work on packages with source code continuously being modified.

.. toctree::
   :maxdepth: 2

   developing_packages/package_dev_flow
   developing_packages/package_layout
   developing_packages/editable_packages
   developing_packages/workspaces


text:
package net.liftweb
package proto

import net.liftweb.common._
import net.liftweb.util._
import net.liftweb.http._
import scala.reflect.Manifest

import java.util.regex.Pattern

/**
 * This singleton contains the rules for persistence
 */
object ProtoRules extends Factory with LazyLoggable {
  /**
   * The regular expression pattern for matching email addresses.
   */
  val emailRegexPattern = new FactoryMaker(Pattern.compile("^[a-z0-9._%\\-+]+@(?:[a-z0-9\\-]+\\.)+[a-z]{2,}$", Pattern.CASE_INSENSITIVE)) {}

}


text:
package com.microsoftopentechnologies.intellij.serviceexplorer;

import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.microsoftopentechnologies.intellij.helpers.UIHelper;
import com.microsoftopentechnologies.intellij.helpers.azure.AzureCmdException;
import com.microsoftopentechnologies.intellij.helpers.collections.ObservableList;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Node {
    private static final String CLICK_ACTION = "click";
    protected String id;
    protected String name;
    protected Node parent;
    protected ObservableList<Node> childNodes = new ObservableList<Node>();
    protected String iconPath;
    protected Object viewData;
    protected NodeAction clickAction = new NodeAction(this, CLICK_ACTION);
    protected List<NodeAction> nodeActions = new ArrayList<NodeAction>();

    // marks this node as being in a "loading" state; when this field is true
    // the following consequences apply:
    //  [1] all actions associated with this node get disabled
    //  [2] click action gets disabled automatically
    protected boolean loading = false;

    protected PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    private boolean hasRefreshAction;

    public Node(String id, String name) {
        this(id, name, null, null, false, false);
    }

    public Node(String id, String name, Node parent, String iconPath, boolean hasRefreshAction) {
        this(id, name, parent, iconPath, hasRefreshAction, false);
    }

    public Node(String id, String name, Node parent, String iconPath, boolean hasRefreshAction, boolean delayActionLoading) {
        this.id = id;
        this.name = name;
        this.parent = parent;
        this.iconPath = iconPath;
        this.hasRefreshAction = hasRefreshAction;

        if (!delayActionLoading) {
            loadActions();
        }
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        String oldValue = this.name;
        this.name = name;
        propertyChangeSupport.firePropertyChange("name", oldValue, name);
    }

    public Node getParent() {
        return parent;
    }

    public ObservableList<Node> getChildNodes() {
        return childNodes;
    }

    public boolean isDirectChild(Node node) {
        return childNodes.contains(node);
    }

    public boolean isDescendant(Node node) {
        if (isDirectChild(node))
            return true;
        for (Node child : childNodes) {
            if (child.isDescendant(node))
                return true;
        }

        return false;
    }

    // Walk up the tree till we find a parent node who's type
    // is equal to "clazz".
    public Node findParentByType(Class clazz) {
        if (parent == null)
            return null;
        if (parent.getClass().equals(clazz))
            return parent;
        return parent.findParentByType(clazz);
    }

    public boolean hasChildNodes() {
        return !childNodes.isEmpty();
    }

    public void removeDirectChildNode(Node childNode) {
        if (isDirectChild(childNode)) {
            // remove this node's child nodes (so they get an
            // opportunity to clean up after them)
            childNode.removeAllChildNodes();

            // this remove call should cause the NodeListChangeListener object
            // registered on it's child nodes to fire
            childNodes.remove(childNode);
        }
    }

    public void removeAllChildNodes() {
        while (!childNodes.isEmpty()) {
            Node node = childNodes.get(0);

            // remove this node's child nodes (so they get an
            // opportunity to clean up after them)
            node.removeAllChildNodes();

            // this remove call should cause the NodeListChangeListener object
            // registered on it's child nodes to fire
            childNodes.remove(0);
        }
    }

    public String getIconPath() {
        return iconPath;
    }

    public void setIconPath(String iconPath) {
        String oldValue = this.iconPath;
        this.iconPath = iconPath;
        propertyChangeSupport.firePropertyChange("iconPath", oldValue, iconPath);
    }

    public void addChildNode(Node child) {
        childNodes.add(child);
    }

    public void addAction(NodeAction action) {
        nodeActions.add(action);
    }

    // Convenience method to add a new action with a pre-configured listener. If
    // an action with the same name already exists then the listener is added
    // to that action.
    public NodeAction addAction(String name, NodeActionListener actionListener) {
        NodeAction nodeAction = getNodeActionByName(name);
        if (nodeAction == null) {
            addAction(nodeAction = new NodeAction(this, name));
        }
        nodeAction.addListener(actionListener);
        return nodeAction;
    }

    protected void loadActions() {
        // add the click action handler
        addClickActionListener(new NodeActionListener() {
            @Override
            public void actionPerformed(NodeActionEvent e) {
                onNodeClick(e);
            }
        });

        // add the refresh node action
        if (hasRefreshAction) {
            addAction("Refresh", new NodeActionListener() {
                @Override
                public void actionPerformed(NodeActionEvent e) {
                    Futures.addCallback(load(), new FutureCallback<List<Node>>() {
                        @Override
                        public void onSuccess(List<Node> nodes) {
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            UIHelper.showException("An error occurred while refreshing the service.", throwable);
                        }
                    });
                }
            });
        }

        // add the other actions
        Map<String, Class<? extends NodeActionListener>> actions = initActions();

        if (actions != null) {
            for (Map.Entry<String, Class<? extends NodeActionListener>> entry : actions.entrySet()) {
                try {
                    // get default constructor
                    Class<? extends NodeActionListener> listenerClass = entry.getValue();
                    Constructor constructor = listenerClass.getDeclaredConstructor(getClass());

                    // create an instance passing this object as a constructor argument
                    // since we assume that this is an inner class
                    NodeActionListener actionListener = (NodeActionListener) constructor.newInstance(this);
                    addAction(entry.getKey(), actionListener);
                } catch (InstantiationException e) {
                    UIHelper.showException(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    UIHelper.showException(e.getMessage(), e);
                } catch (NoSuchMethodException e) {
                    UIHelper.showException(e.getMessage(), e);
                } catch (InvocationTargetException e) {
                    UIHelper.showException(e.getMessage(), e);
                }
            }
        }
    }

    // sub-classes are expected to override this method and
    // add code for initializing node-specific actions; this
    // method is called when the node is being constructed and
    // is guaranteed to be called only once per node
    // NOTE: The Class<?> objects returned by this method MUST be
    // public inner classes of the sub-class. We assume that they are.
    protected Map<String, Class<? extends NodeActionListener>> initActions() {
        return null;
    }

    // sub-classes are expected to override this method and
    // add a handler for the case when something needs to be
    // done when the user left-clicks this node in the tree view
    protected void onNodeClick(NodeActionEvent e) {
    }

    public List<NodeAction> getNodeActions() {
        return nodeActions;
    }

    public NodeAction getNodeActionByName(final String name) {
        return Iterators.tryFind(nodeActions.iterator(), new Predicate<NodeAction>() {
            @Override
            public boolean apply(NodeAction nodeAction) {
                return name.compareTo(nodeAction.getName()) == 0;
            }
        }).orNull();
    }

    public boolean hasNodeActions() {
        return !nodeActions.isEmpty();
    }

    public void addActions(Iterable<NodeAction> actions) {
        for (NodeAction action : actions) {
            addAction(action);
        }
    }

    public NodeAction getClickAction() {
        return clickAction;
    }

    public void addClickActionListener(NodeActionListener actionListener) {
        clickAction.addListener(actionListener);
    }

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    public Object getViewData() {
        return viewData;
    }

    public void setViewData(Object viewData) {
        this.viewData = viewData;
    }

    public Project getProject() {
        // delegate to parent node if there's one else return null
        if (parent != null) {
            return parent.getProject();
        }

        return null;
    }

    @Override
    public String toString() {
        return getName();
    }

    // Sub-classes are expected to override this method if they wish to
    // refresh items synchronously. The default implementation does nothing.
    protected void refreshItems() throws AzureCmdException {
    }

    // Sub-classes are expected to override this method if they wish
    // to refresh items asynchronously. The default implementation simply
    // delegates to "refreshItems" *synchronously* and completes the Future
    // with the result of calling getChildNodes.
    protected void refreshItems(SettableFuture<List<Node>> future) throws AzureCmdException {
        setLoading(true);
        try {
            refreshItems();
            future.set(getChildNodes());
        } finally {
            setLoading(false);
        }
    }

    protected void runAsBackground(Runnable runnable) {
        runAsBackground("", runnable);
    }

    protected void runAsBackground(final String status, final Runnable runnable) {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                ProgressManager.getInstance().run(
                        new Task.Backgroundable(getProject(), status, false) {
                            @Override
                            public void run(ProgressIndicator progressIndicator) {
                                runnable.run();
                            }
                        });
            }
        });
    }

    public ListenableFuture<List<Node>> load() {
        final SettableFuture<List<Node>> future = SettableFuture.create();

        // background tasks via ProgressManager can be scheduled only on the
        // dispatch thread
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                ProgressManager.getInstance().run(new BackgroundLoader(
                        future, getProject(), "Loading " + getName() + "...", false));
            }
        });

        return future;
    }

    public boolean isLoading() {
        return loading;
    }

    public void setLoading(boolean loading) {
        this.loading = loading;
    }

    class BackgroundLoader extends Task.Backgroundable {
        private SettableFuture<List<Node>> future;

        public BackgroundLoader(SettableFuture<List<Node>> future, Project project, String title, boolean canBeCancelled) {
            super(project, title, canBeCancelled);
            this.future = future;
        }

        @Override
        public void run(ProgressIndicator progressIndicator) {
            progressIndicator.setIndeterminate(true);

            final String nodeName = getName();
            setName(nodeName + " (Refreshing...)");

            Futures.addCallback(future, new FutureCallback<List<Node>>() {
                @Override
                public void onSuccess(List<Node> nodes) {
                    updateName(null);
                }

                @Override
                public void onFailure(Throwable throwable) {
                    updateName(throwable);
                }

                private void updateName(final Throwable throwable) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            setName(nodeName);
                            if (throwable != null) {
                                UIHelper.showException("An error occurred while loading " + getName() + ".", throwable);
                            }
                        }
                    });
                }
            });

            try {
                refreshItems(future);
            } catch (AzureCmdException e) {
                future.setException(e);
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package org.drip.service.stream</title>
<meta name="date" content="2013-08-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.drip.service.stream

Packages that use org.drip.service.stream

Package
Description

org.drip.analytics.curve

org.drip.analytics.date

org.drip.analytics.daycount

org.drip.analytics.definition

org.drip.analytics.holiday

org.drip.analytics.output

org.drip.analytics.period

org.drip.param.definition

org.drip.param.market

org.drip.param.pricer

org.drip.param.quoting

org.drip.param.valuation

org.drip.product.creator

org.drip.product.credit

org.drip.product.definition

org.drip.product.fx

org.drip.product.params

org.drip.product.rates

org.drip.service.bridge

org.drip.service.stream

Classes in org.drip.service.stream used by org.drip.analytics.curve

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.analytics.date

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.analytics.daycount

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.analytics.definition

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.analytics.holiday

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.analytics.output

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.analytics.period

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.param.definition

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.param.market

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.param.pricer

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.param.quoting

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.param.valuation

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.product.creator

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.product.credit

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.product.definition

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.product.fx

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.product.params

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.product.rates

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.service.bridge

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Classes in org.drip.service.stream used by org.drip.service.stream

Class and Description

Serializer

Serializer interface defines the core object serializer methods – serialization into and
        de-serialization out of byte arrays, as well as the object version.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
{{<template/govuk}}

{{$pageTitle}}{{messages.exit_under16_title}}{{/pageTitle}}

{{$main}}

{{messages.exit_under16_title}}

{{messages.exit_under16_explanation}}

{{{messages.exit_under16_tryToFindDOBOut}}}

{{/main}}

{{/template/govuk}}


text:
#pragma once

#include "functional/defs.h"
#include <limits>
#include <string>

namespace marian {
namespace functional {

template <class C>
using IsClass = typename std::enable_if<std::is_class<C>::value, C>::type;

template <int N>
struct Select {
  template <typename T, typename... Args>
  HOST_DEVICE_INLINE static auto apply(T&& /*arg*/, Args&&... args)
      -> decltype(Select<N - 1>::apply(args...)) {
    return Select<N - 1>::apply(args...);
  }
};

template <>
struct Select<0> {
  template <typename T, typename... Args>
  HOST_DEVICE_INLINE static T apply(T&& arg, Args&&... /*args*/) {
    return arg;
  }
};

/******************************************************************************/

template <int V>
struct C {
  static constexpr auto value = V;

  template <typename T, typename... Args>
  HOST_DEVICE_INLINE T operator()(T&& /*arg*/, Args&&... /*args*/) {
    return (T)V;
  }

  std::string to_string() const { return "C<" + std::to_string(V) + ">"; }
};

/******************************************************************************/

struct Capture {
  float value;

  Capture(float val) : value(val){};

  template <typename T, typename... Args>
  HOST_DEVICE_INLINE T operator()(const T& /*arg*/, const Args&... /*args*/) {
    return T(value);
  }

  std::string to_string() const { return "Cap(" + std::to_string(value) + ")"; }
};

/******************************************************************************/

template <int N>
struct Var {
  static constexpr auto index = N;

  template <typename T, typename... Args>
  HOST_DEVICE_INLINE T& operator()(T&& arg, Args&&... args) {
    return Select<N - 1>::apply(arg, args...);
  }

  std::string to_string() const { return "Var<" + std::to_string(N) + ">"; }
};
}  // namespace functional
}  // namespace marian


text:
// based on https://svn.apache.org/repos/asf/mesos/tags/release-0.9.0-incubating-RC0/src/common/json.hpp

#ifndef JSON_CONTAINER_H
#define JSON_CONTAINER_H

#include "../Util/StringUtil.h"

#include <boost/variant.hpp>

#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>

namespace JSON
{

struct String;
struct Number;
struct Object;
struct Array;
struct True;
struct False;
struct Null;

typedef boost::variant<boost::recursive_wrapper<String>,
                       boost::recursive_wrapper<Number>,
                       boost::recursive_wrapper<Object>,
                       boost::recursive_wrapper<Array>,
                       boost::recursive_wrapper<True>,
                       boost::recursive_wrapper<False>,
                       boost::recursive_wrapper<Null> > Value;

struct String
{
    String() {}
    String(const char *value) : value(value) {}
    String(const std::string &value) : value(value) {}
    std::string value;
};

struct Number
{
    Number() {}
    Number(double value) : value(value) {}
    double value;
};

struct Object
{
    std::unordered_map<std::string, Value> values;
};

struct Array
{
    std::vector<Value> values;
};

struct True
{
};

struct False
{
};

struct Null
{
};

struct Renderer : boost::static_visitor<>
{
    Renderer(std::ostream &_out) : out(_out) {}

    void operator()(const String &string) const { out << "\"" << string.value << "\""; }

    void operator()(const Number &number) const
    {
        out.precision(10);
        out << number.value;
    }

    void operator()(const Object &object) const
    {
        out << "{";
        auto iterator = object.values.begin();
        while (iterator != object.values.end())
        {
            out << "\"" << (*iterator).first << "\":";
            boost::apply_visitor(Renderer(out), (*iterator).second);
            if (++iterator != object.values.end())
            {
                out << ",";
            }
        }
        out << "}";
    }

    void operator()(const Array &array) const
    {
        out << "[";
        std::vector<Value>::const_iterator iterator;
        iterator = array.values.begin();
        while (iterator != array.values.end())
        {
            boost::apply_visitor(Renderer(out), *iterator);
            if (++iterator != array.values.end())
            {
                out << ",";
            }
        }
        out << "]";
    }

    void operator()(const True &) const { out << "true"; }

    void operator()(const False &) const { out << "false"; }

    void operator()(const Null &) const { out << "null"; }

  private:
    std::ostream &out;
};

struct ArrayRenderer : boost::static_visitor<>
{
    ArrayRenderer(std::vector<char> &_out) : out(_out) {}

    void operator()(const String &string) const {
        out.push_back('\"');
        out.insert(out.end(), string.value.begin(), string.value.end());
        out.push_back('\"');
    }

    void operator()(const Number &number) const
    {
        const std::string number_string = FixedDoubleToString(number.value);
        out.insert(out.end(), number_string.begin(), number_string.end());
    }

    void operator()(const Object &object) const
    {
        out.push_back('{');
        auto iterator = object.values.begin();
        while (iterator != object.values.end())
        {
            out.push_back('\"');
            out.insert(out.end(), (*iterator).first.begin(), (*iterator).first.end());
            out.push_back('\"');
            out.push_back(':');

            boost::apply_visitor(ArrayRenderer(out), (*iterator).second);
            if (++iterator != object.values.end())
            {
                out.push_back(',');
            }
        }
        out.push_back('}');
    }

    void operator()(const Array &array) const
    {
        out.push_back('[');
        std::vector<Value>::const_iterator iterator;
        iterator = array.values.begin();
        while (iterator != array.values.end())
        {
            boost::apply_visitor(ArrayRenderer(out), *iterator);
            if (++iterator != array.values.end())
            {
                out.push_back(',');
            }
        }
        out.push_back(']');
    }

    void operator()(const True &) const {
        const std::string temp("true");
        out.insert(out.end(), temp.begin(), temp.end());
    }

    void operator()(const False &) const {
        const std::string temp("false");
        out.insert(out.end(), temp.begin(), temp.end());
    }

    void operator()(const Null &) const {
        const std::string temp("null");
        out.insert(out.end(), temp.begin(), temp.end());
    }

  private:
    std::vector<char> &out;
};

inline void render(std::ostream &out, const Object &object)
{
    Value value = object;
    boost::apply_visitor(Renderer(out), value);
}

inline void render(std::vector<char> &out, const Object &object)
{
    Value value = object;
    boost::apply_visitor(ArrayRenderer(out), value);
}

} // namespace JSON

#endif // JSON_CONTAINER_H


text:
using Microsoft.CodeAnalysis.CSharp.Syntax; // lgtm[cs/similar-file]
using Semmle.Extraction.CSharp.Entities.Expressions;
using Semmle.Extraction.Kinds;
using System.IO;

namespace Semmle.Extraction.CSharp.Entities.Statements
{
    internal class Fixed : Statement<FixedStatementSyntax>
    {
        private Fixed(Context cx, FixedStatementSyntax @fixed, IStatementParentEntity parent, int child)
            : base(cx, @fixed, StmtKind.FIXED, parent, child) { }

        public static Fixed Create(Context cx, FixedStatementSyntax node, IStatementParentEntity parent, int child)
        {
            var ret = new Fixed(cx, node, parent, child);
            ret.TryPopulate();
            return ret;
        }

        protected override void PopulateStatement(TextWriter trapFile)
        {
            VariableDeclarations.Populate(Context, Stmt.Declaration, this, -1, childIncrement: -1);
            Create(Context, Stmt.Statement, this, 0);
        }
    }
}


text:
<!DOCTYPE html>

    <title>Back Button Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="css/itemcss/style.css" rel="stylesheet">

 <ion-pane >
    <ion-header-bar align-title="left" class="bar-stable bar-dark">

      </ion-header-bar>

      <ion-content class="content"  scrollbar-y="false">

تظبيطة كلمة

معلومات عن هذا العرض ساري لفترة محدودة

العنوان 4 شارع 9 المعادي

ساري حتي 20/4

تظبيطة مستنياك

15-12-2014

        </ion-content>

    </ion-pane>


text:
import path = require('path')
import ts = require('typescript')
import { exists } from './file-util'

export function readConfig (
  configPath: string,
  _parseConfigHost: ts.ParseConfigHost = ts.sys // for test
): ts.ParsedCommandLine | undefined {
  const result = ts.readConfigFile(configPath, _parseConfigHost.readFile)

  if (result.error) {
    return undefined
  }

  return ts.parseJsonConfigFileContent(
    result.config,
    _parseConfigHost,
    path.dirname(configPath),
    undefined,
    configPath
  )
}

export function findConfig (
  baseDir: string,
  _exists: (filePath: string) => boolean = exists // for test
): string | undefined {
  const configFileName = 'tsconfig.json'

  function loop (dir: string): string | undefined {
    const parentPath = path.dirname(dir)
    // It is root directory if parent and current dirname are the same
    if (dir === parentPath) {
      return undefined
    }

    const configPath = path.join(dir, configFileName)
    if (_exists(configPath)) {
      return configPath
    }

    return loop(parentPath)
  }
  return loop(baseDir)
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.Communication.Identity.Models
{
    internal partial class CommunicationError
    {
        internal static CommunicationError DeserializeCommunicationError(JsonElement element)
        {
            string code = default;
            string message = default;
            Optional<string> target = default;
            Optional<IReadOnlyList<CommunicationError>> details = default;
            Optional<CommunicationError> innerError = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("code"))
                {
                    code = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("message"))
                {
                    message = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("target"))
                {
                    target = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("details"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<CommunicationError> array = new List<CommunicationError>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(DeserializeCommunicationError(item));
                    }
                    details = array;
                    continue;
                }
                if (property.NameEquals("innerError"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    innerError = DeserializeCommunicationError(property.Value);
                    continue;
                }
            }
            return new CommunicationError(code, message, target.Value, Optional.ToList(details), innerError.Value);
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Res. 92(2): 192 (1989)

#### Original name
Gymnohydnotrya B.C. Zhang & Minter

### Remarks
null


text:
import django
from django.db import models as db_models
from django.forms.models import (ModelForm as _ModelForm,
                                 ModelFormMetaclass as _ModelFormMetaclass,
                                 modelform_factory as _modelform_factory,
                                 modelformset_factory as _modelformset_factory,
                                 inlineformset_factory as _inlineformset_factory,
                                 model_to_dict, fields_for_model, BaseModelForm,
                                 save_instance, BaseModelFormSet,
                                 BaseInlineFormSet)
from django.utils import six

from floppyforms import fields
from floppyforms.forms import LayoutRenderer
from floppyforms.models import (ModelChoiceField, ModelMultipleChoiceField)
from floppyforms.widgets import Textarea

__all__ = (
    'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
    'save_instance', 'ModelChoiceField', 'ModelMultipleChoiceField',
    'BaseModelFormSet', 'modelformset_factory', 'BaseInlineFormSet',
    'inlineformset_factory',
)

if django.VERSION > (1, 7):
    from django.forms.models import ALL_FIELDS

    __all__ = __all__ + ('ALL_FIELDS',)

FORMFIELD_OVERRIDES = {
    db_models.BooleanField: {'form_class': fields.BooleanField},
    db_models.CharField: {'form_class': fields.CharField},
    db_models.CommaSeparatedIntegerField: {'form_class': fields.CharField},
    db_models.DateField: {'form_class': fields.DateField},
    db_models.DateTimeField: {'form_class': fields.DateTimeField},
    db_models.DecimalField: {'form_class': fields.DecimalField},
    db_models.EmailField: {'form_class': fields.EmailField},
    db_models.FilePathField: {'form_class': fields.FilePathField},
    db_models.FloatField: {'form_class': fields.FloatField},
    db_models.IntegerField: {'form_class': fields.IntegerField},
    db_models.BigIntegerField: {'form_class': fields.IntegerField},
    db_models.IPAddressField: {'form_class': fields.IPAddressField},
    db_models.GenericIPAddressField: {'form_class': fields.GenericIPAddressField},
    db_models.NullBooleanField: {'form_class': fields.NullBooleanField},
    db_models.PositiveIntegerField: {'form_class': fields.IntegerField},
    db_models.PositiveSmallIntegerField: {'form_class': fields.IntegerField},
    db_models.SlugField: {'form_class': fields.SlugField},
    db_models.SmallIntegerField: {'form_class': fields.IntegerField},
    db_models.TextField: {'form_class': fields.CharField, 'widget': Textarea},
    db_models.TimeField: {'form_class': fields.TimeField},
    db_models.URLField: {'form_class': fields.URLField},
    # Binary field is never editable, so we don't need to convert it.

    db_models.FileField: {'form_class': fields.FileField},
    db_models.ImageField: {'form_class': fields.ImageField},

    db_models.ForeignKey: {'form_class': ModelChoiceField},
    db_models.ManyToManyField: {'form_class': ModelMultipleChoiceField},
    db_models.OneToOneField: {'form_class': ModelChoiceField},
}

for value in FORMFIELD_OVERRIDES.values():
    value['choices_form_class'] = fields.TypedChoiceField

def formfield_callback(db_field, **kwargs):
    defaults = FORMFIELD_OVERRIDES.get(db_field.__class__, {}).copy()
    defaults.update(kwargs)
    return db_field.formfield(**defaults)

class ModelFormMetaclass(_ModelFormMetaclass):
    def __new__(mcs, name, bases, attrs):
        if not attrs.get('formfield_callback'):
            attrs['formfield_callback'] = formfield_callback
        return super(ModelFormMetaclass, mcs).__new__(mcs, name, bases, attrs)

class ModelForm(six.with_metaclass(ModelFormMetaclass, LayoutRenderer, _ModelForm)):
    pass

def modelform_factory(model, form=ModelForm, fields=None, exclude=None,
                      formfield_callback=formfield_callback, *args, **kwargs):
    return _modelform_factory(model, form, fields, exclude, formfield_callback,
                              *args, **kwargs)

def modelformset_factory(model, form=ModelForm,
                         formfield_callback=formfield_callback,
                         *args, **kwargs):
    return _modelformset_factory(model, form, formfield_callback,
                                 *args, **kwargs)

def inlineformset_factory(parent_model, model, form=ModelForm,
                          formset=BaseInlineFormSet, fk_name=None,
                          fields=None, exclude=None, extra=3, can_order=False,
                          can_delete=True, max_num=None,
                          formfield_callback=formfield_callback,
                          *args, **kwargs):
    return _inlineformset_factory(parent_model, model, form, formset, fk_name,
                                  fields, exclude, extra, can_order,
                                  can_delete, max_num, formfield_callback,
                                  *args, **kwargs)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Podaxis pistillaris f. macrosporus G. Cunn.

### Remarks
null


text:
package com.shipdream.lib.android.mvc.samples.note.model;

import com.shipdream.lib.android.mvc.samples.note.model.dto.Note;

import org.parceler.Parcel;

import java.util.List;

@Parcel
public class NoteModel {
    Note viewingNote;
    List<Note> notes;
    List<Long> selectedNoteIds;

    public Note getViewingNote() {
        return viewingNote;
    }

    public void setViewingNote(Note viewingNote) {
        this.viewingNote = viewingNote;
    }

    public List<Note> getNotes() {
        return notes;
    }

    public void setNotes(List<Note> notes) {
        this.notes = notes;
    }

    public List<Long> getSelectedNoteIds() {
        return selectedNoteIds;
    }

    public void setSelectedNoteIds(List<Long> selectedNoteIds) {
        this.selectedNoteIds = selectedNoteIds;
    }

}


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('modules/SugarFeed/feedLogicBase.php');

class CaseFeed extends FeedLogicBase {
    var $module = 'Cases';
    function pushFeed($bean, $event, $arguments){
        $text = '';
	if(empty($bean->fetched_row) && $bean->in_save){
            $accountName = $bean->account_name;
            if(empty($accountName) && $bean->account_id){
                $acc = BeanFactory::getBean('Accounts',$bean->account_id);
                $accountName = $acc->name;
            }
            $text =  '{SugarFeed.CREATED_CASE} [' . $bean->module_dir . ':' . $bean->id . ':' . $bean->name.'] {SugarFeed.FOR} [Accounts:' . $bean->account_id . ':' . $accountName . ']: '. $bean->description;
        }else{
            if(!empty($bean->fetched_row['status'] ) && $bean->fetched_row['status'] != $bean->status && strpos($bean->status, 'Closed') !== false){
                $text =  '{SugarFeed.CLOSED_CASE} [' . $bean->module_dir . ':' . $bean->id . ':' . $bean->name. '] {SugarFeed.FOR} [Accounts:' . $bean->account_id . ':' . $bean->account_name . ']';
            }
        }

        if(!empty($text)){
			SugarFeed::pushFeed2($text, $bean);
        }

    }
}
?>


text:
package org.apache.fineract.portfolio.collectionsheet.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import org.apache.commons.lang.StringUtils;
import org.apache.fineract.commands.domain.CommandWrapper;
import org.apache.fineract.commands.service.CommandWrapperBuilder;
import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService;
import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper;
import org.apache.fineract.infrastructure.core.api.JsonQuery;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.infrastructure.core.serialization.ToApiJsonSerializer;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.portfolio.collectionsheet.CollectionSheetConstants;
import org.apache.fineract.portfolio.collectionsheet.data.IndividualCollectionSheetData;
import org.apache.fineract.portfolio.collectionsheet.service.CollectionSheetReadPlatformService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.google.gson.JsonElement;

@Path("/collectionsheet")
@Component
@Scope("singleton")
public class CollectionSheetApiResourse {

    private final CollectionSheetReadPlatformService collectionSheetReadPlatformService;
    private final ToApiJsonSerializer<Object> toApiJsonSerializer;
    private final FromJsonHelper fromJsonHelper;
    private final ApiRequestParameterHelper apiRequestPrameterHelper;
    private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService;
    private final PlatformSecurityContext context;

    @Autowired
    public CollectionSheetApiResourse(final CollectionSheetReadPlatformService collectionSheetReadPlatformService,
            final ToApiJsonSerializer<Object> toApiJsonSerializer, final FromJsonHelper fromJsonHelper,
            final ApiRequestParameterHelper apiRequestPrameterHelper,
            final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context) {
        this.collectionSheetReadPlatformService = collectionSheetReadPlatformService;
        this.toApiJsonSerializer = toApiJsonSerializer;
        this.fromJsonHelper = fromJsonHelper;
        this.apiRequestPrameterHelper = apiRequestPrameterHelper;
        this.commandsSourceWritePlatformService = commandsSourceWritePlatformService;
        this.context = context;
    }

    @POST
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces({ MediaType.APPLICATION_JSON })
    public String generateCollectionSheet(@QueryParam("command") final String commandParam, final String apiRequestBodyAsJson,
            @Context final UriInfo uriInfo) {
        final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson);
        CommandProcessingResult result = null;

        if (is(commandParam, "generateCollectionSheet")) {
            this.context.authenticatedUser().validateHasReadPermission(CollectionSheetConstants.COLLECTIONSHEET_RESOURCE_NAME);
            final JsonElement parsedQuery = this.fromJsonHelper.parse(apiRequestBodyAsJson);
            final JsonQuery query = JsonQuery.from(apiRequestBodyAsJson, parsedQuery, this.fromJsonHelper);
            final IndividualCollectionSheetData collectionSheet = this.collectionSheetReadPlatformService
                    .generateIndividualCollectionSheet(query);
            final ApiRequestJsonSerializationSettings settings = this.apiRequestPrameterHelper.process(uriInfo.getQueryParameters());
            return this.toApiJsonSerializer.serialize(settings, collectionSheet);
        } else if (is(commandParam, "saveCollectionSheet")) {
            final CommandWrapper commandRequest = builder.saveIndividualCollectionSheet().build();
            result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
            return this.toApiJsonSerializer.serialize(result);
        }
        return null;
    }

    private boolean is(final String commandParam, final String commandValue) {
        return StringUtils.isNotBlank(commandParam) && commandParam.trim().equalsIgnoreCase(commandValue);
    }
}


text:
package com.example.coffee;

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

/**
 * Created by admin on 03/11/16.
 */

public class CafeTest {

    private final int ESPRESSO_BEANS = CoffeeType.Espresso.getRequiredBeans();
    private final int NO_MILK = 0;
    private final int NO_BEAN = 0;
    private final int LATTE_BEANS = CoffeeType.Latte.getRequiredBeans();
    private final int LATTE_MILK = CoffeeType.Latte.getRequiredMilk();

    private Cafe cafeWithBeans() {
        Cafe cafe = new Cafe();
        cafe.restockBean(ESPRESSO_BEANS);
        return cafe;
    }

    @Test
    public void canBrewEspresso() {

        //Given
        Cafe cafe = cafeWithBeans();

        //When
        Coffee coffee = cafe.brew(CoffeeType.Espresso);

        //Then
        Assert.assertEquals("Wrong coffee type", CoffeeType.Espresso, coffee.getCoffeeType());
        Assert.assertEquals("Wrong amount of milk", NO_MILK, coffee.getMilk());
        Assert.assertEquals("Wrong number of beans", ESPRESSO_BEANS, coffee.getBean());
    }

    @Test
    public void canBrewLatte() {

        //Given
        Cafe cafe = new Cafe();
        cafe.restockBean(LATTE_BEANS);
        cafe.restockMilk(LATTE_MILK);

        //When
        Coffee coffee = cafe.brew(CoffeeType.Latte);

        //Then
        Assert.assertEquals("Wrong coffee type", CoffeeType.Latte, coffee.getCoffeeType());
        Assert.assertEquals("Wrong amount of milk", LATTE_MILK, coffee.getMilk());
        Assert.assertEquals("Wrong number of beans", LATTE_BEANS, coffee.getBean());
    }

    @Test
    public void brewingEspressoConsumeBeans() {

        //Given
        Cafe cafe = cafeWithBeans();

        //When
        Coffee coffee = cafe.brew(CoffeeType.Espresso);

        //Then
        Assert.assertEquals(NO_MILK, cafe.getBeanInStock());
    }

    //Then
    @Test (expected = IllegalStateException.class)
    //@Test
    public void latteRequireMilk() {

        //Given
        Cafe cafe = cafeWithBeans();

        //When
        Coffee coffee = cafe.brew(CoffeeType.Latte);
    }
}


text:
import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

readme = open('README.rst').read()
doclink = """
Documentation
-------------

The full documentation is at http://pylunar.rtfd.org."""
history = open('HISTORY.rst').read().replace('.. :changelog:', '')

requirements = None
with open('requirements/prod.txt') as prodFile:
    requirements = [x.strip() for x in prodFile]

test_requirements = None
with open('requirements/test.txt') as testFile:
    test_requirements = [x.strip() for x in testFile]

setup(
    name='pylunar',
    version='0.6.0',
    description='Information for completing the Astronomical League\'s ' +
                'Lunar and Lunar II observing programs.',
    long_description=readme + '\n\n' + doclink + '\n\n' + history,
    author='Michael Reuter',
    author_email='mareuternh@gmail.com',
    url='https://github.com/mareuter/pylunar',
    packages=[
        'pylunar',
    ],
    package_dir={'pylunar': 'pylunar'},
    include_package_data=True,
    install_requires=requirements,
    license='BSD 3-Clause License',
    zip_safe=False,
    keywords='pylunar',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: Implementation :: PyPy',
    ],
    test_suite='tests',
    tests_require=test_requirements
)


text:
package au.com.dius.pact.provider.junitsupport.loader;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Defines the authentication scheme to use with URLs
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface Authentication {
  /**
   * Username to use for basic authentication
   */
  String username() default "";

  /**
   * Password to use for basic authentication
   */
  String password() default "";

  /**
   * Token to use for bearer token authentication
   */
  String token() default "";
}


text:
/**
 * angular2-google-maps - Angular 2 components for Google Maps
 * @version v0.13.0
 * @link https://github.com/SebastianM/angular2-google-maps#readme
 * @license MIT
 */
// exported map types

//# sourceMappingURL=map-types.js.map


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated 10-June-2008 10:07:39.8125000 -->
<!-- Generated by MathSBML 2.7.5 [2-May-2008] -->
<!-- Generated using Mathematica Version 5.2 for Microsoft Windows (June 20, 2005) -->
<sbml xmlns="http://www.sbml.org/sbml/level2/version3"
    level="2"
    version="3">
 <model id="case00813"
     name="case00813"
     metaid="_case00813">
  <!-- <listOfFunctionDefinitions/> -->
  <!-- <listOfUnitDefinitions/> -->
  <!-- <listOfCompartmentTypes/> -->
  <!-- <listOfSpeciesTypes/> -->
  <listOfCompartments>
   <compartment id="C"
       name="C"
       spatialDimensions="3"
       units="volume"
       size="2.3"/>
  </listOfCompartments>
  <listOfSpecies>
   <species id="S1"
       name="S1"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="1."
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S2"
       name="S2"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="0.5"
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
   <species id="S3"
       name="S3"
       compartment="C"
       boundaryCondition="false"
       constant="false"
       initialAmount="0."
       substanceUnits="substance"
       hasOnlySubstanceUnits="false"/>
  </listOfSpecies>
  <listOfParameters>
   <parameter id="kf"
       name="kf"
       value="1.1"/>
   <parameter id="kr"
       name="kr"
       value="0.09"/>
  </listOfParameters>
  <!-- <listOfInitialAssignments/> -->
  <!-- <listOfRules/> -->
  <!-- <listOfConstraints/> -->
  <listOfReactions>
   <reaction id="reaction1"
       name="reaction1"
       reversible="true"
       fast="false">
    <listOfReactants>
     <speciesReference species="S1"/>
     <speciesReference species="S2"/>
    </listOfReactants>
    <listOfProducts>
     <speciesReference species="S3"/>
    </listOfProducts>
    <!-- <listOfModifiers/> -->
    <kineticLaw>
     <math xmlns="http://www.w3.org/1998/Math/MathML">
      <apply>
       <times/>
       <ci>C</ci>
       <apply>
        <plus/>
        <apply>
         <times/>
         <ci>kf</ci>
         <ci>S1</ci>
         <ci>S2</ci>
        </apply>
        <apply>
         <times/>
         <cn type="integer">-1</cn>
         <apply>
          <times/>
          <ci>kr</ci>
          <ci>S3</ci>
         </apply>
        </apply>
       </apply>
      </apply>
     </math>
     <!-- <listOfParameters/> -->
    </kineticLaw>
   </reaction>
  </listOfReactions>
  <!-- <listOfEvents/> -->
 </model>
</sbml>