text:
Run `dotnet build /t:GenerateCode` to generate code.

``` yaml

azure-arm: true
csharp: true
library-name: DevCenter
namespace: Azure.ResourceManager.DevCenter
# default tag is a preview version
require: https://github.com/Azure/azure-rest-api-specs/blob/1b3b9c1dd4d2c875997ea0b392dc71418fb1f28d/specification/devcenter/resource-manager/readme.md
output-folder: $(this-folder)/Generated
clear-output-folder: true
skip-csproj: true
modelerfour:
  flatten-payloads: false

format-by-name-rules:
  'tenantId': 'uuid'
  'ETag': 'etag'
  'location': 'azure-location'
  '*Uri': 'Uri'
  '*Uris': 'Uri'

rename-rules:
  CPU: Cpu
  CPUs: Cpus
  VCPU: vCpu
  VCPUs: vCpus
  Os: OS
  Ip: IP
  Ips: IPs|ips
  ID: Id
  IDs: Ids
  VM: Vm
  VMs: Vms
  Vmos: VmOS
  VMScaleSet: VmScaleSet
  DNS: Dns
  VPN: Vpn
  NAT: Nat
  WAN: Wan
  Ipv4: IPv4|ipv4
  Ipv6: IPv6|ipv6
  Ipsec: IPsec|ipsec
  SSO: Sso
  URI: Uri
  Etag: ETag|etag

rename-mapping:
  DevCenterSku: DevCenterSkuDetails

request-path-to-resource-name:
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/devcenters/{devCenterName}/attachednetworks: AttachedNetworkConnection
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/devcenters/{devCenterName}/attachednetworks/{attachedNetworkConnectionName}: AttachedNetworkConnection
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/projects/{projectName}/attachednetworks: ProjectAttachedNetworkConnectionCollection
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/projects/{projectName}/attachednetworks/{attachedNetworkConnectionName}: ProjectAttachedNetworkConnection
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/devcenters/{devCenterName}/devboxdefinitions: DevBoxDefinition
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/devcenters/{devCenterName}/devboxdefinitions/{devBoxDefinitionName}: DevBoxDefinition
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/projects/{projectName}/devboxdefinitions: ProjectDevBoxDefinition
  /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/projects/{projectName}/devboxdefinitions/{devBoxDefinitionName}: ProjectDevBoxDefinition

```


text:
import fetch from 'jest-fetch-mock';

global.fetch = fetch;

redpajama_set_name: RedPajamaGithub


text:
package it.matiuz.menumaker.model.impl;

import it.matiuz.menumaker.model.Category;
import it.matiuz.menumaker.model.MenuModelPackage;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;

/**
 *
 * An implementation of the model object 'Category'.
 *
 *

 * The following features are implemented:
 *

 *
{@link it.matiuz.menumaker.model.impl.CategoryImpl#getId Id}

 *
{@link it.matiuz.menumaker.model.impl.CategoryImpl#getDescription Description}

 *
{@link it.matiuz.menumaker.model.impl.CategoryImpl#getPriority Priority}

 *

 *

 *
 * @generated
 */
public class CategoryImpl extends EObjectImpl implements Category
{
  /**
   * The default value of the '{@link #getId() Id}' attribute.
   *
   *
   * @see #getId()
   * @generated
   * @ordered
   */
  protected static final int ID_EDEFAULT = 0;

  /**
   * The cached value of the '{@link #getId() Id}' attribute.
   *
   *
   * @see #getId()
   * @generated
   * @ordered
   */
  protected int id = ID_EDEFAULT;

  /**
   * The default value of the '{@link #getDescription() Description}' attribute.
   *
   *
   * @see #getDescription()
   * @generated
   * @ordered
   */
  protected static final String DESCRIPTION_EDEFAULT = null;

  /**
   * The cached value of the '{@link #getDescription() Description}' attribute.
   *
   *
   * @see #getDescription()
   * @generated
   * @ordered
   */
  protected String description = DESCRIPTION_EDEFAULT;

  /**
   * The default value of the '{@link #getPriority() Priority}' attribute.
   *
   *
   * @see #getPriority()
   * @generated
   * @ordered
   */
  protected static final int PRIORITY_EDEFAULT = 0;

  /**
   * The cached value of the '{@link #getPriority() Priority}' attribute.
   *
   *
   * @see #getPriority()
   * @generated
   * @ordered
   */
  protected int priority = PRIORITY_EDEFAULT;

  /**
   *
   *
   * @generated
   */
  protected CategoryImpl ()
  {
    super ();
  }

  /**
   *
   *
   * @generated
   */
  protected EClass eStaticClass ()
  {
    return MenuModelPackage.Literals.CATEGORY;
  }

  /**
   *
   *
   * @generated
   */
  public int getId ()
  {
    return id;
  }

  /**
   *
   *
   * @generated
   */
  public void setId (int newId)
  {
    int oldId = id;
    id = newId;
    if (eNotificationRequired ())
      eNotify (new ENotificationImpl (this, Notification.SET, MenuModelPackage.CATEGORY__ID, oldId, id));
  }

  /**
   *
   *
   * @generated
   */
  public String getDescription ()
  {
    return description;
  }

  /**
   *
   *
   * @generated
   */
  public void setDescription (String newDescription)
  {
    String oldDescription = description;
    description = newDescription;
    if (eNotificationRequired ())
      eNotify (new ENotificationImpl (this, Notification.SET, MenuModelPackage.CATEGORY__DESCRIPTION,
          oldDescription, description));
  }

  /**
   *
   *
   * @generated
   */
  public int getPriority ()
  {
    return priority;
  }

  /**
   *
   *
   * @generated
   */
  public void setPriority (int newPriority)
  {
    int oldPriority = priority;
    priority = newPriority;
    if (eNotificationRequired ())
      eNotify (new ENotificationImpl (this, Notification.SET, MenuModelPackage.CATEGORY__PRIORITY,
          oldPriority, priority));
  }

  /**
   *
   *
   * @generated
   */
  public Object eGet (int featureID, boolean resolve, boolean coreType)
  {
    switch (featureID)
    {
      case MenuModelPackage.CATEGORY__ID:
        return new Integer (getId ());
      case MenuModelPackage.CATEGORY__DESCRIPTION:
        return getDescription ();
      case MenuModelPackage.CATEGORY__PRIORITY:
        return new Integer (getPriority ());
    }
    return super.eGet (featureID, resolve, coreType);
  }

  /**
   *
   *
   * @generated
   */
  public void eSet (int featureID, Object newValue)
  {
    switch (featureID)
    {
      case MenuModelPackage.CATEGORY__ID:
        setId (((Integer) newValue).intValue ());
        return;
      case MenuModelPackage.CATEGORY__DESCRIPTION:
        setDescription ((String) newValue);
        return;
      case MenuModelPackage.CATEGORY__PRIORITY:
        setPriority (((Integer) newValue).intValue ());
        return;
    }
    super.eSet (featureID, newValue);
  }

  /**
   *
   *
   * @generated
   */
  public void eUnset (int featureID)
  {
    switch (featureID)
    {
      case MenuModelPackage.CATEGORY__ID:
        setId (ID_EDEFAULT);
        return;
      case MenuModelPackage.CATEGORY__DESCRIPTION:
        setDescription (DESCRIPTION_EDEFAULT);
        return;
      case MenuModelPackage.CATEGORY__PRIORITY:
        setPriority (PRIORITY_EDEFAULT);
        return;
    }
    super.eUnset (featureID);
  }

  /**
   *
   *
   * @generated
   */
  public boolean eIsSet (int featureID)
  {
    switch (featureID)
    {
      case MenuModelPackage.CATEGORY__ID:
        return id != ID_EDEFAULT;
      case MenuModelPackage.CATEGORY__DESCRIPTION:
        return DESCRIPTION_EDEFAULT == null ? description != null : !DESCRIPTION_EDEFAULT.equals (description);
      case MenuModelPackage.CATEGORY__PRIORITY:
        return priority != PRIORITY_EDEFAULT;
    }
    return super.eIsSet (featureID);
  }

  /**
   *
   *
   * @generated
   */
  public String toString ()
  {
    if (eIsProxy ())
      return super.toString ();

    StringBuffer result = new StringBuffer (super.toString ());
    result.append (" (id: ");
    result.append (id);
    result.append (", description: ");
    result.append (description);
    result.append (", priority: ");
    result.append (priority);
    result.append (')');
    return result.toString ();
  }

} //CategoryImpl


text:
package com.fondesa.lyra.coder.base;

import com.fondesa.lyra.sharedtest.BundleTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

import java.util.Arrays;

import static junit.framework.Assert.assertEquals;

/**
 * Unit test class for {@link DoubleArrayCoder}.
 */
@RunWith(RobolectricTestRunner.class)
public class DoubleArrayCoderTest extends BundleTestCase {
    private DoubleArrayCoder mCoder = new DoubleArrayCoder();

    @Test
    public void testSerializeDoubleArray() {
        double[] expected = generateArrayAndFill();
        mCoder.serialize(bundle(), randomKey(), expected);
        assertEquals(expected, bundle().getDoubleArray(randomKey()));
    }

    @Test
    public void testDeserializeDoubleArray() {
        double[] expected = generateArrayAndFill();
        bundle().putDoubleArray(randomKey(), expected);
        assertEquals(expected, mCoder.deserialize(bundle(), randomKey()));
    }

    private double[] generateArrayAndFill() {
        double[] array = new double[300];
        Arrays.fill(array, 9.0);
        return array;
    }
}


text:
#!/usr/bin/env node
var path = require('path');

var program = require('commander'),
    chalk = require('chalk'),
    updateNotifier = require('update-notifier'),
    fs = require("fs"),
    pkg = require('../package.json'),
    exec = require('child_process').exec;

