text:
  Notre-Dame-de-Monts est
      une ville située dans le département de Vendée en Pays de la Loire. On dénombrait 1 772 habitants en 2008.

Le nombre d'habitations, à Notre-Dame-de-Monts, était réparti en 2011 en 786 appartements et 2 544 maisons soit
 un marché plutôt équilibré.

À proximité de Notre-Dame-de-Monts sont localisées les villes de
Barbâtre localisée à 13 km, 1 710 habitants,
Le Perrier située à 10 km, 1 761 habitants,
Saint-Urbain à 10 km, 1 221 habitants,
Saint-Gervais située à 12 km, 2 064 habitants,
Saint-Jean-de-Monts située à 6 km, 7 650 habitants,
Sallertaine à 13 km, 2 628 habitants,
 entre autres. De plus, Notre-Dame-de-Monts est située à seulement 19 km de Challans.

À Notre-Dame-de-Monts, la valorisation moyenne à la vente d'un appartement s'évalue à 2 986 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 374 € du m². À la location la valeur moyenne se situe à 9,99 € du m² par mois.

La commune offre de multiples  équipements, elle propose entre autres un terrain de tennis, un terrain de sport, deux bases nautiques et deux boucles de randonnée.

redpajama_set_name: RedPajamaGithub


text:
The Nymbol JavaScript library is a really simple way of getting off the ground, with a remotely-hosted
PhoneGap app, or as a way of integrating your Nymbol collections with other websites.

## Usage

This library should be used with frameworks like PhoneGap, where access to the htML or JavaScript source
is not trivial. This library should *never* be used in a standard website environment, as authentication
details are passed in a manner than can be replicated by those able to view the source of the web page.

