text:
/**
 * @fileOverview Privly Application specific code.
 * This file modifies the privly-web adapter found
 * in the shared directory.
 **/

/**
 * Display rendered markdown as a preview of the post.
 */
function previewMarkdown() {
  $( "#post_content" ).html(markdown.toHTML($( "#edit_text" ).val()));
  $( "#update" ).attr("class", "btn btn-warning");
  privlyHostPage.resizeToWrapper();
}

/**
 * Attempt to find the key in local storage and redirect the app if
 * possible to the URL with the key.
 * @return {boolean} Indicates whether the key was resolved from history.
 */
function resolveKeyFromHistory() {
  var urls = Privly.storage.get("Message:URLs");

  // Deprecated
  var oldUrls = Privly.storage.get("ZeroBin:URLs");
  if ( oldUrls !== null ) {
    urls = urls.concat(oldUrls);
    Privly.storage.set("Message:URLs", urls);
    Privly.storage.remove("ZeroBin:URLs");
  }

  if ( urls !== null ) {
    for( var i = 0; i < urls.length; i++ ) {
      var index = urls[i].indexOf(state.webApplicationURL);
      if ( index === 0 ) {
        state.key = privlyParameters.getParameterHash(urls[i]).privlyLinkKey;
        return true;
      }
    }
  }
  return false;
}

/**
 * Application specific content type handler. This function
 * processes the encrypted markdown that should have been returned by
 * the server.
 *
 * @param {jqHR} response The response from the server for the associated
 * data URL.
 */
function processResponseContent(response) {

  // Change the edit button back to the default style
  // if it has been modified. This is usually for
  // when the user has edited content and submitted
  // the form.
  $( "#update" ).attr("class", "btn btn-default");

  var url = state.webApplicationURL;
  state.key = privlyParameters.getParameterHash(url).privlyLinkKey;

  privlyNetworkService.permissions.canShow = true;

  var json = response.json;
  if( json === null ) {return;}

  if (state.key === undefined || state.key === "") {
    if ( ! resolveKeyFromHistory() ) {
      $('div#cleartext').text("You do not have the key required to decrypt this content.");
      return;
    }
  }

  if(json.structured_content !== undefined) {
    var cleartext = zeroDecipher(pageKey(state.key), json.structured_content);
    $("#edit_text").val(cleartext);
    var markdownHTML = markdown.toHTML(cleartext);
    $('div#cleartext').html(markdownHTML);

    // Make all text areas auto resize to show all their contents
    if ( ! privlyHostPage.isInjected() ) {
      $('textarea').autosize();
    }
  } else {
    $('div#cleartext').text("The data behind this link is destroyed or corrupted.");
  }
  privlyHostPage.resizeToWrapper();
}

/**
 * Replace the update handler so that we can ensure content will always be
 * encrypted before pusing updates to the remote server.
 * @param {event} evt The update button event triggered by the user.
 * @param {function} callback An ignored parameter since there is no
 * need to pass in a callback in this case.
 */
function encryptBeforeUpdate(evt, callback) {
  var cipherdata = zeroCipher(state.key, $("#edit_text")[0].value);
  privlyNetworkService.sameOriginPutRequest(state.jsonURL,
    function(response){
      callbacks.contentReturned(response, processResponseContent);
    },
    {post: {structured_content: cipherdata,
    seconds_until_burn: $( "#seconds_until_burn" ).val()}});

  // needed to stop click event from propagating to body
  // and prevent a new window from opening because of click listener
  // on body.
  evt.stopPropagation();

  // Close the editing form
  $("#edit_form").hide();
  state.isInlineEdit = false;
}

function initializeApplication() {

  // Make the Tooltip display this App's name.
  privlyTooltip.appName = "Message";

  $( "#edit_text" ).bind("keyup", previewMarkdown);

  callbacks.pendingContent(processResponseContent);

  // Replace the update function so we never send the cleartext server side.
  callbacks.update = encryptBeforeUpdate;
}

// Initialize the application
document.addEventListener('DOMContentLoaded',
  function() {

    // Don't start the script if it is running in a Headless
    // browser
    if( document.getElementById("logout_link") ) {
      initializeApplication();
    }
  }
);


text:
1. [Introduction](./01-introduction.md)
2. [~~Precompiler Overview~~](./02-precompiler-overview.md)
3. [~~Runtime Overview~~](./03-runtime-overview.md)
4. [References](./04-references.md)
5. [Validators](./05-validators.md)
6. [~~Runtime Compiler~~](./06-runtime-compiler.md)
7. [~~Initial Render~~](./07-initial-render.md)
8. [~~Rerendering (Updating)~~](./08-rerendering-updating.md)
9. [~~The Environment~~](./09-the-environment.md)
10. [~~Optimizations~~](./10-optimizations.md)

# Optimizations

TODO: add content here

* * *

redpajama_set_name: RedPajamaGithub


text:
enum ResultCode
{
	StatusCode_Ok,
	ErrorCode_Data,
	ErrorCode_Memory,
	ErrorCode_Parameter,
	ErrorCode_Threading,
	ErrorCode_Unsupported,
	ErrorCode_OutputEnd,
	ErrorCode_InputEnd,
	ErrorCode_Unknown,
};

ResultCode NativeLzmaCompressMemory(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, unsigned char *outProps, size_t *outPropsSize,
	int level, unsigned dictSize, int lc, int lp, int pb, int algo, int fb, int btMode, int numHashBytes, unsigned mc, unsigned endMark, int numThreads);
ResultCode NativeLzmaCompressMemory_V1(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, unsigned char *outProps, size_t *outPropsSize,
	int level, unsigned dictSize, int lc, int lp, int pb, int algo, int fb, int btMode, int numHashBytes, unsigned mc, unsigned endMark, int numThreads);
ResultCode NativeLzmaCompressStream(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, unsigned char *outProps, size_t *outPropsSize,
	int level, unsigned dictSize, int lc, int lp, int pb, int algo, int fb, int btMode, int numHashBytes, unsigned mc, unsigned endMark, int numThreads);
ResultCode NativeLzmaUncompress(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, const unsigned char *props, size_t propsSize);
ResultCode NativeLzmaUncompress_V1(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, const unsigned char *props, size_t propsSize, bool endMark);

ResultCode NativeLzmaCompress2(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t srcLen, unsigned char *outProp,
	int level, unsigned dictSize, int lc, int lp, int pb, int algo, int fb, int btMode, int numHashBytes, unsigned mc, unsigned endMark, int numThreads, int blockSize, int blockThreads, int totalThreads);
ResultCode NativeLzmaUncompress2(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, unsigned char prop, int endMark);
ResultCode NativeLzmaUncompress2_V1(unsigned char *dest, size_t *destLen, const unsigned char *src, size_t *srcLen, unsigned char prop, int endMark);


text:
// Copyright 2015 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.

export var chromeAgentClient = {};
export default chromeAgentClient;

/**
 * @constructor
 */
chromeAgentClient.ErrorSendingRequest = function(message) {
  this.message = message;
};

/**
 * @constructor
 */
chromeAgentClient.ErrorExecutingRequest = function(message) {
  this.message = message;
};

chromeAgentClient.AGENT_APP_ID_ = 'lfbhahfblgmngkkgbgbccedhhnkkhknb';
chromeAgentClient.AGENT_INSTALL_URL_ =
    'https://chrome.google.com/webstore/detail/' +
    chromeAgentClient.AGENT_APP_ID_;

/**
 * Open a new tab with the Agent extension's page in Chrome Web Store,
 * allowing the user to install it.
 *
 * @return {void}
 */
chromeAgentClient.installAgent = function() {
  window.open(chromeAgentClient.AGENT_INSTALL_URL_);
};

/**
 * Open a new tab with the official documentation for the given
 * Chrome Extensions API, or the top page of the documentation if no API is
 * provided.
 *
 * @param {string} api
 * @return {void}
 */
chromeAgentClient.openApiOnlineDoc = function(api) {
  var urlSuffix = 'api_index';
  if (api) {
    var parts = api.split('.');
    if (parts[0] === 'chrome')
      parts.shift();

    if (parts.length == 1)
      urlSuffix = parts[0];
    else if (parts.length == 2)
      urlSuffix = parts[0] + '#method-' + parts[1];
    else if (parts.length === 3)
      urlSuffix = parts[0] + '_' + parts[1] + '#method-' + parts[2];
  }
  var url = 'https://developer.chrome.com/extensions/' + urlSuffix;
  window.open(url);
};

/**
 * Request the Agent extension to invoke the given API with the given arguments
 * and options. The result of the invocation is passed back asynchronously.
 *
 * @param {!string} api
 * @param {!Array<*>} args
 * @param {!{timeout: number}} options
 * @return {!Promise<*>} Result returned by the API.
 */
chromeAgentClient.callApi = function(api, args, options) {
  if (!/^chrome./.test(api))
    api = 'chrome.' + api;
  return chromeAgentClient.sendRequest_(
    {
      type: 'call_api',
      api: api,
      args: args,
      options: options
    }
  );
};

