text:
package com.microsoft.azure.management.loganalytics.v2020_08_01.implementation;

import com.microsoft.azure.management.loganalytics.v2020_08_01.WorkspacePurgeStatusResponse;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import rx.Observable;
import com.microsoft.azure.management.loganalytics.v2020_08_01.PurgeState;

class WorkspacePurgeStatusResponseImpl extends WrapperImpl<WorkspacePurgeStatusResponseInner> implements WorkspacePurgeStatusResponse {
    private final LogAnalyticsManager manager;
    private String resourceGroupName;
    private String workspaceName;
    private String purgeId;

    WorkspacePurgeStatusResponseImpl(WorkspacePurgeStatusResponseInner inner,  LogAnalyticsManager manager) {
        super(inner);
        this.manager = manager;
    }

    @Override
    public LogAnalyticsManager manager() {
        return this.manager;
    }

    @Override
    public PurgeState status() {
        return this.inner().status();
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OakIdeas.Schema.Core.Events
{
    /// <summary>
    /// Event type: Visual arts event.
    /// </summary>
    /// <see cref="http://www.schema.org/VisualArtsEvent"/>
    public class VisualArtsEvent : Event
    {
    }
}


text:
import * as Fs from 'fs'
import * as Path from 'path'
import { encodePathAsUrl } from './path'

/**
 * Type representing the contents of the gemoji json database
 * which consists of a top-level array containing objects describing
 * emojis.
 */
type IGemojiDb = ReadonlyArray<IGemojiDefinition>

/**
 * Partial (there's more in the db) interface describing the elements
 * in the gemoji json array.
 */
interface IGemojiDefinition {
  /**
   * The unicode string of the emoji if emoji is part of
   * the unicode specification. If missing this emoji is
   * a GitHub custom emoji such as :shipit:
   */
  readonly emoji?: string

  /** One or more human readable aliases for the emoji character */
  readonly aliases: ReadonlyArray<string>

  /** An optional, human readable, description of the emoji  */
  readonly description?: string
}

function getEmojiImageUrlFromRelativePath(relativePath: string): string {
  return encodePathAsUrl(__dirname, 'emoji', relativePath)
}

/**
 * Given a unicode point number, returns a hexadecimal string
 * which is lef padded with zeroes to be at least 4 characters
 */
function getHexCodePoint(cp: number): string {
  const str = cp.toString(16)

  // The combining characters are always stored on disk
  // as zero-padded 4 character strings. Don't ask me why.
  return str.length >= 4 ? str : ('0000' + str).substring(str.length)
}

/**
 * Returns a url to the on disk location of the image
 * representing the given emoji or null in case the
 * emoji unicode string was invalid.
 */
function getUrlFromUnicodeEmoji(emoji: string): string | null {
  const codePoint = emoji.codePointAt(0)

  if (!codePoint) {
    return null
  }

  let filename = getHexCodePoint(codePoint)

  // Some emoji are composed of two unicode code points, they're
  // usually variants of the same theme (like :one:, :two: etc)
  // and they're stored on disk as CP1-CP2.
  if (emoji.length > 2) {
    const combiningCodePoint = emoji.codePointAt(2)

    // 0xfe0f is VARIATION SELECTOR-16 which, best as I can tell means
    // make the character before me all fancy pants. I don't know why
    // but gemoji explicitly excludes this from its naming scheme so
    // we'll do the same.
    if (combiningCodePoint && combiningCodePoint !== 0xfe0f) {
      filename = `${filename}-${getHexCodePoint(combiningCodePoint)}`
    }
  }

  return getEmojiImageUrlFromRelativePath(`unicode/${filename}.png`)
}

/**
 * Read the stored emoji list from JSON into an in-memory representation.
 *
 * @param rootDir - The folder containing the entry point (index.html or main.js) of the application.
 */
export function readEmoji(rootDir: string): Promise<Map<string, string>> {
  return new Promise<Map<string, string>>((resolve, reject) => {
    const path = Path.join(rootDir, 'emoji.json')
    Fs.readFile(path, 'utf8', (err, data) => {
      if (err) {
        reject(err)
        return
      }

      const tmp = new Map<string, string>()

      try {
        const db: IGemojiDb = JSON.parse(data)
        db.forEach(emoji => {
          // Custom emoji don't have a unicode string and are instead stored
          // on disk as their first alias.
          const url = emoji.emoji
            ? getUrlFromUnicodeEmoji(emoji.emoji)
            : getEmojiImageUrlFromRelativePath(`${emoji.aliases[0]}.png`)

          if (!url) {
            log.error(`Could not calculate location of emoji: ${emoji}`)
            return
          }

          emoji.aliases.forEach(alias => {
            tmp.set(`:${alias}:`, url)
          })
        })
      } catch (e) {
        reject(e)
      }

      const emoji = new Map<string, string>()

      // Sort and insert into actual map
      const keys = Array.from(tmp.keys()).sort()
      keys.forEach(k => {
        const value = tmp.get(k)
        if (value) {
          emoji.set(k, value)
        }
      })

      resolve(emoji)
    })
  })
}


text:
#include "Esri/ArcGISRuntime/Toolkit/register.h"
#include "proxies/ArcGISRuntimeEnvironmentProxy.h"
#include "proxies/GeoModelProxy.h"
#include "proxies/MapQuickViewProxy.h"
#include "proxies/SceneQuickViewProxy.h"

#include <QDir>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickStyle>
#include <QtWebView>

#include <ArcGISRuntimeEnvironment.h>
#include <Map.h>
#include <MapQuickView.h>
#include <Scene.h>
#include <SceneQuickView.h>

//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
  QtWebView::initialize();
  QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  QGuiApplication app(argc, argv);

  // Use of Esri location services, including basemaps and geocoding, requires
  // either an ArcGIS identity or an API key. For more information see
  // https://links.esri.com/arcgis-runtime-security-auth.

  // 1. ArcGIS identity: An ArcGIS named user account that is a member of an
  // organization in ArcGIS Online or ArcGIS Enterprise.

  // 2. API key: A permanent key that gives your application access to Esri
  // location services. Create a new API key or access existing API keys from
  // your ArcGIS for Developers dashboard (https://links.esri.com/arcgis-api-keys).

  QString apiKey = QString("");
  if (apiKey.isEmpty())
  {
    apiKey = qgetenv("ARCGIS_RUNTIME_API_KEY");
  }

  if (!apiKey.isEmpty())
  {
    Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(apiKey);
  }

  QQuickStyle::addStylePath("qrc:///esri.com/imports/");

  // Register ArcGIS types with QML.
  qmlRegisterExtendedType<Esri::ArcGISRuntime::MapQuickView,
                          MapQuickViewProxy>("Esri.ArcGISRuntime", 100, 15, "MapView");
  qmlRegisterExtendedType<Esri::ArcGISRuntime::SceneQuickView,
                          SceneQuickViewProxy>("Esri.ArcGISRuntime", 100, 15, "SceneView");
  qmlRegisterUncreatableType<GeoModelProxy>("Esri.ArcGISRuntime",
                                            100,
                                            15,
                                            "Map",
                                            "Map not creatable in QML.");
  qmlRegisterUncreatableType<GeoModelProxy>("Esri.ArcGISRuntime",
                                            100,
                                            15,
                                            "Scene",
                                            "Scene not creatable in QML.");

  qmlRegisterSingletonType<ArcGISRuntimeEnvironmentProxy>(
      "Esri.ArcGISRuntime",
      100,
      15,
      "ArcGISRuntimeEnvironment",
      [](QQmlEngine* engine, QJSEngine*) -> QObject*
      {
        return new ArcGISRuntimeEnvironmentProxy(engine);
      });

  qmlRegisterSingletonType<EnumsProxy>("Esri.ArcGISRuntime",
                                       100,
                                       15,
                                       "Enums",
                                       [](QQmlEngine* engine, QJSEngine*) -> QObject*
                                       {
                                         return new EnumsProxy(engine);
                                       });

  // Register Own types with QML.
  // Initialize application view
  QQmlApplicationEngine engine;
  Esri::ArcGISRuntime::Toolkit::registerComponents(engine);
  engine.load(QUrl("qrc:/demo_app/qml/main.qml"));
  return app.exec();
}

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


text:
package org.experiment.TREC;

/**
 * Created by sonic on 06/09/16.
 */

import org.apache.lucene.benchmark.quality.Judge;
import org.apache.lucene.benchmark.quality.QualityQuery;
import org.apache.lucene.benchmark.quality.QualityQueryParser;
import org.apache.lucene.benchmark.quality.QualityStats;
import org.apache.lucene.benchmark.quality.trec.TrecJudge;
import org.apache.lucene.benchmark.quality.trec.TrecTopicsReader;
import org.apache.lucene.benchmark.quality.utils.SubmissionReport;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.FSDirectory;
import org.experiment.benchmark.EntityQualityBenchmark;
import org.experiment.query.TRECQQParser;
import org.utils.Utilities;

import java.io.*;
import java.nio.file.Paths;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BagOfEntitiesEx {

    private static final int MYTHREADS = 30;
    public static String index;
    private static String topicPath;
    private static String qrelsPath;

    public static void main(String[] args) throws Throwable {

        for(int i = 0;i < args.length;i++) {
            if ("-index".equals(args[i])) {
                index = args[i + 1];
                i++;
            } else if ("-topic".equals(args[i])) {
                topicPath = args[i + 1];
                i++;
            } else if ("-qrels".equals(args[i])) {
                qrelsPath = args[i + 1];
                i++;
            }
        }

        if (args.length == 0) {
            // WT10G
//            index = "/media/sonic/Windows/TREC/index/WT10G";
//            topicPath = "/media/sonic/Windows/TREC/topics/topics.wt10g";
//            qrelsPath = "/media/sonic/Windows/TREC/qrels/qrels.wt10g";
            // disk
//            index = "/media/sonic/Windows/TREC/index/disk45/disk45noCR";
//            topicPath = "/media/sonic/Windows/TREC/topics/topics.disk45.301-450";
//            qrelsPath = "/media/sonic/Windows/TREC/qrels/qrels.disk45.301-450";
            // AP
            index = "/media/sonic/Windows/TREC/index/AP";
            topicPath = "/media/sonic/Windows/TREC/topics/topics.AP.51-150";
            qrelsPath = "/media/sonic/Windows/TREC/qrels/qrels.AP.51-150";
        }

        List<String> similarityList = new ArrayList<>();
        similarityList.add("bm25");
        similarityList.add("LMJelinekMercerSimilarity");
        similarityList.add("lm");
        List<Double> tetaList = new ArrayList<>();
        tetaList.add(1.0); // Baseline
        tetaList.add(0.1);
        tetaList.add(0.2);
        tetaList.add(0.3);
        tetaList.add(0.4);
        tetaList.add(0.5);
        tetaList.add(0.6);
        tetaList.add(0.7);
        tetaList.add(0.8);
        tetaList.add(0.9);
        tetaList.add(0.0);

        String description = "AP"+ "-ENTLM-";
//        String description = "WT10G"+ "-Baseline-";
        File topicsFile = new File(topicPath);
        File qrelsFile = new File(qrelsPath);

        IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
        IndexSearcher searcher = new IndexSearcher(reader);

        TrecTopicsReader qReader = new TrecTopicsReader();
        QualityQuery qqs[] = qReader.readQueries(new BufferedReader(new FileReader(topicsFile)));
        Judge judge = new TrecJudge(new BufferedReader(new FileReader(qrelsFile)));
        QualityQueryParser qqParser = new TRECQQParser(TrecDocIterator.TITLE, TrecDocIterator.CONTENTS);

        ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);

        for (String simstring : similarityList) {
            Similarity simfn = Utilities.getSimilarity(simstring);
            searcher.setSimilarity(simfn);

            EntityQualityBenchmark qrun = new EntityQualityBenchmark(qqs, qqParser, searcher, TrecDocIterator.DOCNO);

            for (double teta : tetaList) {
                qrun.setTeta(teta);
                Runnable worker = new MyRunnable(description, qrun, qqs, judge, qqParser, simstring, teta);
                executor.execute(worker);
                worker.run();
            }
        }

        executor.shutdown();

        // Wait until all threads are finish
        while (!executor.isTerminated()) {

        }
        System.out.println("\nFinished all threads");

    }

