text:
#include<string>
#include<vector>
#include <memory>
#include <stdexcept>
#include "umf/statistics.hpp"
#include "throwJavaException.hpp"

static std::string getJavaStirng(JNIEnv *env, jstring str)
{
    const char* tmp = env->GetStringUTFChars(str, NULL);
    std::string result(tmp);
    env->ReleaseStringUTFChars(str, tmp);
    return result;
}

extern "C" {

using namespace umf;

/*
* Class:     com_intel_umf_Stat
* Method:    n_delete
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1delete(JNIEnv *env, jclass, jlong self);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1delete(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "Stat::n_1delete";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        delete obj;
    }
    catch(const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
}

//long n_Stat(String name, long[] fields);
JNIEXPORT jlong JNICALL Java_com_intel_umf_Stat_n_1Stat(JNIEnv *env, jclass, jstring name, jlongArray fields);
JNIEXPORT jlong JNICALL Java_com_intel_umf_Stat_n_1Stat(JNIEnv *env, jclass, jstring name, jlongArray fields)
{
    static const char method_name[] = "Stat::n_1Stat";

    try
    {
        if (name == 0 || fields == 0) UMF_EXCEPTION(NullPointerException, "Neither name nor fields array can be null.");
        std::vector <StatField> sfs;
        jsize len;
        jlong* addrArray;
        len = env->GetArrayLength(fields);
        addrArray = env->GetLongArrayElements(fields, 0);
        if (addrArray)
        {
            for (int i = 0; i < len; i++)
            {
                std::shared_ptr<StatField>* f = (std::shared_ptr<StatField>*) addrArray[i];
                sfs.push_back(StatField(**f));
            }
            env->ReleaseLongArrayElements(fields, addrArray, 0);
        }
        return (jlong) new std::shared_ptr<Stat>(new Stat(getJavaStirng(env, name), sfs));
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//String n_getName(long nativeObj);
JNIEXPORT jstring JNICALL Java_com_intel_umf_Stat_n_1getName(JNIEnv *env, jclass, jlong self);
JNIEXPORT jstring JNICALL Java_com_intel_umf_Stat_n_1getName(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "Stat::n_1getName";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        return env->NewStringUTF((*obj)->getName().c_str());
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//int n_getState(long nativeObj);
JNIEXPORT jint JNICALL Java_com_intel_umf_Stat_n_1getState(JNIEnv *env, jclass, jlong self);
JNIEXPORT jint JNICALL Java_com_intel_umf_Stat_n_1getState(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "Stat::n_1getState";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        return (*obj)->getState();
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//void n_setUpdateMode(long nativeObj, int updateMode);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1setUpdateMode(JNIEnv *env, jclass, jlong self, jint updateMode);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1setUpdateMode(JNIEnv *env, jclass, jlong self, jint updateMode)
{
    static const char method_name[] = "Stat::n_1setUpdateMode";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        (*obj)->setUpdateMode((Stat::UpdateMode::Type) updateMode);
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
}

//int n_getUpdateMode(long nativeObj);
JNIEXPORT jint JNICALL Java_com_intel_umf_Stat_n_1getUpdateMode(JNIEnv *env, jclass, jlong self);
JNIEXPORT jint JNICALL Java_com_intel_umf_Stat_n_1getUpdateMode(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "Stat::n_1getUpdateMode";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        return (*obj)->getUpdateMode();
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//void n_setUpdateTimeout(long nativeObj, int ms);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1setUpdateTimeout(JNIEnv *env, jclass, jlong self, jint ms);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1setUpdateTimeout(JNIEnv *env, jclass, jlong self, jint ms)
{
    static const char method_name[] = "Stat::n_1setUpdateTimeout";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        (*obj)->setUpdateTimeout(ms);
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
}

//int n_getUpdateTimeout(long nativeObj);
JNIEXPORT jint JNICALL Java_com_intel_umf_Stat_n_1getUpdateTimeout(JNIEnv *env, jclass, jlong self);
JNIEXPORT jint JNICALL Java_com_intel_umf_Stat_n_1getUpdateTimeout(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "Stat::n_1getUpdateTimeout";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        return (*obj)->getUpdateTimeout();
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//void n_update(long nativeObj, boolean doWait);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1update(JNIEnv *env, jclass, jlong self, jboolean doWait);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1update(JNIEnv *env, jclass, jlong self, jboolean doWait)
{
    static const char method_name[] = "Stat::n_1update";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        (*obj)->update(doWait == JNI_TRUE);
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
}

//String[] n_getAllFieldNames(long nativeObj);
JNIEXPORT jobjectArray JNICALL Java_com_intel_umf_Stat_n_1getAllFieldNames(JNIEnv *env, jclass, jlong self);
JNIEXPORT jobjectArray JNICALL Java_com_intel_umf_Stat_n_1getAllFieldNames(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "MetadataStream::n_1getAllFieldNames";
    try
    {
       std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
       if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");

        std::vector<std::string> names = (*obj)->getAllFieldNames();
        jobjectArray result = (jobjectArray)env->NewObjectArray((jsize)names.size(), env->FindClass("java/lang/String"), env->NewStringUTF(""));
        for (jsize i = 0; i<names.size(); i++)
            env->SetObjectArrayElement(result, i, env->NewStringUTF(names[i].c_str()));

        return result;
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//long n_getField(long nativeObj, String name);
JNIEXPORT jlong JNICALL Java_com_intel_umf_Stat_n_1getField(JNIEnv *env, jclass, jlong self, jstring name);
JNIEXPORT jlong JNICALL Java_com_intel_umf_Stat_n_1getField(JNIEnv *env, jclass, jlong self, jstring name)
{
    static const char method_name[] = "Stat::n_1getField";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        return (jlong) new std::shared_ptr<StatField>( new StatField((*obj)->getField(getJavaStirng(env, name))) );
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

JNIEXPORT jlong JNICALL Java_com_intel_umf_Stat_n_1getValue(JNIEnv *env, jclass, jlong self, jstring name);
JNIEXPORT jlong JNICALL Java_com_intel_umf_Stat_n_1getValue(JNIEnv *env, jclass, jlong self, jstring name)
{
    static const char method_name[] = "Stat::n_1getValue";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        return (jlong) new std::shared_ptr<Variant>(new Variant((*obj)->getField(getJavaStirng(env, name)).getValue()));
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
    return 0;
}

//void n_clear(long nativeObj);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1clear(JNIEnv *env, jclass, jlong self);
JNIEXPORT void JNICALL Java_com_intel_umf_Stat_n_1clear(JNIEnv *env, jclass, jlong self)
{
    static const char method_name[] = "Stat::n_1clear";

    try
    {
        std::shared_ptr<Stat>* obj = (std::shared_ptr<Stat>*) self;
        if (obj == NULL || *obj == NULL)  UMF_EXCEPTION(NullPointerException, "Stat (self) is null pointer.");
        (*obj)->clear();
    }
    catch (const std::exception &e) { throwJavaException(env, &e, method_name); }
    catch (...) { throwJavaException(env, 0, method_name); }
}

}


text:
<!--
 Copyright 2021 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.taqo.survey.taqo_email_plugin_example">
    <!-- Flutter needs it to communicate with the running application
         to allow setting breakpoints, to provide hot reload, etc.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

redpajama_set_name: RedPajamaGithub


text:
package org.dainst.chronontology.it;

import com.fasterxml.jackson.databind.JsonNode;
import com.squareup.okhttp.OkHttpClient;
import org.apache.commons.io.FileUtils;
import org.dainst.chronontology.App;
import org.dainst.chronontology.TestConstants;
import org.dainst.chronontology.config.AppConfig;
import org.dainst.chronontology.config.AppConfigurator;
import org.dainst.chronontology.handler.dispatch.ConnectDispatcher;
import org.dainst.chronontology.handler.model.Document;
import org.dainst.chronontology.store.ESServerTestUtil;
import org.dainst.chronontology.store.ElasticsearchDatastore;
import org.dainst.chronontology.store.FilesystemDatastore;
import org.dainst.chronontology.store.rest.JsonRestClient;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import spark.Spark;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * @author Daniel M. de Oliveira
 */
public abstract class IntegrationTest {

    protected static final String TYPE_ROUTE = "/" + TestConstants.TEST_TYPE + "/";

    // A client speaking to the rest api of the app under design
    protected static final JsonRestClient client = new JsonRestClient(TestConstants.SERVER_URL,new OkHttpClient(),false);

    // To allow direct data manipulation for testing purposes
    protected static ElasticsearchDatastore connectDatastore = null;
    // To allow direct data manipulation for testing purposes
    protected static FilesystemDatastore mainDatastore = null;

    @BeforeClass
    public static void beforeClass() throws InterruptedException {
        ESServerTestUtil.startElasticSearchServer();
        startServer();
    }

    @AfterClass
    public static void afterClass() throws InterruptedException {
        stopServer();
        ESServerTestUtil.stopElasticSearchServer();
    }

    @BeforeMethod
    public void beforeMethod() {
        client.authenticate(TestConstants.USER_NAME_ADMIN, TestConstants.PASS_WORD);
    }

    @AfterMethod
    public void afterMethod() throws IOException {
        ESClientTestUtil.deleteESTypeAndMapping();
        FileUtils.deleteDirectory(new File("src/test/resources/period"));
    }

    private static AppConfig makeAppConfig() {

        Properties props= new Properties();
        props.put("serverPort",TestConstants.SERVER_PORT);
        props.put("datastore.elasticsearch.indexName",ESClientTestUtil.getIndexName());
        props.put("datastore.elasticsearch.url",ESServerTestUtil.getUrl());
        props.put("datastore.filesystem.path",TestConstants.TEST_FOLDER);
        props.put("typeNames",TestConstants.TEST_TYPE);
        props.put("credentials", makeCredentials());
        props.put("dataset.dataset1.editor", TestConstants.USER_NAME_1);
        props.put("dataset.dataset1.reader", TestConstants.USER_NAME_3);

        AppConfig config= new AppConfig();
        config.validate(props);
        return config;
    }

    private static String makeCredentials() {
        return TestConstants.USER_NAME_ADMIN + ":" + TestConstants.PASS_WORD
                + "," + TestConstants.USER_NAME_1 + ":" + TestConstants.PASS_WORD
                + "," + TestConstants.USER_NAME_2 + ":" + TestConstants.PASS_WORD
                + "," + TestConstants.USER_NAME_3 + ":" + TestConstants.PASS_WORD;
    }

    protected static void startServer() throws InterruptedException {

        App app=  new AppConfigurator().configure(makeAppConfig());
        ConnectDispatcher controller= (ConnectDispatcher) app.getController().getDispatcher();

        mainDatastore= (FilesystemDatastore) controller.getDatastores()[1];
        connectDatastore= (ElasticsearchDatastore) controller.getDatastores()[0];

        Thread.sleep(1000);
    }

    protected static void stopServer() throws InterruptedException {
        Thread.sleep(200);
        Spark.stop();
    }

    protected String idOf(final JsonNode n) {
        if (n==null) return null;
        if (n.get(Document.RESOURCE)==null) return null;
        if (n.get(Document.RESOURCE).get(Document.ID)==null) return null;
        return (String) n.get(Document.RESOURCE).get(Document.ID).textValue();
    }
}


text:
from awscli.customizations.emr import applicationutils
from awscli.customizations.emr import argumentschema
from awscli.customizations.emr import constants
from awscli.customizations.emr import emrutils
from awscli.customizations.emr import helptext
from awscli.customizations.emr.command import Command

class InstallApplications(Command):
    NAME = 'install-applications'
    DESCRIPTION = ('Installs applications on a running cluster. Currently only'
                   ' Hive and Pig can be installed using this command, and'
                   ' this command is only supported by AMI versions'
                   ' (3.x and 2.x).')
    ARG_TABLE = [
        {'name': 'cluster-id', 'required': True,
         'help_text': helptext.CLUSTER_ID},
        {'name': 'applications', 'required': True,
         'help_text': helptext.INSTALL_APPLICATIONS,
         'schema': argumentschema.APPLICATIONS_SCHEMA},
    ]
    # Applications supported by the install-applications command.
    supported_apps = ['HIVE', 'PIG']

    def _run_main_command(self, parsed_args, parsed_globals):

        parameters = {'JobFlowId': parsed_args.cluster_id}

        self._check_for_supported_apps(parsed_args.applications)
        parameters['Steps'] = applicationutils.build_applications(
            self.region, parsed_args.applications)[2]

        emrutils.call_and_display_response(self._session, 'AddJobFlowSteps',
                                           parameters, parsed_globals)
        return 0

    def _check_for_supported_apps(self, parsed_applications):
        for app_config in parsed_applications:
            app_name = app_config['Name'].upper()

            if app_name in constants.APPLICATIONS:
                if app_name not in self.supported_apps:
                    raise ValueError(
                        "aws: error: " + app_config['Name'] + " cannot be"
                        " installed on a running cluster. 'Name' should be one"
                        " of the following: " +
                        ', '.join(self.supported_apps))
            else:
                raise ValueError(
                    "aws: error: Unknown application: " + app_config['Name'] +
                    ". 'Name' should be one of the following: " +
                    ', '.join(constants.APPLICATIONS))


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

const Promise = require('bluebird');
const mongoose = require('mongoose');
const String = mongoose.Schema.Types.String;
const Number = mongoose.Schema.Types.Number;
const moment = require('moment');
const appEnv = require('./appEnv');

// define schemas and models for articles
const articleSchema = new mongoose.Schema({
  _id: String,
  title: String,
  date: mongoose.Schema.Types.Date,
  url: String
});
const Article = mongoose.model('Article', articleSchema);

// define schemas and models for entities
const entitySchema = new mongoose.Schema({
  _id: String,
  text: String,
  count: Number,
  sentiment: Number,
  date: Date,
  article_id: String
});
const Entity = mongoose.model('Entity', entitySchema);

/** Initialize the database connection */
module.exports.init = () => {
  // step one: initialize mongoose
  const mongoURI = appEnv.getService(/mongolab/ig).credentials.uri;
  mongoose.connect(mongoURI);
  // step two: connect mongoose
  return new Promise((resolve, reject) => {
    const db = mongoose.connection;
    db.on('error', reject);
    db.once('open', resolve);
  });
};

/**
 * Resolves with an array of entities grouped by their text. Can
 * specify a timeframe for the grouping, and can also specify the
 * number of entities to return.
 */
module.exports.aggregateEntities = (start = 0, end = 9999999999999, limit = 100) =>
  new Promise((resolve, reject) => {
    Entity.aggregate(
      { $match: { date: { $gte: new Date(start) , $lt: new Date(end) } } },
      { $group: { _id: {'$toLower' : '$text'}, value: { $sum: '$count'}, sentiment: { $avg: '$sentiment'} } },
      { $sort: { value: -1} },
      { $limit: limit },
      (err, res) => {
        if (err) {
          console.error(err);
          reject(err);
        } else {
          resolve(res);
        }
      }
    );
  });

/**
 * Given an entities text and a timeframe, resolve with the articles
 * that mention that entity.
 */
module.exports.getArticlesForEntity = (entity, start = 0, end = 9999999999999) =>
  this.getArticleIdsForEntity(entity, start, end).then(articleIds =>
    new Promise((resolve, reject) => {
      Article.find(
        { '_id': { $in: articleIds} }, // get all articles by id
        null,                          // return all columns
        { sort: {date: -1}},           // sort by date descending and only get 100
        (err, articles) => {
          if (err) {
            console.error(err);
            reject(err);
          } else {
            resolve(articles);
          }
        }
      );
    })
  );

/**
 * Given an entities text and a timeframe, resolve with the article
 * ids that contain that entity.
 */
module.exports.getArticleIdsForEntity = (entity, start = 0, end = 9999999999999) =>
  new Promise((resolve, reject) => {
    Entity.aggregate(
      { $match: { text: new RegExp('^' + entity + '$', 'i'), date: { $gte: new Date(start) , $lt: new Date(end) } } },
      { $group: { _id: '$text', value: { $push: '$article_id'} } },
      (err, res) => {
        if (err) {
          console.error(err);
          reject(err);
        } else {
          resolve(res[0].value);
        }
      }
    );
  });

/** Resolve with an object that contains the min and max dates in the Articles DB. */
module.exports.getMinAndMaxDates = () =>
  Promise.join(_getMinDate(), _getMaxDate(), (min, max) => ({ min, max }));

/**
 * Given an array of documents from alchemy, convert them into Articles
 * as defined in the Schema, and upload them to our database. If an article
 * with the same id exists, we update the value of what's already there.
 */
module.exports.uploadArticlesFromDocs = docs => {
  // ideally we could do some kind of batch operation like
  // Article.create(docs.map(_adaptFromAlchemyDoc), function (args) {});
  // but I don't believe there's a way to do that with the upsert scheme.
  // so... until we figure that out, we'll live this method as one request per document
  docs.forEach(doc => {
    if (doc) {
      const articleAndEntitityPrimitives = _adaptFromAlchemyDoc(doc);
      if (articleAndEntitityPrimitives) {
        const articlePrimitive = articleAndEntitityPrimitives.article;
        if (articlePrimitive) {
          Article.findByIdAndUpdate(articlePrimitive._id, articlePrimitive, {upsert: true}, () => {});
        }
        const entityPrimitives = articleAndEntitityPrimitives.entities;
        if (entityPrimitives && entityPrimitives.length) {
          entityPrimitives.forEach(ep =>
            Entity.findByIdAndUpdate(ep._id, ep, {upsert: true}, () => {})
          );
        }
      }
    }
  });
}

/** Remove all articles and entities older than 30 days */
module.exports.pruneOlderThan30d = () => {
  const date = moment().startOf('day').subtract(30, 'day').unix()*1000;
  const args = { date: { $lt: new Date(date) } };
  Article.remove(args, e => {
    if (e) { console.error(e); }
  });
  Entity.remove(args, e => {
    if (e) { console.error(e); }
  });
}

/** Remove all entities with a text length of 1 */
module.exports.pruneCharEntities = () =>
  Entity.remove({$where:"this.text.length == 1"}, e => {
    if (e) { console.error(e); }
  });

/** Resolve with the min date in the Articles DB. */
const _getMinDate = () =>
  new Promise((resolve, reject) => {
    Article.find({}, 'date', {limit: 1, sort: {date: 1}}, (e, docs) => {
      if (e) {
        reject(e);
      } else {
        const date = docs[0] ? docs[0].date.getTime() : null;
        resolve(date);
      }
    });
  });

/** Resolve with the max date in the Articles DB. */
const _getMaxDate = () =>
  new Promise((resolve, reject) => {
    Article.find({}, 'date', {limit: 1, sort: {date: -1}}, (e, docs) => {
      if (e) {
        reject(e);
      } else {
        const date = docs[0] ? docs[0].date.getTime() : null;
        resolve(date);
      }
    });
  });

/** Given a response from Alchemy, create a new Article and Entities primitives */
const _adaptFromAlchemyDoc = doc => {
  const enrichedUrl = doc.source && doc.source.enriched && doc.source.enriched.url;
  let article;
  let entities;
  if (enrichedUrl) {
    article = {
      _id: doc.id,
      title: enrichedUrl.title,
      date: new Date(doc.timestamp * 1000),
      url: enrichedUrl.url
    }
    entities = enrichedUrl.entities.map(({ text, count, sentiment }) => {
      return {
        _id: text + doc.id,
        article_id: doc.id,
        date: new Date(doc.timestamp * 1000),
        text: text,
        count: count,
        sentiment: sentiment.score
      }
    }).filter(({ text }) => text.length > 1);
    if (entities.length) {
      return {
        article: article,
        entities: entities
      };
    }
  }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[System.Serializable]
public struct EnemyLoadout
{
	public string name;
	public SpellType mType;
	public GameObject prefab;
	public float maxHealth;
	[HideInInspector]
	public float health;
	public float damage;
	public float knockbackPower;
	public float speed;
}

public class EnemyManager : MonoBehaviour
{
	private static EnemyManager instance;

	public static List<GameObject> enemies;

	public EnemyLoadout waterEnemyLoadout;
	public EnemyLoadout fireEnemyLoadout;
	public EnemyLoadout rockEnemyLoadout;
	private static EnemyLoadout[] enemyLoadouts;

	private static bool awakeHasBeenCalled = false;
	void Awake()
	{
		if(instance == null)
		{
			instance = this;
			DontDestroyOnLoad(gameObject);
		}

		if(!awakeHasBeenCalled)
		{
			print ("[EnemyManager] Start()");
			enemies = new List<GameObject>();
			StartCoroutine ("PurgeEnemyList");

			enemyLoadouts = new EnemyLoadout[3];
			enemyLoadouts[(int)SpellType.Fire]  = fireEnemyLoadout;
			enemyLoadouts[(int)SpellType.Water] = waterEnemyLoadout;
			enemyLoadouts[(int)SpellType.Rock]  = rockEnemyLoadout;

			awakeHasBeenCalled = true;
		}
	}

	public static void RegisterEnemy(GameObject enemy)
	{
		if(!enemies.Contains(enemy))
		{
			enemies.Add (enemy);
		}
	}

	public static GameObject GetClosest(Vector3 pos, float maxDist)
	{
		enemies.RemoveAll(obj => obj == null);

		float closestDist = float.MaxValue;
		GameObject closestEnemy = null;

		foreach (GameObject e in enemies)
		{
			float dist = (e.transform.position - pos).sqrMagnitude;
			if(dist < closestDist)
			{
				closestDist = dist;
				closestEnemy = e;
			}
		}
		if(closestDist > maxDist * maxDist)
		{
			return null;
		}
		return closestEnemy;
	}

	public static GameObject GetNextClosest(GameObject current, Vector3 pos, float maxDist)
	{
		enemies.RemoveAll(obj => obj == null);

		float closestDist = float.MaxValue;
		GameObject closestEnemy = current;

		foreach (GameObject e in enemies)
		{
			float dist = (e.transform.position - pos).sqrMagnitude;
			if(dist < closestDist && e != current)
			{
				closestDist = dist;
				closestEnemy = e;
			}
		}
		if(closestDist > maxDist * maxDist)
		{
			return null;
		}
		return closestEnemy;
	}

	IEnumerator PurgeEnemyList()
	{
		while(true)
		{
			yield return new WaitForSeconds(5.0f);
			enemies.RemoveAll(obj => obj == null);
		}
	}

	public static void InitEnemy(Enemy e)
	{
		EnemyLoadout el = enemyLoadouts [(int)e.loadout.mType];
		e.loadout.name 			 = el.name;
		e.loadout.health		 = el.maxHealth;
		e.loadout.maxHealth 	 = el.maxHealth;
		e.loadout.damage		 = el.damage;
		e.loadout.knockbackPower = el.knockbackPower;
		e.loadout.speed 		 = el.speed;
	}

	public static EnemyLoadout GetEnemyLoadout(SpellType type)
	{
		if(enemyLoadouts == null)
		{
			enemyLoadouts = new EnemyLoadout[3];
			enemyLoadouts[(int)SpellType.Fire]  = instance.fireEnemyLoadout;
			enemyLoadouts[(int)SpellType.Water] = instance.waterEnemyLoadout;
			enemyLoadouts[(int)SpellType.Rock]  = instance.rockEnemyLoadout;
		}
		return enemyLoadouts[(int)type];
	}

}


text:
package net.lshift.diffa.interview;

public interface GroupedAnswer extends Answer {

  String getGroup();
}


text:
namespace _6.Twitter.Models
{
    using Interfaces;

    public class Tweet : ITweet
    {
        private IClient client;

        public Tweet(IClient client)
        {
            this.client = client;
        }

        public void ReceiveMessage(string message)
        {
            this.client.WriteTweet(message);
            this.client.SendTweetToServer(message);
        }
    }
}


text:
<?php

namespace Edge\Ares\Provider;

use Edge\Ares\Decorator\CurlDecoratorInterface;
use Edge\Ares\Exception\HttpException;

/**
 * @author Marek Makovec <marek.makovec@edgedesign.cz>
 */
class HttpProvider implements ProviderInterface
{
    const ARES_API_URL = 'http://wwwinfo.mfcr.cz/cgi-bin/ares/darv_bas.cgi?ico=%s';

    /**
     * @var \Edge\Ares\Decorator\CurlDecoratorInterface
     */
    private $decorator;

    public function __construct(CurlDecoratorInterface $decorator = null)
    {
        $this->decorator = $decorator;
    }

    /**
     * Fetch XML describing subject with given ID.
     *
     * @param integer $ic
     *
     * @throws \Edge\Ares\Exception\HttpException
     * @return string
     */
    public function fetchSubjectXml($ic)
    {
        $url = $this->generateUrl($ic);
        $session = curl_init($url);

        curl_setopt($session, CURLOPT_HEADER, false);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

        if ($this->decorator) {
            $this->decorator->decorate($session);
        }

        $xml = curl_exec($session);

        if($xml === false) {
            throw new HttpException('cURL error: ' . curl_errno($session));
        }

        curl_close($session);

        return $xml;
    }

    /**
     * Create full url where subject information is stored.
     *
     * @param int $ic
     *
     * @return string
     */
    private function generateUrl($ic)
    {
        return sprintf(self::ARES_API_URL, $ic);
    }

}


text:
<?php

namespace Symfony\Component\Routing\Loader;

use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\RouteCollection;

/**
 * A route loader that calls a method on an object to load the routes.
 *
 * @author Ryan Weaver <ryan@knpuniversity.com>
 */
abstract class ObjectRouteLoader extends Loader
{
    /**
     * Returns the object that the method will be called on to load routes.
     *
     * For example, if your application uses a service container,
     * the $id may be a service id.
     *
     * @param string $id
     *
     * @return object
     */
    abstract protected function getServiceObject($id);

    /**
     * Calls the service that will load the routes.
     *
     * @param mixed       $resource Some value that will resolve to a callable
     * @param string|null $type     The resource type
     *
     * @return RouteCollection
     */
    public function load($resource, $type = null)
    {
        $parts = explode(':', $resource);
        if (count($parts) != 2) {
            throw new \InvalidArgumentException(sprintf('Invalid resource "%s" passed to the "service" route loader: use the format "service_name:methodName"', $resource));
        }

        $serviceString = $parts[0];
        $method = $parts[1];

        $loaderObject = $this->getServiceObject($serviceString);

        if (!is_object($loaderObject)) {
            throw new \LogicException(sprintf('%s:getServiceObject() must return an object: %s returned', get_class($this), gettype($loaderObject)));
        }

        if (!method_exists($loaderObject, $method)) {
            throw new \BadMethodCallException(sprintf('Method "%s" not found on "%s" when importing routing resource "%s"', $method, get_class($loaderObject), $resource));
        }

        $routeCollection = call_user_func(array($loaderObject, $method), $this);

        if (!$routeCollection instanceof RouteCollection) {
            $type = is_object($routeCollection) ? get_class($routeCollection) : gettype($routeCollection);

            throw new \LogicException(sprintf('The %s::%s method must return a RouteCollection: %s returned', get_class($loaderObject), $method, $type));
        }

        // make the service file tracked so that if it changes, the cache rebuilds
        $this->addClassResource(new \ReflectionClass($loaderObject), $routeCollection);

        return $routeCollection;
    }

    /**
     * {@inheritdoc}
     */
    public function supports($resource, $type = null)
    {
        return 'service' === $type;
    }

    private function addClassResource(\ReflectionClass $class, RouteCollection $collection)
    {
        do {
            $collection->addResource(new FileResource($class->getFileName()));
        } while ($class = $class->getParentClass());
    }
}


text:
package monsters;

import java.util.Random;

import monsters.Monster;
import monsters.interfaces.MTIndexInterface;
import monsters.animals.GiantDuck;
import monsters.animals.SquirrelGold;
import monsters.humans.GunMan;
import monsters.humans.KnifeMan;

/**
 *  Randomized Monster instance generator. Notice that the generator
 *  method is static - no need initilization. Within any class
 *  out here, which imports this class, call it like this:
 *
 *      Monster m = RandomMonsterGen.GET();
 *
 *  @author Wonho Lim
 */
public class RandomMonsterGen implements MTIndexInterface {

    private static int rnGen()
    {
        return  new Random().nextInt ( DEFAULT_MONSTER_KINDS_NUMBER );
    }

    public static Monster GET()
    {
        switch ( rnGen() ) {
            case MTI_ANIMAL_GIANT_DUCK:     return new GiantDuck();
            case MTI_HUMAN_GUN_MAN:         return new GunMan();
            case MTI_HUMAN_KNIFE_MAN:       return new KnifeMan();
            case MTI_ANIMAL_SQUIRREL_GOLD:  return new SquirrelGold();

            default:                        return null;
        }
    }
}


text:
<select name="section_id" id="section_id" class="form-control">
    <option>Select One</option>
    <?php
    foreach ($allsection as $section):
        ?>
        <option value="<?php echo $section->section_id; ?>">
            <?php echo $section->section_name; ?>
        </option>
        <?php
    endforeach;
    ?>
</select>


text:
$names =["Henry","Paul"]
$c =Hash.new 0
class Election
	def verify?(name)
		$names.include?(name)
	end

	def user
		puts "-----------------------------------------------------"
		puts "Input your name to check if you are legible to vote"
		puts "-----------------------------------------------------"
		voter=gets.chomp
		if verify?(voter)
			puts "You can vote"
			vote_for
		else
			puts "Please you can't vote"

		end
	end

	def count
		total =0
		$c.each do |name, score|
			puts "#{name} has #{score} votes"
			total += score
		end
			puts "------------------------------------"
			puts "The total vote casted is #{total}"
			puts "------------------------------------"
	end

	def vote_for
		puts"Enter 1. Vote 2.Query 3.Exit"
		opr=gets.to_i

		case opr
			when 1
				puts "PLease enter the name of the person you want to vote for"
				person=gets.chomp
				$c[person]+=1
				vote_for
			when 2
				count
			when 3
				puts "Thanks for visiting"
		end
	end
end
mine=Election.new.user


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

namespace ServiciosWCF.Servicios.workgroups
{
    public partial class ServiceWCF_SignalDB : Servicios.workgroups.IWorkgroupsService
    {
        LogicaDeNegocios.workgroups.IWorkgroupsLogicaDeNegocios workgroupsLogicaNegocio = new LogicaDeNegocios.LogicaDeNegocios_SignalDB();

        public int InsertarWorkgroups(Dominio.Dtos.workgroupsDTO dto)
        {
            try
            {
                return workgroupsLogicaNegocio.InsertarWorkgroups(dto);
            }
            catch (Exception ex)
            {
                throw ManejoErrores.Handlers.Handlers.ErrorServicios(ex);
            }
        }

        public bool ActualizarWorkgroups(Dominio.Dtos.workgroupsDTO dto)
        {
            try
            {
                return workgroupsLogicaNegocio.ActualizarWorkgroups(dto);
            }
            catch (Exception ex)
            {
                throw ManejoErrores.Handlers.Handlers.ErrorServicios(ex);
            }
        }

        public bool EliminarWorkgroups(int id)
        {
            try
            {
                return workgroupsLogicaNegocio.EliminarWorkgroups(id);
            }
            catch (Exception ex)
            {
                throw ManejoErrores.Handlers.Handlers.ErrorServicios(ex);
            }
        }

        public Dominio.Dtos.workgroupsDTO BuscarWorkgroups(int id)
        {
            try
            {
                return workgroupsLogicaNegocio.BuscarWorkgroups(id);
            }
            catch (Exception ex)
            {
                throw ManejoErrores.Handlers.Handlers.ErrorServicios(ex);
            }
        }

        public List<Dominio.Dtos.workgroupsDTO> ListarWorkgroups(string param)
        {
            try
            {
                return workgroupsLogicaNegocio.ListarWorkgroups(param);
            }
            catch (Exception ex)
            {
                throw ManejoErrores.Handlers.Handlers.ErrorServicios(ex);
            }
        }

        public List<Dominio.Dtos.workgroupsDTO> ListarTodosLosWorkgroup_Activos()
        {
            try
            {
                return workgroupsLogicaNegocio.ListarTodosLosWorkgroup_Activos();
            }
            catch (Exception ex)
            {
                throw ManejoErrores.Handlers.Handlers.ErrorServicios(ex);
            }
        }
    }
}


text:
#import "NSObject.h"

@class NSManagedObjectContext;

@interface MFSeenMessagesManager : NSObject
{
    id _account;
    NSManagedObjectContext *_managedObjectContext;
}

@property(retain) NSManagedObjectContext *managedObjectContext; // @synthesize managedObjectContext=_managedObjectContext;
@property(retain) id account; // @synthesize account=_account;
- (void)_configureManagedObjectContext;
- (void)saveChanges;
- (void)removeMessagesNotOnServer:(id)arg1;
- (void)removeServerDeletedMessages;
- (id)messagesToBeDeletedFromServer;
- (id)seenMessages;
- (void)removeMessageIDs:(id)arg1;
- (id)addMessageID:(id)arg1 dateSeen:(id)arg2;
- (unsigned long long)countOfSeenMessages;
- (id)seenMessageForMessageID:(id)arg1;
- (id)_addAccountWithID:(id)arg1;
- (id)_accountForAccountID:(id)arg1;
- (void)dealloc;
- (id)initWithAccountID:(id)arg1 createAccount:(BOOL)arg2;

@end


text:
package org.batfish.datamodel.flow;

import java.util.List;
import java.util.SortedMap;
import org.batfish.datamodel.Flow;
import org.batfish.datamodel.answers.AnswerElement;

/** A wrapper around new {@link Trace} answers to allow returning an {@link AnswerElement} */
public class TraceWrapperAsAnswerElement extends AnswerElement {
  private final SortedMap<Flow, List<Trace>> _flowTraces;

  public TraceWrapperAsAnswerElement(SortedMap<Flow, List<Trace>> flowTraces) {
    _flowTraces = flowTraces;
  }

  public SortedMap<Flow, List<Trace>> getFlowTraces() {
    return _flowTraces;
  }
}


text:
#!/usr/bin/env ./node_modules/.bin/babel-node
// @flow
/**
 * Extracts i18n strings from each package and writes them out to <package>/dist/strings.js.
 *
 * This file contains i18n._(), i18n._$(), and i18n.ngettext() calls that can be re-extracted
 * by webapp.  This is required for so that we can leverage webapp's translation pipeline
 * which is responsible for uploading strings to Crowdin.
 */
import fs from "fs";
import path from "path";

import {extractStrings} from "@khanacademy/wonder-stuff-i18n";
import ancesdir from "ancesdir";
import fg from "fast-glob";

import {getLogger} from "./internal/logger.js";

const rootDir = ancesdir(__dirname);

const logger = getLogger();

export const generateStringsFileForPackage = (pkgName: string) => {
    const glob = path.join(
        rootDir,
        "packages",
        pkgName,
        "src",
        "**",
        "*.{js,jsx}",
    );
    const files = fg.sync(glob);

    files.sort();

    let strings = [];

    for (const file of files) {
        logger.debug(`processing ${file}`);
        const content = fs.readFileSync(file, "utf-8");
        const extracted = extractStrings(content);
        // NOTE(kevinb): We use for-of here instead of doing
        // strings.push(...extracted) because our babel config
        // has its @babel/plugin-transform-spread plugin using
        // loose: true and `extracted` is not an array (it's a
        // a generator).
        for (const string of extracted) {
            strings.push(string);
            logger.debug(`extracted string: ${JSON.stringify(string)}`);
        }
    }

    const memoMap = new Map();

    strings = strings.filter((string) => {
        if (memoMap.has(string.msgids[0])) {
            // Copy over any comments to the memoized instance.
            const memoedString = memoMap.get(string.msgids[0]);
            if (memoedString) {
                memoedString.comments.push(...string.comments);
            }
            return false;
        }
        memoMap.set(string.msgids[0], string);
        return true;
    });

    strings.sort((a, b) => a.msgids[0].localeCompare(b.msgids[0]));
    if (strings.length === 0) {
        logger.info(`No translateable strings in ${pkgName}`);
        return;
    }

    const outDir = path.join(rootDir, "packages", pkgName, "dist");
    if (!fs.existsSync(outDir)) {
        fs.mkdirSync(outDir, {recursive: true});
    }

    const outPath = path.join(outDir, "strings.js");
    const fd = fs.openSync(outPath, "w");

    const writeLine = (line) => fs.writeSync(fd, line + "\n");

    const header = `// @noflow
 /**
  * WARNING: This is an autogenerated file.  Do not edit by hand.
  * To regenerate, run: yarn extract-strings.
  */
 `;

    writeLine(header);
    writeLine("module.exports = [");
    for (const string of strings) {
        if (string.comments) {
            for (const comment of string.comments) {
                writeLine(`    // I18N: ${comment}`);
            }
        }
        const args = string.msgids
            .map((msgid) => JSON.stringify(msgid))
            .join(",");
        writeLine(`    i18n.${string.type}(${args}, {}),`);
    }
    writeLine("];");
    fs.closeSync(fd);
    logger.info(
        `wrote ${strings.length} strings to ${path.relative(rootDir, outPath)}`,
    );
};

if (require.main === module) {
    fs.readdirSync(path.join(rootDir, "packages")).map(
        generateStringsFileForPackage,
    );
}


text:
struct HandledPubSubItem {
  std::string itemid;
  std::string payload;
};

class TestPubSubTasksListener : public sigslot::has_slots<> {
 public:
  TestPubSubTasksListener() : result_count(0), error_count(0) {}

  void OnReceiveUpdate(buzz::PubSubReceiveTask* task,
                       const std::vector<buzz::PubSubItem>& items) {
    OnItems(items);
  }

  void OnRequestResult(buzz::PubSubRequestTask* task,
                       const std::vector<buzz::PubSubItem>& items) {
    OnItems(items);
  }

  void OnItems(const std::vector<buzz::PubSubItem>& items) {
    for (std::vector<buzz::PubSubItem>::const_iterator item = items.begin();
         item != items.end(); ++item) {
      HandledPubSubItem handled_item;
      handled_item.itemid = item->itemid;
      if (item->elem->FirstElement() != NULL) {
        handled_item.payload = item->elem->FirstElement()->Str();
      }
      this->items.push_back(handled_item);
    }
  }

  void OnPublishResult(buzz::PubSubPublishTask* task) {
    ++result_count;
  }

  void OnRetractResult(buzz::PubSubRetractTask* task) {
    ++result_count;
  }

  void OnError(buzz::IqTask* task, const buzz::XmlElement* stanza) {
    ++error_count;
  }

  std::vector<HandledPubSubItem> items;
  int result_count;
  int error_count;
};

class PubSubTasksTest : public testing::Test {
 public:
  PubSubTasksTest() :
      pubsubjid("room@domain.com"),
      node("topic"),
      itemid("key") {
    runner.reset(new rtc::FakeTaskRunner());
    client = new buzz::FakeXmppClient(runner.get());
    listener.reset(new TestPubSubTasksListener());
  }

  rtc::scoped_ptr<rtc::FakeTaskRunner> runner;
  // Client deleted by deleting runner.
  buzz::FakeXmppClient* client;
  rtc::scoped_ptr<TestPubSubTasksListener> listener;
  buzz::Jid pubsubjid;
  std::string node;
  std::string itemid;
};

TEST_F(PubSubTasksTest, TestRequest) {
  buzz::PubSubRequestTask* task =
      new buzz::PubSubRequestTask(client, pubsubjid, node);
  task->SignalResult.connect(
      listener.get(), &TestPubSubTasksListener::OnRequestResult);
  task->Start();

  std::string expected_iq =
      "<cli:iq type=\"get\" to=\"room@domain.com\" id=\"0\" "
        "xmlns:cli=\"jabber:client\">"
        "<pub:pubsub xmlns:pub=\"http://jabber.org/protocol/pubsub\">"
          "<pub:items node=\"topic\"/>"
        "</pub:pubsub>"
      "</cli:iq>";

  ASSERT_EQ(1U, client->sent_stanzas().size());
  EXPECT_EQ(expected_iq, client->sent_stanzas()[0]->Str());

  std::string result_iq =
      "<iq xmlns='jabber:client' id='0' type='result' from='room@domain.com'>"
      "  <pubsub xmlns='http://jabber.org/protocol/pubsub'>"
      "    <items node='topic'>"
      "      <item id='key0'>"
      "        <value0/>"
      "      </item>"
      "      <item id='key1'>"
      "        <value1/>"
      "      </item>"
      "    </items>"
      "  </pubsub>"
      "</iq>";

  client->HandleStanza(buzz::XmlElement::ForStr(result_iq));

  ASSERT_EQ(2U, listener->items.size());
  EXPECT_EQ("key0", listener->items[0].itemid);
  EXPECT_EQ("<pub:value0 xmlns:pub=\"http://jabber.org/protocol/pubsub\"/>",
            listener->items[0].payload);
  EXPECT_EQ("key1", listener->items[1].itemid);
  EXPECT_EQ("<pub:value1 xmlns:pub=\"http://jabber.org/protocol/pubsub\"/>",
            listener->items[1].payload);
}

TEST_F(PubSubTasksTest, TestRequestError) {
  std::string result_iq =
      "<iq xmlns='jabber:client' id='0' type='error' from='room@domain.com'>"
      "  <error type='auth'>"
      "    <forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
      "  </error>"
      "</iq>";

  buzz::PubSubRequestTask* task =
      new buzz::PubSubRequestTask(client, pubsubjid, node);
  task->SignalResult.connect(
      listener.get(), &TestPubSubTasksListener::OnRequestResult);
  task->SignalError.connect(
      listener.get(), &TestPubSubTasksListener::OnError);
  task->Start();
  client->HandleStanza(buzz::XmlElement::ForStr(result_iq));

  EXPECT_EQ(0, listener->result_count);
  EXPECT_EQ(1, listener->error_count);
}

TEST_F(PubSubTasksTest, TestReceive) {
  std::string items_message =
      "<message xmlns='jabber:client' from='room@domain.com'>"
      "  <event xmlns='http://jabber.org/protocol/pubsub#event'>"
      "    <items node='topic'>"
      "      <item id='key0'>"
      "        <value0/>"
      "      </item>"
      "      <item id='key1'>"
      "        <value1/>"
      "      </item>"
      "    </items>"
      "  </event>"
      "</message>";

  buzz::PubSubReceiveTask* task =
      new buzz::PubSubReceiveTask(client, pubsubjid, node);
  task->SignalUpdate.connect(
      listener.get(), &TestPubSubTasksListener::OnReceiveUpdate);
  task->Start();
  client->HandleStanza(buzz::XmlElement::ForStr(items_message));

  ASSERT_EQ(2U, listener->items.size());
  EXPECT_EQ("key0", listener->items[0].itemid);
  EXPECT_EQ(
      "<eve:value0 xmlns:eve=\"http://jabber.org/protocol/pubsub#event\"/>",
      listener->items[0].payload);
  EXPECT_EQ("key1", listener->items[1].itemid);
  EXPECT_EQ(
      "<eve:value1 xmlns:eve=\"http://jabber.org/protocol/pubsub#event\"/>",
      listener->items[1].payload);
}

TEST_F(PubSubTasksTest, TestPublish) {
  buzz::XmlElement* payload =
      new buzz::XmlElement(buzz::QName(buzz::NS_PUBSUB, "value"));
  std::string expected_iq =
      "<cli:iq type=\"set\" to=\"room@domain.com\" id=\"0\" "
        "xmlns:cli=\"jabber:client\">"
        "<pubsub xmlns=\"http://jabber.org/protocol/pubsub\">"
          "<publish node=\"topic\">"
            "<item id=\"key\">"
              "<value/>"
            "</item>"
          "</publish>"
        "</pubsub>"
      "</cli:iq>";

  std::vector<buzz::XmlElement*> children;
  children.push_back(payload);
  buzz::PubSubPublishTask* task =
      new buzz::PubSubPublishTask(client, pubsubjid, node, itemid, children);
  task->SignalResult.connect(
      listener.get(), &TestPubSubTasksListener::OnPublishResult);
  task->Start();

  ASSERT_EQ(1U, client->sent_stanzas().size());
  EXPECT_EQ(expected_iq, client->sent_stanzas()[0]->Str());

  std::string result_iq =
      "<iq xmlns='jabber:client' id='0' type='result' from='room@domain.com'/>";

  client->HandleStanza(buzz::XmlElement::ForStr(result_iq));

  EXPECT_EQ(1, listener->result_count);
  EXPECT_EQ(0, listener->error_count);
}

TEST_F(PubSubTasksTest, TestPublishError) {
  buzz::XmlElement* payload =
      new buzz::XmlElement(buzz::QName(buzz::NS_PUBSUB, "value"));

  std::vector<buzz::XmlElement*> children;
  children.push_back(payload);
  buzz::PubSubPublishTask* task =
      new buzz::PubSubPublishTask(client, pubsubjid, node, itemid, children);
  task->SignalResult.connect(
      listener.get(), &TestPubSubTasksListener::OnPublishResult);
  task->SignalError.connect(
      listener.get(), &TestPubSubTasksListener::OnError);
  task->Start();

  std::string result_iq =
      "<iq xmlns='jabber:client' id='0' type='error' from='room@domain.com'>"
      "  <error type='auth'>"
      "    <forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>"
      "  </error>"
      "</iq>";

  client->HandleStanza(buzz::XmlElement::ForStr(result_iq));

  EXPECT_EQ(0, listener->result_count);
  EXPECT_EQ(1, listener->error_count);
}

TEST_F(PubSubTasksTest, TestRetract) {
  buzz::PubSubRetractTask* task =
      new buzz::PubSubRetractTask(client, pubsubjid, node, itemid);
  task->SignalResult.connect(
      listener.get(), &TestPubSubTasksListener::OnRetractResult);
  task->SignalError.connect(
      listener.get(), &TestPubSubTasksListener::OnError);
  task->Start();

  std::string expected_iq =
      "<cli:iq type=\"set\" to=\"room@domain.com\" id=\"0\" "
        "xmlns:cli=\"jabber:client\">"
        "<pubsub xmlns=\"http://jabber.org/protocol/pubsub\">"
          "<retract node=\"topic\" notify=\"true\">"
            "<item id=\"key\"/>"
          "</retract>"
        "</pubsub>"
      "</cli:iq>";

  ASSERT_EQ(1U, client->sent_stanzas().size());
  EXPECT_EQ(expected_iq, client->sent_stanzas()[0]->Str());

  std::string result_iq =
      "<iq xmlns='jabber:client' id='0' type='result' from='room@domain.com'/>";

  client->HandleStanza(buzz::XmlElement::ForStr(result_iq));

  EXPECT_EQ(1, listener->result_count);
  EXPECT_EQ(0, listener->error_count);
}


text:
package com.tinkerpop.gremlin.driver.ser;

import com.tinkerpop.gremlin.driver.message.RequestMessage;
import com.tinkerpop.gremlin.driver.message.ResponseMessage;
import com.tinkerpop.gremlin.driver.message.ResponseStatusCode;
import com.tinkerpop.gremlin.structure.Compare;
import com.tinkerpop.gremlin.structure.Edge;
import com.tinkerpop.gremlin.structure.Graph;
import com.tinkerpop.gremlin.structure.Vertex;
import com.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens;
import com.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory;
import com.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * These tests focus on message serialization and not "result" serialization as test specific to results (e.g.
 * vertices, edges, annotated values, etc.) are handled in the IO packages.
 *
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class JsonMessageSerializerV1d0Test {

    public static final JsonMessageSerializerV1d0 SERIALIZER = new JsonMessageSerializerV1d0();
    private static final RequestMessage msg = RequestMessage.build("op")
            .overrideRequestId(UUID.fromString("2D62161B-9544-4F39-AF44-62EC49F9A595")).create();

    @Test
    public void serializeToJsonNullResultReturnsNull() throws Exception {
        final ResponseMessage message = ResponseMessage.build(msg).create();
        final String results = SERIALIZER.serializeResponseAsString(message);
        final JSONObject json = new JSONObject(results);
        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        assertEquals(JSONObject.NULL, json.getJSONObject(SerTokens.TOKEN_RESULT).get(SerTokens.TOKEN_DATA));
    }

    @Test
    public void serializeToJsonIterable() throws Exception {
        final ArrayList<FunObject> funList = new ArrayList<>();
        funList.add(new FunObject("x"));
        funList.add(new FunObject("y"));

        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(funList).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONArray converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONArray(SerTokens.TOKEN_DATA);

        assertEquals(2, converted.length());

        assertEquals("x", converted.get(0));
        assertEquals("y", converted.get(1));
    }

    @Test
    public void serializeToJsonIterator() throws Exception {
        final ArrayList<FunObject> funList = new ArrayList<>();
        funList.add(new FunObject("x"));
        funList.add(new FunObject("y"));

        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(funList.iterator()).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONArray converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONArray(SerTokens.TOKEN_DATA);

        assertEquals(2, converted.length());

        assertEquals("x", converted.get(0));
        assertEquals("y", converted.get(1));
    }

    @Test
    public void serializeToJsonIteratorNullElement() throws Exception {

        ArrayList<FunObject> funList = new ArrayList<>();
        funList.add(new FunObject("x"));
        funList.add(null);
        funList.add(new FunObject("y"));

        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(funList.iterator()).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONArray converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONArray(SerTokens.TOKEN_DATA);

        assertEquals(3, converted.length());

        assertEquals("x", converted.get(0));
        assertEquals(JSONObject.NULL, converted.opt(1));
        assertEquals("y", converted.get(2));
    }

    @Test
    public void serializeToJsonMap() throws Exception {
        final Map<String, Object> map = new HashMap<>();
        final Map<String, String> innerMap = new HashMap<>();
        innerMap.put("a", "b");

        map.put("x", new FunObject("x"));
        map.put("y", "some");
        map.put("z", innerMap);

        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONObject jsonObject = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONObject(SerTokens.TOKEN_DATA);

        assertNotNull(jsonObject);
        assertEquals("some", jsonObject.optString("y"));
        assertEquals("x", jsonObject.optString("x"));

        final JSONObject innerJsonObject = jsonObject.optJSONObject("z");
        assertNotNull(innerJsonObject);
        assertEquals("b", innerJsonObject.optString("a"));
    }

    @Test
    public void serializeHiddenProperties() throws Exception {
        final Graph g = TinkerGraph.open();
        final Vertex v = g.addVertex("abc", 123);
        v.property(Graph.Key.hide("hidden"), "stephen");

        final Iterable iterable = g.V().toList();
        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(iterable).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONArray converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONArray(SerTokens.TOKEN_DATA);

        assertNotNull(converted);
        assertEquals(1, converted.length());

        final JSONObject vertexAsJson = converted.optJSONObject(0);
        assertNotNull(vertexAsJson);

        assertEquals(((Long) v.id()).intValue(), vertexAsJson.get(GraphSONTokens.ID)); // lossy
        assertEquals(GraphSONTokens.VERTEX, vertexAsJson.get(GraphSONTokens.TYPE));

        final JSONObject properties = vertexAsJson.optJSONObject(GraphSONTokens.PROPERTIES);
        assertNotNull(properties);

        assertEquals(123, properties.getJSONArray("abc").getJSONObject(0).getInt(GraphSONTokens.VALUE));
        assertEquals(1, properties.length());

        final JSONObject hiddens = vertexAsJson.optJSONObject(GraphSONTokens.HIDDENS);
        assertNotNull(hiddens);

        assertEquals("stephen", hiddens.getJSONArray("hidden").getJSONObject(0).getString(GraphSONTokens.VALUE));
        assertEquals(1, hiddens.length());
    }

    @Test
    public void serializeEdge() throws Exception {
        final Graph g = TinkerGraph.open();
        final Vertex v1 = g.addVertex();
        final Vertex v2 = g.addVertex();
        final Edge e = v1.addEdge("test", v2);
        e.property("abc", 123);

        final Iterable<Edge> iterable = g.E().toList();
        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(iterable).create());

        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONArray converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONArray(SerTokens.TOKEN_DATA);

        assertNotNull(converted);
        assertEquals(1, converted.length());

        final JSONObject edgeAsJson = converted.optJSONObject(0);
        assertNotNull(edgeAsJson);

        assertEquals(((Long) e.id()).intValue(), edgeAsJson.get(GraphSONTokens.ID));  // lossy
        assertEquals(((Long) v1.id()).intValue(), edgeAsJson.get(GraphSONTokens.OUT));// lossy
        assertEquals(((Long) v2.id()).intValue(), edgeAsJson.get(GraphSONTokens.IN)); // lossy
        assertEquals(e.label(), edgeAsJson.get(GraphSONTokens.LABEL));
        assertEquals(GraphSONTokens.EDGE, edgeAsJson.get(GraphSONTokens.TYPE));

        final JSONObject properties = edgeAsJson.optJSONObject(GraphSONTokens.PROPERTIES);
        assertNotNull(properties);
        assertEquals(123, properties.getInt("abc"));

    }

    @Test
    public void serializeToJsonIteratorWithEmbeddedMap() throws Exception {
        final Graph g = TinkerGraph.open();
        final Vertex v = g.addVertex();
        final Map<String, Object> map = new HashMap<>();
        map.put("x", 500);
        map.put("y", "some");

        final ArrayList<Object> friends = new ArrayList<>();
        friends.add("x");
        friends.add(5);
        friends.add(map);

        v.property("friends", friends);

        final Iterable iterable = g.V().toList();
        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(iterable).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONArray converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONArray(SerTokens.TOKEN_DATA);

        assertNotNull(converted);
        assertEquals(1, converted.length());

        final JSONObject vertexAsJson = converted.optJSONObject(0);
        assertNotNull(vertexAsJson);

        final JSONObject properties = vertexAsJson.optJSONObject(GraphSONTokens.PROPERTIES);
        assertNotNull(properties);

        final JSONArray friendsProperty = properties.optJSONArray("friends");
        assertNotNull(friendsProperty);
        assertEquals(3, friends.size());

        final String object1 = friendsProperty.getJSONObject(0).getJSONArray(GraphSONTokens.VALUE).getString(0);
        assertEquals("x", object1);

        final int object2 = friendsProperty.getJSONObject(0).getJSONArray(GraphSONTokens.VALUE).getInt(1);
        assertEquals(5, object2);

        final JSONObject object3 = friendsProperty.getJSONObject(0).getJSONArray(GraphSONTokens.VALUE).getJSONObject(2);
        assertEquals(500, object3.getInt("x"));
        assertEquals("some", object3.getString("y"));
    }

    @Test
    public void serializeToJsonMapWithElementForKey() throws Exception {
        final TinkerGraph g = TinkerFactory.createClassic();
        final Map<Vertex, Integer> map = new HashMap<>();
        map.put(g.V().<Vertex>has("name", Compare.eq, "marko").next(), 1000);

        final String results = SERIALIZER.serializeResponseAsString(ResponseMessage.build(msg).result(map).create());
        final JSONObject json = new JSONObject(results);

        assertNotNull(json);
        assertEquals(msg.getRequestId().toString(), json.getString(SerTokens.TOKEN_REQUEST));
        final JSONObject converted = json.getJSONObject(SerTokens.TOKEN_RESULT).getJSONObject(SerTokens.TOKEN_DATA);

        assertNotNull(converted);

        // with no embedded types the key (which is a vertex) simply serializes out to an id
        // {"result":{"1":1000},"code":200,"requestId":"2d62161b-9544-4f39-af44-62ec49f9a595","type":0}
        assertEquals(1000, converted.optInt("1"));
    }

    @Test
    public void deserializeRequestNicelyWithNoArgs() throws Exception {
        final UUID request = UUID.fromString("011CFEE9-F640-4844-AC93-034448AC0E80");
        final RequestMessage m = SERIALIZER.deserializeRequest(String.format("{\"requestId\":\"%s\",\"op\":\"eval\"}", request));
        assertEquals(request, m.getRequestId());
        assertEquals("eval", m.getOp());
        assertNotNull(m.getArgs());
        assertEquals(0, m.getArgs().size());
    }

    @Test
    public void deserializeRequestNicelyWithArgs() throws Exception {
        final UUID request = UUID.fromString("011CFEE9-F640-4844-AC93-034448AC0E80");
        final RequestMessage m = SERIALIZER.deserializeRequest(String.format("{\"requestId\":\"%s\",\"op\":\"eval\",\"args\":{\"x\":\"y\"}}", request));
        assertEquals(request, m.getRequestId());
        assertEquals("eval", m.getOp());
        assertNotNull(m.getArgs());
        assertEquals("y", m.getArgs().get("x"));
    }

    @Test(expected = SerializationException.class)
    public void deserializeRequestParseMessage() throws Exception {
        SERIALIZER.deserializeRequest("{\"requestId\":\"%s\",\"op\":\"eval\",\"args\":{\"x\":\"y\"}}");
    }

    @Test
    public void serializeFullResponseMessage() throws Exception {
        final UUID id = UUID.randomUUID();

        final Map<String,Object> metaData = new HashMap<>();
        metaData.put("test", "this");
        metaData.put("one", 1);

        final Map<String,Object> attributes = new HashMap<>();
        attributes.put("test", "that");
        attributes.put("two", 2);

        final ResponseMessage response = ResponseMessage.build(id)
                .responseMetaData(metaData)
                .code(ResponseStatusCode.SUCCESS)
                .result("some-result")
                .statusAttributes(attributes)
                .statusMessage("worked")
                .create();

        final String results = SERIALIZER.serializeResponseAsString(response);
        final ResponseMessage deserialized = SERIALIZER.deserializeResponse(results);

        assertEquals(id, deserialized.getRequestId());
        assertEquals("this", deserialized.getResult().getMeta().get("test"));
        assertEquals(1, deserialized.getResult().getMeta().get("one"));
        assertEquals("some-result", deserialized.getResult().getData());
        assertEquals("that", deserialized.getStatus().getAttributes().get("test"));
        assertEquals(2, deserialized.getStatus().getAttributes().get("two"));
        assertEquals(ResponseStatusCode.SUCCESS.getValue(), deserialized.getStatus().getCode().getValue());
        assertEquals("worked", deserialized.getStatus().getMessage());
    }

    private class FunObject {
        private String val;

        public FunObject(String val) {
            this.val = val;
        }

        public String toString() {
            return this.val;
        }
    }
}


text:
#include <linux/clk-provider.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/clk/ti.h>

#undef pr_fmt
#define pr_fmt(fmt) "%s: " fmt, __func__

/**
 * of_ti_fixed_factor_clk_setup - Setup function for TI fixed factor clock
 * @node: device node for this clock
 *
 * Sets up a simple fixed factor clock based on device tree info.
 */
static void __init of_ti_fixed_factor_clk_setup(struct device_node *node)
{
	struct clk *clk;
	const char *clk_name = node->name;
	const char *parent_name;
	u32 div, mult;
	u32 flags = 0;

	if (of_property_read_u32(node, "ti,clock-div", &div)) {
		pr_err("%s must have a clock-div property\n", node->name);
		return;
	}

	if (of_property_read_u32(node, "ti,clock-mult", &mult)) {
		pr_err("%s must have a clock-mult property\n", node->name);
		return;
	}

	if (of_property_read_bool(node, "ti,set-rate-parent"))
		flags |= CLK_SET_RATE_PARENT;

	parent_name = of_clk_get_parent_name(node, 0);

	clk = clk_register_fixed_factor(NULL, clk_name, parent_name, flags,
					mult, div);

	if (!IS_ERR(clk)) {
		of_clk_add_provider(node, of_clk_src_simple_get, clk);
		of_ti_clk_autoidle_setup(node);
	}
}
CLK_OF_DECLARE(ti_fixed_factor_clk, "ti,fixed-factor-clock",
	       of_ti_fixed_factor_clk_setup);


text:
using DotNetCoreKoans.Engine;
using Xunit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Runtime.InteropServices;

namespace DotNetCoreKoans.Koans;

class AboutPatternMatching : Koan
{
	#region 1: Syntax

	#region 1.1: Test object type
	// Pattern matching can test an object's type
	[Step(1)]
	public void PatternMatchingTestObjectType()
	{
		Hero hero = new Superman();

		var message = GetHeroHelloMessageWithIf(hero);
		Assert.Equal(FILL_ME_IN, message);

		var message2 = GetHeroHelloMessageWithCase(hero);
		Assert.Equal(FILL_ME_IN, message2);
	}

	private string GetHeroHelloMessageWithIf(Hero hero)
	{
		if (hero is Superman)
		{
			return "I'm Superman";
		}
		else if (hero is Batman)
		{
			return "I'm the Dark Knight, you know me as Batman";
		}
		else
		{
			return "Nobody knows me :'(";
		}
	}

	private string GetHeroHelloMessageWithCase(Hero hero)
	{
		switch (hero)
		{
			case Batman batman:
				return "I'm the Dark Knight, you know me as Batman";
			case Superman superman:
				return "I'm Superman";
			default:
				return "Nobody knows me :'(";
		}
	}
	#endregion

	#region 1.2: Cast object
	// Pattern matching can cast object
	[Step(2)]
	public void PatternMatchingCastObject()
	{
		Hero hero = new Batman();

		var gadgets = GetGadgetsWithIf(hero);
		Assert.Equal(FILL_ME_IN, string.Join(",", gadgets));

		var gadgets2 = GetGadgetsWithCase(hero);
		Assert.Equal(FILL_ME_IN, string.Join(",", gadgets2));
	}

	private string[] GetGadgetsWithIf(Hero hero)
	{
		var batman = hero as Batman; // return null if hero is not a batman
		if (batman != null)
		{
			return batman.gadget; // gadget is not in hero class but in batman
		}

		return new string[0];
	}

	private string[] GetGadgetsWithCase(Hero hero)
	{
		switch (hero)
		{
			case Batman batman:
				return batman.gadget; // gadget is not in hero class but in batman

			default:
				return new string[0];
		}
	}
	#endregion

	// Pattern matching case with sugar syntax
	[Step(3)]
	public void PatternMatchingCaseSugarSyntax()
	{
		/// In the two previous examples, each switch case always returns a value.
		/// There is a sugar syntax for that
		/// Let's refactor the second one.
		Hero hero = new Batman();

		var gadgets = hero switch
		{
			Batman batman => batman.gadget,
			_ => new string[0] // default case
		};

		Assert.Equal(FILL_ME_IN, string.Join(",", gadgets));
	}

	#endregion

	#region 2: Special case

	/// Pattern Matching let you make choices based on object/tuple properties.
	/// It's called Special Case.

	// Special case with when
	[Step(4)]
	public void SpecialCaseWithWhenClause()
	{
		Hero hero = new Batman();
		hero.ReplaceBy("Jean-Paul", "Valley");

		var message = hero switch
		{
			Batman batman when batman.lastName == "Wayne" => "Sure, you are Batman", // Special case
			Batman batman => "You look like batman, but I don't think you are",
			_ => "I don't know you" // default case
		};

		Assert.Equal(FILL_ME_IN, message);
	}

	// Special case with destructuring on tuples
	[Step(5)]
	public void SpecialCaseWithDestructuringTuple()
	{
		///
		var hero = ("Batman", "Valley", "Jean-Paul");

		var message = hero switch
		{
			("Batman", "Wayne", _) => "Sure, you are Batman",
			("Batman", _, _) => "You look like Batman, but I don't think you are",
			_ => "I don't know you" // default case
		};

		Assert.Equal(FILL_ME_IN, message);
	}

	// Special case with destructuring on object
	[Step(6)]
	public void SpecialCaseWithDestructuringObject()
	{
		Hero hero = new Batman();

		var message = hero switch
		{
			{ lastName: "Wayne" } => "Sure, you are Batman",
			Batman batman => "You look like Batman, but I don't think you are",
			_ => "I don't know you" // default case
		};

		Assert.Equal(FILL_ME_IN, message);
	}

	#endregion

	#region 3: some warning

	// Evaluation order in pattern matching
	[Step(7)]
	public void PatternMatchingOrder()
	{
		/// Pattern matching is evaluated from top to bottom
		Hero hero = new Batman();

		var message = hero switch
		{
			Batman batman when batman.lastName != "Wayne" => "You look like Batman, but I don't think you are",
			{ lastName: "Wayne" } => "Sure, you are Batman",
			_ => "I don't know you" // default case
		};

		Assert.Equal(FILL_ME_IN, message);
	}

	// Pattern matching with null values
	[Step(8)]
	public void PatternMatchingWithNull()
	{
		// Pattern matching doesn't throw NullReferenceException
		Hero hero = null;

		var message = hero switch
		{
			Batman batman when batman.lastName != "Wayne" => "You look like Batman, but I don't think you are",
			Batman batman => "Sure, you are Batman",
			_ => "I don't know you" // default case
		};

		Assert.Equal(FILL_ME_IN, message);
	}

	#endregion

}

class Hero
{
	public string firstName { get; private set; }
	public string lastName { get; private set; }

	public Hero(string firstName, string lastName)
	{
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public void ReplaceBy(string firstName, string lastName)
	{
		this.firstName = firstName;
		this.lastName = lastName;
	}

}

class Batman : Hero
{
	public string[] gadget = new string[]
	{
		"Batarang", "Batgyro", "Batsuit", "Batmobile", "Belt"
	};

	public Batman() : base("Bruce", "Wayne")
	{ }
}

class Superman : Hero
{
	public Superman() : base("Clark Joseph", "Kent")
	{ }
}


text:
<!DOCTYPE html>

{% include head.html %}

    {% include navigation.html %}
	{% if page.carousel %}
	{% include carousel.html %}
	{% endif %}

       {{ content }}

       {% include footer.html %}
	   {% include scripts.html %}


text:
<!doctype html>

        <meta charset="utf-8">

        <title>Using the command line (bash)</title>

        <meta name="description" content="A framework for easily creating beautiful presentations using HTML">
        <meta name="author" content="Hakim El Hattab">

        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

        <link rel="stylesheet" href="css/reveal.min.css">
        <link rel="stylesheet" href="css/theme/default.css" id="theme">

        <link rel="stylesheet" href="lib/css/zenburn.css">

Using the command line

Disclaimer

Mostly about bash

Windows cmd.exe does some of this (or powershell)

BUT you can use git bash on windows

Command processor

Text (commands) -> Executing programs [ -> Text output ]

 $ ls
 sushi-cat-1.jpg sushi-cat-2.jpg sushi-cat-3.jpg ...

 $ rm angsty-poetry.txt

 $ curl http://www.7digital.com
 <html lang="en-GB" ...

Text!

Text is awesome

You can input it with all ~100 buttons on the keyboard!

You can save it for later

You can READ it after it has been saved

Lots of tools for dealing with it

e.g. diffing, your fave text editor (shoutout to vim <3)

You can generate it easily with a program

Powerful UI for running programs

e.g. an option per letter rather than 26 radio buttons

Some Common unixy programs

Little programs each good at one thing (usually)

mv

rm

cp

curl

find

grep

head

tail

...

OH: "unix: microservices since 1973" #truth
— Pieter Noordhuis (@pnoordhuis) October 22, 2014

Help!

For built-ins:

 $ help

For commands, CONVENTION: --help (or -h)

 $ curl --help
 Usage: curl [options...] <url>
 Options: (H) means HTTP/HTTPS only, (F) means FTP only
      --anyauth       Pick "any" authentication method (H)
  -a, --append        Append to target file when uploading (F/SFTP)
      --basic         Use HTTP Basic Authentication (H)
 ...

 $ curl --help | less

The Manual

More in depth help: man <command>

(May not be installed on git bash)

 $ man curl
 NAME
        curl - transfer a URL

 SYNOPSIS
        curl [options] [URL...]

 DESCRIPTION
        curl  is a tool to transfer data from or to a server...
        RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, TELNET and TFTP)...

Paged

Search with /, n to go to next match, N to go back (vim shortcuts)

Page down (up) or CTRL+D (CTRL+U)

Same keys work for less

More conventions

Short option / long option

  (from ls's help)

  -a, --all    do not ignore entries starting with .

  $ ls -a
  ...
  $ ls --all
  ...

Long options are more readable

Short options are dense, but combinable

  $ ls -lahg

Similar meanings, e.g. -n for "number of" something

 $ tail -n 5 index.html
 ...
 $ head -n 5 index.html

-r / -R for "recursive", -f for force

 $ rm -rf /
 ...

-h for "human readable"

 $ ls -l
 total 88K
 drwxr-xr-x  4 dave users 4096 Sep 29 16:16 css

 $ ls -lh
 total 88K
 drwxr-xr-x  4 dave users 4.0K Sep 29 16:16 css

 $ du -h
 ...

Wait, what?

Colliding abbreviation (-h)

(in these cases --help still works though!)

Other oddballs, e.g. find

 $ find . -iname "*.json"

Often favours power (and experience learning curve!)

 $ find . -name 'foo.cs' '!' -path '.git'

Program predates conventions (or maintainer is anti-social?)

On windows (cmd.exe)

/? instead of -h or --help

Switches are generally in the style /X rather than -x

Powershell

... but it's what you're used to

Bash itself

Good at

Helping you write commands

Executing programs

Home directory - save typing

 $ cd ~

Aliases serve a similar purpose

History

 $ history

Basic wildcards

 $ mv *.jpg pictures/

 $ ls src/**/*.cs

Brace expansion

 $ echo {a,b}{c,d}
 ac ad bc bd

 $ ls
 long-file-name-with-a-msitaek-in-the-middle.txt
 $ mv long-file-name-with-a-{msitaek,mistake}-in-the-middle.txt
 $ ls
 long-file-name-with-a-mistake-in-the-middle.txt

 $ echo {1..10}
 1 2 3 4 5 6 7 8 9 10

 $ cat server-errors-2014-09-2{5..9}.log
 ...

Looping

Syntax is a bit nasty

 $ for i in {1..4}; do touch new-file-$i.txt; done;

 $ touch new-file-1.txt
 $ touch new-file-2.txt
 $ ...

Brace expansion can often achieve similar results depending on the command you're running, e.g.

 $ touch new-file-{1..4}.txt

 $ touch new-file-1.txt new-file-2.txt ...

Using a scripting language can be quicker for more complex stuff

Keyboard shortcuts

A few readline shortcuts:

Tab: auto-complete filenames/directories

Up arrow: Last command

CTRL+W: Delete last word

ALT+B: Jump cursor back a word

CTRL+R: Search through command history (and keep pressing to CTRL+R to cycle through history)

Executing programs

Streams

Simple command

e.g.

 $ ls -lah

Command substitution

 $ whoami
 a-stupidly-long-username-argh-what-a-pain-to-type

 $ sudo chown $(whoami) someone-elses-file.txt

This also works:

 $ sudo chown `whoami` someone-elses-file.txt

Those are backticks, $(..) is prefered.

Piping

 # Search all .cs files (recursively) in src/ for 'ElusiveWidgetFactory'
 $ cat src/**/*.cs | grep ElusiveWidgetFactory

 # Page through 7digital.com HTML
 $ curl www.7digital.com | less

 # Monitor error log file and report lines which match "500"
 $ tail -f /var/log/server/error.log | grep 500

Requires stdin convention to be followed

Rule of Silence - no unnecessary output

Rule of Repair - fail noisily

Redirection

 $ curl "http://api.7digital.com/1.2/release/search?q=..." \
   | xml format > search_results.xml

 echo bin >> .gitignore

 # /dev/null becomes "nul" on windows
 $ curl -vs www.7digital.com >/dev/null

 $ run-the-tests 2>&1 >/dev/null | grep "a-particular-error"

 $ grep "something" < myfile.txt

Final thoughts

We didn't cover "if then else"

Don't try to do too much!

Useful because it's everywhere

Use a real scripting language if it makes sense


text:
require "gemstash"

module Gemstash
  module DB
    # Sequel model for dependencies table.
    class Dependency < Sequel::Model
      def self.insert_by_spec(version_id, spec)
        spec.runtime_dependencies.each do |dep|
          requirements = dep.requirement.requirements
          requirements = requirements.map {|r| "#{r.first} #{r.last}" }
          requirements = requirements.join(", ")
          create(version_id: version_id,
                 rubygem_name: dep.name,
                 requirements: requirements)
        end
      end

      def self.fetch(gems)
        results = db["
          SELECT rubygem.name,
                 version.number, version.platform,
                 dependency.rubygem_name, dependency.requirements
          FROM rubygems rubygem
          JOIN versions version
            ON version.rubygem_id = rubygem.id
          LEFT JOIN dependencies dependency
            ON dependency.version_id = version.id
          WHERE rubygem.name IN ?
            AND version.indexed = ?", gems.to_a, true].to_a
        results.group_by {|r| r[:name] }.each do |gem, rows|
          requirements = rows.group_by {|r| [r[:number], r[:platform]] }

          value = requirements.map do |version, r|
            deps = r.map {|x| [x[:rubygem_name], x[:requirements]] }
            deps = [] if deps.size == 1 && deps.first.first.nil?

            {
              :name => gem,
              :number => version.first,
              :platform => version.last,
              :dependencies => deps
            }
          end

          yield(gem, value)
        end
      end
    end
  end
end