If you're in any way concerned about the security of your data, whether in a standard browser or an HTML5
app, you should consider making requests via the [PHP](https://github.com/Nymbol/nymbol-libraries/tree/master/php) library, and funnelling data between your HTML5 app and your PHP scripts.

## Requirements

Currently, the Nymbol JavaScript library requires jQuery for HTTP requests.

## Getting started

1. Download the nymbol.js file and put it somewhere in your project directory
2. Include a `<script>` tag in your HTML pointing to the JavaScript file
3. Visit <https://nymbol.co.uk/mobile/apps/> and create a new app
4. Click the name of the app and copy the key and secret for use later (see the first code example below)
5. Check out <http://nymbol.co.uk/develop/> for more documentation on the Nymbol API

## Basic usage

```javascript
var nymbol = new Nymbol('hash');
var assets = nymbol.assets.filter(
	{
		collection_id: 1
	} // Filter the query
).read(
	function(data) {
		// Callback
	},
	{
		thumbsize: '300x300',
		thumbdensity: 'high',
		rpp: 10
	} // Add options and pagination
);
```

## RequireJS

The plugin works with and without [RequireJS](http://requirejs.org/). If you use it, you can instantiate
the library like this:

```javascript
require(
	['nymbol'],
	function(Nymbol) {
		var nymbol = new Nymbol('hash');
		var assets = nymbol.assets.filter(
			{
				collection_id: 1
			} // Filter the query
		).read(
			function(data) {
				// Callback
			},
			{
				thumbsize: '300x300',
				thumbdensity: 'high',
				rpp: 10
			} // Add options and pagination
		);
	}
);
```

## Chaining filters

You can chain your filter expressions together, like this:

```javascript
var asset = nymbol.assets.filter(
	{
		collection_id: 1
	}
).filter(
	{
		id: 2 // Get a specific asset
	}
).read(
	function(data) {
		// Callback
	}
);
```

## More on filtering

Below is a list of the things you can query for, and the basic options that are available. The JavaScript
library uses these options to construct a URL, but you can also add further filtering options which are
appended to the API call via querystring parameters. Where you see them listed in the
[documentation](http://nymbol.co.uk/develop/), you can use those parameter names in your `filter()` or
`read(callback)` call.

## Query methods

You can query the following things:

### Collections

```javascript
nymbol.collections.read(callback);
```

#### Parameters

* `id` - (optional) ID of the collection

### Taxonomies

```javascript
nymbol.taxonomies.read(callback);
```

#### Parameters

* `collection_id` - (required) ID of the collection the taxonomy belongs to
* `id` - (optional) ID of the taxonomy

### Taxonomy terms

```javascript
nymbol.terms.read(callback);
```

#### Parameters

* `collection_id` - (required) ID of the collection the taxonomy and terms belong to
* `taxonomy_id` - (required) ID of the taxonomy the term belongs to
* `id` - (optional) ID of the term

### Assets

```javascript
nymbol.assets.read(callback);
```

#### Parameters

* `collection_id` - (required) ID of the collection the asset belongs to
* `id` - (optional) ID of the asset

### Resources

```javascript
nymbol.resources.read(callback);
```

#### Parameters

* `collection_id` - (required) ID of the collection the asset and resource belong to
* `asset_id` - (required) ID of the asset the resource belongs to
* `id` - (optional) ID of the resource

## Common query options

You can also specify the following options via the `read()` function:

* `rpp` - The number of items per page (defaults to 100)
* `page` - The page number, for paginating through results
* `thumbsize` - The size of thumbnails (all taxonomy and asset related API calls can return thumbnails)
* `thumbdensity` - The resolution of the thumbnail (`high`, `low` or `normal`)

Pass them in after the `callback` argument, like so:

```javascript
nymbol.assets.read(callback,
	{
		rpp: 10,
		thumbsize: '150x150'
	}
);
```

## Disabling SSL (not recommended)

By default, all API requests are performed over SSL. You can turn this off by setting the `nonSSL` option
when instantiating the `Nymbol` class.

```javascript
var nymbol = new Nymbol('hash',
	{
		nonSSL: true
	}
);
```

## To do

1. Add more query options


text:
package org.ihtsdo.otf.refset.jpa.helpers;

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

import org.apache.log4j.Logger;
import org.hibernate.search.annotations.Analyze;
import org.ihtsdo.otf.refset.helpers.ProxyTester;

/**
 * Automates JUnit testing of equals and hashcode methods.
 */
public class IndexedFieldTester extends ProxyTester {

  /**
   * Constructs a new getter/setter tester to test objects of a particular
   * class.
   *
   * @param obj Object fto test.
   */
  public IndexedFieldTester(Object obj) {
    super(obj);
  }

  /**
   * Test analyzed indexed fields.
   *
   * @return true, if successful
   * @throws Exception the exception
   */
  public boolean testAnalyzedIndexedFields() throws Exception {
    Logger.getLogger(getClass()).debug(
        "Test analyzed indexed fields - " + clazz.getName());

    Map<String, Boolean> analyzedFieldsMap = getAnalyzedFieldsMap(clazz);
    for (String field : includes) {
      boolean found = false;
      if (analyzedFieldsMap.containsKey(field)) {
        found = analyzedFieldsMap.get(field);
      }
      if (!found) {
        Logger.getLogger(getClass()).info(
            "  " + field + " is not defined as analyzed");
        return false;
      }
    }
    for (String field : analyzedFieldsMap.keySet()) {
      if (analyzedFieldsMap.get(field) && !includes.contains(field)) {
        Logger.getLogger(getClass()).info(
            "  " + field + " should be in the include list as analyzed");
        return false;
      }
    }

    return true;
  }

  /**
   * Test analyzed indexed fields.
   *
   * @return true, if successful
   * @throws Exception the exception
   */
  public boolean testNotAnalyzedIndexedFields() throws Exception {
    Logger.getLogger(getClass()).debug(
        "Test not analyzed indexed fields - " + clazz.getName());

    Map<String, Boolean> analyzedFieldsMap = getAnalyzedFieldsMap(clazz);
    for (String field : includes) {
      boolean found = true;
      if (analyzedFieldsMap.containsKey(field)) {
        found = analyzedFieldsMap.get(field);
      }
      if (found) {
        Logger.getLogger(getClass()).info(
            "  " + field + " is defined as analyzed");
        return false;
      }
    }
    for (String field : analyzedFieldsMap.keySet()) {
      if (!analyzedFieldsMap.get(field) && !includes.contains(field)) {
        Logger.getLogger(getClass()).info(
            "  " + field + " should be in the include list as not analyzed");
        return false;
      }
    }

    return true;
  }

  /**
   * Returns the name analyzed pairs from annotation.
   *
   * @param clazz the clazz
   * @return the name analyzed pairs from annotation
   * @throws NoSuchMethodException the no such method exception
   * @throws SecurityException the security exception
   */
  @SuppressWarnings("static-method")
  private Map<String, Boolean> getAnalyzedFieldsMap(Class<?> clazz)
    throws NoSuchMethodException, SecurityException {

    // initialize the name->analyzed pair map
    Map<String, Boolean> nameAnalyzedPairs = new HashMap<>();

    for (Method m : clazz.getMethods()) {

      // Look at "get" method sfor field annotations
      String fieldName = null;
      if (m.getName().startsWith("get")) {
        fieldName = m.getName().substring(3);
        fieldName =
            fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
      } else if (m.getName().startsWith("is")) {
        fieldName = m.getName().substring(2);
        fieldName =
            fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
      } else {
        continue;
      }

      // check for Field annotation
      if (m.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) {
        nameAnalyzedPairs.put(fieldName.toLowerCase(),
            m.getAnnotation(org.hibernate.search.annotations.Field.class)
                .analyze().equals(Analyze.YES));
      }

      // check for Fields annotation
      if (m.isAnnotationPresent(org.hibernate.search.annotations.Fields.class)) {
        // add all specified fields
        for (org.hibernate.search.annotations.Field f : m.getAnnotation(
            org.hibernate.search.annotations.Fields.class).value()) {
          if (f.name().equals("")) {
            nameAnalyzedPairs.put(fieldName.toLowerCase(),
                f.analyze().equals(Analyze.YES));
          } else {
            nameAnalyzedPairs.put(f.name().toLowerCase(),
                f.analyze().equals(Analyze.YES));
          }
        }
      }
    }
    return nameAnalyzedPairs;
  }

}


text:
package org.bouncycastle.pkcs;

import java.io.IOException;

import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.asn1.pkcs.CertBag;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.SafeBag;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.CertificateList;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.operator.OutputEncryptor;

public class PKCS12SafeBagBuilder
{
    private ASN1ObjectIdentifier bagType;
    private ASN1Encodable        bagValue;
    private ASN1EncodableVector  bagAttrs = new ASN1EncodableVector();

    public PKCS12SafeBagBuilder(PrivateKeyInfo privateKeyInfo, OutputEncryptor encryptor)
    {
        this.bagType = PKCSObjectIdentifiers.pkcs8ShroudedKeyBag;
        this.bagValue = new PKCS8EncryptedPrivateKeyInfoBuilder(privateKeyInfo).build(encryptor).toASN1Structure();
    }

    public PKCS12SafeBagBuilder(PrivateKeyInfo privateKeyInfo)
    {
        this.bagType = PKCSObjectIdentifiers.keyBag;
        this.bagValue = privateKeyInfo;
    }

    public PKCS12SafeBagBuilder(X509CertificateHolder certificate)
        throws IOException
    {
        this(certificate.toASN1Structure());
    }

    public PKCS12SafeBagBuilder(X509CRLHolder crl)
        throws IOException
    {
        this(crl.toASN1Structure());
    }

    public PKCS12SafeBagBuilder(Certificate certificate)
        throws IOException
    {
        this.bagType = PKCSObjectIdentifiers.certBag;
        this.bagValue = new CertBag(PKCSObjectIdentifiers.x509Certificate, new DEROctetString(certificate.getEncoded()));
    }

    public PKCS12SafeBagBuilder(CertificateList crl)
        throws IOException
    {
        this.bagType = PKCSObjectIdentifiers.crlBag;
        this.bagValue = new CertBag(PKCSObjectIdentifiers.x509Crl, new DEROctetString(crl.getEncoded()));
    }

    public PKCS12SafeBagBuilder addBagAttribute(ASN1ObjectIdentifier attrType, ASN1Encodable attrValue)
    {
        bagAttrs.add(new Attribute(attrType, new DERSet(attrValue)));

        return this;
    }

    public PKCS12SafeBag build()
    {
        return new PKCS12SafeBag(new SafeBag(bagType, bagValue, new DERSet(bagAttrs)));
    }
}


text:
package com.google.javascript.jscomp;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;
import com.google.javascript.rhino.Node;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link RecordFunctionInformation}
 *
 */

@RunWith(JUnit4.class)
public final class RecordFunctionInformationTest extends TestCase {

  @Test
  public void testFunction() {
    String g = "function g(){}";
    String fAndG = "function f(){" + g + "}";
    String js = "var h=" + fAndG + ";h()";

    FunctionInformationMap expected =
        FunctionInformationMap.newBuilder()
            .addEntry(
                FunctionInformationMap.Entry.newBuilder()
                    .setId(0)
                    .setSourceName("testcode")
                    .setLineNumber(1)
                    .setModuleName("")
                    .setSize(g.length())
                    .setName("f::g")
                    .setCompiledSource(g)
                    .build())
            .addEntry(
                FunctionInformationMap.Entry.newBuilder()
                    .setId(1)
                    .setSourceName("testcode")
                    .setLineNumber(1)
                    .setModuleName("")
                    .setSize(fAndG.length())
                    .setName("f")
                    .setCompiledSource(fAndG)
                    .build())
            .build();

    test(js, expected);
  }

  @Test
  public void testMotionPreservesOriginalSourceName() {
    String f = "function f(){}";
    String g = "function g(){}";

    String m0_before = f + g;
    String m1_before = "";

    JSModule[] modules = CompilerTestCase.createModules(m0_before, m1_before);
    Compiler compiler = compilerFor(modules);
    Node root = root(compiler);
    Node externsRoot = externs(root);
    Node mainRoot = main(root);

    Node nodeG = mainRoot.getFirstChild().getLastChild();
    mainRoot.getFirstChild().removeChild(nodeG);
    mainRoot.getLastChild().addChildToBack(nodeG.cloneTree());

    FunctionInformationMap expected =
        FunctionInformationMap.newBuilder()
            .addEntry(
                FunctionInformationMap.Entry.newBuilder()
                    .setId(0)
                    .setSourceName("i0.js")
                    .setLineNumber(1)
                    .setModuleName("m0")
                    .setSize(g.length())
                    .setName("f")
                    .setCompiledSource(f)
                    .build())
            .addEntry(
                FunctionInformationMap.Entry.newBuilder()
                    .setId(1)
                    .setSourceName("i0.js")
                    .setLineNumber(1)
                    .setModuleName("m1")
                    .setSize(g.length())
                    .setName("g")
                    .setCompiledSource(g)
                    .build())
            .build();

    test(compiler, externsRoot, mainRoot, expected);
  }

  private void test(String js, FunctionInformationMap expected) {
    Compiler compiler = new Compiler();
    CompilerOptions options = new CompilerOptions();
    options.setEmitUseStrict(false);
    compiler.init(ImmutableList.of(SourceFile.fromCode("externs", "")),
                  ImmutableList.of(SourceFile.fromCode("testcode", js)),
                  options);
    test(compiler, expected);
  }

  private void test(Compiler compiler, FunctionInformationMap expected) {
    Node root = root(compiler);
    test(compiler, externs(root), main(root), expected);
  }

  private void test(Compiler compiler, Node externsRoot, Node mainRoot,
      FunctionInformationMap expected) {
    CollectFunctionNames collectFunctionNames = new CollectFunctionNames(compiler);
    collectFunctionNames.process(externsRoot, mainRoot);

    RecordFunctionInformation processor =
        new RecordFunctionInformation(compiler, collectFunctionNames.getFunctionNames());
    processor.process(externsRoot, mainRoot);
    FunctionInformationMap result = processor.getMap();
    assertThat(result).isEqualTo(expected);
  }

  private Compiler compilerFor(JSModule[] modules) {
      Compiler compiler = new Compiler();
      CompilerOptions options = new CompilerOptions();
      options.setEmitUseStrict(false);
      compiler.initModules(
          ImmutableList.of(SourceFile.fromCode("externs", "")),
          ImmutableList.copyOf(modules),
          options);
      return compiler;
  }

  private Node root(Compiler compiler) {
    return compiler.parseInputs();
  }

  private Node externs(Node root) {
    return root.getFirstChild();
  }

  private Node main(Node root) {
    return root.getSecondChild();
  }
}


text:
//////////////////////////////////
//Auto-generated. Do NOT modify!//
//////////////////////////////////

import { MessageKey, QueryKey, Type, EnumType, registerSymbol } from './Reflection'
import * as Entities from './Signum.Entities'

export interface ModifiableEntity {
  Type: string;
  toStr: string;
  modified: boolean;
  isNew: boolean;
  error?: { [member: string]: string };
  readonlyProperties?: string[];
  mixins?: { [name: string]: MixinEntity }
}

export function liteKeyLong(lite: Lite<Entity>) {
  return lite.EntityType + ";" + (lite.id == undefined ? "" : lite.id) + ";" + getToString(lite);
}

export interface Entity extends ModifiableEntity {
  id: number | string | undefined;
  ticks: string; //max value
}

export interface EnumEntity<T> extends Entity {

}

export interface MixinEntity extends ModifiableEntity {
}

export function getMixin<M extends MixinEntity>(entity: ModifiableEntity, type: Type<M>): M {

  var mixin = tryGetMixin(entity, type);
  if (!mixin)
    throw new Error("Entity " + entity + " does not contain mixin " + type.typeName);
  return mixin;
}

export function tryGetMixin<M extends MixinEntity>(entity: ModifiableEntity, type: Type<M>): M | undefined {
  return entity.mixins && entity.mixins[type.typeName] as M;
}

export type MList<T> = Array<MListElement<T>>;

export interface MListElement<T> {
  rowId: number | string | null;
  element: T;
}

export function newMListElement<T>(element: T): MListElement<T> {
  return { rowId: null, element };
}

export function isMListElement(obj: unknown): obj is MListElement<unknown> {
  return obj != null && (obj as MListElement<unknown>).rowId !== undefined;
}

export function toMList<T>(array: T[]): MList<T> {
  return array.map(newMListElement);
}

export interface Lite<T extends Entity> {
  EntityType: string;
  id?: number | string;
  model?: unknown;

  ModelType?: string;
  entity?: T;
}

export interface ModelState {
  [field: string]: string[];
}

export interface EntityPack<T extends ModifiableEntity> {
  readonly entity: T
  readonly canExecute: { [key: string]: string };
}

//The interfaces add no real members, they are there just to force TS structural typing

export interface ExecuteSymbol<T extends Entity> extends OperationSymbol { _execute_: T /*TRICK*/ };
export interface DeleteSymbol<T extends Entity> extends OperationSymbol { _delete_: T /*TRICK*/ };
export interface ConstructSymbol_Simple<T extends Entity> extends OperationSymbol { _construct_: T /*TRICK*/ };
export interface ConstructSymbol_From<T extends Entity, F extends Entity> extends OperationSymbol { _constructFrom_: T, _from_?: F /*TRICK*/ };
export interface ConstructSymbol_FromMany<T extends Entity, F extends Entity> extends OperationSymbol { _constructFromMany_: T, _from_?: F /*TRICK*/ };

export const toStringDictionary: { [name: string]: ((entity: any) => string) | null } = {};

export function registerToString<T extends ModifiableEntity>(type: Type<T>, toStringFunc: ((e: T) => string) | null) {
  toStringDictionary[type.typeName] = toStringFunc as ((e: ModifiableEntity) => string) | null;
}

export function registerCustomModelConsturctor<T extends Entity, M extends ModelEntity>(type: Type<T>, modelType: Type<T>, constructLiteModel: ((e: T) => M)) {
  var ti = Reflection.tryGetTypeInfo(type.typeName);

  if (ti) {
    var clm = ti.customLiteModels?.[modelType.typeName];

    if (clm == null)
      throw new Error(`Type ${type.typeName} has no registered Lite Model '${modelType}'`);

    clm.constructorFunction = constructLiteModel as any as (e: Entity) => ModelEntity;
  }
}

import * as Reflection from './Reflection'
import { object } from 'prop-types';

export function newNiceName(ti: Reflection.TypeInfo) {
  return FrameMessage.New0_G.niceToString().forGenderAndNumber(ti.gender).formatWith(ti.niceName);
}

function createLiteModel(e: Entity, modelType?: string): ModelEntity | string {

  var ti = Reflection.tryGetTypeInfo(e.Type);

  if (ti == null)
    return getToString(e);

  modelType ??= getDefaultLiteModelType(ti);

  if (modelType == "string")
    return getToString(e);

  var clm = ti.customLiteModels?.[modelType];

  if (clm == null)
    throw new Error(`Type ${e.Type} has no registered Lite Model '${modelType}'`);

  if (clm.constructorFunction)
    return clm.constructorFunction(e);

  if (clm.constructorFunctionString == null)
    throw new Error(`No constructor function for '${modelType}' provided`);

  clm.constructorFunction = compileFunction(clm.constructorFunctionString);

  return clm.constructorFunction!(e);
}

function getDefaultLiteModelType(ti: Reflection.TypeInfo) {
  if (!ti.customLiteModels)
    return "string";

  return Object.keys(ti.customLiteModels).singleOrNull(modelType => ti.customLiteModels![modelType].isDefault) ?? "string"
}

function getOrCreateToStringFunction(type: string) {
  let f = toStringDictionary[type];
  if (f || f === null)
    return f;

  const ti = Reflection.tryGetTypeInfo(type);

  f = toStringDictionary[type] = ti?.toStringFunction ? compileFunction(ti.toStringFunction) : null;

  return f;
}

function compileFunction(functionString: string): (e: any) => any {

  var func = new Function("e", "fd", functionString);

  var funcDeps = {
    getToString: getToString,
    valToString: Reflection.valToString,
    numberToString: Reflection.numberToString,
    dateToString: Reflection.dateToString,
    timeToString: Reflection.timeToString,
    getTypeInfo: Reflection.getTypeInfo,
    newNiceName: newNiceName,
    New : Reflection.New,
    toLite: toLite,
  };

  return e => func(e, funcDeps);
}

export function getToString(entityOrLite: ModifiableEntity | Lite<Entity> | undefined | null, toStringLite?: (e : Entity) => string): string {
  if (entityOrLite == null)
    return "";

  const lite = entityOrLite as Lite<Entity>;
  if (lite.EntityType) {
    if (lite.entity)
      return (toStringLite || getToString)(lite.entity);

    if (Reflection.isLowPopulationSymbol(lite.EntityType))
      return Reflection.symbolNiceName(lite as Lite<Entity & Reflection.ISymbol>);

    if (typeof lite.model == "string")
      return lite.model;

    if (isModifiableEntity(lite.model))
      return getToString(lite.model);

    return lite.EntityType;
  }

  const entity = entityOrLite as ModifiableEntity;
  const toStrFunc = getOrCreateToStringFunction(entity.Type);
  if (toStrFunc)
    return toStrFunc(entity);

  if (Reflection.isLowPopulationSymbol(entity.Type))
    return Reflection.symbolNiceName(entity as Entity & Reflection.ISymbol);

  return entity.toStr || entity.Type;
}

export function toLite<T extends Entity>(entity: T, fat?: boolean, model?: unknown): Lite<T>;
export function toLite<T extends Entity>(entity: T | null | undefined, fat?: boolean, model?: unknown): Lite<T> | null;
export function toLite<T extends Entity>(entity: T | null | undefined, fat?: boolean, model?: unknown): Lite<T> | null {

  if (!entity)
    return null;
  if (fat)
    return toLiteFat(entity, model);

  if (entity.id == undefined)
    throw new Error(`The ${entity.Type} has no Id`);

  return {
    EntityType: entity.Type,
    id: entity.id,
    model: model || createLiteModel(entity),
  }
}

export function toLiteFat<T extends Entity>(entity: T, model?: unknown): Lite<T> {

  return {
    entity: entity,
    EntityType: entity.Type,
    id: entity.id,
    model: model || createLiteModel(entity),
  }
}

export function liteKey(lite: Lite<Entity>) {
  return lite.EntityType + ";" + (lite.id == undefined ? "" : lite.id);
}

export function parseLite(lite: string): Lite<Entity> {
  return {
    EntityType: lite.before(";"),
    id: lite.after(";"),
  };
}

export const liteKeyRegEx = /^([a-zA-Z]+)[;]([0-9a-zA-Z-]+)$/;
export function parseLiteList(text: string): Lite<Entity>[] {
  const lines = text.split("|");
  const liteKeys = lines.map(l => liteKeyRegEx.test(l) ? l : null).notNull();
  const lites = liteKeys.map(lk => parseLite(lk)).filter(l => isLite(l));

  return lites;
}

export function is<T extends Entity>(a: Lite<T> | T | null | undefined, b: Lite<T> | T | null | undefined, compareTicks = false, assertTypesFound = true) {

  if (a == undefined && b == undefined)
    return true;

  if (a == undefined || b == undefined)
    return false;

  const aType = (a as T).Type || (a as Lite<T>).EntityType;
  const bType = (b as T).Type || (b as Lite<T>).EntityType;

  if (!aType || !bType) {
    if (assertTypesFound)
      throw new Error("No Type found");
    else
      return false;
  }

  if (aType != bType)
    return false;

  if (a.id != undefined || b.id != undefined)
    return a.id == b.id && (!compareTicks || (a as T).ticks == (b as T).ticks);

  const aEntity = isEntity(a) ? a as unknown as T: a.entity;
  const bEntity = isEntity(b) ? b as unknown as T : b.entity;

  return aEntity == bEntity;
}

export function isLite(obj: any): obj is Lite<Entity> {
  return obj != null && (obj as Lite<Entity>).EntityType != undefined;
}

export function isModifiableEntity(obj: any): obj is ModifiableEntity {
return obj != null && (obj as ModifiableEntity).Type != undefined;
}

export function isEntity(obj: any): obj is Entity {
  if(!isModifiableEntity(obj))
    return false;
  const ti = Reflection.tryGetTypeInfo(obj.Type);
  return ti != null && ti.entityKind != null;
}

export function isEntityPack(obj: any): obj is EntityPack<ModifiableEntity> {
  return obj != null && (obj as EntityPack<ModifiableEntity>).entity != undefined &&
    (obj as EntityPack<ModifiableEntity>).canExecute !== undefined;
}

export function entityInfo(entity: ModifiableEntity | Lite<Entity> | null | undefined) {
  if (!entity)
    return "undefined";

  const type = isLite(entity) ? entity.EntityType : entity.Type;
  const id = isLite(entity) ? entity.id : isEntity(entity) ? entity.id : "";
  const isNew = isLite(entity) ? entity.entity && entity.entity.isNew : entity.isNew;

  return `${type};${id || ""};${isNew || ""}`;
}

export const BooleanEnum = new EnumType<BooleanEnum>("BooleanEnum");
export type BooleanEnum =
  "False" |
  "True";

export module CalendarMessage {
  export const Today = new MessageKey("CalendarMessage", "Today");
}

export const ComparisonType = new EnumType<ComparisonType>("ComparisonType");
export type ComparisonType =
  "EqualTo" |
  "DistinctTo" |
  "GreaterThan" |
  "GreaterThanOrEqualTo" |
  "LessThan" |
  "LessThanOrEqualTo";

export module ConnectionMessage {
  export const AConnectionWithTheServerIsNecessaryToContinue = new MessageKey("ConnectionMessage", "AConnectionWithTheServerIsNecessaryToContinue");
  export const SessionExpired = new MessageKey("ConnectionMessage", "SessionExpired");
  export const ANewVersionHasJustBeenDeployedSaveChangesAnd0 = new MessageKey("ConnectionMessage", "ANewVersionHasJustBeenDeployedSaveChangesAnd0");
  export const OutdatedClientApplication = new MessageKey("ConnectionMessage", "OutdatedClientApplication");
  export const ANewVersionHasJustBeenDeployedConsiderReload = new MessageKey("ConnectionMessage", "ANewVersionHasJustBeenDeployedConsiderReload");
  export const Refresh = new MessageKey("ConnectionMessage", "Refresh");
}

export const CorruptMixin = new Type<CorruptMixin>("CorruptMixin");
export interface CorruptMixin extends MixinEntity {
  Type: "CorruptMixin";
  corrupt: boolean;
}

export interface EmbeddedEntity extends ModifiableEntity {
}

export module EngineMessage {
  export const ConcurrencyErrorOnDatabaseTable0Id1 = new MessageKey("EngineMessage", "ConcurrencyErrorOnDatabaseTable0Id1");
  export const EntityWithType0AndId1NotFound = new MessageKey("EngineMessage", "EntityWithType0AndId1NotFound");
  export const NoWayOfMappingType0Found = new MessageKey("EngineMessage", "NoWayOfMappingType0Found");
  export const TheEntity0IsNew = new MessageKey("EngineMessage", "TheEntity0IsNew");
  export const ThereAre0ThatReferThisEntityByProperty1 = new MessageKey("EngineMessage", "ThereAre0ThatReferThisEntityByProperty1");
  export const ThereAreRecordsIn0PointingToThisTableByColumn1 = new MessageKey("EngineMessage", "ThereAreRecordsIn0PointingToThisTableByColumn1");
  export const UnauthorizedAccessTo0Because1 = new MessageKey("EngineMessage", "UnauthorizedAccessTo0Because1");
  export const TheresAlreadyA0With1EqualsTo2_G = new MessageKey("EngineMessage", "TheresAlreadyA0With1EqualsTo2_G");
}

export module EntityControlMessage {
  export const Create = new MessageKey("EntityControlMessage", "Create");
  export const Find = new MessageKey("EntityControlMessage", "Find");
  export const Detail = new MessageKey("EntityControlMessage", "Detail");
  export const MoveDown = new MessageKey("EntityControlMessage", "MoveDown");
  export const MoveUp = new MessageKey("EntityControlMessage", "MoveUp");
  export const MoveRight = new MessageKey("EntityControlMessage", "MoveRight");
  export const MoveLeft = new MessageKey("EntityControlMessage", "MoveLeft");
  export const Move = new MessageKey("EntityControlMessage", "Move");
  export const MoveWithDragAndDropOrCtrlUpDown = new MessageKey("EntityControlMessage", "MoveWithDragAndDropOrCtrlUpDown");
  export const MoveWithDragAndDropOrCtrlLeftRight = new MessageKey("EntityControlMessage", "MoveWithDragAndDropOrCtrlLeftRight");
  export const Navigate = new MessageKey("EntityControlMessage", "Navigate");
  export const Remove = new MessageKey("EntityControlMessage", "Remove");
  export const View = new MessageKey("EntityControlMessage", "View");
  export const Add = new MessageKey("EntityControlMessage", "Add");
  export const Paste = new MessageKey("EntityControlMessage", "Paste");
}

export module FrameMessage {
  export const New0_G = new MessageKey("FrameMessage", "New0_G");
  export const Copied = new MessageKey("FrameMessage", "Copied");
  export const Fullscreen = new MessageKey("FrameMessage", "Fullscreen");
  export const ThereAreErrors = new MessageKey("FrameMessage", "ThereAreErrors");
  export const Main = new MessageKey("FrameMessage", "Main");
}

export interface ImmutableEntity extends Entity {
  allowChange: boolean;
}

export module JavascriptMessage {
  export const chooseAType = new MessageKey("JavascriptMessage", "chooseAType");
  export const chooseAValue = new MessageKey("JavascriptMessage", "chooseAValue");
  export const addFilter = new MessageKey("JavascriptMessage", "addFilter");
  export const openTab = new MessageKey("JavascriptMessage", "openTab");
  export const error = new MessageKey("JavascriptMessage", "error");
  export const executed = new MessageKey("JavascriptMessage", "executed");
  export const hideFilters = new MessageKey("JavascriptMessage", "hideFilters");
  export const showFilters = new MessageKey("JavascriptMessage", "showFilters");
  export const groupResults = new MessageKey("JavascriptMessage", "groupResults");
  export const ungroupResults = new MessageKey("JavascriptMessage", "ungroupResults");
  export const ShowGroup = new MessageKey("JavascriptMessage", "ShowGroup");
  export const activateTimeMachine = new MessageKey("JavascriptMessage", "activateTimeMachine");
  export const deactivateTimeMachine = new MessageKey("JavascriptMessage", "deactivateTimeMachine");
  export const showRecords = new MessageKey("JavascriptMessage", "showRecords");
  export const joinMode = new MessageKey("JavascriptMessage", "joinMode");
  export const loading = new MessageKey("JavascriptMessage", "loading");
  export const noActionsFound = new MessageKey("JavascriptMessage", "noActionsFound");
  export const saveChangesBeforeOrPressCancel = new MessageKey("JavascriptMessage", "saveChangesBeforeOrPressCancel");
  export const loseCurrentChanges = new MessageKey("JavascriptMessage", "loseCurrentChanges");
  export const noElementsSelected = new MessageKey("JavascriptMessage", "noElementsSelected");
  export const searchForResults = new MessageKey("JavascriptMessage", "searchForResults");
  export const selectOnlyOneElement = new MessageKey("JavascriptMessage", "selectOnlyOneElement");
  export const popupErrors = new MessageKey("JavascriptMessage", "popupErrors");
  export const popupErrorsStop = new MessageKey("JavascriptMessage", "popupErrorsStop");
  export const insertColumn = new MessageKey("JavascriptMessage", "insertColumn");
  export const editColumn = new MessageKey("JavascriptMessage", "editColumn");
  export const removeColumn = new MessageKey("JavascriptMessage", "removeColumn");
  export const groupByThisColumn = new MessageKey("JavascriptMessage", "groupByThisColumn");
  export const restoreDefaultColumns = new MessageKey("JavascriptMessage", "restoreDefaultColumns");
  export const saved = new MessageKey("JavascriptMessage", "saved");
  export const search = new MessageKey("JavascriptMessage", "search");
  export const Selected = new MessageKey("JavascriptMessage", "Selected");
  export const selectToken = new MessageKey("JavascriptMessage", "selectToken");
  export const find = new MessageKey("JavascriptMessage", "find");
  export const remove = new MessageKey("JavascriptMessage", "remove");
  export const view = new MessageKey("JavascriptMessage", "view");
  export const create = new MessageKey("JavascriptMessage", "create");
  export const moveDown = new MessageKey("JavascriptMessage", "moveDown");
  export const moveUp = new MessageKey("JavascriptMessage", "moveUp");
  export const navigate = new MessageKey("JavascriptMessage", "navigate");
  export const newEntity = new MessageKey("JavascriptMessage", "newEntity");
  export const ok = new MessageKey("JavascriptMessage", "ok");
  export const cancel = new MessageKey("JavascriptMessage", "cancel");
  export const showPeriod = new MessageKey("JavascriptMessage", "showPeriod");
  export const showPreviousOperation = new MessageKey("JavascriptMessage", "showPreviousOperation");
  export const Date = new MessageKey("JavascriptMessage", "Date");
}

export module LiteMessage {
  export const IdNotValid = new MessageKey("LiteMessage", "IdNotValid");
  export const InvalidFormat = new MessageKey("LiteMessage", "InvalidFormat");
  export const Type0NotFound = new MessageKey("LiteMessage", "Type0NotFound");
  export const ToStr = new MessageKey("LiteMessage", "ToStr");
}

export interface ModelEntity extends ModifiableEntity {
}

export module NormalControlMessage {
  export const ViewForType0IsNotAllowed = new MessageKey("NormalControlMessage", "ViewForType0IsNotAllowed");
  export const SaveChangesFirst = new MessageKey("NormalControlMessage", "SaveChangesFirst");
  export const CopyEntityTypeAndIdForAutocomplete = new MessageKey("NormalControlMessage", "CopyEntityTypeAndIdForAutocomplete");
  export const CopyEntityUrl = new MessageKey("NormalControlMessage", "CopyEntityUrl");
}

export module OperationMessage {
  export const Create = new MessageKey("OperationMessage", "Create");
  export const CreateFromRegex = new MessageKey("OperationMessage", "CreateFromRegex");
  export const Create0 = new MessageKey("OperationMessage", "Create0");
  export const StateShouldBe0InsteadOf1 = new MessageKey("OperationMessage", "StateShouldBe0InsteadOf1");
  export const TheStateOf0ShouldBe1InsteadOf2 = new MessageKey("OperationMessage", "TheStateOf0ShouldBe1InsteadOf2");
  export const InUserInterface = new MessageKey("OperationMessage", "InUserInterface");
  export const Operation01IsNotAuthorized = new MessageKey("OperationMessage", "Operation01IsNotAuthorized");
  export const Confirm = new MessageKey("OperationMessage", "Confirm");
  export const PleaseConfirmYouWouldLikeToDelete0FromTheSystem = new MessageKey("OperationMessage", "PleaseConfirmYouWouldLikeToDelete0FromTheSystem");
  export const PleaseConfirmYouWouldLikeTo01 = new MessageKey("OperationMessage", "PleaseConfirmYouWouldLikeTo01");
  export const TheOperation0DidNotReturnAnEntity = new MessageKey("OperationMessage", "TheOperation0DidNotReturnAnEntity");
  export const Logs = new MessageKey("OperationMessage", "Logs");
  export const PreviousOperationLog = new MessageKey("OperationMessage", "PreviousOperationLog");
  export const _0AndClose = new MessageKey("OperationMessage", "_0AndClose");
  export const _0AndNew = new MessageKey("OperationMessage", "_0AndNew");
  export const BulkModifications = new MessageKey("OperationMessage", "BulkModifications");
  export const PleaseConfirmThatYouWouldLikeToApplyTheAboveChangesAndExecute0Over12 = new MessageKey("OperationMessage", "PleaseConfirmThatYouWouldLikeToApplyTheAboveChangesAndExecute0Over12");
  export const Condition = new MessageKey("OperationMessage", "Condition");
  export const Setters = new MessageKey("OperationMessage", "Setters");
  export const AddSetter = new MessageKey("OperationMessage", "AddSetter");
  export const MultiSetter = new MessageKey("OperationMessage", "MultiSetter");
  export const Deleting = new MessageKey("OperationMessage", "Deleting");
  export const Executing0 = new MessageKey("OperationMessage", "Executing0");
  export const _0Errors = new MessageKey("OperationMessage", "_0Errors");
}

export const OperationSymbol = new Type<OperationSymbol>("Operation");
export interface OperationSymbol extends Symbol {
  Type: "Operation";
}

export const OperationType = new EnumType<OperationType>("OperationType");
export type OperationType =
  "Execute" |
  "Delete" |
  "Constructor" |
  "ConstructorFrom" |
  "ConstructorFromMany";

export module PaginationMessage {
  export const All = new MessageKey("PaginationMessage", "All");
}

export const PropertyOperation = new EnumType<PropertyOperation>("PropertyOperation");
export type PropertyOperation =
  "Set" |
  "AddElement" |
  "AddNewElement" |
  "ChangeElements" |
  "RemoveElement" |
  "RemoveElementsWhere" |
  "ModifyEntity" |
  "CreateNewEntity";

export module QuickLinkMessage {
  export const Quicklinks = new MessageKey("QuickLinkMessage", "Quicklinks");
  export const No0Found = new MessageKey("QuickLinkMessage", "No0Found");
}

export module ReactWidgetsMessage {
  export const MoveToday = new MessageKey("ReactWidgetsMessage", "MoveToday");
  export const MoveBack = new MessageKey("ReactWidgetsMessage", "MoveBack");
  export const MoveForward = new MessageKey("ReactWidgetsMessage", "MoveForward");
  export const DateButton = new MessageKey("ReactWidgetsMessage", "DateButton");
  export const OpenCombobox = new MessageKey("ReactWidgetsMessage", "OpenCombobox");
  export const FilterPlaceholder = new MessageKey("ReactWidgetsMessage", "FilterPlaceholder");
  export const EmptyList = new MessageKey("ReactWidgetsMessage", "EmptyList");
  export const EmptyFilter = new MessageKey("ReactWidgetsMessage", "EmptyFilter");
  export const CreateOption = new MessageKey("ReactWidgetsMessage", "CreateOption");
  export const CreateOption0 = new MessageKey("ReactWidgetsMessage", "CreateOption0");
  export const TagsLabel = new MessageKey("ReactWidgetsMessage", "TagsLabel");
  export const RemoveLabel = new MessageKey("ReactWidgetsMessage", "RemoveLabel");
  export const NoneSelected = new MessageKey("ReactWidgetsMessage", "NoneSelected");
  export const SelectedItems0 = new MessageKey("ReactWidgetsMessage", "SelectedItems0");
  export const IncrementValue = new MessageKey("ReactWidgetsMessage", "IncrementValue");
  export const DecrementValue = new MessageKey("ReactWidgetsMessage", "DecrementValue");
}

export module SaveChangesMessage {
  export const ThereAreChanges = new MessageKey("SaveChangesMessage", "ThereAreChanges");
  export const YoureTryingToCloseAnEntityWithChanges = new MessageKey("SaveChangesMessage", "YoureTryingToCloseAnEntityWithChanges");
  export const LoseChanges = new MessageKey("SaveChangesMessage", "LoseChanges");
}

export module SearchMessage {
  export const ChooseTheDisplayNameOfTheNewColumn = new MessageKey("SearchMessage", "ChooseTheDisplayNameOfTheNewColumn");
  export const Field = new MessageKey("SearchMessage", "Field");
  export const AddColumn = new MessageKey("SearchMessage", "AddColumn");
  export const CollectionsCanNotBeAddedAsColumns = new MessageKey("SearchMessage", "CollectionsCanNotBeAddedAsColumns");
  export const InvalidColumnExpression = new MessageKey("SearchMessage", "InvalidColumnExpression");
  export const AddFilter = new MessageKey("SearchMessage", "AddFilter");
  export const AddGroup = new MessageKey("SearchMessage", "AddGroup");
  export const AddValue = new MessageKey("SearchMessage", "AddValue");
  export const DeleteFilter = new MessageKey("SearchMessage", "DeleteFilter");
  export const DeleteAllFilter = new MessageKey("SearchMessage", "DeleteAllFilter");
  export const Filters = new MessageKey("SearchMessage", "Filters");
  export const Find = new MessageKey("SearchMessage", "Find");
  export const FinderOf0 = new MessageKey("SearchMessage", "FinderOf0");
  export const Name = new MessageKey("SearchMessage", "Name");
  export const NewColumnSName = new MessageKey("SearchMessage", "NewColumnSName");
  export const NoActionsFound = new MessageKey("SearchMessage", "NoActionsFound");
  export const NoColumnSelected = new MessageKey("SearchMessage", "NoColumnSelected");
  export const NoFiltersSpecified = new MessageKey("SearchMessage", "NoFiltersSpecified");
  export const Of = new MessageKey("SearchMessage", "Of");
  export const Operation = new MessageKey("SearchMessage", "Operation");
  export const Query0IsNotAllowed = new MessageKey("SearchMessage", "Query0IsNotAllowed");
  export const Query0NotAllowed = new MessageKey("SearchMessage", "Query0NotAllowed");
  export const Query0NotRegistered = new MessageKey("SearchMessage", "Query0NotRegistered");
  export const Rename = new MessageKey("SearchMessage", "Rename");
  export const _0Results_N = new MessageKey("SearchMessage", "_0Results_N");
  export const First0Results_N = new MessageKey("SearchMessage", "First0Results_N");
  export const _01of2Results_N = new MessageKey("SearchMessage", "_01of2Results_N");
  export const Search = new MessageKey("SearchMessage", "Search");
  export const Refresh = new MessageKey("SearchMessage", "Refresh");
  export const Create = new MessageKey("SearchMessage", "Create");
  export const CreateNew0_G = new MessageKey("SearchMessage", "CreateNew0_G");
  export const ThereIsNo0 = new MessageKey("SearchMessage", "ThereIsNo0");
  export const Value = new MessageKey("SearchMessage", "Value");
  export const View = new MessageKey("SearchMessage", "View");
  export const ViewSelected = new MessageKey("SearchMessage", "ViewSelected");
  export const Operations = new MessageKey("SearchMessage", "Operations");
  export const NoResultsFound = new MessageKey("SearchMessage", "NoResultsFound");
  export const NoResultsInThisPage = new MessageKey("SearchMessage", "NoResultsInThisPage");
  export const NoResultsFoundInPage01 = new MessageKey("SearchMessage", "NoResultsFoundInPage01");
  export const GoBackToPageOne = new MessageKey("SearchMessage", "GoBackToPageOne");
  export const Explore = new MessageKey("SearchMessage", "Explore");
  export const PinnedFilter = new MessageKey("SearchMessage", "PinnedFilter");
  export const Label = new MessageKey("SearchMessage", "Label");
  export const Column = new MessageKey("SearchMessage", "Column");
  export const Row = new MessageKey("SearchMessage", "Row");
  export const SplitText = new MessageKey("SearchMessage", "SplitText");
  export const WhenPressedTheFilterWillTakeNoEffectIfTheValueIsNull = new MessageKey("SearchMessage", "WhenPressedTheFilterWillTakeNoEffectIfTheValueIsNull");
  export const WhenPressedTheFilterValueWillBeSplittedAndAllTheWordsHaveToBeFound = new MessageKey("SearchMessage", "WhenPressedTheFilterValueWillBeSplittedAndAllTheWordsHaveToBeFound");
  export const ParentValue = new MessageKey("SearchMessage", "ParentValue");
  export const PleaseSelectA0_G = new MessageKey("SearchMessage", "PleaseSelectA0_G");
  export const PleaseSelectOneOrMore0_G = new MessageKey("SearchMessage", "PleaseSelectOneOrMore0_G");
  export const PleaseSelectAnEntity = new MessageKey("SearchMessage", "PleaseSelectAnEntity");
  export const PleaseSelectOneOrSeveralEntities = new MessageKey("SearchMessage", "PleaseSelectOneOrSeveralEntities");
  export const _0FiltersCollapsed = new MessageKey("SearchMessage", "_0FiltersCollapsed");
  export const DisplayName = new MessageKey("SearchMessage", "DisplayName");
  export const ToPreventPerformanceIssuesAutomaticSearchIsDisabledCheckYourFiltersAndThenClickSearchButton = new MessageKey("SearchMessage", "ToPreventPerformanceIssuesAutomaticSearchIsDisabledCheckYourFiltersAndThenClickSearchButton");
  export const PaginationAll_0Elements = new MessageKey("SearchMessage", "PaginationAll_0Elements");
  export const PaginationPages_0Of01lements = new MessageKey("SearchMessage", "PaginationPages_0Of01lements");
  export const PaginationFirst_01Elements = new MessageKey("SearchMessage", "PaginationFirst_01Elements");
  export const ReturnNewEntity = new MessageKey("SearchMessage", "ReturnNewEntity");
  export const DoYouWantToSelectTheNew01_G = new MessageKey("SearchMessage", "DoYouWantToSelectTheNew01_G");
  export const ShowPinnedFiltersOptions = new MessageKey("SearchMessage", "ShowPinnedFiltersOptions");
  export const HidePinnedFiltersOptions = new MessageKey("SearchMessage", "HidePinnedFiltersOptions");
  export const SummaryHeader = new MessageKey("SearchMessage", "SummaryHeader");
  export const SummaryHeaderMustBeAnAggregate = new MessageKey("SearchMessage", "SummaryHeaderMustBeAnAggregate");
  export const HiddenColumn = new MessageKey("SearchMessage", "HiddenColumn");
  export const ShowHiddenColumns = new MessageKey("SearchMessage", "ShowHiddenColumns");
  export const HideHiddenColumns = new MessageKey("SearchMessage", "HideHiddenColumns");
  export const GroupKey = new MessageKey("SearchMessage", "GroupKey");
  export const DerivedGroupKey = new MessageKey("SearchMessage", "DerivedGroupKey");
  export const Copy = new MessageKey("SearchMessage", "Copy");
  export const MoreThanOne0Selected = new MessageKey("SearchMessage", "MoreThanOne0Selected");
}

export module SelectorMessage {
  export const ConstructorSelector = new MessageKey("SelectorMessage", "ConstructorSelector");
  export const PleaseChooseAValueToContinue = new MessageKey("SelectorMessage", "PleaseChooseAValueToContinue");
  export const PleaseSelectAConstructor = new MessageKey("SelectorMessage", "PleaseSelectAConstructor");
  export const PleaseSelectAType = new MessageKey("SelectorMessage", "PleaseSelectAType");
  export const TypeSelector = new MessageKey("SelectorMessage", "TypeSelector");
  export const ValueMustBeSpecifiedFor0 = new MessageKey("SelectorMessage", "ValueMustBeSpecifiedFor0");
  export const ChooseAValue = new MessageKey("SelectorMessage", "ChooseAValue");
  export const SelectAnElement = new MessageKey("SelectorMessage", "SelectAnElement");
  export const PleaseSelectAnElement = new MessageKey("SelectorMessage", "PleaseSelectAnElement");
  export const _0Selector = new MessageKey("SelectorMessage", "_0Selector");
  export const PleaseChooseA0ToContinue = new MessageKey("SelectorMessage", "PleaseChooseA0ToContinue");
  export const CreationOf0Cancelled = new MessageKey("SelectorMessage", "CreationOf0Cancelled");
  export const ChooseValues = new MessageKey("SelectorMessage", "ChooseValues");
  export const PleaseSelectAtLeastOneValueToContinue = new MessageKey("SelectorMessage", "PleaseSelectAtLeastOneValueToContinue");
}

export interface Symbol extends Entity {
  key: string;
}

export module SynchronizerMessage {
  export const EndOfSyncScript = new MessageKey("SynchronizerMessage", "EndOfSyncScript");
  export const StartOfSyncScriptGeneratedOn0 = new MessageKey("SynchronizerMessage", "StartOfSyncScriptGeneratedOn0");
}

export module ValidationMessage {
  export const _0DoesNotHaveAValid1Format = new MessageKey("ValidationMessage", "_0DoesNotHaveAValid1Format");
  export const _0DoesNotHaveAValid1IdentifierFormat = new MessageKey("ValidationMessage", "_0DoesNotHaveAValid1IdentifierFormat");
  export const _0HasAnInvalidFormat = new MessageKey("ValidationMessage", "_0HasAnInvalidFormat");
  export const _0HasMoreThan1DecimalPlaces = new MessageKey("ValidationMessage", "_0HasMoreThan1DecimalPlaces");
  export const _0HasSomeRepeatedElements1 = new MessageKey("ValidationMessage", "_0HasSomeRepeatedElements1");
  export const _0ShouldBe12 = new MessageKey("ValidationMessage", "_0ShouldBe12");
  export const _0ShouldBe1 = new MessageKey("ValidationMessage", "_0ShouldBe1");
  export const _0ShouldBe1InsteadOf2 = new MessageKey("ValidationMessage", "_0ShouldBe1InsteadOf2");
  export const _0HasToBeBetween1And2 = new MessageKey("ValidationMessage", "_0HasToBeBetween1And2");
  export const _0HasToBeLowercase = new MessageKey("ValidationMessage", "_0HasToBeLowercase");
  export const _0HasToBeUppercase = new MessageKey("ValidationMessage", "_0HasToBeUppercase");
  export const _0IsNecessary = new MessageKey("ValidationMessage", "_0IsNecessary");
  export const _0IsNecessaryOnState1 = new MessageKey("ValidationMessage", "_0IsNecessaryOnState1");
  export const _0IsNotAllowed = new MessageKey("ValidationMessage", "_0IsNotAllowed");
  export const _0IsNotAllowedOnState1 = new MessageKey("ValidationMessage", "_0IsNotAllowedOnState1");
  export const _0IsNotSet = new MessageKey("ValidationMessage", "_0IsNotSet");
  export const _0IsNotSetIn1 = new MessageKey("ValidationMessage", "_0IsNotSetIn1");
  export const _0AreNotSet = new MessageKey("ValidationMessage", "_0AreNotSet");
  export const _0IsSet = new MessageKey("ValidationMessage", "_0IsSet");
  export const _0IsNotA1_G = new MessageKey("ValidationMessage", "_0IsNotA1_G");
  export const BeA0_G = new MessageKey("ValidationMessage", "BeA0_G");
  export const Be0 = new MessageKey("ValidationMessage", "Be0");
  export const BeBetween0And1 = new MessageKey("ValidationMessage", "BeBetween0And1");
  export const BeNotNull = new MessageKey("ValidationMessage", "BeNotNull");
  export const FileName = new MessageKey("ValidationMessage", "FileName");
  export const Have0Decimals = new MessageKey("ValidationMessage", "Have0Decimals");
  export const HaveANumberOfElements01 = new MessageKey("ValidationMessage", "HaveANumberOfElements01");
  export const HaveAPrecisionOf0 = new MessageKey("ValidationMessage", "HaveAPrecisionOf0");
  export const HaveBetween0And1Characters = new MessageKey("ValidationMessage", "HaveBetween0And1Characters");
  export const HaveMaximum0Characters = new MessageKey("ValidationMessage", "HaveMaximum0Characters");
  export const HaveMinimum0Characters = new MessageKey("ValidationMessage", "HaveMinimum0Characters");
  export const HaveNoRepeatedElements = new MessageKey("ValidationMessage", "HaveNoRepeatedElements");
  export const HaveValid0Format = new MessageKey("ValidationMessage", "HaveValid0Format");
  export const InvalidDateFormat = new MessageKey("ValidationMessage", "InvalidDateFormat");
  export const InvalidFormat = new MessageKey("ValidationMessage", "InvalidFormat");
  export const NotPossibleToaAssign0 = new MessageKey("ValidationMessage", "NotPossibleToaAssign0");
  export const Numeric = new MessageKey("ValidationMessage", "Numeric");
  export const OrBeNull = new MessageKey("ValidationMessage", "OrBeNull");
  export const Telephone = new MessageKey("ValidationMessage", "Telephone");
  export const _0ShouldHaveJustOneLine = new MessageKey("ValidationMessage", "_0ShouldHaveJustOneLine");
  export const _0ShouldNotHaveInitialSpaces = new MessageKey("ValidationMessage", "_0ShouldNotHaveInitialSpaces");
  export const _0ShouldNotHaveFinalSpaces = new MessageKey("ValidationMessage", "_0ShouldNotHaveFinalSpaces");
  export const TheLenghtOf0HasToBeEqualTo1 = new MessageKey("ValidationMessage", "TheLenghtOf0HasToBeEqualTo1");
  export const TheLengthOf0HasToBeGreaterOrEqualTo1 = new MessageKey("ValidationMessage", "TheLengthOf0HasToBeGreaterOrEqualTo1");
  export const TheLengthOf0HasToBeLesserOrEqualTo1 = new MessageKey("ValidationMessage", "TheLengthOf0HasToBeLesserOrEqualTo1");
  export const TheNumberOf0IsBeingMultipliedBy1 = new MessageKey("ValidationMessage", "TheNumberOf0IsBeingMultipliedBy1");
  export const TheRowsAreBeingGroupedBy0 = new MessageKey("ValidationMessage", "TheRowsAreBeingGroupedBy0");
  export const TheNumberOfElementsOf0HasToBe12 = new MessageKey("ValidationMessage", "TheNumberOfElementsOf0HasToBe12");
  export const Type0NotAllowed = new MessageKey("ValidationMessage", "Type0NotAllowed");
  export const _0IsMandatoryWhen1IsNotSet = new MessageKey("ValidationMessage", "_0IsMandatoryWhen1IsNotSet");
  export const _0IsMandatoryWhen1IsNotSetTo2 = new MessageKey("ValidationMessage", "_0IsMandatoryWhen1IsNotSetTo2");
  export const _0IsMandatoryWhen1IsSet = new MessageKey("ValidationMessage", "_0IsMandatoryWhen1IsSet");
  export const _0IsMandatoryWhen1IsSetTo2 = new MessageKey("ValidationMessage", "_0IsMandatoryWhen1IsSetTo2");
  export const _0ShouldBeNullWhen1IsNotSet = new MessageKey("ValidationMessage", "_0ShouldBeNullWhen1IsNotSet");
  export const _0ShouldBeNullWhen1IsNotSetTo2 = new MessageKey("ValidationMessage", "_0ShouldBeNullWhen1IsNotSetTo2");
  export const _0ShouldBeNullWhen1IsSet = new MessageKey("ValidationMessage", "_0ShouldBeNullWhen1IsSet");
  export const _0ShouldBeNullWhen1IsSetTo2 = new MessageKey("ValidationMessage", "_0ShouldBeNullWhen1IsSetTo2");
  export const _0ShouldBeNull = new MessageKey("ValidationMessage", "_0ShouldBeNull");
  export const _0ShouldBeADateInThePast = new MessageKey("ValidationMessage", "_0ShouldBeADateInThePast");
  export const BeInThePast = new MessageKey("ValidationMessage", "BeInThePast");
  export const _0ShouldBeGreaterThan1 = new MessageKey("ValidationMessage", "_0ShouldBeGreaterThan1");
  export const _0ShouldBeGreaterThanOrEqual1 = new MessageKey("ValidationMessage", "_0ShouldBeGreaterThanOrEqual1");
  export const _0ShouldBeLessThan1 = new MessageKey("ValidationMessage", "_0ShouldBeLessThan1");
  export const _0ShouldBeLessThanOrEqual1 = new MessageKey("ValidationMessage", "_0ShouldBeLessThanOrEqual1");
  export const _0HasAPrecisionOf1InsteadOf2 = new MessageKey("ValidationMessage", "_0HasAPrecisionOf1InsteadOf2");
  export const _0ShouldBeOfType1 = new MessageKey("ValidationMessage", "_0ShouldBeOfType1");
  export const _0ShouldNotBeOfType1 = new MessageKey("ValidationMessage", "_0ShouldNotBeOfType1");
  export const _0And1CanNotBeSetAtTheSameTime = new MessageKey("ValidationMessage", "_0And1CanNotBeSetAtTheSameTime");
  export const _0Or1ShouldBeSet = new MessageKey("ValidationMessage", "_0Or1ShouldBeSet");
  export const _0And1And2CanNotBeSetAtTheSameTime = new MessageKey("ValidationMessage", "_0And1And2CanNotBeSetAtTheSameTime");
  export const _0Have1ElementsButAllowedOnly2 = new MessageKey("ValidationMessage", "_0Have1ElementsButAllowedOnly2");
  export const _0IsEmpty = new MessageKey("ValidationMessage", "_0IsEmpty");
  export const _0ShouldBeEmpty = new MessageKey("ValidationMessage", "_0ShouldBeEmpty");
  export const _AtLeastOneValueIsNeeded = new MessageKey("ValidationMessage", "_AtLeastOneValueIsNeeded");
  export const PowerOf = new MessageKey("ValidationMessage", "PowerOf");
  export const BeAString = new MessageKey("ValidationMessage", "BeAString");
  export const BeAMultilineString = new MessageKey("ValidationMessage", "BeAMultilineString");
  export const IsATimeOfTheDay = new MessageKey("ValidationMessage", "IsATimeOfTheDay");
  export const ThereAre0InState1 = new MessageKey("ValidationMessage", "ThereAre0InState1");
  export const ThereAre0ThatReferenceThis1 = new MessageKey("ValidationMessage", "ThereAre0ThatReferenceThis1");
  export const _0IsNotCompatibleWith1 = new MessageKey("ValidationMessage", "_0IsNotCompatibleWith1");
  export const _0IsRepeated = new MessageKey("ValidationMessage", "_0IsRepeated");
}

export module VoidEnumMessage {
  export const Instance = new MessageKey("VoidEnumMessage", "Instance");
}

export namespace External {

  export module CollectionMessage {
    export const And = new MessageKey("CollectionMessage", "And");
    export const Or = new MessageKey("CollectionMessage", "Or");
    export const No0Found = new MessageKey("CollectionMessage", "No0Found");
    export const MoreThanOne0Found = new MessageKey("CollectionMessage", "MoreThanOne0Found");
  }

  export const DayOfWeek = new EnumType<DayOfWeek>("DayOfWeek");
  export type DayOfWeek =
    "Sunday" |
    "Monday" |
    "Tuesday" |
    "Wednesday" |
    "Thursday" |
    "Friday" |
    "Saturday";

}


text:
using ByteSizeLib;
using Microsoft.ConfigurationManagement.AdminConsole;
using Microsoft.Deployment.Compression;
using Microsoft.Deployment.Compression.Cab;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;

namespace ConfigMgr.QuickTools.DriverManager
{
    public partial class HPDriverPackCatalogPage : SmsPageControl
    {
        private BackgroundWorker backgroundWorker;
        private readonly ModifyRegistry registry = new ModifyRegistry();
        private XElement catalog;
        private Process extractProcess;
        private WebClient webClient;
        private readonly Queue<KeyValuePair<HPDriverPackage, Uri>> _downloadUrls = new Queue<KeyValuePair<HPDriverPackage, Uri>>();
        private bool downloadQueueFinished = false;
        private readonly Queue<KeyValuePair<HPDriverPackage, string>> _extractFiles = new Queue<KeyValuePair<HPDriverPackage, string>>();
        private bool extractQueueFinished = false;
        private readonly Dictionary<string, string> error = new Dictionary<string, string>();
        private readonly List<string> successful = new List<string>();
        private int totalPacks;
        private int downloadedPacks = 0;
        private readonly int extracted = 1;
        private string currentDownloadFileName;
        private string currentModel;
        private HPDriverPackage currentPackage;
        private string os;
        private string structure;
        private string tempFolderPath;
        private string sourceFolderPath;

        public HPDriverPackCatalogPage(SmsPageData pageData)
            : base(pageData)
        {
            Title = "Select Driver Pack";
            Headline = "Select driver pack to download";

            InitializeComponent();

            checkBoxOverwrite.Visible = false;
        }

        public override void InitializePageControl()
        {
            base.InitializePageControl();

            ControlsInspector.AddControl(dataGridViewDriverPackages, new ControlDataStateEvaluator(ValidateSelectedPack), "Select driver pack to download");
            dataGridViewDriverPackages.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            Initialized = false;
        }

        protected override void ApplyChanges()
        {
            base.ApplyChanges();
        }

        public override void PostApply(BackgroundWorker worker, DoWorkEventArgs e)
        {
            try
            {
                backgroundWorker = worker;

                worker.ReportProgress(0, "Queuing up Driver Pack downloads ...");

                List<HPDriverPackage> packages = (List<HPDriverPackage>)UserData["DriverPackItems"];
                totalPacks = packages.Count;

                foreach (HPDriverPackage package in packages)
                {
                    Uri uri = new Uri(package.Url);

                    _downloadUrls.Enqueue(new KeyValuePair<HPDriverPackage, Uri>(package, uri));
                }

                DownloadFiles();

                do // wait for all the download to finish
                {
                    Thread.Sleep(1000);
                } while (downloadQueueFinished == false);

                worker.ReportProgress(50, "Extracting Driver Packs ...");

                ExtractFiles();

                do // wait for all the extractions to finish
                {
                    Thread.Sleep(500);
                } while (extractQueueFinished == false);

                PrepareCompletion(successful, error);
                base.PostApply(worker, e);
            }
            catch (Exception ex)
            {
                PrepareError(ex.Message);
                throw;
            }
        }

        public override void OnAddSummary(SummaryRequestHandler handler)
        {
            base.OnAddSummary(handler);

            List<HPDriverPackage> list = new List<HPDriverPackage>();
            foreach (DataGridViewRow dataGridViewRow in dataGridViewDriverPackages.Rows)
            {
                if (Convert.ToBoolean(dataGridViewRow.Cells[columnSelected.Name].Value) == true)
                {
                    if (dataGridViewRow.Tag is HPDriverPackage pack)
                    {
                        list.Add(pack);
                    }
                }
            }
            UserData["DriverPackItems"] = list;

            AddAction("GeneralDescription", string.Format("The following driver pack(s) will be imported ({0}):", list.Count));
            AddAction("DriverPackInformation", string.Empty);

            foreach (HPDriverPackage package in list)
            {
                AddActionDetailMessage("DriverPackInformation", package.Model);
            }
        }

        private void PrepareCompletion(List<string> successful, Dictionary<string, string> error)
        {
            RemoveAllSummary();

            if (successful.Count > 0)
            {
                AddAction("GeneralDescription", string.Format("The following driver pack(s) was imported ({0}):", successful.Count));
                UpdateActionStatus("GeneralDescription", SmsSummaryAction.ActionStatus.CompleteWithSuccess);
                AddAction("DriverPackInformation", string.Empty);
                foreach (string message in successful)
                    AddActionDetailMessage("DriverPackInformation", message);

                AddAction("EmptyLine", string.Empty);
            }

            if (error.Count > 0)
            {
                AddAction("ErrorDescription", string.Format("The following driver pack(s) failed to import ({0}):", error.Count));
                UpdateActionStatus("ErrorDescription", SmsSummaryAction.ActionStatus.CompleteWithErrors);
                AddAction("ErrorInformation", string.Empty);
                foreach (KeyValuePair<string, string> item in error)
                {
                    AddActionDetailMessage("ErrorInformation", string.Format("{0}:\n - {1}", item.Key, item.Value));
                }
            }
        }

        private void PrepareError(string errorMessage)
        {
            RemoveAllSummary();
            AddAction("ErrorInfo", errorMessage);
            UpdateActionStatus("ErrorInfo", SmsSummaryAction.ActionStatus.CompleteWithErrors);
        }

        private void RemoveAllSummary()
        {
            foreach (string id in Enumerable.ToList(Enumerable.Select(GetSummaryItems(), i => i.Id)))
                RemoveItem(id);
        }

        public override void OnActivated()
        {
            base.OnActivated();

            Regex regex = new Regex(@"Windows\s(\d\.\d|\d{2}|\d).*(\d{2})-bit");
            Match match = regex.Match(UserData["OS"].ToString());

            os = match.Success ? string.Format("Win{0}-{1}", match.Groups[1].Value, match.Groups[2].Value) : "unknown";
            structure = registry.ReadString("LegacyFolderStructure");
            sourceFolderPath = registry.ReadString("DriverSourceFolder");
            tempFolderPath = registry.ReadString("TempDownloadPath");

            ProcessCatalog();

            Utility.UpdateDataGridViewColumnsSize(dataGridViewDriverPackages, columnPack);
        }

        public override bool OnDeactivate()
        {
            dataGridViewDriverPackages.EndEdit();
            return base.OnDeactivate();
        }

        private void ProcessCatalog()
        {
            dataGridViewDriverPackages.Rows.Clear();

            bool known = false;
            string prefix = string.IsNullOrEmpty(registry.ReadString("HPFolderPrefix")) ? "HP" : registry.ReadString("HPFolderPrefix");

            string tempFile = Path.Combine(Path.GetTempPath(), "HPClientDriverPackCatalog.cab");
            using (FileStream innerCab = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                CabEngine engine = new CabEngine();
                foreach (ArchiveFileInfo archiveFileInfo in engine.GetFileInfo(innerCab))
                {
                    using (Stream stream = engine.Unpack(innerCab, archiveFileInfo.Name))
                    {
                        catalog = XElement.Load(stream);

                        IEnumerable<XElement> nodeList = catalog.Element("HPClientDriverPackCatalog").Element("ProductOSDriverPackList").Elements("ProductOSDriverPack").Where(
                            x => x.Element("OSName").Value == UserData["OS"].ToString()
                            );
                        foreach (XElement node in nodeList)
                        {
                            HPDriverPackage package = new HPDriverPackage(node)
                            {
                                SoftPaq = catalog.Element("HPClientDriverPackCatalog").Element("SoftPaqList").Elements("SoftPaq").Where(
                                x => x.Element("Id").Value == node.Element("SoftPaqId").Value
                                ).FirstOrDefault(),
                                Vendor = prefix
                            };
                            package.ProcessSoftPaq();
                            package.GenerateModelFolderName(os, structure);

                            DataGridViewRow dataGridViewRow = new DataGridViewRow();
                            dataGridViewRow.CreateCells(dataGridViewDriverPackages);

                            dataGridViewRow.Cells[0].Value = false;
                            dataGridViewRow.Cells[1].Value = package.Model;
                            dataGridViewRow.Cells[2].Value = package.VersionShort;
                            dataGridViewRow.Cells[3].Value = package.Size.ToString();

                            dataGridViewRow.Tag = package;
                            dataGridViewDriverPackages.Rows.Add(dataGridViewRow);
                        }
                    }
                }
            }

            // TODO: will implement when I have an HP device to test with
            //string query = "SELECT DISTINCT Model FROM SMS_G_System_COMPUTER_SYSTEM WHERE Manufacturer = 'HP' OR Manufacturer = 'Hewlett-Packard'";
            //List<IResultObject> models = Utility.SearchWMIToList(ConnectionManager, query);

            //foreach (IResultObject model in models)
            //{
            //    string testModel = model["Model"].StringValue;
            //    testModel = Regex.Replace(testModel, "HP", "", RegexOptions.IgnoreCase);
            //    testModel = Regex.Replace(testModel, "COMPAQ", "", RegexOptions.IgnoreCase);
            //    testModel = Regex.Replace(testModel, "SFF", "Small Form Factor");
            //    testModel = Regex.Replace(testModel, "USDT", "Desktop");
            //    testModel = Regex.Replace(testModel, " TWR", " Tower");
            //    testModel = testModel.TrimEnd("PC").Trim();

            //    DataGridViewRow row = dataGridViewDriverPackages.Rows
            //        .Cast<DataGridViewRow>()
            //        .Where(r => r.Cells[1].Value.ToString().Equals(testModel, StringComparison.CurrentCultureIgnoreCase))
            //        .FirstOrDefault();

            //    if (row != null)
            //    {
            //        row.Cells[0].Value = true;
            //        row.Cells[4].Value = "Model detected";
            //        known = true;
            //    }
            //}

            foreach (DataGridViewRow dataGridViewRow in dataGridViewDriverPackages.Rows)
            {
                HPDriverPackage package = (HPDriverPackage)dataGridViewRow.Tag;

                string path = Path.Combine(sourceFolderPath, package.FolderName);

                if (Directory.Exists(path))
                {
                    string[] fileList = Directory.GetFiles(path, "*.version");
                    if (File.Exists(Path.Combine(path, package.VersionFile)))
                    {
                        dataGridViewRow.Cells[0].Value = false;
                        dataGridViewRow.Cells[4].Value = "Downloaded";
                    }
                    else if (fileList.Length > 0)
                    {
                        dataGridViewRow.Cells[0].Value = false;
                        dataGridViewRow.Cells[4].Value = "New version";
                    }
                }
            }

            dataGridViewDriverPackages.Sort(known ? columnStatus : columnPack, known ? ListSortDirection.Descending : ListSortDirection.Ascending);

            Initialized = true;
        }

        private void DownloadFiles()
        {
            if (_downloadUrls.Any())
            {
                KeyValuePair<HPDriverPackage, Uri> data = _downloadUrls.Dequeue();

                HPDriverPackage package = data.Key;

                Uri url = data.Value;
                string filename = Path.GetFileName(url.LocalPath);

                currentDownloadFileName = Path.Combine(tempFolderPath, filename);
                currentModel = package.Model;
                currentPackage = package;

                // check if file already exists and is the same size as the one that will be downloaded
                if (File.Exists(currentDownloadFileName))
                {
                    long fileSize = new FileInfo(currentDownloadFileName).Length;
                    long webSize = Utility.GetFileSize(url);

                    if (fileSize == webSize)
                    {
                        _extractFiles.Enqueue(new KeyValuePair<HPDriverPackage, string>(package, currentDownloadFileName));

                        CheckDownloadQueueCompleted();

                        return;
                    }
                }

                // enable https downloads
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                webClient = new WebClient();
                webClient.DownloadProgressChanged += Client_DownloadProgressChanged;
                webClient.DownloadFileCompleted += Client_DownloadFileCompleted;
                webClient.DownloadFileAsync(url, currentDownloadFileName);

                return;
            }
        }

        private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            // I hate calculating progress bars
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;
            double start = 100 / totalPacks * downloadedPacks;
            backgroundWorker.ReportProgress(Convert.ToInt32((start + (percentage / totalPacks)) * 0.5),
                string.Format("Downloading: {0} - {1} of {2}", currentModel, ByteSize.FromBytes(bytesIn).ToString("#"), ByteSize.FromBytes(totalBytes).ToString("#")
                ));
        }

        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error != null)
                {
                    error.Add(currentModel, "Could download driver pack: " + e.Error.Message);
                }
                else
                {
                    // add the downloaded file into the extraction list
                    _extractFiles.Enqueue(new KeyValuePair<HPDriverPackage, string>(currentPackage, currentDownloadFileName));
                }
            }
            finally
            {
                if (sender as WebClient == webClient)
                {
                    webClient.Dispose();
                    webClient = null;

                    CheckDownloadQueueCompleted();
                }
            }
        }

        private void CheckDownloadQueueCompleted()
        {
            // if queue is still active download next file
            if (_downloadUrls.Count > 0)
            {
                ++downloadedPacks;
                DownloadFiles();
            }
            else
            {
                // all downloads are done, kill of the while loop
                downloadQueueFinished = true;
            }
        }

        private void ExtractFiles()
        {
            if (_extractFiles.Any())
            {
                KeyValuePair<HPDriverPackage, string> data = _extractFiles.Dequeue();

                // add model so we can re-use it in functions
                HPDriverPackage package = data.Key;
                currentModel = package.Model;

                // update my best friend the progress bar
                backgroundWorker.ReportProgress(Convert.ToInt32(50 + ((50 / totalPacks * extracted) * 0.5)), string.Format("Processing {0} : extracting to temp folder", currentModel));
                // generate model folder name

                // hp sp extract does not work directly to network share, put in temp folder first and than copy to share
                string tempFolder = Path.Combine(tempFolderPath, "extract", package.FolderName);
                string destinationFolder = Path.Combine(sourceFolderPath, package.FolderName);

                using (extractProcess = new Process())
                {
                    try
                    {
                        // Start a process to print a file and raise an event when done.
                        extractProcess.StartInfo.FileName = data.Value;
                        extractProcess.StartInfo.Arguments = string.Format("-pdf -f \"{0}\" -s -e", tempFolder);
                        extractProcess.StartInfo.CreateNoWindow = true;
                        extractProcess.StartInfo.UseShellExecute = true;
                        extractProcess.StartInfo.Verb = "RunAs";
                        extractProcess.Start();
                        extractProcess.WaitForExit();
                        extractProcess.Close();

                        // update my best friend the progress bar
                        backgroundWorker.ReportProgress(Convert.ToInt32(50 + ((100 / totalPacks * extracted) * 0.5) - 1), string.Format("Processing {0} : moving to destination folder", currentModel));

                        if (!Directory.Exists(tempFolder))
                            throw new DirectoryNotFoundException("Temp folder not found " + tempFolder);

                        // add a version file to the folder so we can check later if there is an update to the download
                        string versionFile = Path.Combine(tempFolderPath, "extract", package.FolderName, package.VersionFile);
                        File.Create(versionFile).Close();

                        // wipe old soruce folder
                        if (registry.ReadBool("WipeSource") && Directory.Exists(destinationFolder))
                            Directory.Delete(destinationFolder, true);

                        // remove old version file
                        if (Directory.Exists(destinationFolder))
                        {
                            string[] fileList = Directory.GetFiles(destinationFolder, "*.version");
                            foreach (string file in fileList)
                            {
                                File.Delete(file);
                            }
                        }

                        Utility.Copy(tempFolder, destinationFolder, true);

                        Directory.Delete(tempFolder, true);
                    }
                    catch (Exception ex)
                    {
                        error.Add(currentModel, "Cannot extract driver pack: " + ex.Message);

                        CheckExtractQueueCompleted();

                        return;
                    }
                }

                successful.Add(currentModel);

                CheckExtractQueueCompleted();

                return;
            }
        }

        private void CheckExtractQueueCompleted()
        {
            // if queue is still active download next file
            if (_extractFiles.Count > 0)
            {
                ExtractFiles();
            }
            else
            {
                // all downloads are done, kill of the while loop
                extractQueueFinished = true;
            }
        }

        private ControlDataState ValidateSelectedPack()
        {
            foreach (DataGridViewRow dataGridViewRow in dataGridViewDriverPackages.Rows)
            {
                if (Convert.ToBoolean(dataGridViewRow.Cells[0].Value, CultureInfo.InvariantCulture))
                {
                    return ControlDataState.Valid;
                }
            }
            return ControlDataState.Invalid;
        }

        private void DataGridViewDriverPackages_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (!dataGridViewDriverPackages.IsCurrentCellDirty)
                return;
            dataGridViewDriverPackages.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }

        private void DataGridViewDriverPackages_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            ControlsInspector.InspectAll();
            Dirty = !ReadOnly;
        }

        private void DataGridViewDriverPackages_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            Utility.UpdateDataGridViewColumnsSize(dataGridViewDriverPackages, columnPack);
        }

        private void ButtonDeselectAll_Click(object sender, EventArgs e)
        {
            dataGridViewDriverPackages.Focus();
            dataGridViewDriverPackages.BeginEdit(true);
            bool flag = sender == buttonDeselectAll;
            foreach (DataGridViewRow dataGridViewRow in dataGridViewDriverPackages.Rows)
                dataGridViewRow.Cells[0].Value = flag ? false : true;
            dataGridViewDriverPackages.EndEdit();
        }

        private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (dataGridViewDriverPackages.SelectedRows.Count == 0 || dataGridViewDriverPackages.SelectedRows.Count > 1)
                e.Cancel = true;
        }

        private void DataGridViewDriverPackages_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex != -1 && e.RowIndex != -1 && e.Button == MouseButtons.Right)
            {
                dataGridViewDriverPackages.ClearSelection();
                dataGridViewDriverPackages.Rows[e.RowIndex].Selected = true;
            }
        }

        private void DataGridViewDriverPackages_KeyUp(object sender, KeyEventArgs e)
        {
            Utility.SelectDataGridViewWithSpace(e, (DataGridView)sender, columnSelected);
        }

        private void ReleaseNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridViewDriverPackages.SelectedRows)
            {
                if (row.Tag is HPDriverPackage package)
                {
                    Process process = new Process();
                    try
                    {
                        process.StartInfo.FileName = package.ReleaseNotesUrl;
                        process.StartInfo.UseShellExecute = true;
                        process.Start();
                    }
                    catch (Win32Exception) { }
                    finally
                    {
                        process?.Dispose();
                    }
                }
            }
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__int_fscanf_divide_73b.cpp
Label Definition File: CWE369_Divide_by_Zero__int.label.xml
Template File: sources-sinks-73b.tmpl.cpp
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Non-zero
 * Sinks: divide
 *    GoodSink: Check for zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <list>