    public static class MyRunnable implements Runnable {
        private String description;
        private String simstring;
        private double teta;
        private Judge judge;
        private QualityQuery[] qqs;
        private QualityQueryParser qqParser;
        private EntityQualityBenchmark qrun;

        public MyRunnable(String description, EntityQualityBenchmark qrun, QualityQuery[] qqs, Judge judge, QualityQueryParser qqParser, String simstring, double teta) {
            this.description = description;
            this.qrun = qrun;
            this.simstring = simstring;
            this.teta = teta;
            this.judge = judge;
            this.qqs = qqs;
            this.qqParser = qqParser;
        }

        @Override
        public void run() {
            try {
                PrintWriter logger  = new PrintWriter("test-data/Entity/final/" + description + teta + "-" + simstring + "-report1.out", "UTF-8");
                PrintWriter logger2 = new PrintWriter("test-data/Entity/final/" + description + teta + "-" + simstring + "-report2.out", "UTF-8");
                PrintWriter logger3 = new PrintWriter("test-data/Entity/final/" + description + teta + "-" + simstring + "-report3.out", "UTF-8");
                PrintWriter logger4 = new PrintWriter("test-data/Entity/final/" + description + teta + "-" + simstring + "-report4.out", "UTF-8");

                judge.validateData(qqs, logger);

                SubmissionReport submitLog = new SubmissionReport(logger2, simstring+teta);
                QualityStats stats[] = qrun.execute(judge, submitLog, logger);

                printReport(logger3, stats);

                QualityStats avg = QualityStats.average(stats);        // #6 Print precision and recall measures
                QualityStats.RecallPoint[] rp = avg.getRecallPoints();
                avg.log("SUMMARY -- " + simstring, 2, logger4, "  ");

                logger.close();
                logger2.close();
                logger3.close();
                logger4.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        private void printReport(PrintWriter logger3, QualityStats[] stats) {
            NumberFormat nf = NumberFormat.getInstance(Locale.ROOT);
            nf.setMaximumFractionDigits(4);
            nf.setMinimumFractionDigits(4);
            nf.setGroupingUsed(true);

            QualityStats qualityStats = QualityStats.average(stats);

            logger3.println("SUMMARY -- " + simstring);
            logger3.println("MAP : " + nf.format(qualityStats.getAvp()));
            logger3.println("Average Precision @ 1: " + nf.format(qualityStats.getPrecisionAt(1)));
            logger3.println("Average Precision @ 5: " + nf.format(qualityStats.getPrecisionAt(5)));
            logger3.println("Average Precision @ 10: " + nf.format(qualityStats.getPrecisionAt(10)));
            logger3.println("Average Precision @ 20: " + nf.format(qualityStats.getPrecisionAt(20)));
            logger3.println("==========================");
            int qualityQuery = 1;
            for (QualityStats qualityStat : stats) {
                logger3.println("Quality Stat: " + qualityQuery);
                logger3.println("MAP:  " + nf.format(qualityStat.getAvp()));
                logger3.println("P@1:  " + nf.format(qualityStat.getPrecisionAt(1)));
                logger3.println("P@5:  " + nf.format(qualityStat.getPrecisionAt(5)));
                logger3.println("P@10: " + nf.format(qualityStat.getPrecisionAt(10)));
                logger3.println("P@20: " + nf.format(qualityStat.getPrecisionAt(20)));
                logger3.println("=========================");
                qualityQuery++;
            }
        }
    }
}


text:
class Human : public ListItem
{
private:
    Q_OBJECT
    Q_ENUMS(Roles)

    static long id_counter;
    static QString m_unitVersion;

public:
    enum Roles {
        IdRole = Qt::UserRole + 1,
        FilterStringRole,

        ProfessionRole,
        PosXRole,
        PosYRole,
        PosZRole,
        NameRole,

        ArcherLevelRole,
        BlacksmithLevelRole,
        BuilderLevelRole,
        CarpenterLevelRole,
        EngineerLeveRole,
        FarmerLevelRole,
        FishermanLevelRole,
        ForagerLevelRole,
        InfantryLevelRole,
        MinerLevelRole,
        StoneMasonLevelRole,
        WoodChopperLevelRole,
        TailorLevelRole,
        TraderLevelRole,
        HerderLevelRole,
        AdventurerLevelRole,
        Unknown1Role,
        Unknown2Role,
        Unknown3Role,
        Unknown4Role,

        ExperienceRole,

        AutoChopTreesRole,
        GatherBerriesRole,
        HuntChickenRole,
        HuntBoarRole,
        ShowBowRangeRole,
        TrainNearTargetRole,

        RotationRole,

        EquipHandRole,
        EquipOffhandRole,
        EquipHeadRole,
        EquipBodyRole,
        EquipFeetRole,

        HealthRole,

        MoraleRole,
        FatigueRole,
        HungerRole,

        AdditionalRole

        // NOTE: Options and unknown quantities are yet to be added.
    };

    Human(QObject * parent = 0): ListItem(parent){id_counter++;}

    explicit Human(const QString &profession,
                   const float &posX,
                   const float &posY,
                   const float &posZ,
                   const QString &name,

                   const unsigned int &archerLevel,
                   const unsigned int &blacksmithLevel,
                   const unsigned int &builderLevel,
                   const unsigned int &carpenterLevel,
                   const unsigned int &engineerLevel,
                   const unsigned int &farmerLevel,
                   const unsigned int &fishermanLevel,
                   const unsigned int &foragerLevel,
                   const unsigned int &infantryLevel,
                   const unsigned int &minerLevel,
                   const unsigned int &stoneMasonLevel,
                   const unsigned int &woodChopperLevel,
                   const unsigned int &tailorLevel,
                   const unsigned int &traderLevel,
                   const unsigned int &herderLevel,
                   const unsigned int &adventurerLevel,
                   const unsigned int &unknown1Level,
                   const unsigned int &unknown2Level,
                   const unsigned int &unknown3Level,
                   const unsigned int &unknown4Level,

                   const unsigned int &experience,

                   const bool &autoChop,
                   const bool &gatherBerries,
                   const bool &huntChicken,
                   const bool &huntBoar,
                   const bool &showBowRange,
                   const bool &trainNearTarget,

                   const float &rotation,

                   const unsigned int &equipHand,
                   const unsigned int &equipOffhand,
                   const unsigned int &equipHead,
                   const unsigned int &equipBody,
                   const unsigned int &equipFeet,

                   const unsigned int &health,

                   const QBitArray &options,

                   const float &unknownFloat1,
                   const float &morale,
                   const float &fatigue,
                   const float &hunger,

                   // Inventory data
                   const QList<int> &inventoryPreferences,
                   const QList<int> &inventoryItems,
                   const QList<int> &spareInventory,

                   // Patrol data
                   const QList<float> &patrolSetpoints,
                   const int &patrolIndex,

                   const QString &gardedUnitName,

                   const QList<int> &professionEXP,

                   const float &maxWeight,

                   const signed short &dirty,
                   const QString &rawData,

                   QObject * parent = 0);

    // Builder. This returns a Human which is all set up.
    static Human * build(QString & unitString);

    // Writer. Writes the entire Human class to a file in the Timber and Stone format.
    void writeToFile( QFile &unitFile );

    QVariant data(int role) const;
    QHash<int, QByteArray> roleNames() const;
    QString filterString() const;

    // Setters for properties
    void setDirty();
    void setProfession(QString profession);
    void setMorale(float morale);
    void setFatigue(float fatigue);
    void setHunger(float hunger);

    // Getters for properties
    inline long    id() const { return m_id; }

    inline QString profession() const { return m_profession; }
    inline float posX() const { return m_posX; }
    inline float posY() const { return m_posY; }
    inline float posZ() const { return m_posZ; }
    inline QString name() const { return m_name; }

    inline unsigned int archerLevel() const { return m_archerLevel; }
    inline unsigned int blacksmithLevel() const { return m_blacksmithLevel; }
    inline unsigned int builderLevel() const { return m_builderLevel; }
    inline unsigned int carpenterLevel() const { return m_carpenterLevel; }
    inline unsigned int engineerLevel() const { return m_engineerLevel; }
    inline unsigned int farmerLevel() const { return m_farmerLevel; }
    inline unsigned int fishermanLevel() const { return m_fishermanLevel; }
    inline unsigned int foragerLevel() const { return m_foragerLevel; }
    inline unsigned int infantryLevel() const { return m_infantryLevel; }
    inline unsigned int minerLevel() const { return m_minerLevel; }
    inline unsigned int stoneMasonLevel() const { return m_stoneMasonLevel; }
    inline unsigned int woodChopperLevel() const { return m_woodChopperLevel; }
    inline unsigned int tailorLevel() const { return m_tailorLevel; }
    inline unsigned int traderLevel() const { return m_traderLevel; }
    inline unsigned int herderLevel() const { return m_herderLevel; }
    inline unsigned int adventurerLevel() const { return m_adventurerLevel; }
    inline unsigned int unknown1Level() const { return m_unknown1Level; }
    inline unsigned int unknown2Level() const { return m_unknown2Level; }
    inline unsigned int unknown3Level() const { return m_unknown3Level; }
    inline unsigned int unknown4Level() const { return m_unknown4Level; }