// check if the TiApp.xml an TiCh config file exists
if (!fs.existsSync('./app/config.json')) {
    console.log(chalk.red('Please run in an alloy project folder'));
} else {
    tith();
}

// helper, quick copy
function createTiAppFile(fromPath) {
    fs.createReadStream(fromPath).pipe(fs.createWriteStream("tiapp.xml"));
    exec("ti clean", function (err, stdout, stderr) {
        if (err) {
            console.log(chalk.red('Ti Clean command failed'));
        } else {
            console.log(chalk.green(stdout));
            console.log(chalk.green('Project cleaned and ready to build'));
        }
    });
}

function copyFile(fromPath, toPath) {
    fs.readFile(fromPath, function (err, data) {
        fs.writeFile(toPath, data, (err) => {
          if(err) throw err;
        });
    });
}

// main function
function tith() {

    // status command, shows the current config
    function status(cmd) {
        console.log('\n');
        console.log('Current Alloy theme is: ' + chalk.cyan(alloyCfg.global.theme || "not defined"));
        console.log('\n');
    }

    // clear command, clears the current theme in config
    function clear(cmd) {
      alloyCfg.global.theme = "";
      console.log(chalk.yellow("\nClearing theme in config.json\n"));
    }

    // set a new config by name
    function set(name, platform, cmd) {

        if (cmd.fastlane) {
          //Require a platform when specifying fastlane option due to differences in metadata
          if (!platform) {
            console.log(chalk.red("\nSpecifying a platform is required with the Fastlane option! Copying of Fastlane files will be skipped."));
            cmd.fastlane = undefined;
          }
        } else {
          platform = platform || "ios";
        }

        if (name) {

            if (typeof name != "string" ) {
                clear();
                cmd = name;
            } else if (name.substring(0, 1) == "_") {
                clear();
            } else {
                alloyCfg.global.theme = name;
                console.log(chalk.green('\nUpdated Theme to ') + chalk.cyan(alloyCfg.global.theme) + "\n");
            }

            fs.writeFileSync("./app/config.json", JSON.stringify(alloyCfg, null, 4));

            // check if we have an app config
            if (fs.existsSync("./app/themes/" + name + "/" + platform + "/tiapp.xml")) {

                // if it exists in the themes folder, in a platform subfolder
                console.log(chalk.green('Found a tiapp.xml in the theme platform folder\n'));
                createTiAppFile("./app/themes/" + name + "/" + platform + "/tiapp.xml");

            } else if (fs.existsSync("./app/themes/" + name + "/tiapp.xml")) {

                // if it exists in the top level theme folder
                console.log(chalk.green('Found a tiapp.xml in the theme folder\n'));
                createTiAppFile("./app/themes/" + name + "/tiapp.xml");

            } else {
                console.log(chalk.cyan("No tiapp.xml found for " + name) + "\n");
            }

            var externalIcons = ["DefaultIcon", "DefaultIcon-ios", "iTunesConnect", "MarketplaceArtwork"];
            var iconName = '';
            for (var i = 0; i < externalIcons.length; i++) {
                iconName = externalIcons[i];
                // check if we havea DefaultIcon.png
                if (fs.existsSync("./app/themes/" + name + "/" + platform + "/" + iconName + ".png")) {
                    // if it exists in the themes folder, in a platform subfolder
                    console.log(chalk.green('Found a ' + iconName + '.png in the theme platform folder\n'));
                    copyFile("./app/themes/" + name + "/" + platform + "/" + iconName + ".png", "./" + iconName + ".png");
                } else if (fs.existsSync("./app/themes/" + name + "/" + iconName + ".png")) {
                    // if it exists in the top level theme folder
                    console.log(chalk.green('Found a ' + iconName + '.png in the theme folder\n'));
                    copyFile("./app/themes/" + name + "/" + "/" + iconName + ".png", "./" + iconName + ".png");
                } else {
                    console.log(chalk.yellow(iconName + '.png does not exist for this theme.\n'));
                }
            }

            // if it exists in the themes folder, in a platform subfolder
            console.log(chalk.green('Found a DefaultIcon.png in the theme platform folder\n'));
            copyFile("./app/themes/" + name + "/" + platform + "/DefaultIcon.png", "./DefaultIcon.png");

            //TODO: Allow user to set a filePath to their fastlane directory located outside of project.

            // check if a Fastfile exists in the fastlane directory of the root of project
            if (fs.existsSync("./fastlane/Fastfile")) {

              if (cmd.fastlane) {

                //Check for and log which files exist

                // Check for Appfile
                if (fs.existsSync("./app/themes/" + name + "/platform/" + platform + "/fastlane/Appfile")) {

                  console.log(chalk.green("Found an Appfile inside the theme's fastlane folder.\n"));
                  copyFile("./app/themes/" + name + "/platform/" + platform + "/fastlane/Appfile", "./fastlane/Appfile");

                } else {
                    console.log(chalk.yellow("An Appfile does not exist for this theme.\n"));
                }

                /* TODO: Copy over Android's metadata folder
                // Copy over metadata files
                if(platform == "android"){

                }
                */

              } else {
                // Prompt availability of option
                console.log(chalk.yellow("\nA Fastfile exists in your project. Fastlane files can also be copied over from your theme with the --fastlane or -F option."));
              }

            } else {

              // Fastlane? TRUE
              if (cmd.fastlane) {

                // Prompt
                console.log(chalk.yellow("\nYou specified the fastlane option, but no Fastfile can be found in the fastlane directory of your project."));

              }
            }

            function ncp(source, dest, options, callback) {
                var cback = callback;

                // if it exists in the top level theme folder
                console.log(chalk.green('Found a DefaultIcon.png in the theme folder\n'));
                copyFile("./app/themes/" + name + "/" + "/DefaultIcon.png", "./DefaultIcon.png");

                var basePath = process.cwd(),
                        currentPath = path.resolve(basePath, source),
                        targetPath = path.resolve(basePath, dest),
                        filter = options.filter,
                        rename = options.rename,
                        transform = options.transform,
                        clobber = options.clobber !== false,
                        modified = options.modified,
                        dereference = options.dereference,
                        errs = null,
                        started = 0,
                        finished = 0,
                        running = 0,
                        limit = options.limit || 30;

                limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit;

                startCopy(currentPath);

                function startCopy(source) {
                    started++;
                    if (filter) {
                        if (filter instanceof RegExp) {
                            if (!filter.test(source)) {
                                return cb(true);
                            }
                        } else if (typeof filter === 'function') {
                            if (!filter(source)) {
                                return cb(true);
                            }
                        }
                    }
                    return getStats(source);
                }

                function getStats(source) {
                    var stat = dereference ? fs.stat : fs.lstat;
                    if (running >= limit) {
                        return setImmediate(function () {
                            getStats(source);
                        });
                    }
                    running++;
                    stat(source, function (err, stats) {
                        var item = {};
                        if (err) {
                            return onError(err);
                        }

                        // We need to get the mode from the stats object and preserve it.
                        item.name = source;
                        item.mode = stats.mode;
                        item.mtime = stats.mtime; //modified time
                        item.atime = stats.atime; //access time

                        if (stats.isDirectory()) {
                            return onDir(item);
                        } else if (stats.isFile()) {
                            return onFile(item);
                        } else if (stats.isSymbolicLink()) {
                            // Symlinks don't really need to know about the mode.
                            return onLink(source);
                        }
                    });
                }

                function onFile(file) {
                    var target = file.name.replace(currentPath, targetPath);
                    if (rename) {
                        target = rename(target);
                    }
                    isWritable(target, function (writable) {
                        if (writable) {
                            return copyFile(file, target);
                        }
                        if (clobber) {
                            rmFile(target, function () {
                                copyFile(file, target);
                            });
                        }
                        if (modified) {
                            var stat = dereference ? fs.stat : fs.lstat;
                            stat(target, function (err, stats) {
                                //if souce modified time greater to target modified time copy file
                                if (file.mtime.getTime() > stats.mtime.getTime())
                                    copyFile(file, target);
                                else
                                    return cb();
                            });
                        } else {
                            return cb();
                        }
                    });
                }

                function copyFile(file, target) {
                    var readStream = fs.createReadStream(file.name),
                            writeStream = fs.createWriteStream(target, {mode: file.mode});

                    readStream.on('error', onError);
                    writeStream.on('error', onError);

                    if (transform) {
                        transform(readStream, writeStream, file);
                    } else {
                        writeStream.on('open', function () {
                            readStream.pipe(writeStream);
                        });
                    }
                    writeStream.once('finish', function () {
                        if (modified) {
                            //target file modified date sync.
                            fs.utimesSync(target, file.atime, file.mtime);
                            cb();
                        } else
                            cb();
                    });
                }

                function rmFile(file, done) {
                    fs.unlink(file, function (err) {
                        if (err) {
                            return onError(err);
                        }
                        return done();
                    });
                }

                function onDir(dir) {
                    var target = dir.name.replace(currentPath, targetPath);
                    isWritable(target, function (writable) {
                        if (writable) {
                            return mkDir(dir, target);
                        }
                        copyDir(dir.name);
                    });
                }

                function mkDir(dir, target) {
                    fs.mkdir(target, dir.mode, function (err) {
                        if (err) {
                            return onError(err);
                        }
                        copyDir(dir.name);
                    });
                }

                function copyDir(dir) {
                    fs.readdir(dir, function (err, items) {
                        if (err) {
                            return onError(err);
                        }
                        items.forEach(function (item) {
                            startCopy(path.join(dir, item));
                        });
                        return cb();
                    });
                }

                function onLink(link) {
                    var target = link.replace(currentPath, targetPath);
                    fs.readlink(link, function (err, resolvedPath) {
                        if (err) {
                            return onError(err);
                        }
                        checkLink(resolvedPath, target);
                    });
                }

                function checkLink(resolvedPath, target) {
                    if (dereference) {
                        resolvedPath = path.resolve(basePath, resolvedPath);
                    }
                    isWritable(target, function (writable) {
                        if (writable) {
                            return makeLink(resolvedPath, target);
                        }
                        fs.readlink(target, function (err, targetDest) {
                            if (err) {
                                return onError(err);
                            }
                            if (dereference) {
                                targetDest = path.resolve(basePath, targetDest);
                            }
                            if (targetDest === resolvedPath) {
                                return cb();
                            }
                            return rmFile(target, function () {
                                makeLink(resolvedPath, target);
                            });
                        });
                    });
                }

                function makeLink(linkPath, target) {
                    fs.symlink(linkPath, target, function (err) {
                        if (err) {
                            return onError(err);
                        }
                        return cb();
                    });
                }

                function isWritable(path, done) {
                    fs.lstat(path, function (err) {
                        if (err) {
                            if (err.code === 'ENOENT')
                                return done(true);
                            return done(false);
                        }
                        return done(false);
                    });
                }

                function onError(err) {
                    if (options.stopOnError) {
                        return cback(err);
                    } else if (!errs && options.errs) {
                        errs = fs.createWriteStream(options.errs);
                    } else if (!errs) {
                        errs = [];
                    }
                    if (typeof errs.write === 'undefined') {
                        errs.push(err);
                    } else {
                        errs.write(err.stack + '\n\n');
                    }
                    return cb();
                }

                function cb(skipped) {
                    if (!skipped)
                        running--;
                    finished++;
                    if ((started === finished) && (running === 0)) {
                        if (cback !== undefined) {
                            return errs ? cback(errs) : cback(null);
                        }
                    }
                }
            }

        }
    }
    var alloyCfg = JSON.parse(fs.readFileSync("./app/config.json", "utf-8"));
    // setup CLI
    program
        .version(pkg.version, '-v, --version')
        .description(pkg.description);

    program
      .command('status')
      .description("Shows the current configured theme")
      .action(status);

    program
      .command('set <theme> [platform]')
      .description('Updates config.json to use the theme specified by name and platform')
      .option('-F, --fastlane', 'Also copies a theme\'s fastlane files, platform parameter is required with this option.')
      .action(set);

    program
      .command('clear')
      .description("Clears the configured theme")
      .action(set);

    program
      .command('*')
      .description("Any unhandled command will default to status")
      .action(status);

    program.parse(process.argv);

    // check for a new version
    updateNotifier({
        packageName: pkg.name,
        packageVersion: pkg.version
    }).notify();
}