/**
 * Request the Agent extension to execute a script in the given tabs'
 * "isolated world" (with full access to the DOM context but not the
 * JavaScript context).
 *
 * The result of the executions is passed back as a single value for a single
 * requested tab, or as a map of form { tabId1: result1, ... } for multiple
 * requested tabs (special values 'all' and 'window' are considered multiple
 * tabs even if they resolve to just one).
 *
 * The execution is resilient to errors and/or timeouts in individual tabs,
 * which can happen for various reasons (the script itself never returns or
 * attempts to return too much data; a tab may be hung ("Aw, snap!"); a tab may
 * be a special chrome:// tab, in which scripts are prohibited and error out).
 * Such errors are returned in the results map as special string values.
 *
 * Request the Agent extension to execute the given script in the given list
 * of tabs, with the given options. The result of the executions is passed back
 * as a single value for a single requested tab, or as a map of form
 * { tabId1: result1, ... } for multiple requested tabs (special values 'all'
 * and 'window' are considered multiple tabs even if they resolve to just one).
 *
 * @param {!string} code
 * @param {!(Array<number>|string)} tabIds
 * @param {!{allFrames: boolean, runAt: string, timeout: number}} options
 * @return {!Promise<*>} Result returned by the API.
 */
chromeAgentClient.executeScriptInTabs = function(code, tabIds, options) {
  return chromeAgentClient.sendRequest_(
    {
      type: 'execute_script',
      tabIds: tabIds,
      code: code,
      options: options
    }
  );
};

/**
 * Request the Agent extension to insert the given CSS fragment into the given
 * list of tabs, with the given options. If there are any errors, they are
 * returned as a single string for a single requested tab, or as a map of form
 * { tabId1: error1, ... } for multiple requested tabs (special values 'all'
 * and 'window' are considered multiple tabs even if they resolve to just one).
 *
 * Note that the author styles take precedence over any iserted styles, so
 * if there is a clash for some setting, the inserted CSS will have no effect
 * (this is the limitation of the underlying Chrome API).
 *
 * @param {!string} css
 * @param {!(Array<number>|string)} tabIds
 * @param {!{allFrames: boolean, runAt: string, timeout: number}} options
 * @return {!Promise<*>} Result returned by the API.
 */
chromeAgentClient.insertCssIntoTabs = function(css, tabIds, options) {
  return chromeAgentClient.sendRequest_(
    {
      type: 'insert_css',
      tabIds: tabIds,
      css: css,
      options: options
    }
  );
};

/**
 * Send the given request to perform some service to the Agent extension and
 * return back the result.
 *
 * @param {!Object<string, *>} request
 * @return {!Promise<*>} Result returned by the API.
 */
chromeAgentClient.sendRequest_ = function(request) {
  return new Promise(function(resolve, reject) {
    chrome.runtime.sendMessage(
      chromeAgentClient.AGENT_APP_ID_,
      request,
      {}, // options
      function(response) {
        if (chrome.runtime.lastError) {
          reject(new chromeAgentClient.ErrorSendingRequest(
              chrome.runtime.lastError.message));
        } else if (!response.success) {
          reject(new chromeAgentClient.ErrorExecutingRequest(response.error));
        } else {
          resolve(response.result);
        }
      }
    );
  });
};


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

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

#include <time.h>
#include <cups/cups.h>

#include <winpr/crt.h>
#include <winpr/string.h>

#include <freerdp/channels/rdpdr.h>

#include "printer_main.h"

#include "printer_cups.h"

typedef struct rdp_cups_printer_driver rdpCupsPrinterDriver;
typedef struct rdp_cups_printer rdpCupsPrinter;
typedef struct rdp_cups_print_job rdpCupsPrintJob;

struct rdp_cups_printer_driver
{
	rdpPrinterDriver driver;

	int id_sequence;
};

struct rdp_cups_printer
{
	rdpPrinter printer;

	rdpCupsPrintJob* printjob;
};

struct rdp_cups_print_job
{
	rdpPrintJob printjob;

	void* printjob_object;
	int printjob_id;
};

static void printer_cups_get_printjob_name(char* buf, int size)
{
	time_t tt;
	struct tm* t;

	tt = time(NULL);
	t = localtime(&tt);
	sprintf_s(buf, size - 1, "FreeRDP Print Job %d%02d%02d%02d%02d%02d",
		t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
		t->tm_hour, t->tm_min, t->tm_sec);
}

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT printer_cups_write_printjob(rdpPrintJob* printjob, const BYTE* data, size_t size)
{
	rdpCupsPrintJob* cups_printjob = (rdpCupsPrintJob*) printjob;

#ifndef _CUPS_API_1_4

	{
		FILE* fp;

		fp = fopen((const char*) cups_printjob->printjob_object, "a+b");

		if (!fp)
			return ERROR_INTERNAL_ERROR;

		if (fwrite(data, 1, size, fp) < size)
		{
			fclose(fp);
			return ERROR_INTERNAL_ERROR;
			// FIXME once this function doesn't return void anymore!
		}

		fclose(fp);
	}

#else

	cupsWriteRequestData((http_t*) cups_printjob->printjob_object, (const char*) data, size);

#endif

	return CHANNEL_RC_OK;
}

static void printer_cups_close_printjob(rdpPrintJob* printjob)
{
	rdpCupsPrintJob* cups_printjob = (rdpCupsPrintJob*) printjob;

#ifndef _CUPS_API_1_4

	{
		char buf[100];

		printer_cups_get_printjob_name(buf, sizeof(buf));

		if (cupsPrintFile(printjob->printer->name, (const char*) cups_printjob->printjob_object, buf, 0, NULL) == 0)
		{

		}

		unlink(cups_printjob->printjob_object);
		free(cups_printjob->printjob_object);
	}

#else

	cupsFinishDocument((http_t*) cups_printjob->printjob_object, printjob->printer->name);
	cups_printjob->printjob_id = 0;
	httpClose((http_t*) cups_printjob->printjob_object);

#endif

	((rdpCupsPrinter*) printjob->printer)->printjob = NULL;
	free(cups_printjob) ;
}

static rdpPrintJob* printer_cups_create_printjob(rdpPrinter* printer, UINT32 id)
{
	rdpCupsPrinter* cups_printer = (rdpCupsPrinter*) printer;
	rdpCupsPrintJob* cups_printjob;

	if (cups_printer->printjob != NULL)
		return NULL;

	cups_printjob = (rdpCupsPrintJob*) calloc(1, sizeof(rdpCupsPrintJob));
	if (!cups_printjob)
		return NULL;

	cups_printjob->printjob.id = id;
	cups_printjob->printjob.printer = printer;

	cups_printjob->printjob.Write = printer_cups_write_printjob;
	cups_printjob->printjob.Close = printer_cups_close_printjob;

#ifndef _CUPS_API_1_4

	cups_printjob->printjob_object = _strdup(tmpnam(NULL));
	if (!cups_printjob->printjob_object)
	{
		free(cups_printjob);
		return NULL;
	}

#else
	{
		char buf[100];

		cups_printjob->printjob_object = httpConnectEncrypt(cupsServer(), ippPort(), HTTP_ENCRYPT_IF_REQUESTED);

		if (!cups_printjob->printjob_object)
		{
			free(cups_printjob);
			return NULL;
		}

		printer_cups_get_printjob_name(buf, sizeof(buf));

		cups_printjob->printjob_id = cupsCreateJob((http_t*) cups_printjob->printjob_object,
			printer->name, buf, 0, NULL);

		if (!cups_printjob->printjob_id)
		{
			httpClose((http_t*) cups_printjob->printjob_object);
			free(cups_printjob);
			return NULL;
		}

		cupsStartDocument((http_t*) cups_printjob->printjob_object,
			printer->name, cups_printjob->printjob_id, buf, CUPS_FORMAT_AUTO, 1);
	}

#endif

	cups_printer->printjob = cups_printjob;

	return (rdpPrintJob*)cups_printjob;
}

static rdpPrintJob* printer_cups_find_printjob(rdpPrinter* printer, UINT32 id)
{
	rdpCupsPrinter* cups_printer = (rdpCupsPrinter*)printer;

	if (cups_printer->printjob == NULL)
		return NULL;
	if (cups_printer->printjob->printjob.id != id)
		return NULL;

	return (rdpPrintJob*)cups_printer->printjob;
}

static void printer_cups_free_printer(rdpPrinter* printer)
{
	rdpCupsPrinter* cups_printer = (rdpCupsPrinter*) printer;

	if (cups_printer->printjob)
		cups_printer->printjob->printjob.Close((rdpPrintJob*) cups_printer->printjob);

	free(printer->name);
	free(printer->driver);
	free(printer);
}

static rdpPrinter* printer_cups_new_printer(rdpCupsPrinterDriver* cups_driver,
	const char* name, const char* driverName, BOOL is_default)
{
	rdpCupsPrinter* cups_printer;

	cups_printer = (rdpCupsPrinter*) calloc(1, sizeof(rdpCupsPrinter));
	if (!cups_printer)
		return NULL;

	cups_printer->printer.id = cups_driver->id_sequence++;
	cups_printer->printer.name = _strdup(name);
	if (!cups_printer->printer.name)
	{
		free(cups_printer);
		return NULL;
	}

	if (driverName)
		cups_printer->printer.driver = _strdup(driverName);
	else
		cups_printer->printer.driver = _strdup("MS Publisher Imagesetter");
	if (!cups_printer->printer.driver)
	{
		free(cups_printer->printer.name);
		free(cups_printer);
		return NULL;
	}
	cups_printer->printer.is_default = is_default;

	cups_printer->printer.CreatePrintJob = printer_cups_create_printjob;
	cups_printer->printer.FindPrintJob = printer_cups_find_printjob;
	cups_printer->printer.Free = printer_cups_free_printer;

	return (rdpPrinter*) cups_printer;
}