    inline unsigned int experience() const { return m_experience; }

    inline bool autoChop() const { return m_autoChop; }
    inline bool gatherBerries() const { return m_gatherBerries; }
    inline bool huntChicken() const { return m_huntChicken; }
    inline bool huntBoar() const { return m_huntBoar; }
    inline bool showBowRange() const { return m_showBowRange; }
    inline bool trainNearTarget() const { return m_trainNearTarget; }

    inline float rotation() const { return m_rotation; }

    inline unsigned int equipHand() const { return m_equipHand; }
    inline unsigned int equipOffhand() const { return m_equipOffhand; }
    inline unsigned int equipHead() const { return m_equipHead; }
    inline unsigned int equipBody() const { return m_equipBody; }
    inline unsigned int equipFeet() const { return m_equipFeet; }

    inline unsigned int health() const { return m_health; }

    inline bool option(unsigned int optionNumber) const { return m_options[optionNumber]; }

    inline float timeToEat() const { return m_timeToEat; }
    inline float morale() const { return m_morale; }
    inline float fatigue() const { return m_fatigue; }
    inline float hunger() const { return m_hunger; }

    inline QList<int> const * inventoryPreferences() const { return &m_inventoryPreferences; }
    inline QList<int> const * inventoryItems() const { return &m_inventoryItems; }
    inline QList<int> const * spareInventory() const { return &m_spareInventory; }

    inline QList<float> const * patrolSetpoints() const { return &m_patrolSetpoints; }
    inline int patrolIndex() const { return m_patrolIndex; }

    inline QString guardedUnit() const { return m_guardedUnit; }

    inline QList<int> const * professionEXP() const { return &m_professionEXP; }

    inline float maxWeight() { return m_maxWeight; }

    inline signed short dirty() { return m_dirty; }
    inline QString rawData() { return m_rawData; }

    // Utilities and Helpers
    void print();

private:
    long m_id;

    QString m_profession;
    float m_posX;
    float m_posY;
    float m_posZ;
    QString m_name;

    unsigned int m_archerLevel;     // also Merchant: times traded
    unsigned int m_blacksmithLevel; // also Merchant: total trades
    unsigned int m_builderLevel;
    unsigned int m_carpenterLevel;
    unsigned int m_engineerLevel;
    unsigned int m_farmerLevel;
    unsigned int m_fishermanLevel;
    unsigned int m_foragerLevel;
    unsigned int m_infantryLevel;
    unsigned int m_minerLevel;
    unsigned int m_stoneMasonLevel;
    unsigned int m_woodChopperLevel;
    unsigned int m_tailorLevel;
    unsigned int m_traderLevel;
    unsigned int m_herderLevel;
    unsigned int m_adventurerLevel;
    unsigned int m_unknown1Level;
    unsigned int m_unknown2Level;
    unsigned int m_unknown3Level;
    unsigned int m_unknown4Level;

    unsigned int m_experience;

    bool m_autoChop;
    bool m_gatherBerries;
    bool m_huntChicken;
    bool m_huntBoar;
    bool m_showBowRange;

    // This is also used for "already met", for the Merchant
    bool m_trainNearTarget;

    float m_rotation;

    unsigned int m_equipHand;
    unsigned int m_equipOffhand;
    unsigned int m_equipHead;
    unsigned int m_equipBody;
    unsigned int m_equipFeet;

    unsigned int m_health;

    QBitArray m_options; // These contain the options for this unit.

    float m_timeToEat;
    float m_morale;
    float m_fatigue;
    float m_hunger;

    // Inventory data
    QList<int> m_inventoryPreferences;
    QList<int> m_inventoryItems;
    QList<int> m_spareInventory;

    // Patrol data
    QList<float> m_patrolSetpoints;
    int m_patrolIndex;

    QString m_guardedUnit;

    QList<int> m_professionEXP;

    float m_maxWeight;

    signed short m_dirty;
    QString m_rawData;
};

// HumanListModel store Humans
class HumanListModel : public ListModel
{
private:
    Q_OBJECT

public:
    const static short HUMAN_FLAG = 0x01;
    const static short MERCHANT_FLAG = 0x02;
    const static short MIGRANT_FLAG = 0x03;

    HumanListModel(ListItem * prototype, QObject * parent = 0);