text:
package p;

class Child extends Parent {}


text:
package com.feilong.taglib.display;

import static com.feilong.core.bean.ConvertUtil.toLocale;
import static com.feilong.core.util.ResourceBundleUtil.getResourceBundle;
import static com.feilong.core.util.ResourceBundleUtil.toMap;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;

import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.feilong.taglib.display.loadbundle.LoadBundleParam;

/**
 * The Class LocaleSupportUtil.
 *
 * @author feilong
 * @since 1.10.3
 */
public final class LocaleSupportUtil{

    /** Don't let anyone instantiate this class. */
    private LocaleSupportUtil(){
        //AssertionError不是必须的. 但它可以避免不小心在类的内部调用构造器. 保证该类在任何情况下都不会被实例化.
        //see 《Effective Java》 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    //---------------------------------------------------------------

    /**
     * 将 locale 转成 {@link Locale}.
     *
     * @param locale
     *            the locale
     * @param request
     *            the request
     * @return 如果 locale 是null,那么将会使用 {@link javax.servlet.ServletRequest#getLocale()}
     */
    public static Locale toLocal(Object locale,HttpServletRequest request){
        return defaultIfNull(toLocale(locale), request.getLocale());
    }

    //---------------------------------------------------------------

    /**
     * Builds the.
     *
     * @param <T>
     *            the generic type
     * @param bundleParam
     *            the bundle param
     * @return the map
     */
    public static <T extends LoadBundleParam> Map<String, String> build(T bundleParam){
        //获得 key value map.
        return toMap(getResourceBundle(bundleParam.getBaseName(), bundleParam.getLocale()));
    }
}


text:
package com.commercetools.sunrise.productcatalog.productoverview.search.searchbox;

import com.commercetools.sunrise.framework.components.controllers.ControllerComponent;
import com.commercetools.sunrise.framework.hooks.ctprequests.ProductProjectionSearchHook;
import com.commercetools.sunrise.search.searchbox.AbstractSearchBoxControllerComponent;
import io.sphere.sdk.models.LocalizedStringEntry;
import io.sphere.sdk.products.search.ProductProjectionSearch;
import play.mvc.Http;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Locale;
import java.util.Optional;

public final class ProductSearchBoxControllerComponent extends AbstractSearchBoxControllerComponent implements ControllerComponent, ProductProjectionSearchHook {

    @Nullable
    private final LocalizedStringEntry searchText;

    @Inject
    public ProductSearchBoxControllerComponent(final ProductSearchBoxSettings productSearchBoxSettings, final Locale locale) {
        super(productSearchBoxSettings);
        this.searchText = productSearchBoxSettings.getSearchText(Http.Context.current(), locale).orElse(null);
    }

    @Override
    protected Optional<LocalizedStringEntry> getSearchText() {
        return Optional.ofNullable(searchText);
    }