static rdpPrinter** printer_cups_enum_printers(rdpPrinterDriver* driver)
{
	rdpPrinter** printers;
	int num_printers;
	cups_dest_t *dests;
	cups_dest_t *dest;
	int num_dests;
	int i;

	num_dests = cupsGetDests(&dests);
	printers = (rdpPrinter**) calloc(num_dests + 1, sizeof(rdpPrinter*));
	if (!printers)
		return NULL;

	num_printers = 0;

	for (i = 0, dest = dests; i < num_dests; i++, dest++)
	{
		if (dest->instance == NULL)
		{
			printers[num_printers++] = printer_cups_new_printer((rdpCupsPrinterDriver*) driver,
				dest->name, NULL, dest->is_default);
		}
	}
	cupsFreeDests(num_dests, dests);

	return printers;
}

static rdpPrinter* printer_cups_get_printer(rdpPrinterDriver* driver,
        const char* name, const char* driverName)
{
	rdpCupsPrinterDriver* cups_driver = (rdpCupsPrinterDriver*) driver;

	return printer_cups_new_printer(cups_driver, name, driverName,
            cups_driver->id_sequence == 1 ? TRUE : FALSE);
}

static rdpCupsPrinterDriver* cups_driver = NULL;

rdpPrinterDriver* printer_cups_get_driver(void)
{
	if (cups_driver == NULL)
	{
		cups_driver = (rdpCupsPrinterDriver*) calloc(1, sizeof(rdpCupsPrinterDriver));

		if (!cups_driver)
			return NULL;

		cups_driver->driver.EnumPrinters = printer_cups_enum_printers;
		cups_driver->driver.GetPrinter = printer_cups_get_printer;

		cups_driver->id_sequence = 1;
	}

	return (rdpPrinterDriver*) cups_driver;
}


text:
var _this = this;
// These are actually handled by transform-arrow-functions
const _x = function x() {
  babelHelpers.newArrowCheck(this, _this);
  return _x;
}.bind(this);
const y = function y(x) {
  babelHelpers.newArrowCheck(this, _this);
  return x();
}.bind(this);
const z = {
  z: function z() {
    babelHelpers.newArrowCheck(this, _this);
    return y(_x);
  }.bind(this)
}.z;


text:
class FontIdealistSans < Cask
  version 'latest'
  sha256 :no_check

  url 'http://fontfabric.com/downfont/idealist.zip'
  homepage 'http://fontfabric.com/idealist-sans/'

  font 'Idealist Sans.otf'
  font 'Idealist Sans Light.otf'
end


text:
require('sproutcore-touch/system/gesture');
require('sproutcore-touch/system/view');
require('sproutcore-touch/system/gesture_manager');
require('sproutcore-touch/system/gestures');


text:
namespace BaristaLabs.BaristaCore.JavaScript
{
    using System;

    /// <summary>
    ///     Called by the runtime to load the source code of the serialized script.
    /// </summary>
    /// <param name="sourceContext">The context passed to Js[Parse|Run]SerializedScriptCallback</param>
    /// <param name="script">The script returned.</param>
    /// <returns>
    ///     true if the operation succeeded, false otherwise.
    /// </returns>
    public delegate bool JavaScriptSerializedLoadScriptCallback(JavaScriptSourceContext sourceContext, out IntPtr value, out JavaScriptParseScriptAttributes parseAttributes);
}


text:
package io.swagger.codegen.plugin;

import io.swagger.codegen.CliOption;
import io.swagger.codegen.ClientOptInput;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.DefaultGenerator;
import io.swagger.codegen.config.CodegenConfigurator;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static io.swagger.codegen.config.CodegenConfiguratorUtils.*;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;

/**
 * Goal which generates client/server code from a swagger json/yaml definition.
 */
@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class CodeGenMojo extends AbstractMojo {

    @Parameter(name="verbose", required = false, defaultValue = "false")
    private boolean verbose;

    /**
     * Client language to generate.
     */
    @Parameter(name = "language", required = true)
    private String language;

    /**
     * Location of the output directory.
     */
    @Parameter(name = "output",
            property = "swagger.codegen.maven.plugin.output",
            defaultValue = "${project.build.directory}/generated-sources/swagger")
    private File output;

    /**
     * Location of the swagger spec, as URL or file.
     */
    @Parameter(name = "inputSpec", required = true)
    private String inputSpec;

    /**
     * Folder containing the template files.
     */
    @Parameter(name = "templateDirectory")
    private File templateDirectory;

    /**
     * Adds authorization headers when fetching the swagger definitions remotely.
     " Pass in a URL-encoded string of name:header with a comma separating multiple values
     */
    @Parameter(name="auth")
    private String auth;

    /**
     * Path to separate json configuration file.
     */
    @Parameter(name = "configurationFile", required = false)
    private String configurationFile;

    /**
     * Specifies if the existing files should be overwritten during the generation.
     */
    @Parameter(name="skipOverwrite", required=false)
    private Boolean skipOverwrite;

    /**
     * The package to use for generated api objects/classes
     */
    @Parameter(name = "apiPackage")
    private String apiPackage;

    /**
     * The package to use for generated model objects/classes
     */
    @Parameter(name = "modelPackage")
    private String modelPackage;

    /**
     * The package to use for the generated invoker objects
     */
    @Parameter(name = "invokerPackage")
    private String invokerPackage;

    /**
     * groupId in generated pom.xml
     */
    @Parameter(name = "groupId")
    private String groupId;

    /**
     * artifactId in generated pom.xml
     */
    @Parameter(name = "artifactId")
    private String artifactId;

    /**
     * artifact version in generated pom.xml
     */
    @Parameter(name = "artifactVersion")
    private String artifactVersion;

    /**
     * Sets the library
     */
    @Parameter(name = "library", required = false)
    private String library;

    /**
     * Sets the prefix for model enums and classes
     */
    @Parameter(name = "modelNamePrefix", required = false)
    private String modelNamePrefix;

    /**
     * Sets the suffix for model enums and classes
     */
    @Parameter(name = "modelNameSuffix", required = false)
    private String modelNameSuffix;

    /**
     * A map of language-specific parameters as passed with the -c option to the command line
     */
    @Parameter(name = "configOptions")
    private Map<?, ?> configOptions;

    /**
     * Add the output directory to the project as a source root, so that the
     * generated java types are compiled and included in the project artifact.
     */
    @Parameter(defaultValue = "true")
    private boolean addCompileSourceRoot = true;

    @Parameter
    protected Map<String, String> environmentVariables = new HashMap<String, String>();

    @Parameter
    private boolean configHelp = false;

    /**
     * The project being built.
     */
    @Parameter(readonly = true, required = true, defaultValue = "${project}")
    private MavenProject project;

    @Override
    public void execute() throws MojoExecutionException {

        //attempt to read from config file
        CodegenConfigurator configurator = CodegenConfigurator.fromFile(configurationFile);

        //if a config file wasn't specified or we were unable to read it
        if(configurator == null) {
            configurator = new CodegenConfigurator();
        }

        configurator.setVerbose(verbose);

        if(skipOverwrite != null) {
            configurator.setSkipOverwrite(skipOverwrite);
        }

        if(isNotEmpty(inputSpec)) {
            configurator.setInputSpec(inputSpec);
        }

        configurator.setLang(language);

        configurator.setOutputDir(output.getAbsolutePath());

        if(isNotEmpty(auth)) {
            configurator.setAuth(auth);
        }

        if(isNotEmpty(apiPackage)) {
            configurator.setApiPackage(apiPackage);
        }

        if(isNotEmpty(modelPackage)) {
            configurator.setModelPackage(modelPackage);
        }

        if(isNotEmpty(invokerPackage)) {
            configurator.setInvokerPackage(invokerPackage);
        }

        if(isNotEmpty(groupId)) {
            configurator.setGroupId(groupId);
        }

        if(isNotEmpty(artifactId)) {
            configurator.setArtifactId(artifactId);
        }

        if(isNotEmpty(artifactVersion)) {
            configurator.setArtifactVersion(artifactVersion);
        }

        if(isNotEmpty(library)) {
            configurator.setLibrary(library);
        }

        if(isNotEmpty(modelNamePrefix)) {
            configurator.setModelNamePrefix(modelNamePrefix);
        }

        if(isNotEmpty(modelNameSuffix)) {
            configurator.setModelNameSuffix(modelNameSuffix);
        }

        if (null != templateDirectory) {
            configurator.setTemplateDir(templateDirectory.getAbsolutePath());
        }

        if (configOptions != null) {

            if(configOptions.containsKey("instantiation-types")) {
                applyInstantiationTypesKvp(configOptions.get("instantiation-types").toString(), configurator);
            }

            if(configOptions.containsKey("import-mappings")) {
                applyImportMappingsKvp(configOptions.get("import-mappings").toString(), configurator);
            }

            if(configOptions.containsKey("type-mappings")) {
                applyTypeMappingsKvp(configOptions.get("type-mappings").toString(), configurator);
            }

            if(configOptions.containsKey("language-specific-primitives")) {
                applyLanguageSpecificPrimitivesCsv(configOptions.get("language-specific-primitives").toString(), configurator);
            }

            if(configOptions.containsKey("additional-properties")) {
                applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(), configurator);
            }
        }

        if (environmentVariables != null) {

            for(String key : environmentVariables.keySet()) {
                String value = environmentVariables.get(key);
                if(value == null) {
                    // don't put null values
                    value = "";
                }
                System.setProperty(key, value);
                configurator.addSystemProperty(key, value);
            }
        }

        final ClientOptInput input = configurator.toClientOptInput();
        final CodegenConfig config = input.getConfig();

        if(configOptions != null) {
            for (CliOption langCliOption : config.cliOptions()) {
                if (configOptions.containsKey(langCliOption.getOpt())) {
                    input.getConfig().additionalProperties().put(langCliOption.getOpt(),
                            configOptions.get(langCliOption.getOpt()));
                }
            }
        }

        if(configHelp) {
            for (CliOption langCliOption : config.cliOptions()) {
                System.out.println("\t" + langCliOption.getOpt());
                System.out.println("\t    " + langCliOption.getOptionHelp().replaceAll("\n", "\n\t    "));
                System.out.println();
            }
            return;
        }
        try {
            new DefaultGenerator().opts(input).generate();
        } catch (Exception e) {
            // Maven logs exceptions thrown by plugins only if invoked with -e
            // I find it annoying to jump through hoops to get basic diagnostic information,
            // so let's log it in any case:
            getLog().error(e);
            throw new MojoExecutionException("Code generation failed. See above for the full exception.");
        }

        if (addCompileSourceRoot) {
            project.addCompileSourceRoot(output.toString());
        }
    }
}