    Q_INVOKABLE void setData(const long id, const QVariant &value, int role = Human::ProfessionRole);
    Q_INVOKABLE void remove(const long id);
    Q_INVOKABLE float getFirstPosition(const char label);
    Q_INVOKABLE void add(const QString profession, float x, float y, float z, short flags = HUMAN_FLAG);
    Q_INVOKABLE void serveCoffee();
};

#endif // HUMANLISTMODEL_H


text:
package com.amazonaws.services.wafv2.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.wafv2.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * ChallengeResponse JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ChallengeResponseJsonUnmarshaller implements Unmarshaller<ChallengeResponse, JsonUnmarshallerContext> {

    public ChallengeResponse unmarshall(JsonUnmarshallerContext context) throws Exception {
        ChallengeResponse challengeResponse = new ChallengeResponse();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("ResponseCode", targetDepth)) {
                    context.nextToken();
                    challengeResponse.setResponseCode(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("SolveTimestamp", targetDepth)) {
                    context.nextToken();
                    challengeResponse.setSolveTimestamp(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("FailureReason", targetDepth)) {
                    context.nextToken();
                    challengeResponse.setFailureReason(context.getUnmarshaller(String.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return challengeResponse;
    }

    private static ChallengeResponseJsonUnmarshaller instance;

    public static ChallengeResponseJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new ChallengeResponseJsonUnmarshaller();
        return instance;
    }
}


text:
package org.krysalis.barcode4j.applet;

import java.util.EventListener;

/**
 * Listener for changes in the model.
 *
 * @author Jeremias Maerki
 */
public interface BarcodeModelListener extends EventListener {

    void valueChanged();

}


text:
layout: post
title: CQRS / Event Sourcing
---

## What does CQRS mean ?

> `tl;dr`
> The command is acting on models and produce information on the platform. This information is consolidate into different models which are designed specifically for queries which are, in turn, read only. This isolation between read and write, allows us to build and scale differently the read and write concerns systems.

CQRS stands for *[Command Query Responsability Segregation](https://martinfowler.com/bliki/CQRS.html)* and is a pattern isolating the write and read concerns. Different data models and logic are written for the command and for the query.

By doing so, it is then possible to build differently the write concerned systems and the read write. Depending of the business logic, the read might leads 90% of the traffic while the write leads to 10%. Building different systems means that the code are shared between write and read, the servers are not shared as well and we can scale differently the read and the write systems.

Some queries might be build before it is querying, it is the case of statistics about users or platform usage. The information produced by them self leads to the statistics results. The query is simply requesting requesting a document into a database to get the information. The document is created after commands have been successfully executed: the commands are the information production of the platform.

## What does Event Sourcing mean ?

## Why to couple them together ?

The command is acting on the models and leads to updates. The query is read-only and retrieves information from the model.


text:
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 generiert
// Siehe http://java.sun.com/xml/jaxb
// �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2014.02.04 um 12:22:03 PM CET
//

package org.onvif.ver10.device.wsdl;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.onvif.ver10.schema.Dot1XConfiguration;

/**
 *

 * Java-Klasse f�r anonymous complex type.
 *
 *

 * Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Dot1XConfiguration" type="{http://www.onvif.org/ver10/schema}Dot1XConfiguration"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "dot1XConfiguration" })
@XmlRootElement(name = "GetDot1XConfigurationResponse")
public class GetDot1XConfigurationResponse {

	@XmlElement(name = "Dot1XConfiguration", required = true)
	protected Dot1XConfiguration dot1XConfiguration;

	/**
	 * Ruft den Wert der dot1XConfiguration-Eigenschaft ab.
	 *
	 * @return possible object is {@link Dot1XConfiguration }
	 *
	 */
	public Dot1XConfiguration getDot1XConfiguration() {
		return dot1XConfiguration;
	}

	/**
	 * Legt den Wert der dot1XConfiguration-Eigenschaft fest.
	 *
	 * @param value
	 *            allowed object is {@link Dot1XConfiguration }
	 *
	 */
	public void setDot1XConfiguration(Dot1XConfiguration value) {
		this.dot1XConfiguration = value;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Humanizer.DateTimeHumanizeStrategy;
using Humanizer.Localisation.Formatters;
using Humanizer.Localisation.NumberToWords;
using Humanizer.Localisation.Ordinalizers;
using Humanizer.Localisation.CollectionFormatters;

namespace Humanizer.Configuration
{
    /// <summary>
    /// Provides a configuration point for Humanizer
    /// </summary>
    public static class Configurator
    {
        private static readonly LocaliserRegistry<ICollectionFormatter> _collectionFormatters = new CollectionFormatterRegistry();

        /// <summary>
        /// A registry of formatters used to format collections based on the current locale
        /// </summary>
        public static LocaliserRegistry<ICollectionFormatter> CollectionFormatters
        {
            get { return _collectionFormatters; }
        }

        private static readonly LocaliserRegistry<IFormatter> _formatters = new FormatterRegistry();
        /// <summary>
        /// A registry of formatters used to format strings based on the current locale
        /// </summary>
        public static LocaliserRegistry<IFormatter> Formatters
        {
            get { return _formatters; }
        }

        private static readonly LocaliserRegistry<INumberToWordsConverter> _numberToWordsConverters = new NumberToWordsConverterRegistry();
        /// <summary>
        /// A registry of number to words converters used to localise ToWords and ToOrdinalWords methods
        /// </summary>
        public static LocaliserRegistry<INumberToWordsConverter> NumberToWordsConverters
        {
            get { return _numberToWordsConverters; }
        }

        private static readonly LocaliserRegistry<IOrdinalizer> _ordinalizers = new OrdinalizerRegistry();
        /// <summary>
        /// A registry of ordinalizers used to localise Ordinalize method
        /// </summary>
        public static LocaliserRegistry<IOrdinalizer> Ordinalizers
        {
            get { return _ordinalizers; }
        }

        internal static ICollectionFormatter CollectionFormatter
        {
            get
            {
                return CollectionFormatters.ResolveForUiCulture();
            }
        }

        /// <summary>
        /// The formatter to be used
        /// </summary>
        /// <param name="culture">The culture to retrieve formatter for. Null means that current thread's UI culture should be used.</param>
        internal static IFormatter GetFormatter(CultureInfo culture)
        {
            return Formatters.ResolveForCulture(culture);
        }

        /// <summary>
        /// The converter to be used
        /// </summary>
        /// <param name="culture">The culture to retrieve number to words converter for. Null means that current thread's UI culture should be used.</param>
        internal static INumberToWordsConverter GetNumberToWordsConverter(CultureInfo culture)
        {
            return NumberToWordsConverters.ResolveForCulture(culture);
        }

        /// <summary>
        /// The ordinalizer to be used
        /// </summary>
        internal static IOrdinalizer Ordinalizer
        {
            get
            {
                return Ordinalizers.ResolveForUiCulture();
            }
        }

        private static IDateTimeHumanizeStrategy _dateTimeHumanizeStrategy = new DefaultDateTimeHumanizeStrategy();
        /// <summary>
        /// The strategy to be used for DateTime.Humanize
        /// </summary>
        public static IDateTimeHumanizeStrategy DateTimeHumanizeStrategy
        {
            get { return _dateTimeHumanizeStrategy; }
            set { _dateTimeHumanizeStrategy = value; }
        }

        private static readonly Func<PropertyInfo, bool> DefaultEnumDescriptionPropertyLocator = p => p.Name == "Description";
        private static Func<PropertyInfo, bool> _enumDescriptionPropertyLocator = DefaultEnumDescriptionPropertyLocator;
        /// <summary>
        /// A predicate function for description property of attribute to use for Enum.Humanize
        /// </summary>
        public static Func<PropertyInfo, bool> EnumDescriptionPropertyLocator
        {
            get { return _enumDescriptionPropertyLocator; }
            set { _enumDescriptionPropertyLocator = value ?? DefaultEnumDescriptionPropertyLocator; }
        }
    }
}


text:
require_relative '../../lib/chef/provisioning/vsphere_driver/vsphere_url.rb'

describe 'VsphereUrl' do
	expected_host='1.1.1.1'
	expected_port=1818
	expected_path='/path'

	let(:url) {URI("vsphere://#{expected_host}:#{expected_port}#{expected_path}")}

	it "has the vsphere scheme" do
		expect(url.scheme).to eq('vsphere')
	end
	it "has the expected host" do
		expect(url.host).to eq(expected_host)
	end
	it "has the expected port" do
		expect(url.port).to eq(expected_port)
	end
	it "has the expected path" do
		expect(url.path).to eq(expected_path)
	end
	it "has the the default ssl setting" do
		expect(url.use_ssl).to eq(true)
	end
	it "has the the default insecure setting" do
		expect(url.insecure).to eq(false)
	end

	context "when setting from a hash" do
		let(:url) { URI::VsphereUrl.from_config({
			:host => '2.2.2.2',
			:port => 2345,
			:path => "/hoooo",
			:use_ssl => false,
			:insecure => true
		}) }

		it "asigns the correct url" do
			expect(url.to_s).to eq('vsphere://2.2.2.2:2345/hoooo?use_ssl=false&insecure=true')
		end
	end
	context "when ssl is enabled" do
		it "retuns an ssl value of true" do
			url = URI("vsphere://#{expected_host}:#{expected_port}#{expected_path}?use_ssl=true")
			expect(url.use_ssl).to eq(true)
		end
	end
	context "when ssl is disabled" do
		it "retuns an ssl value of true" do
			url = URI("vsphere://#{expected_host}:#{expected_port}#{expected_path}?use_ssl=false")
			expect(url.use_ssl).to eq(false)
		end
	end
	context "when insecure is enabled" do
		it "retuns an insecure value of true" do
			url = URI("vsphere://#{expected_host}:#{expected_port}#{expected_path}?insecure=true")
			expect(url.insecure).to eq(true)
		end
	end
	context "when insecure is disabled" do
		it "retuns an insecure value of true" do
			url = URI("vsphere://#{expected_host}:#{expected_port}#{expected_path}?insecure=false")
			expect(url.insecure).to eq(false)
		end
	end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UfoDataCenter.info
{

    public abstract partial class aUfo
    {
        public int perPage { get; set; }
        public abstract int pages { get; }
    }

    public class Pagination
    {
        public Pagination(int perPage,int pages)
        {
            this.perPage = perPage;
            this.pages = pages;
        }

        public int perPage { get; set; }
        public int pages { get; set; }

        public static int pageCount(int perPage,int count)
        {
            return (count % perPage) == 0 ? count/perPage : (count/perPage) + 1;
        }

        public Href href { get; set; }

    }

    public class Href
    {
        public string nextUrl { get; set; }
        public string prevUrl { get; set; }

    }

}


text:
global.charlieWork = {};
require('./gulper.js')(process.argv[2], process.argv[3]);


text:
Transform /^(\d+)$/ do |number|
  number.to_i
end

Transform(/^table:.+$/) do |table|
  table.map_headers! do |header|
    header.underscore.to_sym
  end
  table.map_column!(:tags, false) do |tags|
    tags.split(/\s*,\s*/).map do |tag_name|
      Tag.find_or_create_by!(name: tag_name)
    end
  end
  table.map_column!(:extensions, false) do |extensions|
    extensions.split(/\s*,\s*/).map do |ext_name|
      Extension.find_or_create_by!(name: ext_name)
    end
  end
  table
end

Given(/^the (about) page exists$/) do |locator|
  FactoryGirl.create(:content, locator: locator)
end

Given(/^the following contents exist:$/) do |contents|
  contents.hashes.each do |content|
    FactoryGirl.create(:content, content)
  end
end

Given(/^the following (articles|experiments) exist:$/) do |category, contents|
  contents.hashes.each do |content|
    FactoryGirl.create(:content, content.merge(category: category))
  end
end

Given(/^that (\d+) (articles|experiments) exist$/) do |number, category|
  FactoryGirl.create_list(:content, number, category: category)
end

When(/^I visit "([^"]+)"$/) do |route|
  visit route
end

When(/^I click on "([^"]+)"$/) do |text|
  find_link(text).click
end

When(/^I trigger "([^"]+)" on "([^"]+)"$/) do |event, text|
  find_link(text).trigger(event)
end

Then(/^I should (not )?see the title "([^"]+)"$/) do |negate, text|
  method = negate.present? ? 'to_not' : 'to'
  expect(page).send(method, have_title(text))
end

Then(/^I should (not )?see the header "([^"]+)"$/) do |negate, text|
  method = negate.present? ? 'to_not' : 'to'
  expect(page).send(method, have_selector('h1', text: text))
end

Then(/^I should (not )?see the link "([^"]+)"(?: pointing to "([^"]+)")?$/) do |negate, text, href|
  method = negate.present? ? 'to_not' : 'to'
  opts = { href: href } if href.present?
  expect(page).send(method, have_link(text, opts))
end

Then(/^I should (not )?see the text "([^"]*)"$/) do |negate, text|
  method = negate.present? ? 'to_not' : 'to'
  expect(page).send(method, have_text(text))
end

Then(/^I should (not )?see "([^"]*)" before "([^"]*)"$/) do |negate, text1, text2|
  method = negate.present? ? 'to_not' : 'to'
  expect(page).send(method, have_before(text1, text2))
end

Then(/^I should (not )?see the tag "([^"]*)"(?: with the value "([^"]*)")?$/) do |negate, xpath, value|
  method = negate.present? ? 'to_not' : 'to'
  expect(page).send(method, have_xpath("//#{xpath}", text: value))
end

Then(/^I should (not )?see the (?:head|script) tag "([^"]*)"(?: with the value "([^"]*)")?$/) do |negate, xpath, value|
  method = negate.present? ? 'to_not' : 'to'
  expect(page).send(method, have_xpath("//#{xpath}", text: value, visible: false))
end


text:
var mediacentre_plugin = mediacentre_plugin || {};

