text:
<!DOCTYPE html >

          <title>dsl - io.gearpump.streaming.dsl</title>
          <meta name="description" content="dsl - io.gearpump.streaming.dsl" />
          <meta name="keywords" content="dsl io.gearpump.streaming.dsl" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

io.gearpump.streaming

dsl

        package

        dsl

<input id="mbrsel-input" type="text" accesskey="/" />

            Visibility

Public

All

Type Members

        class

        CollectionDataSource[T] extends DataSource

        class

        KVStream[K, V] extends AnyRef

        class

        LoggerSink[T] extends DataSink

        class

        Stream[T] extends AnyRef

        class

        StreamApp extends AnyRef

Example:

Example:

    val data = "This is a good start, bingo!! bingo!!"
    app.fromCollection(data.lines.toList).
      // word => (word, count)
      flatMap(line => line.split("[\\s]+")).map((_, 1)).
      // (word, count1), (word, count2) => (word, count1 + count2)
      groupBy(kv => kv._1).reduce(sum(_, _))

    val appId = context.submit(app)
    context.close()

Value Members

        object

        Stream

        object

        StreamApp

        package

        example

        package

        op

        package

        partitioner

        package

        plan

Ungrouped


text:
class Main {
    void m(String[] args) {
        for (@Anno <caret>String arg : args) ;
    }
}
@interface Anno {}

redpajama_set_name: RedPajamaGithub


text:
package pingis;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Bean
  public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {
    };
  }

}


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

package admanager.axis.v202211.customfieldservice;

import static com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME;

import com.google.api.ads.admanager.axis.factory.AdManagerServices;
import com.google.api.ads.admanager.axis.utils.v202211.StatementBuilder;
import com.google.api.ads.admanager.axis.v202211.ApiError;
import com.google.api.ads.admanager.axis.v202211.ApiException;
import com.google.api.ads.admanager.axis.v202211.CustomField;
import com.google.api.ads.admanager.axis.v202211.CustomFieldEntityType;
import com.google.api.ads.admanager.axis.v202211.CustomFieldPage;
import com.google.api.ads.admanager.axis.v202211.CustomFieldServiceInterface;
import com.google.api.ads.admanager.lib.client.AdManagerSession;
import com.google.api.ads.common.lib.auth.OfflineCredentials;
import com.google.api.ads.common.lib.auth.OfflineCredentials.Api;
import com.google.api.ads.common.lib.conf.ConfigurationLoadException;
import com.google.api.ads.common.lib.exception.OAuthException;
import com.google.api.ads.common.lib.exception.ValidationException;
import com.google.api.client.auth.oauth2.Credential;
import java.rmi.RemoteException;

/**
 * This example gets all custom fields that can be applied to line items.
 *
 * <p>Credentials and properties in {@code fromFile()} are pulled from the "ads.properties" file.
 * See README for more info.
 */
public class GetCustomFieldsForLineItems {

  /**
   * Runs the example.
   *
   * @param adManagerServices the services factory.
   * @param session the session.
   * @throws ApiException if the API request failed with one or more service errors.
   * @throws RemoteException if the API request failed due to other errors.
   */
  public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
      throws RemoteException {
    CustomFieldServiceInterface customFieldService =
        adManagerServices.get(session, CustomFieldServiceInterface.class);

    // Create a statement to select custom fields.
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("entityType = :entityType")
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
            .withBindVariableValue("entityType", CustomFieldEntityType.LINE_ITEM.toString());

    // Retrieve a small amount of custom fields at a time, paging through
    // until all custom fields have been retrieved.
    int totalResultSetSize = 0;
    do {
      CustomFieldPage page =
          customFieldService.getCustomFieldsByStatement(statementBuilder.toStatement());

      if (page.getResults() != null) {
        // Print out some information for each custom field.
        totalResultSetSize = page.getTotalResultSetSize();
        int i = page.getStartIndex();
        for (CustomField customField : page.getResults()) {
          System.out.printf(
              "%d) Custom field with ID %d and name '%s' was found.%n",
              i++, customField.getId(), customField.getName());
        }
      }

      statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    } while (statementBuilder.getOffset() < totalResultSetSize);

    System.out.printf("Number of results found: %d%n", totalResultSetSize);
  }

  public static void main(String[] args) {
    AdManagerSession session;
    try {
      // Generate a refreshable OAuth2 credential.
      Credential oAuth2Credential =
          new OfflineCredentials.Builder()
              .forApi(Api.AD_MANAGER)
              .fromFile()
              .build()
              .generateCredential();

      // Construct a AdManagerSession.
      session =
          new AdManagerSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
      System.err.printf(
          "Failed to load configuration from the %s file. Exception: %s%n",
          DEFAULT_CONFIGURATION_FILENAME, cle);
      return;
    } catch (ValidationException ve) {
      System.err.printf(
          "Invalid configuration in the %s file. Exception: %s%n",
          DEFAULT_CONFIGURATION_FILENAME, ve);
      return;
    } catch (OAuthException oe) {
      System.err.printf(
          "Failed to create OAuth credentials. Check OAuth settings in the %s file. "
              + "Exception: %s%n",
          DEFAULT_CONFIGURATION_FILENAME, oe);
      return;
    }

    AdManagerServices adManagerServices = new AdManagerServices();

    try {
      runExample(adManagerServices, session);
    } catch (ApiException apiException) {
      // ApiException is the base class for most exceptions thrown by an API request. Instances
      // of this exception have a message and a collection of ApiErrors that indicate the
      // type and underlying cause of the exception. Every exception object in the admanager.axis
      // packages will return a meaningful value from toString
      //
      // ApiException extends RemoteException, so this catch block must appear before the
      // catch block for RemoteException.
      System.err.println("Request failed due to ApiException. Underlying ApiErrors:");
      if (apiException.getErrors() != null) {
        int i = 0;
        for (ApiError apiError : apiException.getErrors()) {
          System.err.printf("  Error %d: %s%n", i++, apiError);
        }
      }
    } catch (RemoteException re) {
      System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
    }
  }
}


text:
'use strict';

var assert = require('chai').assert;
var sinon = require('sinon');
var _ = require('lodash');
var proxyquire = require('proxyquire');

var inquirerStub = {};
var configStub = {
  '@noCallThru': true
};

var ask = proxyquire('../../src/ask', {
  'inquirer': inquirerStub,
  './config': configStub
});

////////

describe('ask', function () {

  beforeEach(function () {
    _.extend(configStub, {
      template: {},
      units: {},
      dependencies: {
        process: ['factory', 'service', 'provider', 'value', 'constant']
      }
    });
  });

  describe('createUnit', function () {

    it('should create unit without dependencies', function () {
      inquirerStub.prompt = function (questions) {
        inquirerStub.prompt = function (questions) {
          return Promise.resolve({ name: '' });
        };
        return Promise.resolve({
          name: 'TestCtrl',
          type: 'controller',
          module: 'test'
        });
      };
      ask.createUnit(function (unit) {
        assert.deepEqual(unit, {
          name: 'TestCtrl',
          type: 'controller',
          module: { name: 'test' },
          deps: []
        });
      });
    });

    it('should create unit with dependencies', function () {
      inquirerStub.prompt = function (questions) {
        inquirerStub.prompt = function (questions) {
          inquirerStub.prompt = function (questions) {
            return Promise.resolve({ name: '' });
          };
          return Promise.resolve({
            name: 'TestFactory',
            type: 'factory'
          });
        };
        return Promise.resolve({
          name: 'TestCtrl',
          type: 'controller',
          module: 'test'
        });
      };
      ask.createUnit(function (unit) {
        assert.deepEqual(unit, {
          name: 'TestCtrl',
          type: 'controller',
          module: { name: 'test' },
          deps: [
            { name: 'TestFactory', type: 'factory' }
          ]
        });
      });

    });

    it('should list processed units from config', function () {
      inquirerStub.prompt = sinon.stub().returns(Promise.resolve());
      configStub.units.process = ['foo', 'bar', 'baz'];
      ask.createUnit(_.noop);
      var questions = inquirerStub.prompt.getCall(0).args[0];
      var question = _.find(questions, { name: 'type' });
      assert.deepEqual(question.choices, ['foo', 'bar', 'baz']);
    });

    it('should list processed dependencies from config', function () {
      inquirerStub.prompt = function (questions) {
        inquirerStub.prompt = sinon.stub().returns(Promise.resolve({}));
        return Promise.resolve({
          name: 'TestCtrl',
          type: 'controller',
          module: 'test'
        });
      };
      configStub.dependencies.process = ['foo', 'bar', 'baz'];
      ask.createUnit(function () {
        var questions = inquirerStub.prompt.getCall(0).args[0];
        var question = _.find(questions, { name: 'type' });
        assert.deepEqual(question.choices, ['foo', 'bar', 'baz']);
      });
    });

    it('should not even ask if config option empty', function () {
      inquirerStub.prompt = function (questions) {
        inquirerStub.prompt = sinon.spy();
        return Promise.resolve({
          name: 'TestCtrl',
          type: 'controller',
          module: 'test'
        });
      };
      configStub.dependencies.process = [];
      ask.createUnit(function (unit) {
        assert.deepEqual(unit.deps, []);
      });
      assert.notOk(inquirerStub.prompt.called);
    });

  });

  describe('pickUnit', function () {

    it('should pick a unit', function () {
      inquirerStub.prompt = function (question) {
        return Promise.resolve({ unit: 1 });
      };
      ask.pickUnit([
        { name: 'TestFactory', type: 'factory', module: { name: 'test' } },
        { name: 'TestService', type: 'service', module: { name: 'test' } },
        { name: 'TestProvider', type: 'provider', module: { name: 'test' } }
      ], function (unit) {
        assert.deepEqual(unit, {
          name: 'TestService', type: 'service', module: { name: 'test' }
        });
      });
    });

  });

  describe('identifyDeps', function () {

    it('should identify deps', function () {
      inquirerStub.prompt = function (question) {
        return Promise.resolve({ '0': 'factory', '1': 'service', '2': 'provider' });
      };
      ask.identifyDeps([
        { name: 'TestFactory' },
        { name: 'TestService' },
        { name: 'TestProvider' }
      ], function (deps) {
        assert.deepEqual(deps, [
          { name: 'TestFactory', type: 'factory' },
          { name: 'TestService', type: 'service' },
          { name: 'TestProvider', type: 'provider' }
        ]);
      });
    });

    it('should list processed dependencies from config', function () {
      inquirerStub.prompt = sinon.stub().returns(Promise.resolve());
      configStub.dependencies.process = ['foo', 'bar', 'baz'];
      ask.identifyDeps([
        { name: 'TestFactory' },
        { name: 'TestService' },
        { name: 'TestProvider' }
      ], _.noop);
      var questions = inquirerStub.prompt.getCall(0).args[0];
      var question = questions[0];
      assert.deepEqual(question.choices, ['foo', 'bar', 'baz']);
    });

    it('should not even ask if config option empty', function () {
      inquirerStub.prompt = sinon.spy();
      configStub.dependencies.process = [];
      ask.identifyDeps([
        { name: 'TestFactory' },
        { name: 'TestService' },
        { name: 'TestProvider' }
      ], function (identified) {
        assert.deepEqual(identified, []);
      });
      assert.notOk(inquirerStub.prompt.called);
    });

  });

});