text:
package net.morimekta.providence.server;

import net.morimekta.providence.PApplicationException;
import net.morimekta.providence.PApplicationExceptionType;
import net.morimekta.providence.PProcessor;
import net.morimekta.providence.PServiceCall;
import net.morimekta.providence.PServiceCallHandler;
import net.morimekta.providence.PServiceCallType;
import net.morimekta.providence.mio.MessageReader;
import net.morimekta.providence.mio.MessageWriter;
import net.morimekta.providence.serializer.SerializerException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * Service processor wraps the service' Processor implementation of the
 * {@link PServiceCallHandler} so that it can read the service call message
 * parsed into a {@link PServiceCall}, and write the response with proper
 * exception handling.
 */
public class DefaultProcessorHandler implements ProcessorHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultProcessorHandler.class);

    private final PProcessor processor;

    /**
     * Wrap a service with a service call handler to work as the server side
     * of a providence service.
     *
     * @param processor The service call handler.
     */
    public DefaultProcessorHandler(@Nonnull PProcessor processor) {
        this.processor = processor;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void process(MessageReader reader, MessageWriter writer) throws IOException {
        PServiceCall call, reply;
        try {
            call = reader.read(processor.getDescriptor());
        } catch (SerializerException e) {
            if (e.getMethodName() != null) {
                LOGGER.error("Error when reading service call " + processor.getDescriptor().getName() + "." + e.getMethodName() + "()", e);
            } else {
                LOGGER.error("Error when reading service call " + processor.getDescriptor().getName(), e);
            }
            try {
                PApplicationException oe = new PApplicationException(e.getMessage(), e.getExceptionType());
                reply = new PServiceCall<>(e.getMethodName(), PServiceCallType.EXCEPTION, e.getSequenceNo(), oe);
                writer.write(reply);
                return;
            } catch (Exception e2) {
                e.addSuppressed(e2);
                throw e;
            }
        }

        if (call.getType() == PServiceCallType.REPLY || call.getType() == PServiceCallType.EXCEPTION) {
            try {
                PApplicationException oe = new PApplicationException("Invalid service request call type: " + call.getType(),
                                                                     PApplicationExceptionType.INVALID_MESSAGE_TYPE);
                reply = new PServiceCall(call.getMethod(), PServiceCallType.EXCEPTION, call.getSequence(), oe);
                writer.write(reply);
                return;
            } catch (Exception e) {
                throw new IOException("Unable to write error response", e);
            }
        }

        try {
            reply = processor.handleCall(call);
        } catch (Exception e) {
            LOGGER.error("Error when handling service call " + processor.getDescriptor().getName() + "." + call.getMethod() + "()", e);
            try {
                PApplicationException oe = new PApplicationException(e.getMessage(), PApplicationExceptionType.INTERNAL_ERROR);
                reply = new PServiceCall<>(call.getMethod(), PServiceCallType.EXCEPTION, call.getSequence(), oe);
                writer.write(reply);
                return;
            } catch (Exception e2) {
                e.addSuppressed(e2);
                throw e;
            }
        }

        if (reply != null) {
            try {
                writer.write(reply);
            } catch (SerializerException e) {
                LOGGER.error("Error when replying to service call " + processor.getDescriptor().getName() + "." + call.getMethod() + "()", e);
                try {
                    PApplicationException oe = new PApplicationException(e.getMessage(), e.getExceptionType());
                    reply = new PServiceCall<>(call.getMethod(), PServiceCallType.EXCEPTION, call.getSequence(), oe);
                    writer.write(reply);
                } catch (Exception e2) {
                    e.addSuppressed(e2);
                    throw e;
                }
            }
        }

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.douglaswhitehead.model.digitaldata.product</title>
<meta name="date" content="2015-11-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.douglaswhitehead.model.digitaldata.product

Interfaces

Product

Product.Builder

ProductInfo

ProductInfo.Builder

Classes

ProductImpl

ProductImpl.Builder

ProductInfoImpl

ProductInfoImpl.Builder


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>me.deweixu</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <name>spring-boot-demo</name>
    <description>spring-boot-demo</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.9</java.version>
    </properties>

    <modules>
        <module>demo-common</module>
        <module>demo-service</module>
        <module>demo-model</module>
        <module>demo-interface</module>
        <module>demo-web</module>
    </modules>

    <dependencyManagement>
        <dependencies>

            <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>6.0.3</version>
            </dependency>

            <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
            <dependency>
                <groupId>javax.xml.bind</groupId>
                <artifactId>jaxb-api</artifactId>
                <version>2.3.0</version>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <pluginManagement>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>repackage</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.7.0</version>
                        <configuration>
                            <source>1.9</source>
                            <target>1.9</target>
                            <jdkToolchain>
                                <version>9</version>
                            </jdkToolchain>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>

                </plugins>
        </pluginManagement>
    </build>

</project>


text:
using namespace Gwen;

class Checkbox : public GUnit
{
public:
	GWEN_CONTROL_INLINE(Checkbox, GUnit)
	{
		Gwen::Controls::CheckBox* check = new Gwen::Controls::CheckBox(this);
		check->SetPos(10, 10);
		check->onChecked.Add(this, &Checkbox::OnChecked);
		check->onUnChecked.Add(this, &Checkbox::OnUnchecked);
		check->onCheckChanged.Add(this, &Checkbox::OnCheckChanged);

		Gwen::Controls::CheckBoxWithLabel* labeled = new Gwen::Controls::CheckBoxWithLabel(this);
		labeled->SetPos(10, 10);
		labeled->Label()->SetText("Labeled CheckBox");
		labeled->Checkbox()->onChecked.Add(this, &Checkbox::OnChecked);
		labeled->Checkbox()->onUnChecked.Add(this, &Checkbox::OnUnchecked);
		labeled->Checkbox()->onCheckChanged.Add(this, &Checkbox::OnCheckChanged);
		Gwen::Align::PlaceBelow(labeled, check, 10);
	}

	void OnChecked(Controls::Base* pControl)
	{
		UnitPrint(L"Checkbox Checked (using 'OnChecked' event)");
	}

	void OnUnchecked(Controls::Base* pControl)
	{
		UnitPrint(L"Checkbox Unchecked (using 'OnUnchecked' event)");
	}

	void OnCheckChanged(Controls::Base* pControl)
	{
		UnitPrint(L"Checkbox CheckChanged (using 'OnCheckChanged' event)");
	}
};

DEFINE_UNIT_TEST(Checkbox, L"Checkbox");


text:
namespace Invoices.DataAccess
{
    public partial class ProductEditDto
    {
    }
}


text:
using System;

namespace FluentCommand.Import;

/// <summary>
/// Import field mapping
/// </summary>
public class ImportFieldMapping
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ImportFieldMapping"/> class.
    /// </summary>
    /// <param name="fieldDefinition">The definition.</param>
    public ImportFieldMapping(FieldDefinition fieldDefinition) : this(fieldDefinition, null)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="ImportFieldMapping"/> class.
    /// </summary>
    /// <param name="fieldDefinition">The field definition.</param>
    /// <param name="fieldMap">The field field map.</param>
    /// <exception cref="ArgumentNullException">definition is null</exception>
    public ImportFieldMapping(FieldDefinition fieldDefinition, FieldMap fieldMap)
    {
        if (fieldDefinition == null)
            throw new ArgumentNullException(nameof(fieldDefinition));

        Definition = fieldDefinition;
        FieldMap = fieldMap;
    }

    /// <summary>
    /// Gets the field definition.
    /// </summary>
    /// <value>
    /// The field definition.
    /// </value>
    public FieldDefinition Definition { get; }

    /// <summary>
    /// Gets the field mapping.
    /// </summary>
    /// <value>
    /// The field mapping.
    /// </value>
    public FieldMap FieldMap { get; }
}


text:
package io.realm.internal.fields;

import java.util.List;
import java.util.Locale;
import java.util.Set;

import io.realm.RealmFieldType;
import io.realm.internal.Table;

/**
 * A field descriptor that uses dynamic table lookup.
 * Use when cache cannot be trusted...
 */
class DynamicFieldDescriptor extends FieldDescriptor {
    private final Table table;

    /**
     * Build a dynamic field descriptor for the passed field description string.
     *
     * @param table the start table.
     * @param fieldDescription the field description.
     * @param validInternalColumnTypes valid types for the last field in the field description.
     * @param validFinalColumnTypes valid types for the last field in the field description.
     */
    DynamicFieldDescriptor(Table table, String fieldDescription, Set<RealmFieldType> validInternalColumnTypes, Set<RealmFieldType> validFinalColumnTypes) {
        super(fieldDescription, validInternalColumnTypes, validFinalColumnTypes);
        this.table = table;
    }

    @Override
    protected void compileFieldDescription(List<String> fields) {
        final int nFields = fields.size();
        long[] columnIndices = new long[nFields];

        Table currentTable = table;
        String currentClassName = null;
        String currentColumnName = null;
        RealmFieldType currentColumnType = null;
        for (int i = 0; i < nFields; i++) {
            currentColumnName = fields.get(i);
            if ((currentColumnName == null) || (currentColumnName.length() <= 0)) {
                throw new IllegalArgumentException(
                        "Invalid query: Field descriptor contains an empty field.  A field description may not begin with or contain adjacent periods ('.').");
            }

            currentClassName = currentTable.getClassName();

            final long columnIndex = currentTable.getColumnIndex(currentColumnName);
            if (columnIndex < 0) {
                throw new IllegalArgumentException(
                        String.format(Locale.US, "Invalid query: field '%s' not found in table '%s'.", currentColumnName, currentClassName));
            }

            currentColumnType = currentTable.getColumnType(columnIndex);
            if (i < nFields - 1) {
                verifyInternalColumnType(currentClassName, currentColumnName, currentColumnType);
                currentTable = currentTable.getLinkTarget(columnIndex);
            }

            columnIndices[i] = columnIndex;
        }

        setCompilationResults(currentClassName, currentColumnName, currentColumnType, columnIndices, new long[nFields]);
    }
}


text:
using UnityEngine;
using System.Collections;

public class StemMesh : MonoBehaviour {

  const int TRIANGLE_INDICES_PER_QUAD = 6;
  const int VERTICES_PER_QUAD = 4;

  public Collider[] segments;
  public int sides = 4;
  public AnimationCurve stemCurve;
  public float growthProgress = 0.0f;
  public float stumpDiminishTime = 2.0f;

  private Vector3[] vertices_;
  private bool[] broken;
  private float stump_width_ = 1.0f;
  private bool is_diminishing_ = false;

  void Start () {
    broken = new bool[segments.Length];
    for (int i = 0; i < broken.Length; ++i)
      broken[i] = false;

    MeshFilter filter = GetComponent<MeshFilter>();
    filter.mesh = new Mesh();
    InitMesh();
    filter.mesh.RecalculateBounds();
    filter.mesh.RecalculateNormals();
  }

  void Update () {
    UpdateMesh();
    MeshFilter filter = GetComponent<MeshFilter>();

    filter.mesh.MarkDynamic();
    filter.mesh.vertices = vertices_;
    filter.mesh.RecalculateBounds();
    filter.mesh.RecalculateNormals();
  }

  public bool IsBroken() {
    if (broken == null)
      return false;

    for (int i = 0; i < broken.Length; ++i) {
      if (broken[i])
        return true;
    }
    return false;
  }

  public bool IsStumpClear() {
    return stump_width_ == 0.0f;
  }

  public void RemoveStump() {
    is_diminishing_ = true;
  }

  private void InitMesh() {
    Mesh mesh = GetComponent<MeshFilter>().mesh;

    int num_vertices = sides * segments.Length;
    vertices_ = new Vector3[num_vertices];
    Vector2[] uv = new Vector2[num_vertices];

    int[] triangles = new int[TRIANGLE_INDICES_PER_QUAD * (num_vertices - sides)];

    for (int v = 0; v < num_vertices; ++v) {
      vertices_[v] = new Vector3(0, 0, 0);
      uv[v] = new Vector3(0, 0, 0);
    }

    int vertex_index = 0;
    for (int seg = 0; seg < segments.Length - 1; ++seg) {
      if (segments[seg + 1].GetComponent<HingeJoint>() == null) {
        for (int i = 0; i < sides * TRIANGLE_INDICES_PER_QUAD; ++i)
          triangles[vertex_index++] = 0;
      }
      else {
        for (int side = 0; side < sides; ++side) {
          int next_side = (side + 1) % sides;
          triangles[vertex_index++] = sides * seg + side;
          triangles[vertex_index++] = sides * seg + next_side;
          triangles[vertex_index++] = sides * (seg + 1) + next_side;

          triangles[vertex_index++] = sides * seg + side;
          triangles[vertex_index++] = sides * (seg + 1) + next_side;
          triangles[vertex_index++] = sides * (seg + 1) + side;
        }
      }
    }

    mesh.vertices = vertices_;
    mesh.uv = uv;
    mesh.triangles = triangles;
  }

  protected void Separate(int index) {
    for (int i = 0; i < index; ++i)
      segments[i] = null;
  }

  private void Break(int index) {
    for (int i = index; i < segments.Length; ++i) {
      segments[i] = null;
    }
  }

  private void KillStump() {
    for (int i = 0; i < broken.Length && !broken[i]; ++i)
      segments[i].collider.enabled = false;
  }

  private void UpdateMesh() {
    if (is_diminishing_ && stump_width_ != 0.0f) {
      stump_width_ -= Time.deltaTime / stumpDiminishTime;
      stump_width_ = Mathf.Clamp(stump_width_, 0.0f, 1.0f);
      if (stump_width_ == 0.0f)
        KillStump();
    }

    for (int i = 0; i < segments.Length; ++i) {
      if (!broken[i] && segments[i].GetComponent<HingeJoint>() == null) {
        InitMesh();
        broken[i] = true;
      }
    }

    int vertex_index = 0;
    float angle = 360.0f / sides;

    bool is_stump = true;
    for (int i = 0; i < segments.Length; ++i) {
      float phase = (1.0f * i) / (segments.Length - 1);
      float width = Mathf.Clamp(segments.Length * growthProgress - i, 0.0f, 1.0f);

      is_stump = is_stump && !broken[i];
      if (is_stump)
        width *= stump_width_;

      Vector3 offset = new Vector3(width * stemCurve.Evaluate(phase), 0, 0);

      for (int side = 0; side < sides; ++side) {
        vertices_[vertex_index++] =
            transform.InverseTransformPoint(segments[i].transform.TransformPoint(offset));
        offset = Quaternion.AngleAxis(angle, Vector3.up) * offset;
      }
    }
  }
}


text:
'use strict';

var ResourceFactory = require('../ResourceFactory');

var TextAd = function(adbutler) {
    return ResourceFactory.makeResource.call(adbutler, '/text-ads');
};

// Custom Resource Methods
// TextAd.customMethod1 = function() {};
// TextAd.customMethod2 = function() {};

module.exports = TextAd;


text:
const unsigned int max_message_size = 16384;
/// Maximum size of incoming requests/responses (message: protocol message)
const unsigned int max_raw_message_size = 12288;

struct ConnInfo
{
    std::string address;
    std::string port;
    bool isInet;
};

extern int createFastCGISocket(void);

extern ConnInfo getBindAddress(void);
extern ConnInfo getBrokerAddress(void);
extern unsigned int getNThreads(void);

# endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.capitalone.dashboard</groupId>
	<artifactId>jira-feature-collector</artifactId>
	<packaging>jar</packaging>
	<version>1.0.1</version>
	<name>jira-feature-collector</name>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.7</java.version>
		<junit.version>4.11</junit.version>
		<final.name>jira-feature-collector</final.name>
	</properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.1.RELEASE</version>
	</parent>

	<scm>
		<connection></connection>
		<developerConnection></developerConnection>
		<url></url>
		<tag>HEAD</tag>
	</scm>

	<distributionManagement>
		<repository>
			<id>nexus</id>
			<url></url>
		</repository>
		<snapshotRepository>
			<id>nexus</id>
			<url></url>
		</snapshotRepository>
	</distributionManagement>

	<!-- Package as an executable jar -->
	<build>
		<finalName>${final.name}</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.sonatype.plugins</groupId>
				<artifactId>nexus-staging-maven-plugin</artifactId>
				<version>1.6.3</version>
				<extensions>true</extensions>
				<configuration>
					<serverId>nexus</serverId>
					<nexusUrl></nexusUrl>
					<stagingProgressTimeoutMinutes>15</stagingProgressTimeoutMinutes>
					<stagingProgressPauseDurationSeconds>15</stagingProgressPauseDurationSeconds>
				</configuration>
			</plugin>
		</plugins>

		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
			</testResource>
		</testResources>
	</build>

	<dependencies>
		<!-- Project Deps -->
		<dependency>
			<groupId>com.capitalone.dashboard</groupId>
			<artifactId>core</artifactId>
			<version>0.4.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
			<version>1.1.1</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>

		<!-- Unit Testing and Mocks -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>testing</scope>
		</dependency>

		<!-- Jira Connection Transient Dependencies -->
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client</artifactId>
			<version>1.14.1-beta</version>
		</dependency>
		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client-jackson2</artifactId>
			<version>1.14.1-beta</version>
		</dependency>
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client-java7</artifactId>
			<version>1.14.1-beta</version>
		</dependency>

		<!-- String Template (ST Readers) -->
		<dependency>
			<groupId>org.antlr</groupId>
			<artifactId>ST4</artifactId>
			<version>4.0.8</version>
		</dependency>
		<dependency>
			<groupId>org.antlr</groupId>
			<artifactId>antlr4-runtime</artifactId>
			<version>4.3</version>
		</dependency>
		<dependency>
			<groupId>org.scala-lang</groupId>
			<artifactId>scala-library</artifactId>
			<version>2.10.4</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.findbugs</groupId>
			<artifactId>findbugs</artifactId>
			<version>3.0.1</version>
		</dependency>

		<!-- Logging Dependencies -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
	</dependencies>
</project>


text:
const Timer = require('timer-shim').Timer

module.exports = function () {
  const timer = new Timer()
  timer.pause()

  return {
    setTimeout: timer.setTimeout,
    clearTimeout: timer.clearTimeout,
    setInterval: timer.setInterval,
    clearInterval: timer.clearInterval,
    wind: timer.wind
  }
}


text:
package core.classes.clinic;
import java.util.Date;

import core.classes.opd.PrescribeItem;
import core.classes.opd.Prescription;

public class clinic_patient_treatment {

	private int treatment_id;
	private clinic_visit clinic_visit_id;
	private Date clinic_date;
	private Prescription prescriptionItems_ID;
	private String clinic_doc;
	private String clinic_diagnosis;
	private String clinic_remarks;

	public int getTreatment_id() {
		return treatment_id;
	}
	public void setTreatment_id(int treatment_id) {
		this.treatment_id = treatment_id;
	}
	public clinic_visit getClinic_visit_id() {
		return clinic_visit_id;
	}
	public void setClinic_visit_id(clinic_visit clinic_visit_id) {
		this.clinic_visit_id = clinic_visit_id;
	}
	public Date getClinic_date() {
		return clinic_date;
	}
	public void setClinic_date(Date clinic_date) {
		this.clinic_date = clinic_date;
	}
	public Prescription getPrescriptionItems_ID() {
		return prescriptionItems_ID;
	}
	public void setPrescriptionItems_ID(Prescription prescriptionItems_ID) {
		this.prescriptionItems_ID = prescriptionItems_ID;
	}
	public String getClinic_doc() {
		return clinic_doc;
	}
	public void setClinic_doc(String clinic_doc) {
		this.clinic_doc = clinic_doc;
	}
	public String getClinic_diagnosis() {
		return clinic_diagnosis;
	}
	public void setClinic_diagnosis(String clinic_diagnosis) {
		this.clinic_diagnosis = clinic_diagnosis;
	}
	public String getClinic_remarks() {
		return clinic_remarks;
	}
	public void setClinic_remarks(String clinic_remarks) {
		this.clinic_remarks = clinic_remarks;
	}

}


text:
package org.glowroot.agent.plugin.jsp;

class HttpJspPages {

    // this is a (configurable) constant in org.apache.jasper.Constants.JSP_PACKAGE_NAME
    private static final String ORG_APACHE_JSP = "org.apache.jsp";
    private static final String TRAILING_JSP = "_jsp";
    // 002d is hex encoding for illegal class name character '-'
    private static final String WEB_INF = "WEB_002dINF";

    private HttpJspPages() {}

    static String getFilename(Class<?> jspClass) {
        String name = jspClass.getName();
        if (name.startsWith(ORG_APACHE_JSP)) {
            // TODO which application servers does this cover?
            name = name.substring(ORG_APACHE_JSP.length()).replace('.', '/');
            if (name.endsWith(TRAILING_JSP)) {
                name = name.substring(0, name.length() - TRAILING_JSP.length()) + ".jsp";
            }
            int index = name.indexOf(WEB_INF);
            if (index != -1) {
                name = name.substring(0, index) + "WEB-INF"
                        + name.substring(index + WEB_INF.length());
            }
        } else {
            // fallback
            int index = name.lastIndexOf('.');
            if (index != -1) {
                name = name.substring(index + 1);
            }
        }
        return name;
    }
}


text:
package gov.nih.nci.cagrid.fqp;

import java.util.HashMap;
import java.util.Map;

import gov.nih.nci.cagrid.fqp.common.TimeLimitedCache;
import junit.framework.TestCase;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

public class TimeLimitedCacheTestCase extends TestCase {

    public TimeLimitedCacheTestCase(String name) {
        super(name);
    }

    public void testCacheSizeLimit() {
        // create a cache with max of 3 items
        TimeLimitedCache<String, String> cache = new TimeLimitedCache<String, String>(Long.MAX_VALUE, 3);
        // map to hang on to everything
        Map<String, String> map = new HashMap<String, String>();

        // put four items in the cache and map, verify only three are available in the map
        for (int i = 0; i < 4; i++) {
            String key = "key" + i;
            String val = "value" + i;
            cache.cacheItem(key, val);
            map.put(key, val);
        }

        // go through the keys again, verifying the returned object is null for 0,
        // and == what's in the map for the rest
        for (int i = 0; i < 4; i++) {
            String key = "key" + i;
            String val = map.get(key);
            assertNotNull("Map should have contained a value for " + key, val);
            String cached = cache.getItem(key);
            if (i == 0) {
                assertNull("Cache should have removed item", cached);
            } else {
                assertNotNull("Cache removed item for key " + key + " but should not have");
                assertEquals("Cached item was not as expected", val, cached);
            }
        }
    }

    public void testCacheTimeout() {
        // create a cache with a 1 second timeout
        TimeLimitedCache<String, String> cache = new TimeLimitedCache<String, String>(1000);
        // put four items in the cache
        for (int i = 0; i < 4; i++) {
            String key = "key" + i;
            String val = "value" + i;
            cache.cacheItem(key, val);
        }
        // wait 2000 ms for the items in the cache to age
        sleep(2000);
        // verify everything in the cache is gone
        for (int i = 0; i < 4; i++) {
            String key = "key" + i;
            String val = cache.getItem(key);
            assertNull("Cache should have removed old item, but did not for key " + key, val);
        }
    }

    private void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException ex) {
            // meh
        }
    }

    public static void main(String[] args) {
        TestRunner runner = new TestRunner();
        TestResult result = runner.doRun(new TestSuite(TimeLimitedCacheTestCase.class));
        System.exit(result.errorCount() + result.failureCount());
    }

}