mediacentre_plugin.init = function($, namespace, refCount) {
// Avoid `console` errors in browsers that lack a console.
    (function () {
        var method;
        var noop = function () {
        };
        var methods = [
            'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
            'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
            'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
            'timeStamp', 'trace', 'warn'
        ];
        var length = methods.length;
        var console = (window.console = window.console || {});

        while (length--) {
            method = methods[length];

            // Only stub undefined methods.
            if (!console[method]) {
                console[method] = noop;
            }
        }

    }());

    (function ($, namespace, refCount) {
        // init material design
        //$.material.init();
        $(document).ready(function () {
            // Prevent block info to glitching up when launching a res
            $(namespace + ' .launch-res').on('click', function (e) {
                e.stopPropagation();
            });

            // Since the line-clamp only work in -webkit- based browsers
            // & dotdotdot allow to dynamically ellipsis div w/ dynamic width

            // Ellipsis block info title
            $(namespace + " .res-title").dotdotdot({
                watch: "window",
                height: 48
            });
            // Ellipsis block info text
            $(namespace + " .res-txt").dotdotdot({
                watch: "window",
                height: 96
            });
            // Ellipsis block info footer
            $(namespace + " .res-footer").dotdotdot({
                watch: "window",
                height: 48
            });
            // Open block infos on click on ressource img
            // $('.res-card').each(function(){
            //     $('.res-img', $(this)).click(function(e) {
            //         $('.res-card > .res-block-infos').removeClass('opened');
            //         var $resblockinfo = $(this).prev('.res-block-infos');
            //         if($resblockinfo.hasClass('opened')){
            //             $resblockinfo.removeClass('opened');
            //         }else{
            //             $resblockinfo.addClass('opened');
            //         }
            //     });
            // });

            // show modal on fab click
            var modalAffect = $('.modal.affectations');
            var modalAffectationsHeight = modalAffect.height();
            var openModalAffect = function () {
                modalAffect.addClass('opened');
                $('.overlay').addClass('is-visible');
                modalAffect.css('moz-transform', 'translateY(0)').css('ms-transform', 'translateY(0)').css('-webkit-transform', 'translateY(0)').css('transform', 'translateY(0)');
            };
            var closeModalAffect = function () {
                modalAffect.removeClass('opened');
                $('.overlay').removeClass('is-visible');
                modalAffect.css('moz-transform', 'translateY(' + modalAffectationsHeight + 'px)').css('ms-transform', 'translateY(' + modalAffectationsHeight + 'px)').css('-webkit-transform', 'translateY(' + modalAffectationsHeight + 'px)').css('transform', 'translateY(' + modalAffectationsHeight + 'px)');
            };

            modalAffect.css('moz-transform', 'translateY(' + modalAffectationsHeight + 'px)').css('ms-transform', 'translateY(' + modalAffectationsHeight + 'px)').css('-webkit-transform', 'translateY(' + modalAffectationsHeight + 'px)').css('transform', 'translateY(' + modalAffectationsHeight + 'px)');
            $(namespace + ' .fab-affectations').on('click', openModalAffect);
            $('.modal .mdi-close, .overlay, .modal-footer .btn-primary').on('click', closeModalAffect);

            var isMobile = {
                Android: function () {
                    return navigator.userAgent.match(/Android/i);
                },
                BlackBerry: function () {
                    return navigator.userAgent.match(/BlackBerry/i);
                },
                iOS: function () {
                    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
                },
                Opera: function () {
                    return navigator.userAgent.match(/Opera Mini/i);
                },
                Windows: function () {
                    return navigator.userAgent.match(/IEMobile/i);
                },
                any: function () {
                    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
                }
            };

            if (isMobile.any()) {

                $(namespace + ' .res-card', $(this)).click(function () {

                    var $resblockinfo = $(this).find('.res-block-infos');

                    $(namespace + ' .res-card > .res-block-infos').removeClass('opened');

                    if ($resblockinfo.hasClass('opened')) {
                        $resblockinfo.removeClass('opened');
                    } else {
                        $resblockinfo.addClass('opened');
                    }
                });

            } else {
                // Open block infos on hover
                $(namespace + ' .res-card').on({
                    mouseenter: function () {
                        $(this).find('.res-block-infos').addClass('opened');
                    },
                    mouseleave: function () {
                        $(this).find('.res-block-infos').removeClass('opened');
                    }
                });
            }
        });

    }($,namespace, refCount));

// Bootstrap Mediaquerie are here !
    (function ($, namespace, refCount) {

        function scrollFab($, namespace) {
            var content = $(namespace);
            var bottom = $(window).height() - content.position().top - content.height() + $('html, body').scrollTop();

            if (bottom < 24) {
                $(namespace + ' .fab-affectations').css('bottom', '24px').removeClass('is-absolute');
            } else {
                $(namespace + ' .fab-affectations').css('bottom', '24px').addClass('is-absolute');
            }
        }

        function viewPortChanged($, namespace) {
            // Executes in MD+ breakpoints
            if (isDetectedDivs('md') || isDetectedDivs('lg')) {
                // close filters by default
                $(namespace + ' .filters-list.collapse').addClass('in');

            } else {
                // Executes in MD- breakpoints
                // open filters header by default
                $(namespace + ' .filters-list.collapse').removeClass('in');
            }
            //this function runs every time you are scrolling
            // set the position of filters and FAB to absolute when footer enter the viewport
            $(window).scroll(function () {
                scrollFab($, namespace);
            });
        }

        var detectionDivs = {
            'xs': $('

'),
            'sm': $('

'),
            'md': $('

'),
            'lg': $('

')
        };

        function applyDetectionDivs($, namespace) {
            $('

').appendTo('body ' + namespace);
            $.each(detectionDivs, function(alias){
                detectionDivs[alias].appendTo(namespace + ' .responsive-bootstrap-toolkit');
            });
        }

        function isDetectedDivs(str) {
            return detectionDivs[ str ] && detectionDivs[ str ].is(':visible');
        }

        // Execute only after document has fully loaded
        $(document).ready(function () {
            applyDetectionDivs($, namespace);
            setTimeout(function() {
                scrollFab($, namespace);
                viewPortChanged($, namespace);
                $(namespace + " .filter-options.collapse").on('shown.bs.collapse', function () {
                    scrollFab($, namespace);
                }).on('hidden.bs.collapse', function () {
                    scrollFab($, namespace);
                });
            }, 300);
        });

        // Execute code each time window is resized
        $(window).resize(function () {
                viewPortChanged($, namespace);
            }
        );

    }($, namespace, refCount));
};


text:
#include <SFUI/GuiRenderer.hpp>

#include <SFUI/ResourceManager.hpp>
#include <SFML/Graphics/RenderQueue.hpp>

namespace sf
{
    namespace ui
    {
        GuiRenderer::GuiRenderer(sf::RenderWindow& renderWindow)
            :   mView(Vector2f(0.f, 0.f), Vector2f(renderWindow.GetWidth(), renderWindow.GetHeight())),
                mRenderWindow(renderWindow),
                mMouseInside(true)
        {
            SetSize(renderWindow.GetWidth(), renderWindow.GetHeight());
            SetColor(Color(0, 0, 0, 0));

            Widget::mFocusedWidget = Widget::mHoveredWidget = this;
        }

        GuiRenderer::~GuiRenderer()
        {
            ResourceManager::Kill();
        }

        void    GuiRenderer::SetFocusedWidget(Widget* widget)
        {
            Widget::mFocusedWidget = widget;
        }

        Widget* GuiRenderer::GetFocusedWidget() const
        {
            return Widget::mFocusedWidget;
        }

        Widget* GuiRenderer::GetHoveredWidget() const
        {
            return Widget::mHoveredWidget;
        }

        void    GuiRenderer::SetHoveredWidget(Widget* widget, const Vector2ui& mouse, Vector2f absPos)
        {
            Widgets&  widgets = widget->mChildren;

            for (Widgets::reverse_iterator it = widgets.rbegin(); it != widgets.rend(); ++it)
            {
                Widget* currentWidget = *it;

                if (currentWidget->IsVisible() && currentWidget->IsFocusable())
                {
                    absPos += currentWidget->GetPosition();

                    if (mouse.x >= absPos.x && mouse.x <= absPos.x + currentWidget->mSize.x &&
                        mouse.y >= absPos.y && mouse.y <= absPos.y + currentWidget->mSize.y)
                    {
                        Widget::mHoveredWidget = currentWidget;
                        SetHoveredWidget(currentWidget, mouse, absPos);
                        return;
                    }
                    absPos -= currentWidget->GetPosition();
                }
            }
        }

        void    GuiRenderer::InjectEvent(const Event& event)
        {
            // We left the injection for unwanted events
            if (event.Type == Event::MouseEntered || event.Type == Event::MouseLeft ||
                event.Type == Event::GainedFocus || event.Type == Event::LostFocus)
            {
                return;
            }
            // If the view need to be resized
            else if (event.Type == Event::Resized)
            {
                SetSize(event.Size.Width, event.Size.Height);
                return;
            }
            // Handle the focus on click
            else if (event.Type == Event::MouseButtonPressed)
            {
                HandleFocus();
            }
            // Set the hovered widget
            else if (event.Type == Event::MouseMoved)
            {
                static Widget*  lastHovered = this;

                Widget::mHoveredWidget = this;
                SetHoveredWidget(this, Vector2ui(event.MouseMove.X, event.MouseMove.Y), GetPosition());

                if (lastHovered != Widget::mHoveredWidget)
                {
                    sf::Event newEvent = event;

                    newEvent.Type = Event::MouseLeft;
                    lastHovered->DistributeEvent(newEvent);

                    newEvent.Type = Event::MouseEntered;
                    Widget::mHoveredWidget->DistributeEvent(newEvent);

                    lastHovered = Widget::mHoveredWidget;
                }
            }
            if (Widget::mFocusedWidget)
                Widget::mFocusedWidget->DistributeEvent(event);
        }

        void    GuiRenderer::HandleFocus()
        {
            if (Widget::mHoveredWidget)
                if (Widget::mHoveredWidget->IsFocusable())
                    Widget::mFocusedWidget = Widget::mHoveredWidget;
        }

        void    GuiRenderer::OnChange(Widget::Property property)
        {
            if (property == Widget::SIZE)
                mView.Reset(FloatRect(0, 0, GetWidth(), GetHeight()));
        }

        void    GuiRenderer::Display()
        {
            const View& otherView = mRenderWindow.GetView();

            mRenderWindow.SetView(mView);

            mRenderWindow.Draw(*this);

            mRenderWindow.SetView(otherView);
        }

    }
}


text:
namespace pw::unit_test {

// An event handler implementation that logs human-readable messages to the
// standard Pigweed logging system, pw_log.
class LoggingEventHandler : public EventHandler {
 public:
  // If verbose is set, expectations values are always displayed.
  LoggingEventHandler(bool verbose = false) : verbose_(verbose) {}

  void RunAllTestsStart() override;
  void RunAllTestsEnd(const RunTestsSummary& run_tests_summary) override;
  void TestCaseStart(const TestCase& test_case) override;
  void TestCaseEnd(const TestCase& test_case, TestResult result) override;
  void TestCaseExpect(const TestCase& test_case,
                      const TestExpectation& expectation) override;
  void TestCaseDisabled(const TestCase& test_case) override;

 private:
  bool verbose_;
};

}  // namespace pw::unit_test


text:
/**
 *
Treetank Core

 *
 *

 * This module represents the core functionality of Treetank with the ability to be included as library and
 * extended by application-specific datas.
 *

 *

 * The root package for all packages include:
 *

 *
access: Direct access layer for interaction with treetank

 *
api: Interfaces for offering abstract implementations

 *
io: classes for writing data to the disk or in the cloud

 *
log: transaction log for buffering data between two versions relying on a Berkeley DB

 *
bucket: Bucketlayer, all revisions which are storing data are represented by these classes

 *
revision: revisioning algorithms

 *

 *

 *
 * @author Sebastian Graf, University of Konstanz
 */
package org.treetank;


text:
Locations

  <select id="loc-search" style="width: 75%">
    <option value="" disabled selected>Select a Language...</option>
    <% locations.forEach(function(loc) { %>
      <option data-name="<%= loc.name %>" value="<%= loc.name %>"><%= loc.name %></option>
    <% }); %>
  </select>
  <form id=loc-edit>
    <fieldset>
      <legend>Edit Location</legend>

        Name
        <input type=text name=locName id=loc-name-edit required placeholder="Back Cabinet">

      <input id=loc-delete-btn type=submit class=redBtn value='Delete'>
      <input id=loc-update-btn type=submit class=greenBtn value='Update'>
    </fieldset>
  </form>
  <form id=loc-add>
    <fieldset>

<legend>Add Locations</legend>

        Name
        <input type=text name=locName id=loc-name required placeholder="Back Cabinet">

      <input type=submit class=greenBtn value=Add>
    </fieldset>
  </form>


text:
.a2 { background-image: url('../img/hoge1.png'); background-repeat: no-repeat; width: 180px; height: 50px; background-position: 0 0; }

.aq { background-image: url('../img/hoge1.png'); background-repeat: no-repeat; width: 180px; height: 50px; background-position: -180px 0; }


text:
#ifndef USER_SYSTEM_H_
#define USER_SYSTEM_H_
#include "os_type.h"
#include "cmd.h"

enum system_event
{
  RESERVED = 0,
  GET_STATION_MAC,
  GET_AP_MAC,
};

uint32_t ICACHE_FLASH_ATTR SYSTEM_Handler(PACKET_CMD *cmd);
uint32_t ICACHE_FLASH_ATTR NTP_SetTimeZone(PACKET_CMD *cmd);
uint32_t ICACHE_FLASH_ATTR NTP_Time(PACKET_CMD *cmd);
void start_sntp_service(void);

#endif /* USER_WIFI_H_ */


text:
package org.spanna.material;

import org.spanna.DyeColor;
import org.spanna.Material;

/**
 * Represents dye
 */
public class Dye extends MaterialData implements Colorable {
    public Dye() {
        super(Material.INK_SACK);
    }

    /**
     *
     * @deprecated Magic value
     */
    @Deprecated
    public Dye(final int type) {
        super(type);
    }

    public Dye(final Material type) {
        super(type);
    }

    /**
     *
     * @deprecated Magic value
     */
    @Deprecated
    public Dye(final int type, final byte data) {
        super(type, data);
    }

    /**
     *
     * @deprecated Magic value
     */
    @Deprecated
    public Dye(final Material type, final byte data) {
        super(type, data);
    }

    /**
     * Gets the current color of this dye
     *
     * @return DyeColor of this dye
     */
    public DyeColor getColor() {
        return DyeColor.getByDyeData(getData());
    }

    /**
     * Sets the color of this dye
     *
     * @param color New color of this dye
     */
    public void setColor(DyeColor color) {
        setData(color.getDyeData());
    }

    @Override
    public String toString() {
        return getColor() + " DYE(" + getData() + ")";
    }

    @Override
    public Dye clone() {
        return (Dye) super.clone();
    }
}


text:
from django.shortcuts import render
from django.http.response import HttpResponseRedirect
from django.http import HttpRequest
from django.urls import reverse
from django.contrib.auth.decorators import login_required, permission_required
from django.utils import timezone
from django.contrib.auth.models import User

from .models import Task, Attendance, Emergency
from RoomManage.models import Room
from RoomManage.views import Room_Status

# Create your views here.

title = '任务管理'

@login_required()
def index(request):
    clock_status = True
    if request.method == 'POST':
        if 'clock_in' in request.POST:
            attendance = Attendance.objects.create(clock_in=timezone.now(),
                                                   clock_out=None,
                                                   user=request.user)
            attendance.save()
            return render(request,'TaskManage/index.html',{'clock_status': False})
        elif 'clock_out' in request.POST:
            attendance = Attendance.objects.filter(user=request.user).get(clock_out=None)
            attendance.clock_out = timezone.now()
            attendance.save()
            return render(request, 'TaskManage/index.html', {'clock_status': True})

    try:
        if Attendance.objects.filter(user=request.user).get(clock_out=None):
            clock_status = False
    except:
        pass

    context = {
        'title': title,
        'clock_status': clock_status,
    }
    return render(request,'TaskManage/index.html',{'clock_status': clock_status})

@login_required()
def tasklist(request):
    task_list = Task.objects.filter(user=request.user.id).exclude(task_status=task_status.done)
    if task_list is None:
        return render(request,'TaskManage/index.html')

    context = {
        'title': title,
        'task_list': task_list,
    }
    return render(request,'TaskManage/tasklist.html',{'task_list': task_list})

@login_required()
def detail(request, task_num):
    task = Task.objects.get(id=task_num)
    if request.user.id != task.user.id:
        return HttpResponseRedirect(reverse('TaskManage:tasklist'))

    if request.method == 'POST':
        if request.POST['done']:
            task.task_status = task_status.done
            task.save()
        return HttpResponseRedirect(reverse('TaskManage:detail',args=(task_num,)))

    context = {
        'title': title,
        'task': task,
    }
    return render(request,'TaskManage/detail.html',{'task': task})

@login_required()
@permission_required('Emergency.create_emergency')
def emergency(request):
    room_list = Room.objects.filter(room_status=room_status.check_ing)
    user_list = User.objects.all().exclude(is_superuser=True)

    if request.method == 'POST':
        user_id = request.POST['user_id']
        room_id = request.POST['room_id']

        date = timezone.now()
        user = user_list.get(id=user_id)
        room = room_list.get(id=room_id)
        emer = Emergency.objects.create(date_time=date,
                                        user=user,
                                        room=room)
        emer.save()
        create_task(user, room, date)

        if 'submit' in request.POST:
            return HttpResponseRedirect(reverse('TaskManage:emergence'))
        elif 'submit_return' in request.POST:
            return HttpResponseRedirect(reverse('TaskManage:index'))

    context = {
        'title': title,
        'room_list': room_list,
        'user_list': user_list
    }
    return render(request, 'TaskManage/emergency.html', {'room_list':room_list, 'user_list':user_list})

def create_task(user, room, date):

    task = Task.objects.create(user=user,
                               room=room,
                               date=date,
                               context='发生紧急事件',
                               task_status=task_status.undo)
    task.save()

class Task_Status(object):
    def __init__(self):
        self.done = '已完成'
        self.undo = '未完成'

task_status = Task_Status()

room_status = Room_Status()


text:
package com.chaumoha;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class FightActivity extends Activity{

	private GraphicsView graphicsView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		graphicsView = new GraphicsView(this);
		setContentView(graphicsView);
		Canvas canvas = new Canvas();
	}

	class GraphicsView extends SurfaceView implements SurfaceHolder.Callback, Runnable{

		public GraphicsView(Context context) {
			super(context);
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			// TODO Auto-generated method stub

		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			// TODO Auto-generated method stub

		}

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			// TODO Auto-generated method stub

		}

		@Override
		public void run() {
			// TODO Auto-generated method stub

		}

	}

}


text:
<?php
/**
 * User: Alex Gusev <alex@flancer64.com>
 */

namespace Praxigento\Odoo\Repo\Odoo\Data\SaleOrder\Shipping;

class Tax
    extends \Praxigento\Odoo\Repo\Odoo\Data\SaleOrder\Line\Tax
{

}


text:
"use strict";
gereji.apps.register("basket", function(sandbox){
    var app;
    return {
        init: function(){
			if(location.href.indexOf("/product/") == -1)
				return gereji.apps.stop("basket");
		},
		kill: function(){
		}
	}
});


text:
These settings apply only when `--go` is specified on the command line.

``` yaml $(go) && !$(track2)
go:
  license-header: MICROSOFT_MIT_NO_VERSION
  namespace: storage
  clear-output-folder: true
```

``` yaml $(go) && $(track2)
license-header: MICROSOFT_MIT_NO_VERSION
module-name: sdk/resourcemanager/storage/armstorage
module: github.com/Azure/azure-sdk-for-go/$(module-name)
output-folder: $(go-sdk-folder)/$(module-name)
azure-arm: true
modelerfour:
  lenient-model-deduplication: true
directive:
  - from: swagger-document
    where: $.definitions.CorsRule
    transform: $['properties']['allowedMethods']['items']['x-ms-enum']['name'] = 'CorsRuleAllowedMethodsItem'
  - from: swagger-document
    where: $.definitions.ActiveDirectoryProperties
    transform: $['properties']['accountType']['x-ms-enum']['name'] = 'ActiveDirectoryPropertiesAccountType'
```

### Go multi-api

``` yaml $(go) && $(multiapi)
batch:
  - tag: package-2022-05
  - tag: package-2021-09
  - tag: package-2021-08
  - tag: package-2021-06
  - tag: package-2021-04
  - tag: package-2021-02
  - tag: package-2021-01
  - tag: package-2020-08-preview
  - tag: package-2019-06
  - tag: package-2019-04
  - tag: package-2018-11
  - tag: package-2018-07
  - tag: package-2018-03
  - tag: package-2018-02
  - tag: package-2017-10
  - tag: package-2017-06
  - tag: package-2016-12
  - tag: package-2016-05
  - tag: package-2016-01
  - tag: package-2015-06
  - tag: package-2015-05-preview
```

### Tag: package-2022-05 and go

These settings apply only when `--tag=package-2022-05 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2022-05' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2022-05-01/$(namespace)
```

### Tag: package-2021-09 and go

These settings apply only when `--tag=package-2021-09 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-09' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-09-01/$(namespace)
```

### Tag: package-2021-08 and go

These settings apply only when `--tag=package-2021-08 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-08' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-08-01/$(namespace)
```

### Tag: package-2021-06 and go

These settings apply only when `--tag=package-2021-06 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-06' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-06-01/$(namespace)
```

### Tag: package-2021-04 and go

These settings apply only when `--tag=package-2021-04 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-04' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-04-01/$(namespace)
```

### Tag: package-2021-02 and go

These settings apply only when `--tag=package-2021-02 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-02' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-02-01/$(namespace)
```

### Tag: package-2021-01 and go

These settings apply only when `--tag=package-2021-01 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2021-01' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2021-01-01/$(namespace)
```

### Tag: package-2020-08-preview and go

These settings apply only when `--tag=package-2020-08-preview --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2020-08-preview' && $(go)
output-folder: $(go-sdk-folder)/services/preview/$(namespace)/mgmt/2020-08-01-preview/$(namespace)
```

### Tag: package-2019-06 and go

These settings apply only when `--tag=package-2019-06 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2019-06' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2019-06-01/$(namespace)
```

### Tag: package-2019-04 and go

These settings apply only when `--tag=package-2019-04 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2019-04' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2019-04-01/$(namespace)
```

### Tag: package-2018-11 and go

These settings apply only when `--tag=package-2018-11 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2018-11' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2018-11-01/$(namespace)
```

### Tag: package-2018-07 and go

These settings apply only when `--tag=package-2018-07 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2018-07' && $(go)
output-folder: $(go-sdk-folder)/services/preview/$(namespace)/mgmt/2018-07-01-preview/$(namespace)
```

### Tag: package-2018-03 and go

These settings apply only when `--tag=package-2018-03 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2018-03' && $(go)
output-folder: $(go-sdk-folder)/services/preview/$(namespace)/mgmt/2018-03-01-preview/$(namespace)
```

### Tag: package-2018-02 and go

These settings apply only when `--tag=package-2018-02 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2018-02' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2018-02-01/$(namespace)
```

### Tag: package-2017-10 and go

These settings apply only when `--tag=package-2017-10 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2017-10' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2017-10-01/$(namespace)
```

### Tag: package-2017-06 and go

These settings apply only when `--tag=package-2017-06 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2017-06' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2017-06-01/$(namespace)
```

### Tag: package-2016-12 and go

These settings apply only when `--tag=package-2016-12 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2016-12' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2016-12-01/$(namespace)
```

### Tag: package-2016-05 and go

These settings apply only when `--tag=package-2016-05 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2016-05' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2016-05-01/$(namespace)
```

### Tag: package-2016-01 and go

These settings apply only when `--tag=package-2016-01 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2016-01' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2016-01-01/$(namespace)
```

### Tag: package-2015-06 and go

These settings apply only when `--tag=package-2015-06 --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2015-06' && $(go)
output-folder: $(go-sdk-folder)/services/$(namespace)/mgmt/2015-06-15/$(namespace)
```

### Tag: package-2015-05-preview and go

These settings apply only when `--tag=package-2015-05-preview --go` is specified on the command line.
Please also specify `--go-sdk-folder=<path to the root directory of your azure-sdk-for-go clone>`.

``` yaml $(tag) == 'package-2015-05-preview' && $(go)
output-folder: $(go-sdk-folder)/services/preview/$(namespace)/mgmt/2015-05-01-preview/$(namespace)
```


text:
package graphite

import (
	"strings"

	"github.com/influxdb/influxdb/toml"
)

const (
	// DefaultBindAddress is the default binding interface if none is specified.
	DefaultBindAddress = ":2003"

	// DefaultDatabase is the default database if none is specified.
	DefaultDatabase = "graphite"

	// DefaultNameSeparator represents the default field separator.
	DefaultNameSeparator = "."

	// DefaultNamePosition represents the default location of the name.
	DefaultNamePosition = "last"

	// DefaultProtocol is the default IP protocol used by the Graphite input.
	DefaultProtocol = "tcp"

	// DefaultConsistencyLevel is the default write consistency for the Graphite input.
	DefaultConsistencyLevel = "one"
)

// Config represents the configuration for Graphite endpoints.
type Config struct {
	BindAddress      string        `toml:"bind-address"`
	Database         string        `toml:"database"`
	Enabled          bool          `toml:"enabled"`
	Protocol         string        `toml:"protocol"`
	NamePosition     string        `toml:"name-position"`
	NameSeparator    string        `toml:"name-separator"`
	BatchSize        int           `toml:"batch-size"`
	BatchTimeout     toml.Duration `toml:"batch-timeout"`
	ConsistencyLevel string        `toml:"consistency-level"`
}

// NewConfig returns a new Config with defaults.
func NewConfig() Config {
	return Config{
		BindAddress:      DefaultBindAddress,
		Database:         DefaultDatabase,
		Protocol:         DefaultProtocol,
		NamePosition:     DefaultNamePosition,
		NameSeparator:    DefaultNameSeparator,
		ConsistencyLevel: DefaultConsistencyLevel,
	}
}

// LastEnabled returns whether the server should interpret the last field as "name".
func (c *Config) LastEnabled() bool {
	return c.NamePosition == strings.ToLower("last")
}

// WithDefaults takes the given config and returns a new config with any required
// default values set.
func (c *Config) WithDefaults() *Config {
	d := *c
	if d.BindAddress == "" {
		d.BindAddress = DefaultBindAddress
	}
	if d.Database == "" {
		d.Database = DefaultDatabase
	}
	if d.Protocol == "" {
		d.Protocol = DefaultProtocol
	}
	if d.NamePosition == "" {
		d.NamePosition = DefaultNamePosition
	}
	if d.NameSeparator == "" {
		d.NameSeparator = DefaultNameSeparator
	}
	if d.ConsistencyLevel == "" {
		d.ConsistencyLevel = DefaultConsistencyLevel
	}
	return &d
}


text:
module Softlayer
  module Container
    module Network
      module Message
        module Delivery
          autoload :Email, 'softlayer/container/network/message/delivery/email'
        end
      end
    end
  end
end


text:
package org.elasticsearch.cluster;

import java.util.List;

public interface ClusterStateTaskListener {

    /**
     * A callback called when execute fails.
     */
    void onFailure(String source, Throwable t);

    /**
     * called when the task was rejected because the local node is no longer master
     */
    void onNoLongerMaster(String source);

    /**
     * Called when the result of the {@link ClusterStateTaskExecutor#execute(ClusterState, List)} have been processed
     * properly by all listeners.
     */
    void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState);
}


text:
package org.apache.poi.hdf.model.hdftypes;

import org.apache.poi.util.LittleEndian;

/**
 * Represents a CHP fkp. The style properties for paragraph and character runs
 * are stored in fkps. There are PAP fkps for paragraph properties and CHP fkps
 * for character run properties. The first part of the fkp for both CHP and PAP
 * fkps consists of an array of 4 byte int offsets that represent a
 * Paragraph's or Character run's text offset in the main stream. The ending
 * offset is the next value in the array. For example, if an fkp has X number of
 * Paragraph's stored in it then there are (x + 1) 4 byte ints in the beginning
 * array. The number X is determined by the last byte in a 512 byte fkp.
 *
 * CHP and PAP fkps also store the compressed styles(grpprl) that correspond to
 * the offsets on the front of the fkp. The offset of the grpprls is determined
 * differently for CHP fkps and PAP fkps.
 *
 * @author Ryan Ackley
 */
public final class CHPFormattedDiskPage extends FormattedDiskPage
{

    /**
     * This constructs a CHPFormattedDiskPage from a raw fkp (512 byte array
     * read from a Word file).
     *
     * @param fkp The 512 byte array to read data from
     */
    public CHPFormattedDiskPage(byte[] fkp)
    {
        super(fkp);
    }

    /**
     * Gets the chpx for the character run at index in this fkp.
     *
     * @param index The index of the chpx to get.
     * @return a chpx grpprl.
     */
    public byte[] getGrpprl(int index)
    {
        int chpxOffset = 2 * LittleEndian.getUnsignedByte(_fkp, ((_crun + 1) * 4) + index);

        //optimization if offset == 0 use "Normal" style
        if(chpxOffset == 0)
        {
            return new byte[0];

        }

        int size = LittleEndian.getUnsignedByte(_fkp, chpxOffset);

        byte[] chpx = new byte[size];

        System.arraycopy(_fkp, ++chpxOffset, chpx, 0, size);
        return chpx;
    }
}


text:
=================
The Command state
=================

.. autoclass:: sermin.Command
    :members:


text:
package org.wso2.carbon.deployment.synchronizer.git;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizerException;
import org.wso2.carbon.deployment.synchronizer.RepositoryCreator;
import org.wso2.carbon.deployment.synchronizer.RepositoryInformation;
import org.wso2.carbon.deployment.synchronizer.RepositoryManager;
import org.wso2.carbon.deployment.synchronizer.git.internal.GitDeploymentSynchronizerConstants;

public class DefaultGitRepositoryManager extends RepositoryManager {

    private static final Log log = LogFactory.getLog(DefaultGitRepositoryManager.class);
    protected String gitServerUrl;
    protected String gitServerAdminUserName;
    protected String gitServerAdminPassword;

    public DefaultGitRepositoryManager() {
        readDefaultGitRepositoryConfiguration();
    }

    public DefaultGitRepositoryManager(RepositoryCreator repositoryCreator) {
        super(repositoryCreator);
        readDefaultGitRepositoryConfiguration();
    }

    private void readDefaultGitRepositoryConfiguration () throws DeploymentSynchronizerException {

        String gitRepositoryUrlParam = readConfigurationParameter(GitDeploymentSynchronizerConstants.GIT_REPO_BASE_URL);
        if (gitRepositoryUrlParam == null) {
            handleError("Required parameter " + GitDeploymentSynchronizerConstants.GIT_REPO_BASE_URL + " not found");
        }
        gitServerUrl = gitRepositoryUrlParam;

        String gitRepositoryUsernameParam = readConfigurationParameter(GitDeploymentSynchronizerConstants.GIT_USERNAME);
        if (gitRepositoryUsernameParam != null) {
            gitServerAdminUserName = gitRepositoryUsernameParam;
        }

        String gitRepositoryPasswordParam = readConfigurationParameter(GitDeploymentSynchronizerConstants.GIT_PASSWORD);
        if (gitRepositoryPasswordParam != null) {
            gitServerAdminPassword = gitRepositoryPasswordParam;
        }
    }

    private String readConfigurationParameter(String parameterKey) {
        return ServerConfiguration.getInstance().getFirstProperty(parameterKey);
    }

    @Override
    public RepositoryInformation getUrlInformation(int tenantId) throws DeploymentSynchronizerException {

        TenantGitRepositoryContext tenantGitRepoCtx = TenantGitRepositoryContextCache.
                getTenantRepositoryContextCache().
                retrieveCachedTenantGitContext(tenantId);

        return new GitRepositoryInformation(tenantGitRepoCtx.getRemoteRepoUrl());
    }

    @Override
    public RepositoryInformation getCredentialsInformation(int tenantId) throws DeploymentSynchronizerException {
        return new GitRepositoryInformation(gitServerAdminUserName, gitServerAdminPassword);
    }

    @Override
    public void provisionRepository(int tenantId) throws DeploymentSynchronizerException {

        TenantGitRepositoryContext tenantGitRepoCtx = TenantGitRepositoryContextCache.
                getTenantRepositoryContextCache().
                retrieveCachedTenantGitContext(tenantId);

        if(tenantGitRepoCtx == null) {
            String errorMsg = "TenantGitRepositoryContext not available for tenant " + tenantId;
            log.error(errorMsg);
            handleError(errorMsg);
        }

        String repositoryUrl = repositoryCreator.createRepository(tenantId, gitServerUrl, gitServerAdminUserName,
                gitServerAdminPassword).getUrl();

        tenantGitRepoCtx.setRemoteRepoUrl(repositoryUrl);
        TenantGitRepositoryContextCache.getTenantRepositoryContextCache().
                updateTenantGitRepositoryContext(tenantId, tenantGitRepoCtx);
    }

    @Override
    public void addRepository(int tenantId, String url) throws DeploymentSynchronizerException {

    }

    private void handleError (String errorMsg) throws DeploymentSynchronizerException {
        log.error(errorMsg);
        throw new DeploymentSynchronizerException(errorMsg);
    }

    private void handleError (String errorMsg, Exception e) throws DeploymentSynchronizerException {
        log.error(errorMsg, e);
        throw new DeploymentSynchronizerException(errorMsg, e);
    }
}


text:
int main(int argc, const char* argv[])
{
   std::cout << x << std::endl;
}


text:
'use strict'

require('../../../test/init-api')
const { Maybe } = require('../../utils/maybe')
const { generateDeploymentProcess } = require('../../../test/mocks')
const client = require('../../octopus-client')
const subject = require('../process')
const { sandbox } = require('../../../test/sandbox')

describe('api/process', () => {
  describe('#find', () => {
    let process

    beforeEach(() => {
      process = generateDeploymentProcess({ id: 'collect-my-gems' })
      sandbox.stub(client, 'get').callsFake(async () => Maybe.some(process))
    })

    it('finds a deployment process', async () => {
      const actual = await subject.find(process.id)
      expect(actual.value).to.deep.equal(process)
      expect(client.get).to.be.calledWith(`/deploymentProcesses/${process.id}`)
    })

    describe('when deployment process does not exist', () => {
      it('returns none', async () => {
        process = null
        const actual = await subject.find('does-not-exist')
        expect(actual.hasValue).to.be.false
      })
    })
  })
})


text:
How MAX works
=============

MAX is a piece of software that lets developers design programs for controlling MIDI
syntheriszers and other advanced audio things such as Samplers and Effects Processors.

MAX is primarily a graphical based languge for building the programs (known as "patchers") that control MIDI devices
and is used in WebLab to take signals from the network, 'do some magic' send commands to the MIDI
device and then send commands back on the network to syncrhonise all the web clients.

Simple right? Not really. :)

This document describes roughly how the MAX product is configured to let you play music from your
website via MIDI.

## Sequencer ##

The sequencer is the main "patcher" and it is broken in to two areas:

1.  The reciever
2.  The interesting bit

The receiver sets up a UDP port to listen to incoming OSC commands sent from the `hub` server.  The port that listens to incoming requests has a script attached to it and once it gets a command sets a global internal variable describing what the `hub` knows to be the configuration of the "sequencer".

The interesting bit is interesting, and described below the image (I am doing this so you get some context).

![Sequencer](/docs/images/sequencer.png "Sequencer")

The main body of this MAX patcher is the interesting bit.   At a high-level it is a collection of sub-patchers (they are the bits starting with "p_").  The flow is roughly as follows:

1.  `loadbang` is triggered when the script is loaded and sends a 1 or if the user presses spacebar, the key module fires and is filtered on ASCII char 32
2.  If either loadbang or keypress is 0, then the `toggle` module is toggled.
3.  If the toggle `bangs` a 1, then the [p_sequencer](#p_sequencer) sub-patcher is loaded - this is the main script that beats once every 250ms.
4.  Every time the p_sequencer bangs, it is sent through to the 16 bar timer and to playback.js script.  This script works out what note on the MIDI it should be playing for the current timestamp.  At the same time for each 250ms beat p_loop_start is executed and an OSC command is crafted and sent back the `hub` server.
5.  At this point the patcher is trying to play a MIDI note, it is displayed on the little keyboard control, but also sent through to the [p_picthmappings](#p_picthmappings) sub-patchers which converts the note to the correct scale.
6.  The output is then sent to the [p_actuators](#p_actuators) script which creates the NOTE ON and NOTE OFF midi command (100ms duration)
7.  NOTEOUT is then fired with all the corretly mapped settings.

## p_Sequencer ##
![p_sequencer](/docs/images/sequencer-p_sequencer.png "p_sequencer")

## Actuators ##
![p_actuators](/docs/images/actuators.png "p_actuators")

## Loop Start ##
![p_loop_start](/docs/images/loop_start.png "p_loop_start")

## Pitch Mappings ##
![p_pitch_mappings](/docs/images/pitch-mappings.png "p_pitch_mappings")

## Epoch ##
![p_epoch](/docs/images/epoch.png "p_epoch")


text:
import sys
import serial
import time
import math

x = sys.argv[1]
y = sys.argv[2]
#theta = sys.argv[3]

port1 = "/dev/ttyPCH1"
port2 = "/dev/ttyPCH2"
baudRate = 38400

ser1 = serial.Serial(port1,baudRate)
ser2 = serial.Serial(port2,baudRate)

def serialSend1(send):
    for i in send:
            ser1.write(chr(i))

def serialSend2(send):
    for i in send:
            ser2.write(chr(i))

def serialRead1(read):
    serialSend1(read)
    data=[]
    for i in range(6):
        data.append(ser1.read())
    return data

def serialRead2(read):
    serialSend2(read)
    data=[]
    for i in range(6):
        data.append(ser2.read())
    return data

def driveM1(speed):
    address = 0x81
    command = 6
    dataBytes = int(speed,0)
    checksum = (address+command+dataBytes)&0x7F
    serialSend1([address,command,dataBytes,checksum])

def driveM2(speed):
    address = 0x80
    command = 6
    dataBytes = int(speed,0)
    checksum = (address+command+dataBytes)&0x7F
    serialSend2([address,command,dataBytes,checksum])

def driveM3(speed):
    address = 0x81
    command = 7
    dataBytes = int(speed,0)
    checksum = (address+command+dataBytes)&0x7F
    serialSend1([address,command,dataBytes,checksum])

def driveAll(speed):
    driveM1(speed)
    driveM2(speed)
    driveM3(speed)

def readCurrentSpeedM1():
    address = 0x81
    command = 30
    # Read the current speed from the motor.
    data = serialRead1([address,command])
    # Read the first four bytes (in hex) as the speed.
    speed = (data[0].encode("hex")) + (data[1].encode("hex")) + (data[2].encode("hex")) + (data[3].encode("hex"))
    # Convert the speed to an integer.
    speed = int(speed, 16)
    # If the fifth byte indicates that the speed is negative, take the 2's complement.
    if ((ord(data[4]) == 1) and (speed != 0)):
		speed = ~(0xffffffff - speed) + 1
    # Calculate the speed in rotations per second (negating to account for wiring).
    rotations_per_second = -float(speed) * 125 / 8192
    print 'M1 Speed:\n' + str(rotations_per_second)
    return rotations_per_second

def readCurrentSpeedM2():
    address = 0x80
    command = 30
    # Read the speed information from the motor.
    data = serialRead2([address,command])
    # Read the first four bytes (in hex) as the speed.
    speed = (data[0].encode("hex")) + (data[1].encode("hex")) + (data[2].encode("hex")) + (data[3].encode("hex"))
    # Convert the speed to an integer.
    speed = int(speed, 16)
    # If the fifth byte indicates that the value is negative, take the 2's complement.
    if ((ord(data[4]) == 1) and (speed != 0)):
		speed = ~(0xffffffff - speed) + 1
    # Calculate the speed in rotations per second (negating to account for wiring).
    rotations_per_second = -float(speed) * 125 / 8192
    print 'M2 Speed:\n' + str(rotations_per_second)
    return rotations_per_second

def readCurrentSpeedM3():
    address = 0x81
    command = 31
    # Read the current speed from the motor.
    data = serialRead1([address,command])
    # Read the first four bytes (in hex) as the speed.
    speed = (data[0].encode("hex")) + (data[1].encode("hex")) + (data[2].encode("hex")) + (data[3].encode("hex"))
    # Convert the speed to an integer.
    speed = int(speed, 16)
    # If the fifth byte indicates that the speed is negative, take the 2's complement.
    if ((ord(data[4]) == 1) and (speed != 0)):
		speed = ~(0xffffffff - speed) + 1
    # Calculate the speed in rotations per second (negating to account for wiring).
    rotations_per_second = -float(speed) * 125 / 8192
    print 'M3 Speed:\n' + str(rotations_per_second)
    return rotations_per_second

def speedComponentM1(speed,xr,yr):
    speed = float(speed)-64
    x1 = -math.sqrt(2)/2
    y1 = -math.sqrt(2)/2
    xr = float(xr)
    yr = float(yr)
    speedM1 = speed*(x1*xr+y1*yr)/math.sqrt(x1*x1+y1*y1)
    return str(int(speedM1+64))

def speedComponentM2(speed,xr,yr):
    speed = float(speed)-64
    x2 = 1
    y2 = 0
    xr = float(xr)
    yr = float(yr)
    speedM2 = speed*(x2*xr+y2*yr)/math.sqrt(x2*x2+y2*y2)
    return str(int(speedM2+64))

def speedComponentM3(speed,xr,yr):
    speed = float(speed)-64
    x3 = -math.sqrt(2)/2
    y3 = math.sqrt(2)/2
    xr = float(xr)
    yr = float(yr)
    speedM3 = speed*(x3*xr+y3*yr)/math.sqrt(x3*x3+y3*y3)
    return str(int(speedM3+64))

################# Implementation #####################

speed = '100';
speedM1 = speedComponentM1(speed,x,y)
speedM2 = speedComponentM2(speed,x,y)
speedM3 = speedComponentM3(speed,x,y)
print 'M1 Speed Input:' + str(speedM1)
print 'M2 Speed Input:' + str(speedM2)
print 'M3 Speed Input:' + str(speedM3)
driveM1(speedM1)
driveM2(speedM2)
driveM3(speedM3)
time.sleep(0.10)
readCurrentSpeedM1()
readCurrentSpeedM2()
readCurrentSpeedM3()
time.sleep(3)
driveAll('64')


text:
/**
 * @namespace Phaser.Utils.Array
 */

module.exports = {

    Matrix: require('./matrix'),

    Add: require('./Add'),
    AddAt: require('./AddAt'),
    BringToTop: require('./BringToTop'),
    CountAllMatching: require('./CountAllMatching'),
    Each: require('./Each'),
    EachInRange: require('./EachInRange'),
    FindClosestInSorted: require('./FindClosestInSorted'),
    GetAll: require('./GetAll'),
    GetFirst: require('./GetFirst'),
    GetRandom: require('./GetRandom'),
    MoveDown: require('./MoveDown'),
    MoveTo: require('./MoveTo'),
    MoveUp: require('./MoveUp'),
    NumberArray: require('./NumberArray'),
    NumberArrayStep: require('./NumberArrayStep'),
    QuickSelect: require('./QuickSelect'),
    Range: require('./Range'),
    Remove: require('./Remove'),
    RemoveAt: require('./RemoveAt'),
    RemoveBetween: require('./RemoveBetween'),
    RemoveRandomElement: require('./RemoveRandomElement'),
    Replace: require('./Replace'),
    RotateLeft: require('./RotateLeft'),
    RotateRight: require('./RotateRight'),
    SafeRange: require('./SafeRange'),
    SendToBack: require('./SendToBack'),
    SetAll: require('./SetAll'),
    Shuffle: require('./Shuffle'),
    SpliceOne: require('./SpliceOne'),
    StableSort: require('./StableSort'),
    Swap: require('./Swap')

};


text:
module.exports = function (channel, row, callback) {

    var http = require('http'),
        path = require('path'),
        async = require('async'),
        fs = require('fs'),
        dbPath = channel.db.getDbPath();

    async.waterfall([
        function (cb) {
            if (!row || !row._id) return cb(new Error('no valid channel supplied'));
            cb(null, row._id);
        },
        channel.beginFetchChannel,
        function (row, cb) {
            if (row) {
                var file = fs.createWriteStream(path.resolve(dbPath, 'tmp', row._id+'.gif'));
                http.get(row.url, function (response) {
                    response.pipe(file);
                }).on('error', function (err) {
                    cb(err);
                });
                file.on('finish', function () {
                    fs.stat(path.resolve(dbPath, 'tmp', row._id+'.gif'), function (err, stats) {
                        if (err || stats.size==0) {
                            cb(err);
                        } else {
                            cb(err);
                        }
                    });
                });
                file.on('error', function (err) {
                    cb(err);
                });
            }
        }
    ],
    function (err) {
        callback(err, row);
    });
};