text:
(function($) {

  $.fn.centerBox = function() {
    return this.each(function() {
      var s = this.style;
      s.left = (($(window).width() - $(this).width()) / 2) + "px";
      s.top = (($(window).height() - $(this).height()) / 2) + "px";
    });
  }

  $.showDialog = function(url, options) {
    options = options || {};
    options.load = options.load || function() {};
    options.cancel = options.cancel || function() {};
    options.validate = options.validate || function() { return true };
    options.submit = options.submit || function() {};

    var overlay = $('

')
      .css("opacity", "0");
    var dialog = $('

');
    if ($.browser.msie) {
      var frame = $('')
        .css("opacity", "0").appendTo(document.body);
      if (parseInt($.browser.version)<7) {
        dialog.css("position", "absolute");
        overlay.css("position", "absolute");
        $("html,body").css({width: "100%", height: "100%"});
      }
    }
    overlay.appendTo(document.body).fadeTo(100, 0.6);
    dialog.appendTo(document.body).centerBox().fadeIn(400);

    $(document).keydown(function(e) {
      if (e.keyCode == 27) dismiss(); // dismiss on escape key
    });
    function dismiss() {
      dialog.fadeOut("fast", function() {
        $("#dialog, #overlay, #overlay-frame").remove();
      });
      $(document).unbind("keydown");
    }
    overlay.click(function() { dismiss(); });

    function showError(name, message) {
      var input = dialog.find(":input[name=" + name + "]");
      input.addClass("error").next("div.error").remove();
      $('

').text(message).insertAfter(input);
    }

    $.get(url, function(html) {
      $(html).appendTo(dialog);
      dialog.centerBox().each(function() {
        options.load(dialog.children()[0]);
        $(":input:first", dialog).each(function() { this.focus() });
        $("button.cancel", dialog).click(function() { // dismiss on cancel
          dismiss();
          options.cancel();
        });
        $("form", dialog).submit(function(e) { // invoke callback on submit
          e.preventDefault();
          dialog.find("div.error").remove().end().find(".error").removeClass("error");
          var data = {};
          $.each($("form :input", dialog).serializeArray(), function(i, field) {
            data[field.name] = field.value;
          });
          $("form :file", dialog).each(function() {
            data[this.name] = this.value; // file inputs need special handling
          });
          options.submit(data, function callback(errors) {
            if ($.isEmptyObject(errors)) {
              dismiss();
            } else {
              for (var name in errors) {
                showError(name, errors[name]);
              }
            }
          });
          return false;
        });
      });
    });
  }

  $.futonDialogs = {
    createDatabase : function() {
      $.showDialog("dialog/_create_database.html", {
        submit: function(data, callback) {
          if (!data.name || data.name.length == 0) {
            callback({name: "Please enter a name."});
            return;
          }
          $.couch.db(data.name).create({
            error: function(status, id, reason) { callback({name: reason}) },
            success: function(resp) {
              location.hash = "#/" + encodeURIComponent(data.name);
              callback();
            }
          });
        }
      });
      return false;
    }

    , deleteDatabase : function(dbName) {
      $.showDialog("dialog/_delete_database.html", {
        submit: function(data, callback) {
          $.couch.db(dbName).drop({
            success: function(resp) {
              callback();
              location.href = "#/";
              if (window !== null) {
                $("#dbs li").filter(function(index) {
                  return $("a", this).text() == dbName;
                }).remove();
                // $.futon.navigation.removeDatabase(dbName);
              }
            }
          });
        }
      });
    }

    , compactAndCleanup : function(dbName) {
      var db = $.couch.db(dbName);
      $.showDialog("dialog/_compact_cleanup.html", {
        submit: function(data, callback) {
          switch (data.action) {
            case "compact_database":
              db.compact({success: function(resp) { callback() }});
              break;
            case "compact_views":
              var groupname = page.viewName.substring(8,
                  page.viewName.indexOf("/_view"));
              db.compactView(groupname, {success: function(resp) { callback() }});
              break;
            case "view_cleanup":
              db.viewCleanup({success: function(resp) { callback() }});
              break;
          }
        }
      });
    }
  }

})(jQuery);

// Also add pretty JSON

(function($) {
  var _escape = function(string) {
    return string.replace(/&/g, "&")
                 .replace(/</g, "<")
                 .replace(/>/g, ">");
  };

  // JSON pretty printing
  $.formatJSON = function (val, options) {
    options = $.extend({
      escapeStrings: true,
      indent: 4,
      linesep: "\n",
      quoteKeys: true
    }, options || {});
    var itemsep = options.linesep.length ? "," + options.linesep : ", ";

    function format(val, depth) {
      var tab = [];
      for (var i = 0; i < options.indent * depth; i++) tab.push("");
      tab = tab.join(" ");

      var type = typeof val;
      switch (type) {
        case "boolean":
        case "number":
        case "string":
          var retval = val;
          if (type == "string" && !options.escapeStrings) {
            retval = indentLines(retval.replace(/\r\n/g, "\n"), tab.substr(options.indent));
          } else {
            if (options.html) {
              retval = escape(JSON.stringify(val));
            } else {
              retval = JSON.stringify(val);
            }
          }
          if (options.html) {
            retval = "" + retval + "";
          }
          return retval;

        case "object": {
          if (val === null) {
            if (options.html) {
              return "null";
            }
            return "null";
          }
          if (val.constructor == Date) {
            return JSON.stringify(val);
          }

          var buf = [];

          if (val.constructor == Array) {
            buf.push("[");
            for (var index = 0; index < val.length; index++) {
              buf.push(index > 0 ? itemsep : options.linesep);
              buf.push(tab, format(val[index], depth + 1));
            }
            if (index >= 0) {
              buf.push(options.linesep, tab.substr(options.indent));
            }
            buf.push("]");
            if (options.html) {
              return "" + buf.join("") + "";
            }

          } else {
            buf.push("{");
            var index = 0;
            for (var key in val) {
              buf.push(index > 0 ? itemsep : options.linesep);
              var keyDisplay = options.quoteKeys ? JSON.stringify(key) : key;
              if (options.html) {
                if (options.quoteKeys) {
                  keyDisplay = keyDisplay.substr(1, keyDisplay.length - 2);
                }
                keyDisplay = "" + _escape(keyDisplay) + "";
                if (options.quoteKeys) {
                  keyDisplay = '"' + keyDisplay + '"';
                }
              }
              buf.push(tab, keyDisplay,
                ": ", format(val[key], depth + 1));
              index++;
            }
            if (index >= 0) {
              buf.push(options.linesep, tab.substr(options.indent));
            }
            buf.push("}");
            if (options.html) {
              return "" + buf.join("") + "";
            }
          }

          return buf.join("");
        }
      }
    }

    function indentLines(text, tab) {
      var lines = text.split("\n");
      for (var i in lines) {
        lines[i] = (i > 0 ? tab : "") + _escape(lines[i]);
      }
      return lines.join("
");
    }

    return format(val, 1);
  };

  // File size pretty printing
  var formatSize = function(size) {
    var jump = 512;
    if (size < jump) return size + " bytes";
    var units = ["KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    var i = 0;
    while (size >= jump && i < units.length) {
      i += 1;
      size /= 1024
    }
    return size.toFixed(1) + ' ' + units[i - 1];
  }
})(jQuery);


text:
/*
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
*/

#include <stdio.h>
#include <stdlib.h>

#define INT sizeof(int)

typedef struct fib {
  int *sequence;
  int length;
} _fib;

int even(int);
_fib fibonacci(int);

int main(void) {
  _fib numbers;
  int i, sum_even;

  numbers = fibonacci(4000000);

  sum_even = 0;
  for (i = 0; i < numbers.length; i++) {
    if (even(numbers.sequence[i]))
      sum_even += numbers.sequence[i];
  }

  printf ("%d", sum_even);

  return 0;
}

int even(int value) {
  return !(value & 1);
}

_fib fibonacci(int limit) {
  _fib numbers;
  int a, b;

  numbers.sequence = NULL;
  numbers.length = 0;
  a = 0;
  b = 1;

  while ((a+b) < limit) {
    numbers.sequence = (int *) realloc (numbers.sequence, ++numbers.length * INT);
    numbers.sequence[numbers.length-1] = a+b;

    a = b;
    b = numbers.sequence[numbers.length-1];
  }

  return numbers;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Meliola capitai anon.

### Remarks
null


text:
ifndef VERBOSE
	# Don't show make output about changing directories
	MAKEFLAGS += --no-print-directory
endif

# Check for ninja and use it if available
NINJA_BUILD := $(shell ninja --version 2>/dev/null)

NPROCS := 1
OS := $(shell uname -s)

ifeq ($(OS),Linux)
	NPROCS := $(shell grep -c ^processor /proc/cpuinfo)
endif
ifeq ($(OS),Darwin) #Mac OS
	NPROCS := $(shell sysctl -n hw.ncpu || echo 1)
endif

ifdef NINJA_BUILD
	CMAKE_GENERATOR ?= "Ninja"
	MAKE = ninja
	MAKE_ARGS =
else
	CMAKE_GENERATOR ?= "Unix Makefiles"
	MAKE = make
	MAKE_ARGS = -j$(NPROCS)
endif

# Get additional arguments after target argument. (e.g. make release install)
ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
# and turn them into do-nothing targets
$(eval $(ARGS):;@:)

# Default is "Debug", also possible is "Release"
BUILD_TYPE ?= "Debug"

# Default is no DROPDEBUG
DROP_DEBUG ?= 0

# To enable MAVLink passthrough plugin build
ENABLE_MAVLINK_PASSTHROUGH ?= 0

CURRENT_DIR := $(shell pwd)
ROOT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
CURL_BUILD_DIR := $(ROOT_DIR)/core/third_party/curl-android-ios

# Set default cmake here but replace with special version for Android build.
CMAKE_BIN = cmake

INSTALL_PREFIX ?= /usr/local
BUILD_BACKEND ?= NO

# Function to create build_* directory and call make there.
define cmake-build
+@$(eval BUILD_DIR = build/$@)

+@if [ ! -e $(BUILD_DIR)/CMakeCache.txt ]; then \
	mkdir -p $(BUILD_DIR) \
	&& (cd $(BUILD_DIR) \
        && $(CMAKE_BIN) $(ROOT_DIR) $(1) \
        -DEXTERNAL_DIR:STRING=$(EXTERNAL_DIR) \
        -DCMAKE_BUILD_TYPE=$(BUILD_TYPE) \
        -DCMAKE_INSTALL_PREFIX=$(INSTALL_PREFIX) \
		-DCMAKE_BUILD_BACKEND=$(BUILD_BACKEND) \
		-DDROP_DEBUG=$(DROP_DEBUG) \
		-DENABLE_MAVLINK_PASSTHROUGH=$(ENABLE_MAVLINK_PASSTHROUGH) \
        -G$(CMAKE_GENERATOR)) \
	|| (rm -rf $(BUILD_DIR)) \
fi

+@(echo "Build dir: $(BUILD_DIR)" \
	&& (cd $(BUILD_DIR) && $(MAKE) $(MAKE_ARGS) $(ARGS)) \
  )
endef

all: default

default:
	$(call cmake-build)

ios: ios_curl default
	$(call cmake-build, \
		-DCMAKE_TOOLCHAIN_FILE=iOS.cmake \
		-DIOS_PLATFORM:STRING=OS)

ios_simulator: ios_curl default
	$(call cmake-build, \
		-DCMAKE_TOOLCHAIN_FILE=iOS.cmake \
		-DIOS_PLATFORM:STRING=SIMULATOR)

android_x86: android_curl default
	$(call cmake-build, \
		-DCMAKE_TOOLCHAIN_FILE=$(ANDROID_TOOLCHAIN_CMAKE) \
		-DANDROID_STL:STRING=c++_static \
		-DANDROID_ABI=x86)

android_x86_64: android_curl default
	$(call cmake-build, \
		-DCMAKE_TOOLCHAIN_FILE=$(ANDROID_TOOLCHAIN_CMAKE) \
		-DANDROID_STL:STRING=c++_static \
		-DANDROID_ABI=x86_64)

android_armeabi-v7a: android_curl default
	$(call cmake-build, \
		-DCMAKE_TOOLCHAIN_FILE=$(ANDROID_TOOLCHAIN_CMAKE) \
		-DANDROID_STL:STRING=c++_static \
		-DANDROID_ABI=armeabi-v7a \
		-DANDROID_PLATFORM=android-16)

android_arm64-v8a: android_curl default
	$(call cmake-build, \
		-DCMAKE_TOOLCHAIN_FILE=$(ANDROID_TOOLCHAIN_CMAKE) \
		-DANDROID_STL:STRING=c++_static \
		-DANDROID_ABI=arm64-v8a)

android_curl: android_env_check
	+@if [ ! -e $(CURL_BUILD_DIR)/prebuilt-with-ssl/android ]; then \
		$(CURL_BUILD_DIR)/curl-compile-scripts/build_Android.sh; \
	fi

ios_curl:
	+@if [ ! -e $(CURL_BUILD_DIR)/prebuilt-with-ssl/ios ]; then \
		$(CURL_BUILD_DIR)/curl-compile-scripts/build_iOS.sh; \
	fi

android: \
    android_x86 \
    android_x86_64 \
    android_armeabi-v7a \
    android_arm64-v8a

fix_style:
	@$(ROOT_DIR)/fix_style.sh $(ROOT_DIR)
ifdef EXTERNAL_DIR
	@$(ROOT_DIR)/fix_style.sh $(EXTERNAL_DIR)
endif

run_all_tests: default
	${MAKE} -C build/default check

run_unit_tests: default
	build/default/unit_tests_runner

run_unit_tests_offline: default
	build/default/unit_tests_runner --gtest_filter="-CurlTest.*"

run_integration_tests: default
	build/default/integration_tests/integration_tests_runner

distclean:
	@rm -rf build/
	@rm -rf logs/

clean:
	@if [ -d build ]; then find build -mindepth 2 ! -regex 'build/[a-zA-Z_]*/third_party.*' -delete; fi

android_env_check:
ifndef ANDROID_TOOLCHAIN_CMAKE
	$(error ANDROID_TOOLCHAIN_CMAKE is undefined, please point the \
	    environment variable to build/cmake/android.toolchain.cmake from android-ndk.)
endif
ifndef NDK_ROOT
	$(error NDK_ROOT is undefined, please point the environment variable to android-ndk root.)
endif
ifndef ANDROID_CMAKE_BIN
	$(error ANDROID_CMAKE_BIN is undefined, please point the \
	    environment variable to cmake/3.6.3155560/bin/cmake from android-sdk.)
else
	@# We need cmake from the Android SDK (currently at 3.6 because 3.7 fails the test).
	$(eval CMAKE_BIN = $(ANDROID_CMAKE_BIN))
endif

.PHONY:
	clean fix_style run_all_tests run_unit_tests run_integration_tests android_env_check


text:
package gnu.xml.validation.xmlschema;

import org.w3c.dom.TypeInfo;
import gnu.xml.validation.datatype.SimpleType;

/**
 * Abstract superclass providing simple type derivation.
 *
 * @author Chris Burdess
 */
abstract class XMLSchemaTypeInfo
  implements TypeInfo
{

  protected boolean simpleTypeIsDerivedFrom(SimpleType simpleType,
                                            String typeNamespace,
                                            String typeName,
                                            int derivationMethod)
  {
    switch (derivationMethod)
      {
      case TypeInfo.DERIVATION_RESTRICTION:
        SimpleType baseType = simpleType.baseType;
        while (baseType != null)
          {
            if (baseType.name.getNamespaceURI().equals(typeNamespace) &&
                baseType.name.getLocalPart().equals(typeName))
              {
                return true;
              }
            baseType = baseType.baseType;
          }
        break;
        // TODO other methods
      }
    return false;
  }

}


text:
define( function( require ) {
  'use strict';

  var
    Property = require( 'AXON/Property' ),
    PropertySet = require( 'AXON/PropertySet' ),
    inherit = require( 'PHET_CORE/inherit' ),
    CharacterModel = require( 'model/CharacterModel' );

  function GameModel() {
    var gameModel = this;

    PropertySet.call( this, {
      started: false,
      running: false,
      time: 0
    } );

    this.player = new CharacterModel( this );
  }

  return inherit( PropertySet, GameModel, {
    step: function( dt ) {
      this.time = this.time + dt;
    }
  } );
} );


text:
class Solution {
public:
    char nextGreatestLetter(vector<char>& letters, char target) {
        int idx = 0;
        for (int i = 0; i < letters.size(); i++) {
            if (letters[i] > target) {
                idx = i;
                break;
            }
        }
        return letters[idx];
    }
};


text:
/*

         ###
#  #  #########     _______ _     _  ______ _     _
##  ######## @ ##   |______ |     | |  ____ |     |
##################  |       |_____| |_____| |_____|
##  #############      f  r  a  m  e  w  o  r  k
#  #  #########
         ###

(c) 2015 - 2018 FUGU framework project

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.

*/

using Microsoft.Extensions.DependencyInjection;
using System;

namespace Fugu.Localization
{
    public class LocalizationBuilder
    {
        public readonly IServiceCollection ServiceCollection;

        public LocalizationBuilder(IServiceCollection serviceCollection)
        {
            Contract.NotNull(serviceCollection, nameof(serviceCollection));

            ServiceCollection = serviceCollection;
        }

        public LocalizationBuilder AddLocalizationStore<TLocalizationStore>() where TLocalizationStore : class, ILocalizationStore
        {
            ServiceCollection.AddSingleton<ILocalizationStore, TLocalizationStore>();

            return this;
        }

        public LocalizationBuilder AddMissingTranslationResolver<TMissingTranslationResolver>() where TMissingTranslationResolver : class, IMissingTranslationResolver
        {
            ServiceCollection.AddSingleton<IMissingTranslationResolver, TMissingTranslationResolver>();

            return this;
        }

        public LocalizationBuilder AddDefaultMissingTranslationResolver()
        {
            AddMissingTranslationResolver<DefaultMissingTranslationResolver>();

            return this;
        }

        public LocalizationBuilder AddFileSystemLocalizationStore(Action<FileSystemLocalizationStoreOptions> configure = null)
        {
            if (configure != null)
            {
                ServiceCollection.Configure(configure);
            }

            AddLocalizationStore<FileSystemLocalizationStore>();

            return this;
        }
    }
}


text:
<!DOCTYPE html><html><head><meta charset="utf-8" />
<meta http-equiv="refresh" content="0;url=/place/norway/spending/" />
</head></html>


text:
<?php
	$servername = "localhost";
	$username = "root";
	$password = "";
	$dbname = "test";

	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);
	// Check connection
	if ($conn->connect_error) {
	    die("Connection failed: " . $conn->connect_error);
	}

	if ($_SERVER["REQUEST_METHOD"] == "POST") {
		header('Access-Control-Allow-Origin: *');
		return $_POST;
		$action = $_POST['ACTION'];
		switch ($action) {
			case 'save_order':
				saveOrder($_POST);
				break;

			default:
				break;
		}
	}

function saveOrder($POST_PARAMS)
{
	$sql = "INSERT INTO pizza_orders (id, cust_name, cust_tel, cust_email, pizza_size, pizza_topping, delivery_time, delivery_instructions)
	VALUES ('John', 'Doe', 'john@example.com')";

	if ($conn->query($sql) === TRUE) {
	    echo "New record created successfully";
	} else {
	    echo "Error: " . $sql . "<br>" . $conn->error;
	}

	$conn->close();
}


text:
.sap-desktop .sapUILinkActionSheetLink:focus {
	outline-color: @sapUiInvertedFocus;
}

.sap-desktop[data-sap-ui-browser^="ie"]
    .sapUILinkActionSheetLink:focus:before {
        border-color: @sapUiInvertedFocus;
    }

.sapUILinkActionSheet > {
	.sapUILinkActionSheetLink,
	.sapUILinkActionSheetLink:visited,
	.sapUILinkActionSheetLink:active {
		border-top: 0.0625rem solid fade(@sapUiLightestBorder, 20%);
		text-shadow: 0 -0.0625rem 0 fade(@sapUiDarkShadowTint, 60%);
        font-size: @sapMFontMediumSize;
	}
}

.sap-desktop .sapUILinkActionSheetLink:hover {
	background-color: @sapUiBtnFooterBGStandardHover;
}


text:
'use strict';
var assert = require('assert');
var FieldOverrider = require('./utils/FieldOverrider');
var TimeUnit = require('../TimeUnit');

function ProcessTimerInterceptor(timeServer) {
  this.timeServer = timeServer;
}

ProcessTimerInterceptor.prototype.intercept = function() {
  this.uptimeOverrider = new FieldOverrider(
    process,
    'uptime',
    this.uptime.bind(this)
  );
  this.hrtimeOverrider = new FieldOverrider(
    process,
    'hrtime',
    this.hrtime.bind(this)
  );
};

ProcessTimerInterceptor.prototype.release = function() {
  var currentProcessTime = process.hrtime();
  this.uptimeOverrider.restore();
  this.hrtimeOverrider.restore();
  return currentProcessTime;
};

ProcessTimerInterceptor.prototype.uptime = function() {
  return this.timeServer.currentTime.toSeconds();
};

function toHrtimeFormat(time) {
  return [
    Math.floor(time.toSeconds()),
    time.toNanoseconds() %
      (TimeUnit.seconds.coefficient / TimeUnit.nanoseconds.coefficient)
  ];
}

ProcessTimerInterceptor.prototype.hrtime = function(previousValue) {
  if (previousValue !== undefined) {
    assert(previousValue.length === 2);
    var previousTime = TimeUnit.seconds(previousValue[0]).extended(
      TimeUnit.nanoseconds(previousValue[1])
    );
    return toHrtimeFormat(this.timeServer.currentTime.shortened(previousTime));
  }

  return toHrtimeFormat(this.timeServer.currentTime);
};

module.exports = ProcessTimerInterceptor;


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Gamma Functions</title>
<link rel="stylesheet" href="../math.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../index.html" title="Math Toolkit 1.9.0">
<link rel="up" href="../special.html" title="Chapter 6. Special Functions">
<link rel="prev" href="number_series/primes.html" title="Prime Numbers">
<link rel="next" href="sf_gamma/tgamma.html" title="Gamma">

Home
Libraries
People
FAQ
More

Gamma Functions

Gamma

Log Gamma

Digamma

Ratios of Gamma Functions

Incomplete Gamma Functions

Incomplete Gamma Function
      Inverses

Derivative of
      the Incomplete Gamma Function

Copyright © 2006-2010, 2012-2014 Nikhar Agrawal,
      Anton Bikineev, Paul A. Bristow, Marco Guazzone, Christopher Kormanyos, Hubert
      Holin, Bruno Lalande, John Maddock, Johan Råde, Gautam Sewani, Benjamin Sobotta,
      Thijs van den Berg, Daryle Walker and Xiaogang Zhang

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<title>Barcode Scanner Test</title>

BarcodeScanner.js Tester

Tolerances have been increased, mash on your keyboard!

LOGGER
------


text:
chef_gem 'chef-rewind'
require 'chef/rewind'

case node['platform_family']
when 'debian', 'rhel', 'fedora', 'freebsd'
  node.set['java']['install_flavor'] = 'openjdk'
  # for some reason unwinding packages doesn't work so instead we change action
  node['java']['openjdk_packages'].each do |p|
    begin
      resources("package[#{p}]").action node['unjava']['package_action']
    rescue
      Chef::Log.warn "Unable to change action on package #{p}."
    end
  end
  node['unjava']['resources'].each do |r|
    begin
      unwind r
    rescue
      Chef::Log.warn "Unable to unwind resource #{r} on #{node['platform']}."
    end
  end
else
  fail "Preventing Java installation in #{node['platform_family']} not supported so readding not necessary."
end


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

namespace Azure.ResourceManager.Logic
{
    public partial class IntegrationAccountAgreementData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("location");
            writer.WriteStringValue(Location);
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(Metadata))
            {
                writer.WritePropertyName("metadata");
#if NET6_0_OR_GREATER
				writer.WriteRawValue(Metadata);
#else
                JsonSerializer.Serialize(writer, JsonDocument.Parse(Metadata.ToString()).RootElement);
#endif
            }
            writer.WritePropertyName("agreementType");
            writer.WriteStringValue(AgreementType.ToSerialString());
            writer.WritePropertyName("hostPartner");
            writer.WriteStringValue(HostPartner);
            writer.WritePropertyName("guestPartner");
            writer.WriteStringValue(GuestPartner);
            writer.WritePropertyName("hostIdentity");
            writer.WriteObjectValue(HostIdentity);
            writer.WritePropertyName("guestIdentity");
            writer.WriteObjectValue(GuestIdentity);
            writer.WritePropertyName("content");
            writer.WriteObjectValue(Content);
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static IntegrationAccountAgreementData DeserializeIntegrationAccountAgreementData(JsonElement element)
        {
            Optional<IDictionary<string, string>> tags = default;
            AzureLocation location = default;
            ResourceIdentifier id = default;
            string name = default;
            ResourceType type = default;
            Optional<SystemData> systemData = default;
            Optional<DateTimeOffset> createdTime = default;
            Optional<DateTimeOffset> changedTime = default;
            Optional<BinaryData> metadata = default;
            IntegrationAccountAgreementType agreementType = default;
            string hostPartner = default;
            string guestPartner = default;
            IntegrationAccountBusinessIdentity hostIdentity = default;
            IntegrationAccountBusinessIdentity guestIdentity = default;
            IntegrationAccountAgreementContent content = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    systemData = JsonSerializer.Deserialize<SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("createdTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            createdTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("changedTime"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            changedTime = property0.Value.GetDateTimeOffset("O");
                            continue;
                        }
                        if (property0.NameEquals("metadata"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            metadata = BinaryData.FromString(property0.Value.GetRawText());
                            continue;
                        }
                        if (property0.NameEquals("agreementType"))
                        {
                            agreementType = property0.Value.GetString().ToIntegrationAccountAgreementType();
                            continue;
                        }
                        if (property0.NameEquals("hostPartner"))
                        {
                            hostPartner = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("guestPartner"))
                        {
                            guestPartner = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("hostIdentity"))
                        {
                            hostIdentity = IntegrationAccountBusinessIdentity.DeserializeIntegrationAccountBusinessIdentity(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("guestIdentity"))
                        {
                            guestIdentity = IntegrationAccountBusinessIdentity.DeserializeIntegrationAccountBusinessIdentity(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("content"))
                        {
                            content = IntegrationAccountAgreementContent.DeserializeIntegrationAccountAgreementContent(property0.Value);
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new IntegrationAccountAgreementData(id, name, type, systemData.Value, Optional.ToDictionary(tags), location, Optional.ToNullable(createdTime), Optional.ToNullable(changedTime), metadata.Value, agreementType, hostPartner, guestPartner, hostIdentity, guestIdentity, content);
        }
    }
}


text:
package org.teavm.flavour.templates;

import org.teavm.jso.dom.xml.Node;

class RootSlot extends Slot {
    Node domNode;

    RootSlot(Node domNode) {
        this.domNode = domNode;
    }
}


text:
"""
HW1

Analyzing Chipotle Order Data for DAT5 @GA-DC

Author: Nathan Danielsen
Email: nathanjdanielsen@gmail.com

"""
import csv
from collections import defaultdict
import string

class BurritoFoo(object):
	"""
	Made to order class to analyze mexico food, costs and ingredients.

	Data Header
	['order_id', 'quantity', 'item_name', 'choice_description', 'item_price']
	"""
	def __init__(self, file):
		self._file = open(file, 'rU') # is there a better way to do this?

		self.data = [line for line in csv.reader(self._file, delimiter='\t')]

		self.header = self.data[0]

		self.orders = self.data[1:]

		self.numtransactions = max([int(row[0]) for row in self.orders])

		self.totalcost =  round(sum([float(row[4][1:].strip(' ')) for row in self.orders]), 2)

	@staticmethod
	def description_cleaner(order):
		order =  order[3]

		if order == "NULL":
			return []
		else:
			order = order.split(',')
			cleaned = [item.strip('[] ').lower() for item in order]
			return cleaned

	def item_filter(self, item):

		filtered_orders = []

		item = item.lower()

		for row in self.orders: # looks at all orders
			item_name = row[2]
			item_name = item_name.lower()
			item_name = item_name.split()

			if item in item_name:
				filtered_orders.append(row)

		return filtered_orders

	def toppings(self, item):
		"""
		Takes a single word 'item' noun

		Returns the number of times the noun has shown up in order history, numbers of toppings and quantit of orders

		"""
		item_count, toppings_count, quantity = 0, 0, 0

		filtered_orders = self.item_filter(item)

		item_count = len(filtered_orders)

		for row in filtered_orders:
			quantity += int(row[1])
			toppings_count += len(self.description_cleaner(row))

		return item_count, toppings_count, quantity

	def part1(self):

		'''
		PART 1: read in the data, parse it, and store it in a list of lists called 'data'
		Hint: this is a tsv file, and csv.reader() needs to be told how to handle it
		'''
		return self.datadump

	def part2(self):
		'''
		PART 2: separate the header and data into two different lists
		'''
		return self.header, self.data

	def part3(self):

		'''
		PART 3: calculate the average price of an order
		Hint: examine the data to see if the 'quantity' column is relevant to this calculation
		Hint: work smarter, not harder! (this can be done in a few lines of code)
		'''
		return self.totalcost / self.numtransactions

	def part4(self, items):
		'''
		PART 4: create a list (or set) of all unique sodas and soft drinks that they sell
		Note: just look for 'Canned Soda' and 'Canned Soft Drink', and ignore other drinks like 'Izze'
		'''
		unique_elems = set()
		for order in self.orders: # going through all the order data
			for item in items:
				if item == order[2]:
					description = self.description_cleaner(order)
					unique_elems.update(description)

		unique = list(unique_elems)
		return unique

	def part5(self, item):
		'''
		PART 5: calculate the average number of toppings per burrito
		Note: let's ignore the 'quantity' column to simplify this task
		Hint: think carefully about the easiest way to count the number of toppings
		Hint: 'hello there'.count('e')
		'''
		item_count, toppings_count, quantity = self.toppings(item)

		return float(toppings_count) / item_count

	def part6(self, item ):
		'''
		PART 6: create a dictionary in which the keys represent chip orders and
		  the values represent the total number of orders
		Expected output: {'Chips and Roasted Chili-Corn Salsa': 18, ... }
		Note: please take the 'quantity' column into account!
		Advanced: learn how to use 'defaultdict' to simplify your code
		'''
		item_dict = defaultdict(int)

		# for k in s:
		# 	item_dict[k] += 1
		item = item.lower()

		for row in self.orders: # looks at all orders
			item_name = row[2]
			item_name = item_name.lower()
			item_name = item_name.split()
			#print row
			if item in item_name:
				item_dict[row[2]] += int(row[1])

		return item_dict

	def extraFatScore(self, orders):
		"""
		Counts the extra fatty toppings in a set of orders and returns a score of total toppings
		"""
		unhealthy = ['cheese', 'guacamole', 'sour cream']

		total_score = 0

		if len(orders) == 5 and type(orders[3]) == str: ### for evaluating a single order and confirming 3rd element is string, not another order
			order = orders
			fatty_sides = [side for side in unhealthy if side in self.description_cleaner(order)]
			total_score += len(fatty_sides)

		else :
			for order in orders:
				score = len([side for side in unhealthy if side in self.description_cleaner(order)])
				total_score += score

		return total_score

	def bonus(self, query):
		"""
		Quesiton: Are vegetarians and chicken eaters less likely to get sour cream and fatty toppings than beef and other meat eaters?

		Funciton takes in a single string or list of strings for proteins in an order, and returns the average number of the fatty toppings [1-3]
		"""

		# query = ['Steak', 'Chicken', 'Veggie', 'Barbacoa', 'Carnitas']

		def average_fattyscore(protein):

				try:
					filtered_orders = self.item_filter(protein)
					fatty_score = reduce(lambda x,y : x + y, map(self.extraFatScore, filtered_orders))
					averaged_score = float(fatty_score) / len(filtered_orders)

					return protein, round(averaged_score, 2)

				except TypeError:

					return protein, None

		if type(query) == list:

			return map(average_fattyscore, query)

		else:

			return	average_fattyscore(query)

	def answers(self):

		print "Answers to HW 1 for DAT5"
		print "by Nathan Danielsen"
		print '\n'

		print "Parts 1 and 2 are too verbose to print here \n"

		print "PART3 : Average price per order is $%s \n" % self.part3()

		print "PART4 : These are the sodas served: %s \n" % self.part4(["Canned Soda", "Canned Soft Drink"])

		print "PART5 : Average toppings per burrito is %s \n" % self.part5("Burrito")

		print "PART6 : Chips Orders and Quantity of Order Type"
		for key, value in self.part6("Chips").items():
			print '\t', key,":", value

		print '\n'

		print "BONUS : My self-defined question was: \n"
		print "Which types of proteins(Steak, Chicken, etc) have more fatty toppings defined as guacamole, sour cream and cheese?\n"
		print "Veggie as the 'main' topping was my control. \n"

		results = self.bonus(['Steak', 'Chicken', 'Carnitas', 'Veggie', 'Barbacoa'])
		print "The results are: \n"
		for protein, average in results:
			print '\t', protein, "orders have", average, "average fatty toppings"
		print '\n'

		print "My conclusion is that people who order steak and carnitas dishes indulge a little more on fatty toppings. Chicken eaters are less likely to order fatty toppings and are probably watching their waistlines. \n"

		print "Bene note: Too lazy to do a true statistical analysis with only built in python tools."

		print "My conclusion is that people who order steak and carnitas dishes indulge a little more on fatty toppings. Chicken eaters are less likely to order fatty toppings and are probably watching their waistlines. I'm too lazy at the moment to do a more indepth statistical analysis"

if __name__ == "__main__":

	burrito = BurritoFoo('orders.tsv')

	print burrito.answers()


text:
package telemetry

import (
	"github.com/prometheus/client_golang/prometheus"

	"go.ligato.io/vpp-agent/v3/pkg/version"
)

var (
	currentVersion = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Namespace: "ligato",
		Subsystem: "build",
		Name:      "info",
		Help:      "Which version is running. 1 for 'agent_version' label with current version.",
	},
		[]string{"version", "revision", "build_date", "built_by"},
	)
	processMetrics = prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{
		Namespace: "ligato",
	})
)

func init() {
	prometheus.MustRegister(currentVersion)
	prometheus.MustRegister(processMetrics)

	ver, rev, date := version.Data()
	currentVersion.WithLabelValues(ver, rev, date, version.BuiltBy()).Set(1)
}


text:
function oldWay() {

const fetch = require('node-fetch');
const data = { animal: 'dog', action: 'fetch' };
const options = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
        },
    body: JSON.stringify(data)
    };
function handleJson(data) {
    console.log(data.origin, data.json);
    }
fetch('https://httpbin.org/post', options)
    .then(response => response.json())
    .then(handleJson)
    .catch(console.log);

}

////////////////////////////////////////////////////////////////////////////////////////////////////
function newWay() {

const fetchJson = require('./node-fetch-json.js');
const data = { animal: 'dog', action: 'fetch' };
function handleJson(data) {
    console.log(data.origin, data.json);
    }
fetchJson('https://httpbin.org/post', { method: 'POST', body: data })
    .then(handleJson)
    .catch(console.log);

}

////////////////////////////////////////////////////////////////////////////////////////////////////
oldWay();
newWay();


text:
namespace boost { namespace mpl {

template< typename Tag > struct insert_range_impl;
template< typename Sequence, typename Pos, typename Range > struct insert_range;

}}

#endif // BOOST_MPL_INSERT_RANGE_FWD_HPP_INCLUDED


text:
Runs at https://zifb.in

This project now uses Docker and requires Python 3 (it's been tested with 3.8).

The CLI will remain py2 compat, but will not be tested after January 1st, 2020.


text:
@implementation Photographer

@dynamic name;
@dynamic photos;

@end

@implementation Photographer (CoreDataGeneratedAccessors)

- (void)addPhotosObject:(Photo *)value {

}

- (void)removePhotosObject:(Photo *)value {

}

- (void)addPhotos:(NSSet *)values {

}

- (void)removePhotos:(NSSet *)values {

}

@end


text:
function giveTruckingMoney(wage)
	exports.global:giveMoney(source, wage)
end
addEvent("giveTruckingMoney", true)
addEventHandler("giveTruckingMoney", getRootElement(), giveTruckingMoney)

function respawnTruck(vehicle)
	removePedFromVehicle(source, vehicle)
	respawnVehicle(vehicle)
	setElementData(vehicle, "locked", 0, false)
	setVehicleLocked(vehicle, false)
end
addEvent("respawnTruck", true)
addEventHandler("respawnTruck", getRootElement(), respawnTruck)


text:
<?php

namespace Github\Api\Issue;

use Github\Api\AbstractApi;
use Github\Exception\MissingArgumentException;

/**
 * @link   http://developer.github.com/v3/issues/comments/
 * @author Joseph Bielawski <stloyd@gmail.com>
 */
class Comments extends AbstractApi
{
    public function configure($bodyType = null)
    {
        switch ($bodyType) {
            case 'raw':
                $header = sprintf('Accept: application/vnd.github.%s.raw+json', $this->client->getOption('api_version'));
                break;

            case 'text':
                $header = sprintf('Accept: application/vnd.github.%s.text+json', $this->client->getOption('api_version'));
                break;

            case 'html':
                $header = sprintf('Accept: application/vnd.github.%s.html+json', $this->client->getOption('api_version'));
                break;

            default:
                $header = sprintf('Accept: application/vnd.github.%s.full+json', $this->client->getOption('api_version'));
        }

        $this->client->setHeaders(array($header));
    }

    public function all($username, $repository, $issue, $page = 1)
    {
        return $this->get('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/issues/'.rawurlencode($issue).'/comments', array(
            'page' => $page
        ));
    }

    public function show($username, $repository, $comment)
    {
        return $this->get('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/issues/comments/'.rawurlencode($comment));
    }

    public function create($username, $repository, $issue, array $params)
    {
        if (!isset($params['body'])) {
            throw new MissingArgumentException('body');
        }

        return $this->post('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/issues/'.rawurlencode($issue).'/comments', $params);
    }

    public function update($username, $repository, $comment, array $params)
    {
        if (!isset($params['body'])) {
            throw new MissingArgumentException('body');
        }

        return $this->patch('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/issues/comments/'.rawurlencode($comment), $params);
    }

    public function remove($username, $repository, $comment)
    {
        return $this->delete('repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/issues/comments/'.rawurlencode($comment));
    }
}


text:
<?xml version="1.0"?>
<!--
  ~ Copyright 2015 Geeoz Software
  ~
  ~ 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.
  -->

<ruleset name="PMD Rules"
         xmlns="http://pmd.sf.net/ruleset/1.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
         xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
    <description>
        Specifies the PMD rules to be used (and excluded) in Play projects.
    </description>

    <rule ref="rulesets/java/basic.xml"/>
    <rule ref="rulesets/java/braces.xml"/>
    <rule ref="rulesets/java/design.xml"/>
    <rule ref="rulesets/java/imports.xml"/>
    <rule ref="rulesets/java/strings.xml"/>

</ruleset>


text:
package hudson.cli;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import hudson.model.UnprotectedRootAction;
import jenkins.model.Jenkins;

import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import hudson.Extension;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.util.FullDuplexHttpService;
import org.kohsuke.stapler.HttpResponses;

/**
 * Shows usage of CLI and commands.
 *
 * @author ogondza
 */
@Extension @Symbol("cli")
@Restricted(NoExternalUse.class)
public class CLIAction implements UnprotectedRootAction, StaplerProxy {

    private static final Logger LOGGER = Logger.getLogger(CLIAction.class.getName());

    private transient final Map<UUID, FullDuplexHttpService> duplexServices = new HashMap<>();

    public String getIconFileName() {
        return null;
    }

    public String getDisplayName() {
        return "Jenkins CLI";
    }

    public String getUrlName() {
        return "cli";
    }

    public void doCommand(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
        final Jenkins jenkins = Jenkins.getActiveInstance();
        jenkins.checkPermission(Jenkins.READ);

        // Strip trailing slash
        final String commandName = req.getRestOfPath().substring(1);
        CLICommand command = CLICommand.clone(commandName);
        if (command == null) {
            rsp.sendError(HttpServletResponse.SC_NOT_FOUND, "No such command");
            return;
        }

        req.setAttribute("command", command);
        req.getView(this, "command.jelly").forward(req, rsp);
    }

    @Override
    public Object getTarget() {
        StaplerRequest req = Stapler.getCurrentRequest();
        if (req.getRestOfPath().length()==0 && "POST".equals(req.getMethod())) {
            // CLI connection request
            if ("false".equals(req.getParameter("remoting"))) {
                throw new PlainCliEndpointResponse();
            } else {
                // remoting=true (the historical default) no longer supported.
                throw HttpResponses.forbidden();
            }
        } else {
            return this;
        }
    }

    /**
     * Serves {@link PlainCLIProtocol} response.
     */
    private class PlainCliEndpointResponse extends FullDuplexHttpService.Response {

        PlainCliEndpointResponse() {
            super(duplexServices);
        }

        @Override
        protected FullDuplexHttpService createService(StaplerRequest req, UUID uuid) throws IOException {
            return new FullDuplexHttpService(uuid) {
                @Override
                protected void run(InputStream upload, OutputStream download) throws IOException, InterruptedException {
                    final AtomicReference<Thread> runningThread = new AtomicReference<>();
                    class ServerSideImpl extends PlainCLIProtocol.ServerSide {
                        boolean ready;
                        List<String> args = new ArrayList<>();
                        Locale locale = Locale.getDefault();
                        Charset encoding = Charset.defaultCharset();
                        final PipedInputStream stdin = new PipedInputStream();
                        final PipedOutputStream stdinMatch = new PipedOutputStream();
                        ServerSideImpl(InputStream is, OutputStream os) throws IOException {
                            super(is, os);
                            stdinMatch.connect(stdin);
                        }
                        @Override
                        protected void onArg(String text) {
                            args.add(text);
                        }
                        @Override
                        protected void onLocale(String text) {
                            for (Locale _locale : Locale.getAvailableLocales()) {
                                if (_locale.toString().equals(text)) {
                                    locale = _locale;
                                    return;
                                }
                            }
                            LOGGER.log(Level.WARNING, "unknown client locale {0}", text);
                        }
                        @Override
                        protected void onEncoding(String text) {
                            try {
                                encoding = Charset.forName(text);
                            } catch (UnsupportedCharsetException x) {
                                LOGGER.log(Level.WARNING, "unknown client charset {0}", text);
                            }
                        }
                        @Override
                        protected void onStart() {
                            ready();
                        }
                        @Override
                        protected void onStdin(byte[] chunk) throws IOException {
                            stdinMatch.write(chunk);
                        }
                        @Override
                        protected void onEndStdin() throws IOException {
                            stdinMatch.close();
                        }
                        @Override
                        protected void handleClose() {
                            ready();
                            Thread t = runningThread.get();
                            if (t != null) {
                                t.interrupt();
                            }
                        }
                        private synchronized void ready() {
                            ready = true;
                            notifyAll();
                        }
                    }
                    try (ServerSideImpl connection = new ServerSideImpl(upload, download)) {
                        connection.begin();
                        synchronized (connection) {
                            while (!connection.ready) {
                                connection.wait();
                            }
                        }
                        PrintStream stdout = new PrintStream(connection.streamStdout(), false, connection.encoding.name());
                        PrintStream stderr = new PrintStream(connection.streamStderr(), true, connection.encoding.name());
                        if (connection.args.isEmpty()) {
                            stderr.println("Connection closed before arguments received");
                            connection.sendExit(2);
                            return;
                        }
                        String commandName = connection.args.get(0);
                        CLICommand command = CLICommand.clone(commandName);
                        if (command == null) {
                            stderr.println("No such command " + commandName);
                            connection.sendExit(2);
                            return;
                        }
                        command.setTransportAuth(Jenkins.getAuthentication());
                        command.setClientCharset(connection.encoding);
                        CLICommand orig = CLICommand.setCurrent(command);
                        try {
                            runningThread.set(Thread.currentThread());
                            int exit = command.main(connection.args.subList(1, connection.args.size()), connection.locale, connection.stdin, stdout, stderr);
                            stdout.flush();
                            connection.sendExit(exit);
                            try { // seems to avoid ReadPendingException from Jetty
                                Thread.sleep(1000);
                            } catch (InterruptedException x) {
                                // expected; ignore
                            }
                        } finally {
                            CLICommand.setCurrent(orig);
                            runningThread.set(null);
                        }
                    }
                }
            };
        }
    }

}


text:
package hu.ibello.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="action")
public class ActionElement extends Element {

	private Long timeoutMs;
	private TextFormatKind nameFormat;

	public Long getTimeoutMs() {
		return timeoutMs;
	}

	@XmlAttribute(name="timeout-ms")
	public void setTimeoutMs(Long timeoutMs) {
		this.timeoutMs = timeoutMs;
	}

	public TextFormatKind getNameFormat() {
		return nameFormat;
	}

	@XmlAttribute(name="name-format")
	public void setNameFormat(TextFormatKind nameFormat) {
		this.nameFormat = nameFormat;
	}

	@Override
	public ElementType getType() {
		return ElementType.ACTION;
	}
}


text:
package com.littleinc.orm_benchmark.greendao;

import java.util.List;
import com.littleinc.orm_benchmark.greendao.DaoSession;
import de.greenrobot.dao.DaoException;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
/**
 * Entity mapped to table MESSAGE.
 */
public class Message {

    private Long id;
    private String content;
    private Long client_id;
    private Integer created_at;
    private Double sorted_by;
    private Long command_id;
    private long sender_id;
    private long channel_id;

    /** Used to resolve relations */
    private transient DaoSession daoSession;

    /** Used for active entity operations. */
    private transient MessageDao myDao;

    private List<User> readers;

    public Message() {
    }

    public Message(Long id) {
        this.id = id;
    }

    public Message(Long id, String content, Long client_id, Integer created_at, Double sorted_by, Long command_id, long sender_id, long channel_id) {
        this.id = id;
        this.content = content;
        this.client_id = client_id;
        this.created_at = created_at;
        this.sorted_by = sorted_by;
        this.command_id = command_id;
        this.sender_id = sender_id;
        this.channel_id = channel_id;
    }

    /** called by internal mechanisms, do not call yourself. */
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getMessageDao() : null;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Long getClient_id() {
        return client_id;
    }

    public void setClient_id(Long client_id) {
        this.client_id = client_id;
    }

    public Integer getCreated_at() {
        return created_at;
    }

    public void setCreated_at(Integer created_at) {
        this.created_at = created_at;
    }

    public Double getSorted_by() {
        return sorted_by;
    }

    public void setSorted_by(Double sorted_by) {
        this.sorted_by = sorted_by;
    }

    public Long getCommand_id() {
        return command_id;
    }

    public void setCommand_id(Long command_id) {
        this.command_id = command_id;
    }

    public long getSender_id() {
        return sender_id;
    }

    public void setSender_id(long sender_id) {
        this.sender_id = sender_id;
    }

    public long getChannel_id() {
        return channel_id;
    }

    public void setChannel_id(long channel_id) {
        this.channel_id = channel_id;
    }

    /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
    public List<User> getReaders() {
        if (readers == null) {
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            UserDao targetDao = daoSession.getUserDao();
            List<User> readersNew = targetDao._queryMessage_Readers(id);
            synchronized (this) {
                if(readers == null) {
                    readers = readersNew;
                }
            }
        }
        return readers;
    }

    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    public synchronized void resetReaders() {
        readers = null;
    }

    /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

}


text:
package org.wikidata.wdtk.datamodel.implementation;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.wikidata.wdtk.datamodel.helpers.Equality;
import org.wikidata.wdtk.datamodel.helpers.Hash;
import org.wikidata.wdtk.datamodel.helpers.ToString;
import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue;
import org.wikidata.wdtk.datamodel.interfaces.MediaInfoIdValue;
import org.wikidata.wdtk.datamodel.interfaces.ValueVisitor;

/**
 * Jackson implementation of {@link MediaInfoIdValue}.
 *
 * @author Thomas Pellissier Tanon
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonDeserialize()
public class MediaInfoIdValueImpl extends EntityIdValueImpl implements MediaInfoIdValue {

	/**
	 * Constructor.
	 *
	 * @param id
	 * 		the identifier of the entity, such as "M42"
	 * @param siteIri
	 *      the siteIRI that this value refers to
	 */
	MediaInfoIdValueImpl(
			String id,
			String siteIri) {
		super(id, siteIri);
		assertHasJsonEntityType(JSON_ENTITY_TYPE_MEDIA_INFO);
	}
	/**
	 * Constructor used for deserialization with Jackson.
	 *
	 * @param value
	 *     the inner JSON object deserialized as a {@link JacksonInnerEntityId}
	 * @param siteIri
	 *     the siteIRI that this value refers to.
	 */
	@JsonCreator
	MediaInfoIdValueImpl(
			@JsonProperty("value") JacksonInnerEntityId value,
			@JacksonInject("siteIri") String siteIri) {
		super(value, siteIri);
		assertHasJsonEntityType(JSON_ENTITY_TYPE_MEDIA_INFO);
	}

	@JsonIgnore
	@Override
	public String getEntityType() {
		return EntityIdValue.ET_MEDIA_INFO;
	}

	@JsonIgnore
	@Override
	public boolean isPlaceholder() {
		return getId().equals("M0");
	}

	@Override
	public <T> T accept(ValueVisitor<T> valueVisitor) {
		return valueVisitor.visit(this);
	}

	@Override
	public int hashCode() {
		return Hash.hashCode(this);
	}

	@Override
	public boolean equals(Object obj) {
		return Equality.equalsEntityIdValue(this, obj);
	}

	@Override
	public String toString() {
		return ToString.toString(this);
	}
}


text:
/* MM must occasionally print some message.  It uses the standard library
 * routine prink().  (The name "printf" is really a macro defined as "printk").
 * Printing is done by calling the TTY task directly, not going through FS.
 */

#include "mm.h"
#include <minix/com.h>

#define STD_OUTPUT          1	/* file descriptor for standard output */
#define BUF_SIZE          100	/* print buffer size */

PRIVATE int buf_count;		/* # characters in the buffer */
PRIVATE char print_buf[BUF_SIZE];	/* output is buffered here */
PRIVATE message putch_msg;	/* used for message to TTY task */

FORWARD void F_l_u_s_h();

/*===========================================================================*
 *				putc					     *
 *===========================================================================*/
PUBLIC void putc(c)
char c;
{

  /* Accumulate another character.  If '\n' or buffer full, print it. */
  print_buf[buf_count++] = c;
  if (c == '\n' || buf_count == BUF_SIZE) F_l_u_s_h();
}

/*===========================================================================*
 *				F_l_u_s_h				     *
 *===========================================================================*/
PRIVATE void F_l_u_s_h()
{
/* Flush the print buffer by calling TTY task. */

  if (buf_count == 0) return;
  putch_msg.m_type = TTY_WRITE;
  putch_msg.PROC_NR  = 0;
  putch_msg.TTY_LINE = 0;
  putch_msg.ADDRESS  = print_buf;
  putch_msg.COUNT = buf_count;
  sendrec(TTY, &putch_msg);
  buf_count = 0;
}


text:
package nl.knaw.dans.dccd.repository;

import java.io.StringWriter;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import junit.framework.TestCase;
import nl.knaw.dans.dccd.model.Project;
import nl.knaw.dans.dccd.model.entities.Entity;
import nl.knaw.dans.dccd.model.entities.ProjectEntity;
import nl.knaw.dans.dccd.repository.fedora.FedoraRepositoryService;

public class TestFedoraRepositoryOnlineTest extends TestCase {

	public void testFedoraRepository() {
		// empty
	}

	public void SKIPtestFedoraGetObjectXML() {
		//getObjectXML
    	// use the Fedora repo, for testing
    	String protocol = "http";
    	String host = "localhost";
    	int port = 8082;
    	String user = "fedoraAdmin";
    	String pass = "fedoraAdmin";
    	String context = "fedora";

    	try {
			FedoraRepositoryService fs = new FedoraRepositoryService(protocol, host, port, user, pass, context);
			System.out.print(fs.getObjectXML("dccd:135"));// yep, hardcoded PID, could be demo:100
    	} catch (DccdRepositoryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void SKIPtestFedoraRetrieveEntityTree() {
		Project project = new Project();
//		project.setSid("dccd:51"); // must be there for testing!!!
		project.setStoreId("dccd:51"); // must be there for testing!!!

    	// use the Fedora repo, for testing
    	String protocol = "http";
    	String host = "localhost";
    	int port = 8082;
    	String user = "fedoraAdmin";
    	String pass = "fedoraAdmin";
    	String context = "fedora";
    	try {
			FedoraRepositoryService fs = new FedoraRepositoryService(protocol, host, port, user, pass, context);

			fs.retrieveEntityTree(project);
			assertNotNull(project.entityTree);
			assertNotNull(project.entityTree.getProjectEntity());
			assertNull(project.entityTree.getProjectEntity().getTridasAsObject());
			// output the tree
			List<String> lines = project.entityTree.getProjectEntity().toTreeString("");
			for (String line : lines)
				System.out.println(line);

			// now get the project entity tridas?
			ProjectEntity projectEntity = project.entityTree.getProjectEntity();
			fs.retrieveEntity(project.getSid(), projectEntity);
			assertNotNull(projectEntity.getTridasAsObject());

			// get all and see if the result is correct?
			List<Entity> entities = project.entityTree.getEntities();
			for (Entity entity : entities) {
				fs.retrieveEntity(project.getSid(), entity);
				assertNotNull(entity.getTridasAsObject());
			}
			projectEntity.connectTridasObjectTree();
			// can we marshall?
			// note: should be part of a util.tridas package?

	    	// show tridas xml
	    	// note: we are not testing JAXB
			JAXBContext jaxbContext = null;
			try {
				System.out.println("\n TRiDaS XML");
				jaxbContext = JAXBContext.newInstance("org.tridas.schema");
				// now marshall the pruned clone
				Marshaller marshaller = jaxbContext.createMarshaller();
				marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//testing
				java.io.StringWriter sw = new StringWriter();
				marshaller.marshal(projectEntity.getTridasAsObject(), sw);
				System.out.print(sw.toString());
			} catch (JAXBException e1) {
				e1.printStackTrace();
				fail("JAXB exception");
			}
		} catch (Exception e) {
			e.printStackTrace();
			fail("exception");
		}

	}

    public void SKIPtestGetDendroProjects()
    {
    	//note: It only works when the server is up
    	//RepositoryService repo = new XMLFilesRepositoryService();

    	// Note: should also test the FedoraRepositoryService constructor/initialization!

    	// use the Fedora repo, for testing
    	String protocol = "http";
    	String host = "localhost";
    	int port = 8082;
    	String user = "fedoraAdmin";
    	String pass = "fedoraAdmin";
    	String context = "fedora";
    	try {
			FedoraRepositoryService fs = new FedoraRepositoryService(protocol, host, port, user, pass, context);
			// Note: should we really retrieve all
			// better have some fake store,
			// probably fixed when using the common dans project!
			fs.getDendroProjects(1);
		} catch (Exception e) {
			e.printStackTrace();
			fail("exception");
		}
    }

}


text:
require 'unit/spec_helper'

describe 'sprout-git::git_duet' do
  let(:chef_run) { ChefSpec::Runner.new }

  it 'includes the homebrew recipe' do
    chef_run.converge(described_recipe)
    expect(chef_run).to include_recipe('homebrew')
  end

  it 'includes the git_duet_global recipe' do
    chef_run.converge(described_recipe)
    expect(chef_run).to include_recipe('sprout-git::git_duet_global')
  end

  it 'includes the git_duet_rotate_authors recipe' do
    chef_run.converge(described_recipe)
    expect(chef_run).to include_recipe('sprout-git::git_duet_rotate_authors')
  end

  it 'includes the authors recipe' do
    chef_run.converge(described_recipe)
    expect(chef_run).to include_recipe('sprout-git::authors')
  end

  it 'taps git-duet/homebrew-tap' do
    chef_run.converge(described_recipe)
    expect(chef_run).to tap_homebrew_tap('git-duet/homebrew-tap')
  end

  it 'brew installs git-duet' do
    chef_run.converge(described_recipe)
    expect(chef_run).to install_package('git-duet')
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/llChat"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/black"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_emoji_input_layout"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:gravity="center"
        android:minHeight="48dp"
        android:padding="12dp">

        <ImageButton
            android:id="@+id/btnAdd"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:background="@color/transparent"
            android:scaleType="fitCenter"
            android:src="@drawable/btn_multi_bg" />

        <!--<ImageView-->
        <!--android:id="@+id/btn_face"-->
        <!--android:layout_width="25dp"-->
        <!--android:layout_height="25dp"-->
        <!--android:layout_marginRight="12dp"-->
        <!--android:src="@drawable/ic_emoji_keyboad_show" />-->
        <ToggleButton
            android:id="@+id/btn_face"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignBottom="@id/et"
            android:layout_margin="@dimen/margin_default_large_large"
            android:background="@drawable/toggle_btn_face"
            android:scaleType="fitCenter"
            android:textOff=""
            android:textOn="" />

        <com.keyboard.view.EmoticonsEditText
            android:id="@+id/et_chat"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@drawable/bg_emoji_edit"
            android:cursorVisible="true"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:hint="@string/say_sth"
            android:inputType="text"
            android:padding="6dp"
            android:textColor="@color/text_black"
            android:textCursorDrawable="@null"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/btn_send"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="12dp"
            android:background="@drawable/bg_round_corner_white"
            android:gravity="center"
            android:paddingBottom="7dp"
            android:paddingTop="7dp"
            android:text="@string/send_away"
            android:textColor="@color/text_black_content"
            android:textSize="14sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/replace"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:orientation="vertical" />

</LinearLayout>


text:
$(document).ready(function(){

  $('#grouping-selection-form').submit(function(){
    setTimeout(function(){

    var targets = $('[data-draggable="target"]');
    for (i=0; i< targets.length; i++){
      targets[i].setAttribute('aria-dropeffect', 'none');
    }

    var students = $('[data-draggable="student"]');
    for (i = 0; i < students.length; i++){
      students[i].setAttribute('draggable', 'true');
      students[i].setAttribute('aria-grabbed', 'false');
    }

    var selections = {
            students   : [],
            owner      : null,
            droptarget : null
    };

  function addSelection(student){
    if (!selections.owner){
      selections.owner = student.parentNode;
    } else if (selections.owner != student.parentNode) {
      return;
    }

    student.setAttribute('aria-grabbed', 'true');

    selections.students.push(student);
  }

  function removeSelection(student){
    student.setAttribute('aria-grabbed', 'false')

    for (var i = 0; i < selections.students.length; i++){
      if (selections.students[i] == student){
        selections.students.splice(i,1);
        break;
      }
    }
  }

  function clearSelections(){
    if (selections.students.length){
      selections.owner = null;
      for (var i = 0; i < selections.students.length; i++){
        selections.students[i].setAttribute('aria-grabbed', 'false')
      }
      selections.students = [];
    }
  }

  function hasModifier(event){
      return (event.ctrlKey || event.metaKey || event.shiftKey);
  }

  function addDropEffects(){
    for (var i=0; i<targets.length;i++){
      if (targets[i] != selections.owner && targets[i].getAttribute('aria-dropeffect') == 'none'){
        targets[i].setAttribute('aria-dropeffect', 'move');
      }
    }
    for (var i=0; i< students.length;i++){
      if (students[i].parentNode != selections.owner && students[i].getAttribute('aria-grabbed')){
        students[i].removeAttribute('aria-grabbed');
      }
    }
  }

  function clearDropEffects(){
    if(selections.students.length){
      for (var i=0; i<targets.length; i++){
        if(targets[i].getAttribute('aria-dropeffect') != 'none'){
          targets[i].setAttribute('aria-dropeffect', 'none')
        }
      }
      for (var i = 0; i < students.length; i ++){
          if(!students[i].getAttribute('aria-grabbed')) {
               students[i].setAttribute('aria-grabbed', 'false');
           }
      }
    }
  }

  document.getElementById('group-display-area').addEventListener('mousedown', function(event){
    if (event.target.getAttribute('draggable')){
      clearDropEffects();
      if (!hasModifier(event) && event.target.getAttribute('aria-grabbed') == 'false'){
        clearSelections();
        addSelection(event.target);
      }
    } else if(!hasModifier(event)){
      clearDropEffects();
      clearSelections();
    } else {
      clearDropEffects();
    }

  }, false);

  document.getElementById('group-display-area').addEventListener('mouseup', function(event) {
       if (event.target.getAttribute('draggable') && hasModifier(event)) {
           if(event.target.getAttribute('aria-grabbed') == 'true'){
               removeSelection(event.target);
               if(!selections.items.length) {
                   selections.owner = null;
               }
           } else {
               addSelection(event.target);
           }
       }

   }, false);

  document.getElementById('group-display-area').addEventListener('dragstart', function(event){
    if (selections.owner != event.target.parentNode){
      event.preventDefault();
      return;
    }
    if (hasModifier(event) && event.target.getAttribute('aria-grabbed') == 'false'){
      addSelection(event.target);
    }
    event.dataTransfer.setData('text', '');
    addDropEffects();

    student = event.target
    event.dataTransfer.setData('text', '')
  }, false);

  function getContainer(element){
    do {
      if (element.nodeType === 1 && element.getAttribute('aria-dropeffect')){
        return element;
      }
    }
    while(element = element.parentNode);
  };

  var related = null;
  document.getElementById('group-display-area').addEventListener('dragenter', function(event){
    related = event.target
  }, false)

  document.getElementById('group-display-area').addEventListener('dragleave', function(event){
    var droptarget = getContainer(related)
    if (droptarget == selections.owner){
      droptarget = null;
    }
    if (droptarget != selections.droptarget){
      if (selections.droptarget){
        selections.droptarget.className = selections.droptarget.className.replace(/dragover/g,'');
      }
      if (droptarget){
        droptarget.className += ' dragover';
      }
      selections.droptarget = droptarget;
    }
  }, false);

  document.getElementById('group-display-area').addEventListener('dragover', function(event){
    if (selections.students.length){
      event.preventDefault();
    }
  }, false);

  document.getElementById('group-display-area').addEventListener('dragend', function(event){
    if (selections.droptarget){
      for(var i =0; i < selections.students.length; i++){
        selections.droptarget.appendChild(selections.students[i]);
      }
      event.preventDefault();
    }
    if (selections.students.length){
      clearDropEffects();
      if (selections.droptarget){
        clearSelections();
        selections.droptarget.className = selections.droptarget.className.replace(/ dragover/g, '');
        selections.droptarget = null;
      }
    }
  }, false);
  }, 1000);
});

  $('#grouping-selection-form').on("submit", function(event){
    event.preventDefault()
    var requestData = $(this).serialize()
    var path = $(this).attr('action')

    $.ajax({
      url: path,
      type: 'post',
      data: requestData,

    }).done(function(serverData){
      console.log('success')
      console.log(serverData)
      // $('#group-display-area').empty();
      $('#group-display-area').append(serverData);

    }).fail(function(){
      console.log('fail')
    });
  });

  $('#group-display-area').on("click", '#save-group-button', function(event){
    var collectedGroups = []

    $('.g').each(function(){
      groupMembers = []
      $(this).find('.s').each(function(){
        groupMembers.push(this.innerText)
      })
      collectedGroups.push(groupMembers)
    })

    var groupName = $('#save-group-name').val()

    $.ajax({
      url: "/groups/new",
      type: 'post',
      data: {grouping: collectedGroups, name: groupName},

    }).done(function(serverData){
      console.log('success')
      $('#group-display-area').empty()
      $('body').append(serverData)
    }).fail(function(){
      console.log('fail')
    })
  })

  $('.delete-group-form').on("click", function(event){
    event.preventDefault()
    var path = $(this).attr("action")

    var deletedForm = this

    $.ajax({
      url: path,
      type: 'delete',

    }).done(function(serverData){
      console.log('success')
      $(deletedForm).parent().remove()
    }).fail(function(){
      console.log('fail')
    })
  })

  $('#review-delete-form').on("submit", function(event) {
    event.preventDefault()

    var path = $(this).attr('action')
    var requestData = $('#review-delete-form').serialize()
    console.log(requestData)
    var targetedDeleteForm = this

    $.ajax({
      url: path,
      type: 'put',
      data: requestData,
      dataType: 'json'

    }).done(function(){
      $(targetedDeleteForm).parent().remove()
      console.log('success')
    }).fail(function(){
      console.log('fail')
    })
  })

  $('.favorite-unfavorite-image-text').on("click", function(event){
    event.preventDefault();

    var baseRoute = $(this).parent().attr("href");
    if (baseRoute[9] == "u") {
      var route = baseRoute.substr(0,8) + "/favorite"
    } else{
      var route = baseRoute.substr(0,8) + "/unfavorite"
    }

    $.ajax({
      url: route,
      type: 'get',
      dataType: 'json',
    }).done(function(serverData){
    var baseRoute = $('.favorite-unfavorite-image-text').parent().attr("href")
    if (baseRoute[9] == "u" ) {
      var newRoute = baseRoute.substr(0,8) + "/favorite";
    } else{
      var newRoute = baseRoute.substr(0,8) + "/unfavorite";
    }

      $('.favorite-unfavorite-container > a').attr("href", newRoute);
      $('.favorite-unfavorite-image-text').attr("src", serverData);

    }).fail(function(serverData){
      console.log(serverData)
      console.log('fail');
    });
  });

  $('.favorite-unfavorite-image-genre').on("click", function(event){
    event.preventDefault();

    var baseRoute = $(this).parent().attr("href");
    if (baseRoute[10] == "u") {
      var route = baseRoute.substr(0,9) + "/favorite"
    } else{
      var route = baseRoute.substr(0,9) + "/unfavorite"
    }

    var originalTarget = this;

    $.ajax({
      url: route,
      type: 'get',
      dataType: 'json',
    }).done(function(serverData){

      if (baseRoute[10] == "u") {
        var newRoute = baseRoute.substr(0,8) + serverData.genre_id + "/favorite";
      } else {
        var newRoute = baseRoute.substr(0,8) + serverData.genre_id + "/unfavorite";
      }

      $(originalTarget).parent().attr("href", newRoute);
      $(originalTarget).attr("src", serverData.image_location);

    }).fail(function(serverData){
      console.log('fail');
    });
  });

  $('ul.nav > li').on("click", function (e) {
    $(this).addClass('active')
  })

  $('.col-xs-2').mouseover(function(){
    var tabBackgroundColor = $(this).children().css("background-color")
    $("#display-area").css("background-color", tabBackgroundColor)
  })

   var ajaxRequest;

   var searchResults = []

   var typingTimer;
   var doneTypingInterval = 300;

   //on keyup, start the countdown
   $('#search-texts').keyup(function(){
       clearTimeout(typingTimer);
          typingTimer = setTimeout(doneTyping, doneTypingInterval);
   });

   //user is "finished typing," do something
  function doneTyping () {
    var query = $('#search-texts').val();
    console.log(query)

    if(query.length >= 3){
      var resultTitle = $('.new-search-result').children().first().text()
      if (searchResults.indexOf(resultTitle) === -1){

        ajaxRequest = $.ajax({
          url: '/texts/search',
          type: 'get',
          data: {'search_keyword': query},

        });

        ajaxRequest.done(function(serverData){
          console.log('success')
            $('#search-dropdown').append(serverData);
            resultTitle = $('.new-search-result').children().first().text()
            searchResults.push(resultTitle)
            console.log(searchResults)
          $('#search-texts').on("keyup", function(e){
            if (e.keyCode === 8){
              $('#search-texts').siblings().remove()
              searchResults = []
            }
          })
        })

        ajaxRequest.fail(function(serverData){
          console.log('fail')
        })
       }
    };
   }

});