text:
namespace QwLua.Reflection
{
    public static class MethodExtensions
    {
    }
}


text:
layout: post
title: Hot Unknown Stud #1 Hard jack-hammer fuck
titleinfo: pornvd
desc: Watch Hot Unknown Stud #1 Hard jack-hammer fuck. Pornhub is the ultimate xxx porn and sex site.
---

Hot Unknown Stud #1 Hard jack-hammer fuck

Watch Hot Unknown Stud #1 Hard jack-hammer fuck. Pornhub is the ultimate xxx porn and sex site.


text:
package com.forec.realtime.unsafe;

import org.apache.log4j.Logger;

/**
 * Not thread safe
 * @author Ettore Majorana
 *
 */

@SuppressWarnings("restriction")
public class MatrixHandler {

	private static final Logger log = Logger.getLogger(MatrixHandler.class);
	protected final static long UNSET = -1l;
	private final static long LONG_SIZE_IN_BYTES = 8;
	private final long[] indexes;
	private final int rows;
	private final int columns;
	private int currShift;

	protected MatrixHandler(int rows, int columns){
		this.indexes = new long[rows];
		this.rows = rows;
		this.columns = columns;
		this.currShift = 0;
		for (int i = 0; i < rows; i++) {
			long startIndex = UnsafeHolder.getUnsafe().allocateMemory(LONG_SIZE_IN_BYTES * (long)columns);
			indexes[i] = startIndex;
		}
	}