using namespace std;

namespace CWE369_Divide_by_Zero__int_fscanf_divide_73
{

#ifndef OMITBAD

void badSink(list<int> dataList)
{
    /* copy data out of dataList */
    int data = dataList.back();
    /* POTENTIAL FLAW: Possibly divide by zero */
    printIntLine(100 / data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<int> dataList)
{
    int data = dataList.back();
    /* POTENTIAL FLAW: Possibly divide by zero */
    printIntLine(100 / data);
}

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(list<int> dataList)
{
    int data = dataList.back();
    /* FIX: test for a zero denominator */
    if( data != 0 )
    {
        printIntLine(100 / data);
    }
    else
    {
        printLine("This would result in a divide by zero");
    }
}

#endif /* OMITGOOD */

} /* close namespace */


text:
package org.opencb.hpg.bigdata.analysis.tools.manifest;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by pfurio on 23/05/17.
 */
public class ManifestTest {

    @Test
    public void testDefault() {
        Manifest manifest = new Manifest();

        manifest.setContact(new Contact("John", "john@email.org"));
        manifest.setDescription("Manifest description");
        manifest.setGit(new Git("http://github.com", "Git commit", "tag"));
        manifest.setId("Tool id");
        manifest.setName("Tool name");
        manifest.setVersion("v1");
        manifest.setPublication("URL to publication");
        manifest.setLanguage(new ProgrammingLanguage("bash", "v1"));
        manifest.setDependencies(Arrays.asList("Java", "htsjdk"));
        manifest.setSettings(new Settings(" ", "setEnv.sh", true));
        manifest.setWebsite("http://www.mywebsite.org");

        Execution execution1 = new Execution("exec1", "tool exec1", "Description", "usage", Arrays.asList(
                new Param("input", "Input blabla", null, false, true, false, false, 0, false, null, Param.Type.STRING),
                new Param("output", "Output blabla", null, false, true, true, false, 0, false, null, Param.Type.STRING)
        ));

        Execution execution2 = new Execution("exec2", "tool exec2", "Description", "usage", Arrays.asList(
                new Param("input", "Input blabla", null, false, true, false, false, 0, false, null, Param.Type.STRING),
                new Param("output", "Output blabla", null, false, true, true, false, 0, false, null, Param.Type.STRING)
        ));

        manifest.setExecutions(Arrays.asList(execution1, execution2));

        try {
            manifest.serialize(new FileOutputStream("/tmp/manifest-test.yml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testLoad() throws Exception {
        Manifest manifest = Manifest.load(getClass().getResource("/manifest-test.yml").openStream());
        System.out.println("Manifest = " + manifest);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:orientation="horizontal">

    <TextView
        android:id="@+id/label"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:layout_weight="1.5"
        android:text="PivotY"
        android:textSize="10sp"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4"/>

    <TextView
        android:id="@+id/value"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="0"
        android:textSize="10sp"/>

</LinearLayout>


text:
ifeq ($(origin PBCPP_DIR), undefined)
PBCPP_DIR = ../
endif

include ../common.mk

#
# Define the targets before including the rules since the rules contains a target itself.
#

EXECS = exhalign

all: bin make.dep $(EXECS)

BUILTEXECS = $(addprefix bin/, $(EXECS))
DISTRIB_SET = exhalign
DISTRIB_EXECS = $(addprefix bin/, $(DISTRIB_SET))
INSTALL_EXECS = $(addprefix install-, $(DISTRIB_SET))

include ../make.rules

include make.dep

exhalign:        bin/exhalign

bin/exhalign: bin/ExhaustiveAlign.o
	$(CPP)  -static -O3 $< -o $@  -L $(HDF5LIBDIR) -l $(HDF5LIBCPP)  -l $(HDF5LIB) -lz -lpthread

#
# Set up a default value for the install dir if one does
# not exist.
#
INSTALL_DIR ?= $(ASSEMBLY_HOME)/bin
BUILD_DIR ?= bin
install:
	/usr/bin/install -m 555 $(DISTRIB_EXECS) -t $(INSTALL_DIR)

install-%:
	/usr/bin/install -m 555 bin/$* -t $(INSTALL_DIR)

clean:
	-rm bin/*


text:
<?php

namespace Itkg\Core\Response;

use Symfony\Component\HttpFoundation\Response;

/**
 * Interface PostProcessorInterface
 *
 * Describe respone post processing
 *
 * @package Itkg\Core\Response
 */
interface PostProcessorInterface
{
    /**
     * @param Response $response
     */
    public function process(Response $response);
}


text:
/*
 * Powerdog Industries kindly requests feedback from anyone modifying
 * this function:
 *
 * Date: Thu, 05 Jun 1997 23:17:17 -0400
 * From: Kevin Ruddy <kevin.ruddy@powerdog.com>
 * To: James FitzGibbon <james@nexis.net>
 * Subject: Re: Use of your strptime(3) code (fwd)
 *
 * The reason for the "no mod" clause was so that modifications would
 * come back and we could integrate them and reissue so that a wider
 * audience could use it (thereby spreading the wealth).  This has
 * made it possible to get strptime to work on many operating systems.
 * I'm not sure why that's "plain unacceptable" to the FreeBSD team.
 *
 * Anyway, you can change it to "with or without modification" as
 * you see fit.  Enjoy.
 *
 * Kevin Ruddy
 * Powerdog Industries, Inc.
 */
/*
 * Copyright (c) 1994 Powerdog Industries.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer
 *    in the documentation and/or other materials provided with the
 *    distribution.
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgement:
 *      This product includes software developed by Powerdog Industries.
 * 4. The name of Powerdog Industries may not be used to endorse or
 *    promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY POWERDOG INDUSTRIES ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE POWERDOG INDUSTRIES BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifdef LIBC_RCS
static const char rcsid[] =
  "$FreeBSD: src/lib/libc/stdtime/strptime.c,v 1.17.2.2 2001/07/31 00:06:24 dd Exp $";
#endif

#ifndef lint
#ifndef NOID
static char copyright[] =
"@(#) Copyright (c) 1994 Powerdog Industries.  All rights reserved.";
static char sccsid[] = "@(#)strptime.c	0.1 (Powerdog) 94/03/27";
#endif /* !defined NOID */
#endif /* not lint */

#include <time.h>
#include <ctype.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#ifdef	_THREAD_SAFE
#include <pthread.h>
#include "pthread_private.h"
#endif
//#include "timelocal.h"

static char * _strptime(const char *, const char *, struct tm *);

#ifdef	_THREAD_SAFE
static struct pthread_mutex	_gotgmt_mutexd = PTHREAD_MUTEX_STATIC_INITIALIZER;
static pthread_mutex_t		gotgmt_mutex   = &_gotgmt_mutexd;
#endif
static int got_GMT;

#define asizeof(a)	(sizeof (a) / sizeof ((a)[0]))

static char *
_strptime(const char *buf, const char *fmt, struct tm *tm)
{
	char	c;
	const char *ptr;
	int	i,
		len;
	int Ealternative, Oalternative;
	char isLeapYear;
	int mon,year;

	ptr = fmt;
	while (*ptr != 0) {
		if (*buf == 0)
			break;

		c = *ptr++;

		if (c != '%') {
			if (isspace((unsigned char)c))
				while (*buf != 0 && isspace((unsigned char)*buf))
					buf++;
			else if (c != *buf++)
				return 0;
			continue;
		}

		Ealternative = 0;
		Oalternative = 0;
		c = *ptr++;
		switch (c) {
		case 0:
		case '%':
			if (*buf++ != '%')
				return 0;
			break;

		case 'M':
		case 'S':
			if (*buf == 0 || isspace((unsigned char)*buf))
				break;

			if (!isdigit((unsigned char)*buf))
				return 0;

			len = 2;
			for (i = 0; len && *buf != 0 && isdigit((unsigned char)*buf); buf++) {
				i *= 10;
				i += *buf - '0';
				len--;
			}

			if (c == 'M') {
				if (i > 59)
					return 0;
				tm->tm_min = i;
			} else {
				if (i > 60)
					return 0;
				tm->tm_sec = i;
			}

			if (*buf != 0 && isspace((unsigned char)*buf))
				while (*ptr != 0 && !isspace((unsigned char)*ptr))
					ptr++;
			break;

		case 'H':
		case 'I':
		case 'k':
		case 'l':
			/*
			 * Of these, %l is the only specifier explicitly
			 * documented as not being zero-padded.  However,
			 * there is no harm in allowing zero-padding.
			 *
			 * XXX The %l specifier may gobble one too many
			 * digits if used incorrectly.
			 */
			if (!isdigit((unsigned char)*buf))
				return 0;

			len = 2;
			for (i = 0; len && *buf != 0 && isdigit((unsigned char)*buf); buf++) {
				i *= 10;
				i += *buf - '0';
				len--;
			}
			if (c == 'H' || c == 'k') {
				if (i > 23)
					return 0;
			} else if (i > 12)
				return 0;

			tm->tm_hour = i;

			if (*buf != 0 && isspace((unsigned char)*buf))
				while (*ptr != 0 && !isspace((unsigned char)*ptr))
					ptr++;
			break;

		case 'd':
		case 'e':
			/*
			 * The %e specifier is explicitly documented as not
			 * being zero-padded but there is no harm in allowing
			 * such padding.
			 *
			 * XXX The %e specifier may gobble one too many
			 * digits if used incorrectly.
			 */
			if (!isdigit((unsigned char)*buf))
				return 0;

			len = 2;
			for (i = 0; len && *buf != 0 && isdigit((unsigned char)*buf); buf++) {
				i *= 10;
				i += *buf - '0';
				len--;
			}
			if (i > 31)
				return 0;

			tm->tm_mday = i;

			if (*buf != 0 && isspace((unsigned char)*buf))
				while (*ptr != 0 && !isspace((unsigned char)*ptr))
					ptr++;
			break;

		case 'm':
			if (!isdigit((unsigned char)*buf))
				return 0;

			len = 2;
			for (i = 0; len && *buf != 0 && isdigit((unsigned char)*buf); buf++) {
				i *= 10;
				i += *buf - '0';
				len--;
			}
			if (i < 1 || i > 12)
				return 0;

			tm->tm_mon = i - 1;

			if (*buf != 0 && isspace((unsigned char)*buf))
				while (*ptr != 0 && !isspace((unsigned char)*ptr))
					ptr++;
			break;

		case 'Y':
		case 'y':
			if (*buf == 0 || isspace((unsigned char)*buf))
				break;

			if (!isdigit((unsigned char)*buf))
				return 0;

			len = (c == 'Y') ? 4 : 2;
			for (i = 0; len && *buf != 0 && isdigit((unsigned char)*buf); buf++) {
				i *= 10;
				i += *buf - '0';
				len--;
			}
			if (c == 'Y')
				i -= 1900;
			if (c == 'y' && i < 69)
				i += 100;
			if (i < 0)
				return 0;

			tm->tm_year = i;

			if (*buf != 0 && isspace((unsigned char)*buf))
				while (*ptr != 0 && !isspace((unsigned char)*ptr))
					ptr++;
			break;
		}
	} // Fix up yday field
	year = tm->tm_year + 1900;
	isLeapYear = (year%4==0) - (year%100==0) + (year%400==0) - (year%4000==0);
	mon = tm->tm_mon; // 0 == January
	tm->tm_yday =
		(mon>0)*31 + // Jan
		(mon>1)*(28+isLeapYear) + // Feb
		(mon>2)*31 + // March
		(mon>3)*30 + // April
		(mon>4)*31 + // May
		(mon>5)*30 + // June
		(mon>6)*31 + // July
		(mon>7)*31 + // Aug
		(mon>8)*30 + // Sept
		(mon>9)*31 + // Oct
		(mon>10)*30 + // Nov
		+ tm->tm_mday - 1;

	return (char *)buf;
}

char *
strptime(const char *buf, const char *fmt, struct tm *tm)
{
	char *ret;
	got_GMT = 0;
	ret = _strptime(buf, fmt, tm);
	return ret;
}


text:
<?php

namespace Propel\Tests\Runtime\Parser;

use Propel\Runtime\Parser\AbstractParser;
use Propel\Runtime\Parser\XmlParser;
use Propel\Tests\TestCase;

/**
 * Test for JsonParser class
 *
 * @author Francois Zaninotto
 */
class AbstractParserTest extends TestCase
{
    public function testGetParser()
    {
        $parser = AbstractParser::getParser('XML');
        $this->assertTrue($parser instanceof XmlParser);
    }

    /**
     * @expectedException \Propel\Runtime\Exception\FileNotFoundException
     */
    public function testGetParserThrowsExceptionOnWrongParser()
    {
        $parser = AbstractParser::getParser('Foo');
    }

    public function testLoad()
    {
        $fixtureFile = __DIR__ . '/fixtures/test_data.xml';
        $parser = AbstractParser::getParser('XML');
        $content = $parser->load($fixtureFile);
        $expectedContent = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<foo>
  <bar prop="0"/>
  <bar prop="1"/>
</foo>

EOF;
        $this->assertEquals($expectedContent, $content, 'AbstractParser::load() executes PHP code in files');
    }

    public function testDump()
    {
        $testContent = "Foo Content";
        $testFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'propel_test_' . microtime();
        $parser = AbstractParser::getParser('XML');
        $parser->dump($testContent, $testFile);
        $content = file_get_contents($testFile);
        $this->assertEquals($testContent, $content);
        unlink($testFile);
    }

}