    @Override
    public ProductProjectionSearch onProductProjectionSearch(final ProductProjectionSearch search) {
        if (searchText != null) {
            return search.withText(searchText);
        } else {
            return search;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI" />
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <meta name="description" content="">
    <meta name="keywords"  content="">
    <meta name="theme-color" content="">

    <meta property="og:title" content="Offline - 谢聪博客 | xcTorres Blog">

    <meta property="og:type" content="website">
    <meta property="og:description" content="阅读过的页面可以在离线时访问哦 ;)">

    <meta property="og:image" content="https://xctorres.github.io//img/avatar-xcTorres.png">
    <meta property="og:url" content="https://xctorres.github.io//offline.html">
    <meta property="og:site_name" content="谢聪博客 | xcTorres Blog">

    <title>Offline - 谢聪博客 | xcTorres Blog</title>

    <link rel="manifest" href="/pwa/manifest.json">

    <link rel="shortcut icon" href="/img/favicon.ico">

    <link rel="canonical" href="https://xctorres.github.io//offline.html">

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/hux-blog.min.css">

    <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link href="/css/timeline.css" rel="stylesheet">

            <button type="button" class="navbar-toggle">
                Toggle navigation

            </button>
            xcTorres Blog

                        Home

                        About

                        Archive

                        Book

                        Music

                        Gallery

Offline

          阅读过的页面可以在离线时访问哦 ;)

        知

						  |

						  |

                    Copyright © xcTorres Blog 2022

                    Powered by xcTorres Blog |


text:
package org.apache.camel.itest.springboot;

import org.apache.camel.itest.springboot.util.ArquillianPackager;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class CamelJbpmTest extends AbstractSpringBootTestSupport {

    @Deployment
    public static Archive<?> createSpringBootPackage() throws Exception {
        return ArquillianPackager.springBootPackage(createTestConfig());
    }

    public static ITestConfig createTestConfig() {
        return new ITestConfigBuilder()
                .module(inferModuleName(CamelJbpmTest.class))
                .dependency("org.kie:kie-api:7.30.0.Final")
                .dependency("org.kie:kie-dmn-api:7.30.0.Final")
                .dependency("org.kie:kie-dmn-model:7.30.0.Final")
                .dependency("org.kie:kie-internal:7.30.0.Final")
                .dependency("org.drools:drools-compiler:7.30.0.Final")
                .dependency("org.drools:drools-core:7.30.0.Final")
                .unitTestExpectedNumber(0)
                .build();
    }

    @Test
    public void componentTests() throws Exception {
        this.runComponentTest(config);
        this.runModuleUnitTestsIfEnabled(config);
    }

}


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/tools/quic/quic_simple_server_socket.h"

#include "net/base/net_errors.h"
#include "net/log/net_log_source.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_constants.h"

namespace net {

std::unique_ptr<UDPServerSocket> CreateQuicSimpleServerSocket(
    const IPEndPoint& address,
    IPEndPoint* server_address) {
  auto socket =
      std::make_unique<UDPServerSocket>(/*net_log=*/nullptr, NetLogSource());

  socket->AllowAddressReuse();

  int rc = socket->Listen(address);
  if (rc < 0) {
    LOG(ERROR) << "Listen() failed: " << ErrorToString(rc);
    return nullptr;
  }

  // These send and receive buffer sizes are sized for a single connection,
  // because the default usage of QuicSimpleServer is as a test server with
  // one or two clients.  Adjust higher for use with many clients.
  rc = socket->SetReceiveBufferSize(
      static_cast<int32_t>(quic::kDefaultSocketReceiveBuffer));
  if (rc < 0) {
    LOG(ERROR) << "SetReceiveBufferSize() failed: " << ErrorToString(rc);
    return nullptr;
  }

  rc = socket->SetSendBufferSize(20 * quic::kMaxOutgoingPacketSize);
  if (rc < 0) {
    LOG(ERROR) << "SetSendBufferSize() failed: " << ErrorToString(rc);
    return nullptr;
  }

  rc = socket->GetLocalAddress(server_address);
  if (rc < 0) {
    LOG(ERROR) << "GetLocalAddress() failed: " << ErrorToString(rc);
    return nullptr;
  }

  VLOG(1) << "Listening on " << server_address->ToString();
  return socket;
}

}  // namespace net


text:
/*
 * SparseAccumulator.h
 *
 *  Created on: 14.05.2014
 *      Author: Michael Wegner (michael.wegner@student.kit.edu)
 */

#ifndef SPARSEACCUMULATOR_H_
#define SPARSEACCUMULATOR_H_

#include <list>
#include <cassert>

namespace NetworKit {

/**
 * The SparseAccumulator class represents the sparse accumulator datastructure as described in Kepner, Jeremy, and John Gilbert, eds.
 * Graph algorithms in the language of linear algebra. Vol. 22. SIAM, 2011. It is used as temporal storage for efficient computations on matrices.
 */
class SparseAccumulator {
private:
	/** row indicator used to avoid resetting the occupied vector */
	count row;

protected:
	/** dense vector of doubles which stores the computed values */
	std::vector<double> values; // w

	/** dense vector of integers which stores whether a valid value is stored in values at each position */
	std::vector<count> occupied; // b

	/** unordered list to store the position of valid values in values vector */
	std::list<index> indices; // LS

public:
	/**
	 * Constructs the SparseAccumulator with size @a size.
	 * @param size The size of the SparseAccumulator.
	 */
	SparseAccumulator(count size) : row(1), values(size), occupied(size, 0) {}

	/**
	 * Stores @a value at @a pos. If a valid value is already stored at @a pos then @value is added to that.
	 * @param value The value to store or add at @a pos in values.
	 * @param pos The position in values.
	 */
	void scatter(double value, index pos) {
		assert(pos < values.size());

		if (occupied[pos] < row) {
			values[pos] = value;
			occupied[pos] = row;
			indices.push_back(pos);
		} else {
			values[pos] += value;
		}
	}

	/**
	 * Calls @a handle for each non zero value of the current row.
	 * @note handle signature: handle(index row, index column, double value)
	 * @return The number of non zero values in the current row.
	 *
	 */
	template<typename L> count gather(L handle) {
		count nonZeros = 0;
		for (index idx : indices) {
			handle(row - 1, idx, values[idx]);
			nonZeros++;
		}

		return nonZeros;
	}

	/**
	 * Sets the SparseAccumulator to the next row which invalidates all currently stored data.
	 */
	void increaseRow() {
		row++;
		indices.clear();
	}
};

} /* namespace NetworKit */

#endif /* SPARSEACCUMULATOR_H_ */


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide an exception class for unexternalization operations.
//
//@CLASSES:
//  bslx::TestInStreamException: exception containing unexternalization info
//
//@SEE_ALSO: bslx_testinstream
//
//@DESCRIPTION: This component defines a simple exception object for testing
// exceptions during unexternalization operations.  The exception object
// 'bslx::TestInStreamException' contains information about an
// unexternalization request, which can be queried by the "catcher" of the
// exception.
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1:  Throw and Catch
///- - - - - - - - - - - - - -
// In the following example, the 'bslx::TestInStreamException' object is
// thrown, caught, and examined.   First, set up a 'try' block and throw the
// exception with the indication that the exception occurred during
// unexternalization of an 'unsigned int':
//..
//  try {
//      throw TestInStreamException(bslx::TypeCode::e_UINT32);
//..
// Then, catch the exception and verify the indicated cause of the exception:
//..
//  } catch (const bslx::TestInStreamException& e) {
//      assert(bslx::TypeCode::e_UINT32 == e.dataType());
//  }
//..

#include <bslscm_version.h>

#include <bslx_typecode.h>

namespace BloombergLP {
namespace bslx {

                        // ===========================
                        // class TestInStreamException
                        // ===========================

class TestInStreamException {
    // This class defines an exception object for unexternalization operations.
    // Instances of this class contain information about an unexternalization
    // request.

    // DATA
    TypeCode::Enum d_dataType;  // type of the input data requested

  public:
    // CREATORS
    explicit TestInStreamException(TypeCode::Enum type);
        // Create an exception object initialized with the specified 'type'.

    //! ~TestInStreamException() = default;
        // Destroy this object.  Note that this method's definition is compiler
        // generated.

    // ACCESSORS
    TypeCode::Enum dataType() const;
        // Return the type code that was supplied at construction of this
        // exception object.
};

// ============================================================================
//                           INLINE DEFINITIONS
// ============================================================================

                        // ---------------------------
                        // class TestInStreamException
                        // ---------------------------

// CREATORS
inline
TestInStreamException::TestInStreamException(TypeCode::Enum type)
: d_dataType(type)
{
}

// ACCESSORS
inline
TypeCode::Enum TestInStreamException::dataType() const
{
    return d_dataType;
}

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package rawstreamer

import (
	"encoding/binary"
	"math"
)

const (
	EncodingSignedInt = 1 + iota
	EncodingUnsignedInt
	EncodingFloatingPoint

	EncodingLittleEndian = 1 << 6
	EncodingBigEndian    = 1 << 7
)

const EncodingMask byte = ^byte(EncodingLittleEndian | EncodingBigEndian)

var EncodingString = map[byte]string{
	EncodingSignedInt:     "int",
	EncodingUnsignedInt:   "uint",
	EncodingFloatingPoint: "float",
}

func ReadFloat32(buf []byte, format byte, endianness binary.ByteOrder) float32 {
	encoding := format & EncodingMask

	if encoding == EncodingFloatingPoint {
		return math.Float32frombits(endianness.Uint32(buf))
	} else {
		offset := 0
		if endianness == binary.LittleEndian {
			offset = len(buf) - 1
		}
		var neg byte = 0
		if encoding == EncodingSignedInt && buf[offset]&(1<<7) != 0 {
			neg = 0xFF
		}
		tmp := []byte{neg, neg, neg, neg}

		if endianness == binary.BigEndian {
			copy(tmp[4-len(buf):], buf)
		} else {
			copy(tmp, buf)
		}

		sample := endianness.Uint32(tmp)

		div := math.Pow(2, float64(len(buf)*8-1))
		if encoding == EncodingSignedInt {
			return float32(float64(int32(sample)) / div)
		} else {
			return float32(float64(sample)/div - 1.0)
		}
	}
}

func WriteFloat32(buf []byte, sample float32, format byte, endianness binary.ByteOrder) {
	encoding := format & EncodingMask

	if encoding == EncodingFloatingPoint {
		endianness.PutUint32(buf, math.Float32bits(sample))
	} else {
		mult := math.Pow(2, float64(len(buf)*8-1))
		var offset float64 = -0.5 // Round instead of floor
		if encoding == EncodingUnsignedInt {
			offset = mult - 1.5
		}

		bits := uint32(float64(sample)*mult + offset)

		tmp := make([]byte, 4)
		endianness.PutUint32(tmp, bits)

		if endianness == binary.BigEndian {
			copy(buf, tmp[4-len(buf):4])
		} else {
			copy(buf, tmp)
		}
	}
}


text:
//
//  SonyCameraSettingView03Controller.m
//  dConnectDeviceSonyCamera
//
//  Copyright (c) 2014 NTT DOCOMO, INC.
//  Released under the MIT license
//  http://opensource.org/licenses/mit-license.php
//

#import "SonyCameraSettingView03Controller.h"

@interface SonyCameraSettingView03Controller ()

@end

@implementation SonyCameraSettingView03Controller

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Boost.Geometry (aka GGL, Generic Geometry Library)</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Examples

File List

File Members

home

travis

build

boostorg

boost

boost

geometry

algorithms

detail

overlay

Namespaces |
Functions

get_intersection_points.hpp File Reference

Namespaces

 	boost

 	boost::geometry

Functions

template<typename Geometry1 , typename Geometry2 , typename RobustPolicy , typename Turns >

void 	boost::geometry::get_intersection_points (Geometry1 const &geometry1, Geometry2 const &geometry2, RobustPolicy const &robust_policy, Turns &turns)

April 2, 2011

Copyright © 2007-2011 Barend Gehrels, Amsterdam, the Netherlands

Copyright © 2008-2011 Bruno Lalande, Paris, France

Copyright © 2009-2010 Mateusz Loskot, London, UK

<address style="text-align: right;">
Documentation is generated by Doxygen
</address>


text:
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

angular.module('mm.core.courses')

/**
 * Controller to handle the courses list.
 *
 * @module mm.core.courses
 * @ngdoc controller
 * @name mmCoursesListCtrl
 */
.controller('mmCoursesListCtrl', function($scope, $mmCourses, $mmCoursesDelegate, $mmUtil) {

    // Convenience function to fetch courses.
    function fetchCourses(refresh) {
        return $mmCourses.getUserCourses(refresh).then(function(courses) {
            $scope.courses = courses;
            angular.forEach(courses, function(course) {
                course._handlers = [];
                $mmCoursesDelegate.getNavHandlersFor(course.id).then(function(handlers) {
                    course._handlers = handlers;
                });
            });
            $scope.filterText = ''; // Filter value MUST be set after courses are shown.
        }, function(error) {
            if (typeof error != 'undefined' && error !== '') {
                $mmUtil.showErrorModal(error);
            } else {
                $mmUtil.showErrorModal('mm.courses.errorloadcourses', true);
            }
        });
    }
    fetchCourses().finally(function() {
        $scope.coursesLoaded = true;
    });

    $scope.refreshCourses = function() {
        fetchCourses(true).finally(function() {
            $scope.$broadcast('scroll.refreshComplete');
        });
    };
});


text:
using System;
using System.Collections.Generic;
using OpenSource.Data.HashFunction.ELF64;
using OpenSource.Data.HashFunction.Test._Utilities;
using System.Text;
using Xunit;

namespace OpenSource.Data.HashFunction.Test.ELF64
{
    public class ELF64_Implementation_Tests
    {

        #region HashSizeInBits

        [Fact]
        public void ELF64_Implementation_HashSizeInBits_IsNotChanged()
        {
            var elf64 = new ELF64_Implementation();

            Assert.Equal(32, elf64.HashSizeInBits);
        }

        #endregion

        public class IStreamableHashFunction_Tests_ELF64
            : IStreamableHashFunction_TestBase<IELF64>
        {
            protected override IEnumerable<KnownValue> KnownValues { get; } =
                new KnownValue[] {
                new KnownValue(32, TestConstants.Empty, 0x00000000),
                new KnownValue(32, TestConstants.FooBar, 0x06d65882),
                new KnownValue(32, TestConstants.LoremIpsum, 0x09e0a53e),
                };

            protected override IELF64 CreateHashFunction(int hashSize) =>
                new ELF64_Implementation();
        }

    }
}


text:
package hu.unideb.bernkastel.controller;

import com.google.gson.annotations.Expose;
import hu.unideb.bernkastel.model.*;
import org.apache.commons.math3.util.Precision;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static hu.unideb.bernkastel.view.Main.logger;

/**
 * The representation of a game world.
 *
 * @author Bernkastel
 */
final public class Game {
    /** The Location the Magus is currently in.*/
    @Expose(serialize = true, deserialize = true)
    private Location currentLocation;

    /** The worldState.*/
    @Expose(serialize = true, deserialize = true)
    private WorldState worldState;

    /** The Chasm.*/
    @Expose(serialize = true, deserialize = true)
    private Chasm chasm;

    /**
     * Part of the Singleton Design Pattern. The single instance gets created on the first call of  {@link #getInstance()}.
     */
    private static Game instance;

    /**
     * Private constructor part of Singleton Design Pattern. Get the single Game object with {@link #getInstance()}
     */
    private Game() {}

    /**
     *  Part of the Singleton Design Pattern, the instance gets created only when it is called for first time.
     * @return a new {@code Game} object if called for the first time, otherwise returns the same {@code instance} object.
     */
    public static Game getInstance() {
            if (instance == null) {
                instance = new Game();
            }
            return instance;
    }

    /**
     * Setter method for {@code gameInstance}.
     * @param gameInstance the {@code Game} to set {@code instance} to.
     */
    public static void setInstance(Game gameInstance){
        instance = gameInstance;
    }

    /**
     * Resets the game, setting each value to the default. Called before starting a new game.
     * Sets currentLocation to Castle Location, initializes events that will be randomised.
     * Initializes worldState and Chasm.
     */
    public void resetGame(){
        logger.debug("Resetting Game");
        LocationBuilder locationBuilder = new LocationBuilder();
        Location startLocation = locationBuilder.build(LocationId.CASTLE);

        RandomEventsBuilder randomEventsBuilder = new RandomEventsBuilder();
        List<Event> events = randomEventsBuilder.build("events1");

        worldState = new WorldState(events);
        chasm = new Chasm();
        currentLocation = startLocation;
    }

    /** Resets {@code worldState}, calling its constructor and setting the default values. */
    public void resetWorldState(){
        List<Event> events = new ArrayList<>();
        worldState = new WorldState(events);
    }

    /**
     * Checks if the game world has enough currencies to pick a {@code Choice} of {@code cost} cost.
     * @param currencyType the type of currency the Choice costs
     * @param cost the cost of the Choice
     * @return {@code boolean} that is true if there are enough currencies for the Choice that costs {@code cost}, returns false otherwise
     */
    public boolean hasSufficientFundsForChoice(CurrencyType currencyType, Integer cost){
        return getCurrencyAmount(currencyType) >= calculateChoiceCost( cost );
    }

    /**
     * Checks if the game world has at least {@code cost} currencies of {@code currencyType}.
     * @param currencyType the type of currency
     * @param cost the cost to check
     * @return true if there are atleast {@code cost} currencies of {@code currencyType}, false otherwise
     */
    public boolean hasSufficientFunds(CurrencyType currencyType, Integer cost){
        return getCurrencyAmount(currencyType) >=  cost ;
    }

    /**
     * Calculates actual choice cost based on the base cost and the relationship with the current location.
     * Choices get progressively more expensive as the Magus explores, and picks Choices.
     * @param choiceBaseCost the base cost of the Choice
     * @return the actual cost of the Choice, determined by the {@code worldState.relationship} with the {@code currentLocation}
     */
    public Integer calculateChoiceCost(Integer choiceBaseCost){
        return (int) (choiceBaseCost * Math.pow(1.07, worldState.getRelationships().get(currentLocation.getLocationId())/50.0) );
    }

    /**
     * Picks the {@code choice} and applies its effects. Checks if the {@code choice} can be picked with {@link #hasSufficientFundsForChoice}.
     * If it can, it subtracts the cost of the choice, from the currently available currencies. Increases the relationship value of the Location specified by the choice.
     * If the current location is the Castle, updates the Chasms {@code gatheringBatchSize}.
     * @param choice The choice picked by the Magus.
     */
    public void pickChoice(Choice choice){
        logger.debug("Choice {} has been picked.", choice.getText() );
        if( hasSufficientFundsForChoice( choice.getCurrencyType() , choice.getBaseCost() ) ){
            Integer cost = choice.getBaseCost();
            Integer calculatedCost = calculateChoiceCost( cost );
            Integer currencyAmount = getCurrencyAmount(choice.getCurrencyType());
            LocationId locationId = currentLocation.getLocationId();

            worldState.setRelationshipValue(locationId, worldState.getRelationshipValue(locationId) + cost);
            worldState.setCurrency(choice.getCurrencyType(),  currencyAmount - calculatedCost);
            if(choice.getAffectedFlag() != null){
                logger.debug("Setting flag: {} ", choice.getAffectedFlag());
                worldState.setFlag(choice.getAffectedFlag());
            }
            if(currentLocation.getLocationId() == LocationId.CASTLE){
                updateGatheringBatchSize(chasm.getGatheringBatchSize() , calculateGatheringBonus( cost ) );
                logger.debug("Updated GatheringBatchSize: {}", chasm.getGatheringBatchSize());
            }
        }
    }

    /**
     * Getter method for {@code Event} that has not happened yet.
     * @return the {@code Event}, if there is an event that has not happened yet, and its prerequisite {@code Flags} is true, returns null otherwise.
     */
    public Event getRandomEventNotYetOccured(){
        for( Event event : worldState.getEventOccurrences().keySet() ){
            logger.debug("RandomEvents: Event {} ; occured: {}", event.getEventFlag(), worldState.getEventOccurrences().get(event));
            if( worldState.getEventOccurrences().get(event) == false  && worldState.getFlags().get(event.getEventFlag()) == true) {
                worldState.setEventOccured(event);
                return event;
            }
        }
        return null;
    }

    /**
     * Increses the Chasm {@code gatheringBatchSize} by {@code bonus}.
     * @param currentGatheringBatchSize the current {@code gatheringBatchSize}
     * @param bonus the value to increase the {@code gatheringBatchSize} with
     */
    private void updateGatheringBatchSize(Double currentGatheringBatchSize, Double bonus) {
        chasm.setGatheringBatchSize( currentGatheringBatchSize + bonus );
    }

    /**
     *  Collect a single batch (specified by gatheringBatchSize) of Favors.
     */
    public void collectBatchOfFavors() {
        Integer favors = worldState.getCurrency(CurrencyType.FAVOR);
        setCurrencyAmount(CurrencyType.FAVOR, favors + chasm.getGatheringBatchSize().intValue());
    }

    /**
     *  Increases the current amount of {@code gathersFavors} in the Chasm by the current {@code gatheringBatchSize}.
     */
    public void gatherFavors() {
        logger.debug( "Gathering {} favors.", chasm.getGatheringBatchSize() );
        chasm.setGatheredFavors( chasm.getGatheredFavors() + chasm.getGatheringBatchSize().intValue());
    }

    /**
     * Raises currently available Favors by the amount of Favors gathered in the Chasm.
     */
    public void harvestGatheredFavors() {
        logger.debug( "Harvesting {} favors!", chasm.getGatheredFavors());
        worldState.setCurrency(CurrencyType.FAVOR, getCurrencyAmount(CurrencyType.FAVOR) + chasm.getGatheredFavors());
        chasm.setGatheredFavors(0);
    }

    /**
     * Calculates the bonus a spell adds to the Favor production of the Chasm.
     * Spells cast in the Castle upgrade the Chasms ability to gather Favors, based on their cost.
     * @param costOfSpell The cost of the spell.
     * @return the bonus the spell adds to the Favor gathering batch size
     */
    public Double calculateGatheringBonus(Integer costOfSpell){
        return  (costOfSpell/15.0 * Math.pow(1.07, worldState.getRelationships().get(currentLocation.getLocationId())/5.0) );
    }

    /**
     * Checks if the  value for {@code flag} key in worldState {@code flags} is true.
     * @param flag the {@code Flags} to
     * @return True if the {@code boolean} value for {@code flag} key in worldState {@code flags} is true, false otherwise.
     */
    public boolean isFlagSet(Flags flag) {
        return worldState.getFlag(flag);
    }

    /**
     * Creates a single {@code currencyType} if game has enough currencies to do so.
     * @param currencyType the type of currency to create.
     * @param neededCurrency the currency to be exchanged
     * @param cost the amount of {@code neededCurrency} that needs to be exchanged for a {@code currencyType}
     */
    public void createCurrency(CurrencyType currencyType, CurrencyType neededCurrency, Integer cost) {
        if (hasSufficientFunds(neededCurrency, cost)) {
            logger.debug("Creating a {}", currencyType);

            if (currencyType == CurrencyType.FORTUNE) {
                logger.debug("Adding 1 Fortune");
                worldState.setCurrency(CurrencyType.FORTUNE, worldState.getCurrency(CurrencyType.FORTUNE) + 1);

            } else if (currencyType == CurrencyType.FATE) {
                logger.debug("Adding 1 Fate");
                worldState.setCurrency(CurrencyType.FATE, worldState.getCurrency(CurrencyType.FATE) + 1);
            }
        }
    }

    /**
     * Getter method for current amount of {@code currencyType} currency.
     * @param currencyType the type of currency to get amount of.
     * @return the currently available amount of {@code currencyType} currency.
     */
    public Integer getCurrencyAmount(CurrencyType currencyType){
        return worldState.getCurrency(currencyType);
    }

    /**
     * Setter method for {@code value} amount of {@code currencyType} currency.
     * @param currencyType the type of currency to set
     * @param value the value to set the {@code currencyType} of currency to.
     */
    public void setCurrencyAmount(CurrencyType currencyType, Integer value){
        worldState.setCurrency(currencyType, value);
    }

    /**
     * Getter method for currentLocation.
     * @return the current location of the Magus.
     */
    public Location getCurrentLocation() {
        return currentLocation;
    }

    /**
     * Setter method for currentLocation.
     * @param currentLocation the Location to set the current location of the Magus to.
     */
    public void setCurrentLocation(Location currentLocation) {
        this.currentLocation = currentLocation;
    }

    /**
     * Getter method for {@code LocationId} of currentLocation.
     * @return the {@code LocationId} of the {@code currentLocation}
     */
    public LocationId getCurrentLocationId() {
        return currentLocation.getLocationId();
    }

    /**
     * Getter method for specific flag in {@code flags} in WorldState.
     * @param flag the {@code Flags} as the key
     * @return the value of {@code flag} in {@code flags} in WorldState, a {@code boolean} representing that the events or milestone has passed.
     */
    public boolean getFlag(Flags flag) {
        return worldState.getFlag(flag);
    }

    /**
     * Setter method for {@code flags} in WorldState.
     * @param flags map of {@code Flags} keys and {@code boolean} values, that represent events or milestones, and if they have passed
     */
    public void setFlag(Flags flags) {
        worldState.setFlag(flags);
    }

    /**
     * Getter method for {@code flags} in WorldState.
     * @return map of {@code Flags} keys and {@code boolean} values, that represent events or milestones, and if they have passed
     */
    public Map<Flags, Boolean> getFlags(){
        return worldState.getFlags();
    }

    /**
     * Getter method for gatheredFavors in Chasm.
     * @return the amount of Favors gathered in the Chasm.
     */
    public Integer getGatheredFavors() {
        return chasm.getGatheredFavors();
    }

    /**
     * Setter method for gatheredFavors in Chasm.
     * @param gatheredFavors the amount of Favors to set.
     */
    public void setGatheredFavors(Integer gatheredFavors) {
        chasm.setGatheredFavors(gatheredFavors);
    }

    /**
     * Getter method for gatheringMultiplier in Chasm.
     * @return the gatheringMultiplier rounded to two decimal places.
     */
    public Double getGatheringMultiplier() {
        logger.debug( " GatheringBatchSize is: {} " , chasm.getGatheringBatchSize());
        return Precision.round( chasm.getGatheringBatchSize(),2) / Constants.baseGatheringBatchSize;
    }

    /**
     * Getter method for gatheringBatchSize in Chasm.
     * @return the amount of Favors to gather in a gathering.
     */
    public Double getGatheringBatchSize(){
        return chasm.getGatheringBatchSize();
    }

    /**
     * Setter method for gatheringBatchSize in Chasm.
     * @param gatheringBatchSize the amount of Favors to gather in a gathering.
     */
    public void setGatheringBatchSize(Double gatheringBatchSize){
        chasm.setGatheringBatchSize(gatheringBatchSize);
    }

    /**
     * The Game toString method.
     * @return the Game object formatted as a String.
     */
    @Override
    public String toString() {
        return "Game{" +
                "currentLocation=" + currentLocation +
                ", worldState=" + worldState +
                ", chasm=" + chasm +
                '}';
    }
}


text:
<Alloy>
	<TableViewRow id="Wrapper" />
</Alloy>


text:
layout: page
title: Sky Solutions Seminar
date: 2016-05-24
author: Grace Andersen
tags: weekly links, java
status: published
summary: Nam vulputate orci lectus, at.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 05/16/2017
  endDate: 05/17/2017
  ctyhocn: HUTKSHX
  groupCode: SSS
published: true
---
Nunc quis tincidunt mauris. Suspendisse volutpat pharetra dictum. Vestibulum iaculis ligula non orci pellentesque faucibus. Aenean ut scelerisque libero. Nam pulvinar consectetur dui id consectetur. Nullam venenatis, quam in varius blandit, eros metus ullamcorper massa, et iaculis diam elit nec justo. Etiam vel ligula lorem. Integer sed mi sed mauris tincidunt elementum.

* Fusce vitae risus at dui eleifend ullamcorper quis et turpis.

Nam volutpat porta sapien et sagittis. Morbi ac diam quis nibh tristique gravida. Integer non sem auctor, pellentesque est nec, semper nisi. Proin eget justo tristique, pulvinar ipsum et, venenatis ligula. Duis eros ante, malesuada sed lectus ut, egestas semper velit. Nulla lorem orci, dictum ac ullamcorper finibus, dapibus vitae mi. In varius hendrerit libero a pharetra. Nunc tellus ex, viverra at sodales ut, elementum non nisl. Curabitur mattis quis nisi lacinia condimentum. Morbi id blandit lectus, sed convallis libero. Sed odio sem, malesuada et odio sed, interdum vehicula enim.


text:
#pragma once

#include <utility>
#include <string_view>

#include "field.hpp"
#include "debug.hpp"
#include "value_traits.hpp"

namespace med {

template <std::size_t MIN, std::size_t MAX>
struct octets
{
	template <typename TO, typename FROM> requires (sizeof(TO) == sizeof(FROM))
	static void copy(TO* out, FROM const* in, std::size_t size)
	{
		if constexpr (MIN != MAX) //varying string
		{
			std::memcpy(out, in, size);
		}
		else //fixed string
		{
			(void)size;
			copy_impl(out, in, std::make_index_sequence<MIN>{});
		}
	}

private:
	template <typename TO, typename FROM>
	static constexpr void copy_octet(TO*, FROM const*) { }

	template <typename TO, typename FROM, std::size_t OFS, std::size_t... Is>
	static void copy_octet(TO* out, FROM const* in)
	{
		out[OFS] = in[OFS];
		copy_octet<TO, FROM, Is...>(out, in);
	}

	template <typename TO, typename FROM, std::size_t... Is>
	static void copy_impl(TO* out, FROM const* in, std::index_sequence<Is...>)
	{
		copy_octet<TO, FROM, Is...>(out, in);
	}
};

//variable length octets with external storage
class octets_var_extern
{
public:
	bool is_set() const                         { return m_data != nullptr; }

	std::size_t size() const                    { return m_size; }
	uint8_t const* data() const                 { return m_data; }

	void clear()                                { m_data = nullptr; m_size = 0; }
	void assign(void const* b_, void const* e_)
	{
		m_data = static_cast<uint8_t const*>(b_);
		m_size = num_octs_t(static_cast<uint8_t const*>(e_) - m_data);
	}

private:
	uint8_t const* m_data {nullptr};
	num_octs_t     m_size {0}; //not using size_t to reduce layout size
};

//variable length octets with internal storage
template <std::size_t MAX_LEN>
class octets_var_intern
{
public:
	bool is_set() const                         { return m_is_set; }

	std::size_t size() const                    { return m_size; }
	void resize(std::size_t v)                  { m_size = num_octs_t((v <= MAX_LEN) ? v : MAX_LEN); m_is_set = true; }
	uint8_t const* data() const                 { return is_set() ? m_data : nullptr; }
	uint8_t* data()                             { return m_data; }
	void clear()                                { m_size = 0; m_is_set = false; }

	//let external data to be set externally (risky but more efficient)
	uint8_t* emplace(std::size_t num)           { resize(num); return data(); }

	//limits are tested externally (octet_string_impl::set_encoded)
	void assign(uint8_t const* beg_, uint8_t const* end_)
	{
		m_size = num_octs_t(end_ - beg_);
		octets<0, MAX_LEN>::copy(m_data, beg_, m_size);
		m_is_set = true;
	}

private:
	uint8_t     m_data[MAX_LEN];
	num_octs_t  m_size {0};
	bool        m_is_set {false};
};

//fixed length octets with external storage
template <std::size_t LEN>
class octets_fix_extern
{
public:
	bool is_set() const                         { return nullptr != data(); }

	constexpr std::size_t size() const          { return LEN; }
	uint8_t const* data() const                 { return m_data; }

	void clear()                                { m_data = nullptr; }
	void assign(uint8_t const* p, void const*)  { m_data = p; }

private:
	uint8_t const* m_data {nullptr};
};

//fixed length octets with internal storage
template <std::size_t LEN>
class octets_fix_intern
{
public:
	bool is_set() const                         { return m_is_set; }

	static constexpr std::size_t size()         { return LEN; }
	uint8_t const* data() const                 { return m_data; }
	uint8_t* data()                             { return m_data; }

	void clear()                                { m_is_set = false; }
	//let external data to be set externally (risky but more efficient)
	uint8_t* emplace()                          { m_is_set = true; return data(); }

	//copy external data
	void assign(uint8_t const* p, void const*)  { octets<LEN, LEN>::copy(m_data, p, 0); m_is_set = true; }

private:
	uint8_t     m_data[LEN];
	bool        m_is_set {false};
};

template <class TRAITS, class VALUE = octets_var_extern>
struct octet_string_impl : IE<IE_OCTET_STRING>
{
	using traits     = TRAITS;
	using elem_type  = typename traits::value_type;
	using value_type = VALUE;
	using base_t = octet_string_impl;

	constexpr std::size_t size() const          { return m_value.size(); }

	elem_type const* data() const               { return m_value.data(); }
	using const_iterator = elem_type const*;
	const_iterator begin() const                { return data(); }
	const_iterator end() const                  { return begin() + size(); }
	const_iterator cbegin() const               { return begin(); }
	const_iterator cend() const                 { return end(); }

	auto* data()                                { return m_value.data(); }
	using iterator = elem_type const*;
	iterator begin()                            { return data(); }
	iterator end()                              { return begin() + size(); }

	void clear()                                { m_value.clear(); }

	template <class... ARGS>
	void copy(base_t const& from, ARGS&&...)
	{
		clear();
		m_value.assign(from.begin(), from.end());
	}

	template <class T = VALUE> decltype(std::declval<T>().resize(0))
	resize(std::size_t new_size)                { return m_value.resize(new_size); }

	template <class T = VALUE> decltype(std::declval<T>().emplace())
	emplace()                                   { return m_value.emplace(); }
	template <class T = VALUE> decltype(std::declval<T>().emplace(0))
	emplace(std::size_t num_bytes)              { return m_value.emplace(num_bytes); }

	bool set(std::size_t len, void const* data) { return set_encoded(len, data); }
	bool set()                                  { return set_encoded(0, this); }
	bool set(ADataContainer auto const& s)      { return this->set(s.size(), s.data()); }
	template <typename T, std::size_t N>
	bool set(T const(&arr)[N])                  { return set(N * sizeof(T), arr); }

	//NOTE: do not override!
	bool set_encoded(std::size_t len, void const* data)
	{
		if constexpr (traits::min_octets != 0)
		{
			if (len < traits::min_octets)
			{
				CODEC_TRACE("ERROR: len=%zu < min=%zu", len, traits::min_octets);
				//m_value.clear();
				return false;
			}
		}
		if constexpr (traits::max_octets != inf())
		{
			if (len > traits::max_octets)
			{
				CODEC_TRACE("ERROR: len=%zu > max=%zu", len, traits::max_octets);
				//m_value.clear();
				return false;
			}
		}
		auto it = static_cast<iterator>(data);
		m_value.assign(it, it + len);
		return is_set();
	}

	value_type const& get() const               { return m_value; }
	bool is_set() const                         { return m_value.is_set(); }
	explicit operator bool() const              { return is_set(); }

	bool operator==(octet_string_impl const& rhs) const noexcept
	{
		return size() == rhs.size() && 0 == std::memcmp(data(), rhs.data(), size());
	}

protected:
	value_type  m_value;
};

template <class VALUE = octets_var_extern, class = void, class = void>
struct octet_string;

//ASCII-printable string not zero-terminated
template <class ...T>
struct ascii_string : octet_string<T...>
{
	using base_t = octet_string<T...>;
	using base_t::set;

	std::string_view get() const            { return std::string_view{(char const*)this->data(), this->size()}; }
	bool set(char const* psz)               { return this->set(std::string_view{psz}); }
	template <std::size_t N>
	bool set(char const(&arr)[N])           { return this->set(std::string_view{arr, strnlen(arr, N)}); }

	template <std::size_t N>
	void print(char (&sz)[N]) const
	{
		auto const& s = this->get();
		std::snprintf(sz, sizeof(sz), "%.*s", int(s.size()), s.data());
	}
};

constexpr std::size_t MAX_OCTS = std::numeric_limits<num_octs_t>::max();

template <class VALUE>
struct octet_string<VALUE, void, void>
		: octet_string_impl<detail::octet_traits<uint8_t, 0, MAX_OCTS>, VALUE> {};
template <class VALUE, class EXT_TRAITS>
struct octet_string<VALUE, EXT_TRAITS, void>
		: octet_string_impl<detail::octet_traits<uint8_t, 0, MAX_OCTS, EXT_TRAITS>, VALUE> {};

template <std::size_t MIN>
struct octet_string<min<MIN>, void, void>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX_OCTS>, octets_var_extern> {};
template <class VALUE, std::size_t MIN>
struct octet_string<VALUE, min<MIN>, void>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX_OCTS>, VALUE> {};
template <std::size_t MIN, class VALUE>
struct octet_string<min<MIN>, VALUE, void>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX_OCTS>, VALUE> {};

template <std::size_t MAX>
struct octet_string<max<MAX>, void, void>
		: octet_string_impl<detail::octet_traits<uint8_t, 0, MAX>, octets_var_extern> {};
template <class VALUE, std::size_t MAX>
struct octet_string<VALUE, max<MAX>, void>
		: octet_string_impl<detail::octet_traits<uint8_t, 0, MAX>, VALUE> {};
template <std::size_t MAX, class VALUE>
struct octet_string<max<MAX>, VALUE, void>
		: octet_string_impl<detail::octet_traits<uint8_t, 0, MAX>, VALUE> {};

template <std::size_t MIN, std::size_t MAX>
struct octet_string<min<MIN>, max<MAX>, void>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX>, octets_var_extern> {};
template <class VALUE, std::size_t MIN, std::size_t MAX>
struct octet_string<VALUE, min<MIN>, max<MAX>>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX>, VALUE> {};
template <std::size_t MIN, std::size_t MAX, class VALUE>
struct octet_string<min<MIN>, max<MAX>, VALUE>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX>, VALUE> {};

template <std::size_t FIXED>
struct octet_string<octets_fix_extern<FIXED>, void, void>
		: octet_string_impl<detail::octet_traits<uint8_t, FIXED>, octets_fix_extern<FIXED>>
{
	using base_t = octet_string_impl<detail::octet_traits<uint8_t, FIXED>, octets_fix_extern<FIXED>>;
	using base_t::set;

	void set(uint8_t const(&data)[FIXED])   { this->set_encoded(FIXED, &data[0]); }
};

template <std::size_t FIXED>
struct octet_string<octets_fix_intern<FIXED>, void, void>
		: octet_string_impl<detail::octet_traits<uint8_t, FIXED>, octets_fix_intern<FIXED>>
{
	using base_t = octet_string_impl<detail::octet_traits<uint8_t, FIXED>, octets_fix_intern<FIXED>>;
	using base_t::set;

	void set(uint8_t const(&data)[FIXED])   { this->set_encoded(FIXED, &data[0]); }
};
template <std::size_t MAX, std::size_t MIN>
struct octet_string<octets_var_intern<MAX>, min<MIN>, void>
		: octet_string_impl<detail::octet_traits<uint8_t, MIN, MAX>, octets_var_intern<MAX>> {};

}	//end: namespace med


text:
package org.localmatters.lesscss4j.model.expression;

public class MultiplyExpression extends CompoundExpression {
    public MultiplyExpression() {
    }

    public MultiplyExpression(MultiplyExpression copy) {
        super(copy);
    }

    public MultiplyExpression(Expression left, Expression right) {
        super(left, right);
    }

    @Override
    public ConstantValue evaluate(ConstantValue left, ConstantValue right) {
        return left.multiply(right);
    }

    @Override
    public MultiplyExpression clone() {
        return new MultiplyExpression(this);
    }
}


text:
"use strict";

module.exports = function getShortMessages(messages) {
  return messages.filter(function(object) {
    return object.message.length < 50;
  }).map(function(object) {
    return object.message;
  });
};


text:
from conans import ConanFile, CMake
from conans.errors import ConanException

class TinyAesCConan(ConanFile):
    name = "tiny-AES-c"
    version = "1.0.0"
    license = "The Unlicense"
    url = "https://github.com/kokke/tiny-AES-c"
    description = "Small portable AES128/192/256 in C"
    topics = ("encryption", "crypto", "AES")
    settings = "os", "compiler", "build_type", "arch"

    generators = "cmake"
    exports_sources = ["CMakeLists.txt", "*.c", '*.h', '*.hpp']
    exports = ["unlicense.txt"]

    _options_dict = {
        # enable AES128
        "AES128": [True, False],

        # enable AES192
        "AES192": [True, False],

        # enable AES256
        "AES256": [True, False],

        # enable AES encryption in CBC-mode of operation
        "CBC": [True, False],

        # enable the basic ECB 16-byte block algorithm
        "ECB": [True, False],

        # enable encryption in counter-mode
        "CTR": [True, False],
    }

    options = _options_dict

    default_options = {
        "AES128": True,
        "AES192": False,
        "AES256": False,
        "CBC": True,
        "ECB": True,
        "CTR": True
    }

    def configure(self):
        if not self.options.CBC and not self.options.ECB and not self.options.CTR:
            raise ConanException("Need to at least specify one of CBC, ECB or CTR modes")

        if not self.options.AES128 and not self.options.AES192 and not self.options.AES256:
            raise ConanException("Need to at least specify one of AES{128, 192, 256} modes")

    def build(self):
        cmake = CMake(self)

        for key in self._options_dict.keys():
            if self.options[key]:
                cmake.definitions["CMAKE_CFLAGS"].append(key)

        cmake.configure()
        cmake.build()

    def package(self):
        self.copy("*.h", dst="include")
        self.copy("*.hpp", dst="include")
        self.copy("*.a", dst="lib", keep_path=False)
        self.copy("unlicense.txt")

    def package_info(self):
        self.cpp_info.libs = ["tiny-aes"]


text:
<?php

namespace Zend\Validator\Barcode;

/**
 * @category   Zend
 * @package    Zend_Validate
 */
class Code93ext extends AbstractAdapter
{
    /**
     * Constructor for this barcode adapter
     */
    public function __construct()
    {
        $this->setLength(-1);
        $this->setCharacters(128);
        $this->useChecksum(false);
    }
}


text:
package entitysearch

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"net/http"
)

// EntitiesClient is the the Entity Search API lets you send a search query to Bing and get back search results that
// include entities and places. Place results include restaurants, hotel, or other local businesses. For places, the
// query can specify the name of the local business or it can ask for a list (for example, restaurants near me). Entity
// results include persons, places, or things. Place in this context is tourist attractions, states, countries, etc.
type EntitiesClient struct {
	BaseClient
}

// NewEntitiesClient creates an instance of the EntitiesClient client.
func NewEntitiesClient() EntitiesClient {
	return NewEntitiesClientWithBaseURI(DefaultBaseURI)
}

// NewEntitiesClientWithBaseURI creates an instance of the EntitiesClient client.
func NewEntitiesClientWithBaseURI(baseURI string) EntitiesClient {
	return EntitiesClient{NewWithBaseURI(baseURI)}
}

// Search sends the search request.
//
// query is the user's search term. acceptLanguage is a comma-delimited list of one or more languages to use for
// user interface strings. The list is in decreasing order of preference. For additional information, including
// expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the
// setLang query parameter are mutually exclusive; do not specify both. If you set this header, you must also
// specify the cc query parameter. Bing will use the first supported language it finds from the list, and combine
// that language with the cc parameter value to determine the market to return results for. If the list does not
// include a supported language, Bing will find the closest language and market that supports the request, and may
// use an aggregated or default market for the results instead of a specified one. You should use this header and
// the cc query parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang
// query parameters. A user interface string is a string that's used as a label in a user interface. There are very
// few user interface strings in the JSON response objects. Any links in the response objects to Bing.com
// properties will apply the specified language. pragma is by default, Bing returns cached content, if available.
// To prevent Bing from returning cached content, set the Pragma header to no-cache (for example, Pragma:
// no-cache). userAgent is the user agent originating the request. Bing uses the user agent to provide mobile users
// with an optimized experience. Although optional, you are strongly encouraged to always specify this header. The
// user-agent should be the same string that any commonly used browser would send. For information about user
// agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). clientID is bing uses this
// header to provide users with consistent behavior across Bing API calls. Bing often flights new features and
// improvements, and it uses the client ID as a key for assigning traffic on different flights. If you do not use
// the same client ID for a user across multiple requests, then Bing may assign the user to multiple conflicting
// flights. Being assigned to multiple conflicting flights can lead to an inconsistent user experience. For
// example, if the second request has a different flight assignment than the first, the experience may be
// unexpected. Also, Bing can use the client ID to tailor web results to that client ID's search history, providing
// a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing the
// activity generated by a client ID. The relevance improvements help with better quality of results delivered by
// Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you
// should consider this header required. Persisting the client ID across multiple requests for the same end user
// and device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher
// click-through rates via better quality of results from the Bing APIs. Each user that uses your application on
// the device must have a unique, Bing generated client ID. If you do not include this header in the request, Bing
// generates an ID and returns it in the X-MSEdge-ClientID response header. The only time that you should NOT
// include this header in a request is the first time the user uses your app on that device. Use the client ID for
// each Bing API request that your app makes for this user on the device. Persist the client ID. To persist the ID
// in a browser app, use a persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a
// session cookie. For other apps such as mobile apps, use the device's persistent storage to persist the ID. The
// next time the user uses your app on that device, get the client ID that you persisted. Bing responses may or may
// not include this header. If the response includes this header, capture the client ID and use it for all
// subsequent Bing requests for the user on that device. If you include the X-MSEdge-ClientID, you must not include
// cookies in the request. clientIP is the IPv4 or IPv6 address of the client device. The IP address is used to
// discover the user's location. Bing uses the location information to determine safe search behavior. Although
// optional, you are encouraged to always specify this header and the X-Search-Location header. Do not obfuscate
// the address (for example, by changing the last octet to 0). Obfuscating the address results in the location not
// being anywhere near the device's actual location, which may result in Bing serving erroneous results. location
// is a semicolon-delimited list of key/value pairs that describe the client's geographical location. Bing uses the
// location information to determine safe search behavior and to return relevant local content. Specify the
// key/value pair as <key>:<value>. The following are the keys that you use to specify the user's location. lat
// (required): The latitude of the client's location, in degrees. The latitude must be greater than or equal to
// -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and positive values indicate
// northern latitudes. long (required): The longitude of the client's location, in degrees. The longitude must be
// greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate western longitudes
// and positive values indicate eastern longitudes. re (required): The radius, in meters, which specifies the
// horizontal accuracy of the coordinates. Pass the value returned by the device's location service. Typical values
// might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts (optional):
// The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of seconds
// since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the
// direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key
// only if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the
// client device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The
// radius, in meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify
// the alt key. Although many of the keys are optional, the more information that you provide, the more accurate
// the location results are. Although optional, you are encouraged to always specify the user's geographical
// location. Providing the location is especially important if the client's IP address does not accurately reflect
// the user's physical location (for example, if the client uses VPN). For optimal results, you should include this
// header and the X-MSEdge-ClientIP header, but at a minimum, you should include this header. countryCode is a
// 2-character country code of the country where the results come from. This API supports only the United States
// market. If you specify this query parameter, it must be set to us. If you set this parameter, you must also
// specify the Accept-Language header. Bing uses the first supported language it finds from the languages list, and
// combine that language with the country code that you specify to determine the market to return results for. If
// the languages list does not include a supported language, Bing finds the closest language and market that
// supports the request, or it may use an aggregated or default market for the results instead of a specified one.
// You should use this query parameter and the Accept-Language query parameter only if you specify multiple
// languages; otherwise, you should use the mkt and setLang query parameters. This parameter and the mkt query
// parameter are mutually exclusive—do not specify both. market is the market where the results come from. You are
// strongly encouraged to always specify the market, if known. Specifying the market helps Bing route the request
// and return an appropriate and optimal response. This parameter and the cc query parameter are mutually
// exclusive—do not specify both. responseFilter is a comma-delimited list of answers to include in the response.
// If you do not specify this parameter, the response includes all search answers for which there's relevant data.
// responseFormat is the media type to use for the response. The following are the possible case-insensitive
// values: JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes JSON-LD objects
// that contain the search results. safeSearch is a filter used to filter adult content. Off: Return webpages with
// adult text, images, or videos. Moderate: Return webpages with adult text, but not adult images or videos.
// Strict: Do not return webpages with adult text, images, or videos. The default is Moderate. If the request comes
// from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch
// value and uses Strict. If you use the site: query operator, there is the chance that the response may contain
// adult content regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of
// the content on the site and your scenario supports the possibility of adult content. setLang is the language to
// use for user interface strings. Specify the language using the ISO 639-1 2-letter language code. For example,
// the language code for English is EN. The default is EN (English). Although optional, you should always specify
// the language. Typically, you set setLang to the same language specified by mkt unless the user wants the user
// interface strings displayed in a different language. This parameter and the Accept-Language header are mutually
// exclusive; do not specify both. A user interface string is a string that's used as a label in a user interface.
// There are few user interface strings in the JSON response objects. Also, any links to Bing.com properties in the
// response objects apply the specified language.
func (client EntitiesClient) Search(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, responseFilter []AnswerType, responseFormat []ResponseFormat, safeSearch SafeSearch, setLang string) (result SearchResponse, err error) {
	req, err := client.SearchPreparer(ctx, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, countryCode, market, responseFilter, responseFormat, safeSearch, setLang)
	if err != nil {
		err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", nil, "Failure preparing request")
		return
	}

	resp, err := client.SearchSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", resp, "Failure sending request")
		return
	}

	result, err = client.SearchResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", resp, "Failure responding to request")
	}

	return
}

// SearchPreparer prepares the Search request.
func (client EntitiesClient) SearchPreparer(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, responseFilter []AnswerType, responseFormat []ResponseFormat, safeSearch SafeSearch, setLang string) (*http.Request, error) {
	queryParameters := map[string]interface{}{
		"q": autorest.Encode("query", query),
	}
	if len(countryCode) > 0 {
		queryParameters["cc"] = autorest.Encode("query", countryCode)
	}
	if len(market) > 0 {
		queryParameters["mkt"] = autorest.Encode("query", market)
	} else {
		queryParameters["mkt"] = autorest.Encode("query", "en-us")
	}
	if responseFilter != nil && len(responseFilter) > 0 {
		queryParameters["ResponseFilter"] = autorest.Encode("query", responseFilter, ",")
	}
	if responseFormat != nil && len(responseFormat) > 0 {
		queryParameters["ResponseFormat"] = autorest.Encode("query", responseFormat, ",")
	}
	if len(string(safeSearch)) > 0 {
		queryParameters["SafeSearch"] = autorest.Encode("query", safeSearch)
	}
	if len(setLang) > 0 {
		queryParameters["SetLang"] = autorest.Encode("query", setLang)
	}

	preparer := autorest.CreatePreparer(
		autorest.AsGet(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPath("/entities"),
		autorest.WithQueryParameters(queryParameters),
		autorest.WithHeader("X-BingApis-SDK", "true"))
	if len(acceptLanguage) > 0 {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
	}
	if len(pragma) > 0 {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("Pragma", autorest.String(pragma)))
	}
	if len(userAgent) > 0 {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("User-Agent", autorest.String(userAgent)))
	}
	if len(clientID) > 0 {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
	}
	if len(clientIP) > 0 {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
	}
	if len(location) > 0 {
		preparer = autorest.DecoratePreparer(preparer,
			autorest.WithHeader("X-Search-Location", autorest.String(location)))
	}
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// SearchSender sends the Search request. The method will close the
// http.Response Body if it receives an error.
func (client EntitiesClient) SearchSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}

// SearchResponder handles the response to the Search request. The method always
// closes the http.Response Body.
func (client EntitiesClient) SearchResponder(resp *http.Response) (result SearchResponse, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}