	protected void set(int row, int column, long value){
		if(row >= rows){
			throw new IllegalArgumentException("Row in input is greater than maximum allowed");
		}
		if(column >= columns){
			throw new IllegalArgumentException("Column in input is greater than maximum allowed");
		}
		row = shiftedRow(row);
		long offset = calcOffset(row,column);
		log.debug(String.format("set [%d,%d] = %d",row,column,value));
		UnsafeHolder.getUnsafe().putLong(offset, value);
	}

	protected long get(int row, int column){
		row = shiftedRow(row);
		long offset = calcOffset(row, column);
		long value = UnsafeHolder.getUnsafe().getLong(offset);
		log.debug(String.format("get [%d,%d] = %d",row,column,value));
		return value;
	}

	private int shiftedRow(int row) {
		return (row + currShift) % (rows);
	}

	public void destroy(){
		for(int i = 0; i < rows; i++){
			UnsafeHolder.getUnsafe().freeMemory(indexes[i]);
		}
	}

	private long calcOffset(int row, int column) {
		return indexes[row] + column*LONG_SIZE_IN_BYTES;
	}

	protected void shift() {
		currShift = (currShift + 1) % (indexes.length-1);
	}

	protected void copy(int dest, int source){
		for(int i = 0; i < columns; i++){
			long value = get(source, i);
			set(dest, i, value);
		}
	}

}


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.10
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

package com.badlogic.gdx.physics.bullet;

import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Matrix3;
import com.badlogic.gdx.math.Matrix4;

public class btBvhSubtreeInfo extends BulletBase {
	private long swigCPtr;

	protected btBvhSubtreeInfo(final String className, long cPtr, boolean cMemoryOwn) {
		super(className, cPtr, cMemoryOwn);
		swigCPtr = cPtr;
	}

	protected btBvhSubtreeInfo(long cPtr, boolean cMemoryOwn) {
		this("btBvhSubtreeInfo", cPtr, cMemoryOwn);
		construct();
	}

	public static long getCPtr(btBvhSubtreeInfo obj) {
		return (obj == null) ? 0 : obj.swigCPtr;
	}

	@Override
	protected void finalize() throws Throwable {
		if (!destroyed)
			destroy();
		super.finalize();
	}

  @Override protected synchronized void delete() {
		if (swigCPtr != 0) {
			if (swigCMemOwn) {
				swigCMemOwn = false;
				gdxBulletJNI.delete_btBvhSubtreeInfo(swigCPtr);
			}
			swigCPtr = 0;
		}
		super.delete();
	}

  public void setQuantizedAabbMin(int[] value) {
    gdxBulletJNI.btBvhSubtreeInfo_quantizedAabbMin_set(swigCPtr, this, value);
  }

  public int[] getQuantizedAabbMin() {
    return gdxBulletJNI.btBvhSubtreeInfo_quantizedAabbMin_get(swigCPtr, this);
  }

  public void setQuantizedAabbMax(int[] value) {
    gdxBulletJNI.btBvhSubtreeInfo_quantizedAabbMax_set(swigCPtr, this, value);
  }

  public int[] getQuantizedAabbMax() {
    return gdxBulletJNI.btBvhSubtreeInfo_quantizedAabbMax_get(swigCPtr, this);
  }

  public void setRootNodeIndex(int value) {
    gdxBulletJNI.btBvhSubtreeInfo_rootNodeIndex_set(swigCPtr, this, value);
  }

  public int getRootNodeIndex() {
    return gdxBulletJNI.btBvhSubtreeInfo_rootNodeIndex_get(swigCPtr, this);
  }

  public void setSubtreeSize(int value) {
    gdxBulletJNI.btBvhSubtreeInfo_subtreeSize_set(swigCPtr, this, value);
  }

  public int getSubtreeSize() {
    return gdxBulletJNI.btBvhSubtreeInfo_subtreeSize_get(swigCPtr, this);
  }

  public void setPadding(int[] value) {
    gdxBulletJNI.btBvhSubtreeInfo_padding_set(swigCPtr, this, value);
  }

  public int[] getPadding() {
    return gdxBulletJNI.btBvhSubtreeInfo_padding_get(swigCPtr, this);
  }

  public btBvhSubtreeInfo() {
    this(gdxBulletJNI.new_btBvhSubtreeInfo(), true);
  }

  public void setAabbFromQuantizeNode(btQuantizedBvhNode quantizedNode) {
    gdxBulletJNI.btBvhSubtreeInfo_setAabbFromQuantizeNode(swigCPtr, this, btQuantizedBvhNode.getCPtr(quantizedNode), quantizedNode);
  }

}


text:
class Thing < ActiveRecord::Base

end


text:
In this lab, you will work with several tools from BCC to investigate an application that is supposed to be CPU-bound and active, but in fact spends up a lot of time off-CPU for some reason.

- - -

#### Task 1: Basic Workload Characterization

Run the following command to compile the target application:

```
$ gcc -g -std=gnu99 -fno-omit-frame-pointer -fno-inline -lpthread blocky.c -o blocky     # on Fedora
$ gcc -g -std=gnu99 -fno-omit-frame-pointer -fno-inline -pthread  blocky.c -o blocky     # on Ubuntu
```

Now, run `./blocky`. It prints out the number of requests processed, going at a nice pace. But is it really using all processors effectively? Run `top` (or `htop`) to find out -- it looks like the application is barely making a dent in CPU utilization. Most of the time, the system is idle.

- - -

#### Task 2: Profiling The CPU-Bound Part

> As with all BPF-based tools, you will need a root shell to run the following commands.

To understand where the application is spending CPU time (which, as we saw, is not most of the wall-clock time), run the following command:

```
# profile -F 997 -p $(pidof blocky)
```

> Note: The `profile` tool requires BCC support for `perf_events`, which was introduced in Linux 4.9. If you are running an older kernel, this tool will not work. You can use `perf record` instead, as discussed in [a previous lab](perf.md).

After a few seconds, hit Ctrl+C to stop the `profile` tool. The call stacks you get should point to the `request_processor` and `do_work` functions, which are supposed to burn a lot of CPU. But, as we saw above, there's something blocking the application from making progress.

> Bonus: You can also use `profile` to get flame graphs by using the `-f` switch, which will output folded stacks in the exact format that the flamegraph.pl script expects. If you have time, run `profile -F 997 -f -p $(pidof blocky) > folded-stacks`, hit Ctrl+C after a few seconds, and then run `flamegraph.pl folded-stacks > profile.svg` to generate the flame graph. It's important to mention that this method of generating flame graphs is a lot more efficient than using [`perf`](perf.md), because the stack aggregation (folding) is performed in-kernel rather than in user-space.

- - -

#### Task 3: Identifying On- and Off-CPU Time

To determine how much time the application is spending on-CPU and off-CPU, the `cpudist` tool can be very useful. It produces a histogram of time spent in each of the two CPU states, and helps understand the context-switching characteristics of your application. Let's run it:

```
# cpudist -p $(pidof blocky)
```

After a few seconds, hit Ctrl+C to get a report. You will probably see a bimodal distribution, with a mode around the quantum length on your system (which is typically in the 4-8ms bin), and another, bigger mode around very short intervals -- tens or hundreds of microseconds each. It is these smaller intervals that we should be worried about. These bursts of activity indicate that the application threads want to do some work, and are successful at doing it for a very short time, but then they get switched out.

Now, let's try to identify how long the application threads spend off-CPU, using the same tool:

```
# cpudist -O -p $(pidof blocky)
```

Again, hit Ctrl+C after a few seconds to get the histogram. You might get a bimodal distribution again, but the biggest mode this time is in the much longer bins -- 8-16ms and 16-32ms. Again, these are time intervals when some application thread was off the CPU waiting for something. So we have a great number of multi-millisecond waits. Where are these waits coming from?

- - -

#### Task 4: Getting Off-CPU Stacks

The `offcputime` tool from BCC can be used to answer this final question. It collects stack traces whenever an application thread is blocked (switched off the CPU), and identifies the duration of time that blockage lasted. The output can be interpreted as a flame graph, much like on-CPU data. Let's run it in folded mode to generate data suitable for producing a flame graph:

```
# offcputime -f -p $(pidof blocky) > folded-stacks
```

After a few seconds, hit Ctrl+C. At this point, you can also stop the blocky process. To generate a flame graph, run:

```
# FlameGraph/flamegraph.pl folded-stacks > offcpu.svg
```

Inspecting the flame graph should show two sources of contention: one in the `backend_handler` function, which calls `nanosleep`, and another in the `request_processor` function, which calls `__lll_lock_wait`, which calls the `futex` syscall. These are specific, identifiable places in the source code that can now be inspected to understand why they're causing blockages. If you review [blocky.c](blocky.c), you'll find that the `backend_handler` function is the main culprit: it acquires a lock which the `request_processor` threads also require to make progress, and then occasionally sleeps while holding the lock!

- - -


text:
require 'test_helper'

class GithubBasicDetectiveTest < ActiveSupport::TestCase
  setup do
    @full_name = 'ciitest/test-repo'
    @repo_name = 'test-repo'
    @description = 'This is for testing the CII Best Practices BadgeApp'
    @evidence = Evidence.new({})
    @repo_url = "https://github.com/#{@full_name}"
  end

  # rubocop:disable Metrics/BlockLength
  test 'Mocked GitHub retrieves name, description (no emojis), and license' do
    VCR.use_cassette('unit_test_github_basic_detective') do
      detective = GithubBasicDetective.new
      results = detective.analyze(@evidence, repo_url: @repo_url)

      assert results.key?(:name)
      assert results[:name].key?(:value)
      assert_equal @repo_name, results[:name][:value]

      assert results.key?(:description)
      assert results[:description].key?(:value)
      assert_equal @description, results[:description][:value]

      assert results.key?(:license)
      assert results[:license].key?(:value)
      assert_equal 'MIT', results[:license][:value]

      # Did we correctly determine the implementation language of our
      # stub test project by ciitest?
      assert_equal 'Python', results[:implementation_languages][:value]

      # Do several unit tests of language_cleanup, it's more complex.
      # This does not invoke network calls, we are directly providing
      # test values to more thoroughly test the method language_cleanup.
      assert_equal '', detective.language_cleanup({})
      assert_equal 'C', detective.language_cleanup(C: 1000) # singleton
      # We need to use the older hash syntax to spell some names
      # rubocop:disable Style/HashSyntax
      assert_equal 'C++, C', detective.language_cleanup( # actually sorts
        C: 1000, :"C++" => 5000
      )
      assert_equal 'C#, JavaScript', detective.language_cleanup(
        HTML: 1000, :"C#" => 5000, JavaScript: 800
      )
      # This is the list from https://api.github.com/repos/
      # assimilation/assimilation-official/languages
      assert_equal 'Python, C, Shell, C++, CMake, C#, Ruby',
                   detective.language_cleanup(
                     Python: 1_151_127,
                     C: 1_059_779,
                     Shell: 285_358,
                     :"C++" => 44_086,
                     CMake: 33_855,
                     :"C#" => 29_834,
                     HTML: 2_290,
                     Ruby: 1_359
                   )
      # rubocop:enable Style/HashSyntax
    end
  end
  # rubocop:enable Metrics/BlockLength
end


text:
/**
* Adds days to a date object.
*
* @param {Date} date - The date where the function will add the days passed by parameter.
* @param {Number} days - The number of days that will be added to the date object.
*/
var addDays = function (date, days) {
	date.setDate(date.getDate() + days);
};

/**
* Clones a date object.
*
* @param {Date} date - The date which will be cloned.
* @returns {Date} A date object cloned from the source date object.
*/
var clone = function (date) {
    try {
        var copy;

        if (null == date || "object" != typeof date) {
            return date;
        }

        if (date instanceof Date) {
            copy = new Date();
            copy.setTime(date.getTime());
            return copy;
        }
    } catch (ex) {
        throw new Error("An error ocurred cloning the date object");
    }
};

/**
* Creates a list of years from an initial year to the current year passed by parameter.
*
* @param {Number} currentYear - The current year.
* @returns {Array} Array of years.
*/
var getYears = function (currentYear) {
	var years = [],
		initialYear = 2000,
		startYear =  initialYear || 1980;

	while (startYear <= (currentYear + 1)) {
		years.push(startYear++);
	}

	return years;
};

/**
* Gets the sunday of the current week.
*
* @returns {Date} Date object which represents the sunday of the current week.
*/
var getSundayOfCurrentWeek = function () {
	var currentDate = new Date(),
		day = currentDate.getDay(),
		diff = currentDate.getDate() - day + (day == 0 ? -7 : 0); // adjust when day is sunday
	return new Date(currentDate.setDate(diff));
};

/**
* Gets the current week number of the current year.
*
* @returns {Number} Current week number.
*/
var getCurrentWeekNumber = function () {
	var date = new Date();
	date.setHours(0, 0, 0);
	date.setDate(date.getDate() + 4 - (date.getDay() || 7));
	return Math.ceil((((date - new Date(date.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);
};

/**
* Creates a list of years from an initial year to the current year passed by parameter.
*
* @param {Number} year - The year of the month.
* @param {Number} month - The month where we want to have the weeks.
* @returns {Array} Array of weeks by month.
*/
var getWeeksByMonth = function (year, month) {
	var firstDate = new Date(year, month, 1),
		numDays = new Date(year, month + 1, 0).getDate(),
		sunday = new Date(firstDate.setDate(firstDate.getDate() - firstDate.getDay())),
		weeksArray = [new Date(sunday)],
		weeksByMonthArray = [],
		start = 1,
		end = 7 - firstDate.getDay();

	while (start <= numDays) {
		while (sunday.setDate(sunday.getDate() + 1) && sunday.getDay() !== 0) {
			weeksArray.push(new Date(sunday));
		}

		weeksByMonthArray.push(weeksArray);

		start = end + 1;
		end = end + 7;
		firstDate = new Date(year, month, start);
		sunday = new Date(firstDate.setDate(firstDate.getDate() - firstDate.getDay()));
		weeksArray = [new Date(sunday)];

		if (end > numDays) {
			end = numDays;
		}
	}

	return weeksByMonthArray;
};

//Returns all weeks per month in the year passed by parameter
/**
* Creates a list with all weeks by month in the year passed by parameter.
*
* @param {Number} year - The year which we want the weeks by month.
* @returns {Array} Array of weeks by year.
*/
var getWeeksByYear = function (year) {
	var weeksByYear = [],
		MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

	for (var i = 0; i < MONTHS.length; i++) { //Months
		var weeksByMonth = getWeeksByMonth(year, i);
		for (var j = 0; j < weeksByMonth.length; j++) { //weeksByYear
			weeksByYear.push(weeksByMonth[j]);
		}
	}

	return weeksByYear;
};


text:
<?php

class Google_Service_Reports_UsageReports extends Google_Collection
{
  protected $collection_key = 'warnings';
  public $etag;
  public $kind;
  public $nextPageToken;
  protected $usageReportsType = 'Google_Service_Reports_UsageReport';
  protected $usageReportsDataType = 'array';
  protected $warningsType = 'Google_Service_Reports_UsageReportsWarnings';
  protected $warningsDataType = 'array';

  public function setEtag($etag)
  {
    $this->etag = $etag;
  }
  public function getEtag()
  {
    return $this->etag;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  public function setUsageReports($usageReports)
  {
    $this->usageReports = $usageReports;
  }
  public function getUsageReports()
  {
    return $this->usageReports;
  }
  public function setWarnings($warnings)
  {
    $this->warnings = $warnings;
  }
  public function getWarnings()
  {
    return $this->warnings;
  }
}


text:
package org.msbotframework4j.connector;

/**
 * @author Maksim Kanev
 */
public class BotConnectorApiException extends RuntimeException {

  public BotConnectorApiException() {
  }

  public BotConnectorApiException(String message) {
    super(message);
  }

  public BotConnectorApiException(String message, Throwable cause) {
    super(message, cause);
  }
}


text:
from typing import List, Optional

from flask import Response, request
from marshmallow import ValidationError
from sqlalchemy import func

from airflow.api_connexion import security
from airflow.api_connexion.exceptions import BadRequest, NotFound
from airflow.api_connexion.parameters import check_limit, format_parameters
from airflow.api_connexion.schemas.variable_schema import variable_collection_schema, variable_schema
from airflow.models import Variable
from airflow.security import permissions
from airflow.utils.session import provide_session

@security.requires_access([(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_VARIABLE)])
def delete_variable(variable_key: str) -> Response:
    """Delete variable"""
    if Variable.delete(variable_key) == 0:
        raise NotFound("Variable not found")
    return Response(status=204)

@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE)])
def get_variable(variable_key: str) -> Response:
    """Get a variables by key"""
    try:
        var = Variable.get(variable_key)
    except KeyError:
        raise NotFound("Variable not found")
    return variable_schema.dump({"key": variable_key, "val": var})

@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_VARIABLE)])
@format_parameters({'limit': check_limit})
@provide_session
def get_variables(session, limit: Optional[int], offset: Optional[int] = None) -> Response:
    """Get all variable values"""
    total_entries = session.query(func.count(Variable.id)).scalar()
    query = session.query(Variable).order_by(Variable.id)
    if offset:
        query = query.offset(offset)
    if limit:
        query = query.limit(limit)
    variables = query.all()
    return variable_collection_schema.dump(
        {
            "variables": variables,
            "total_entries": total_entries,
        }
    )

@security.requires_access([(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_VARIABLE)])
def patch_variable(variable_key: str, update_mask: Optional[List[str]] = None) -> Response:
    """Update a variable by key"""
    try:
        data = variable_schema.load(request.json)
    except ValidationError as err:
        raise BadRequest("Invalid Variable schema", detail=str(err.messages))

    if data["key"] != variable_key:
        raise BadRequest("Invalid post body", detail="key from request body doesn't match uri parameter")

    if update_mask:
        if "key" in update_mask:
            raise BadRequest("key is a ready only field")
        if "value" not in update_mask:
            raise BadRequest("No field to update")

    Variable.set(data["key"], data["val"])
    return variable_schema.dump(data)

@security.requires_access([(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_VARIABLE)])
def post_variables() -> Response:
    """Create a variable"""
    try:
        data = variable_schema.load(request.json)

    except ValidationError as err:
        raise BadRequest("Invalid Variable schema", detail=str(err.messages))
    Variable.set(data["key"], data["val"])
    return variable_schema.dump(data)