text:
package jj2000.j2k.wavelet.synthesis;

import jj2000.j2k.image.DataBlk;

/**
 * This extends the synthesis wavelet filter general definitions of
 * SynWTFilter by adding methods that work for int data
 * specifically. Implementations that work on int data should inherit
 * from this class.
 *
 *
See the SynWTFilter class for details such as
 * normalization, how to split odd-length signals, etc.
 *
 *
The advantage of using the specialized method is that no casts
 * are performed.
 *
 * @see SynWTFilter
 * */
public abstract class SynWTFilterInt extends SynWTFilter {

    /**
     * A specific version of the synthetize_lpf() method that works on int
     * data. See the general description of the synthetize_lpf() method in the
     * SynWTFilter class for more details.
     *
     * @param lowSig This is the array that contains the low-pass
     * input signal.
     *
     * @param lowOff This is the index in lowSig of the first sample to
     * filter.
     *
     * @param lowLen This is the number of samples in the low-pass
     * input signal to filter.
     *
     * @param lowStep This is the step, or interleave factor, of the
     * low-pass input signal samples in the lowSig array.
     *
     * @param highSig This is the array that contains the high-pass
     * input signal.
     *
     * @param highOff This is the index in highSig of the first sample to
     * filter.
     *
     * @param highLen This is the number of samples in the high-pass
     * input signal to filter.
     *
     * @param highStep This is the step, or interleave factor, of the
     * high-pass input signal samples in the highSig array.
     *
     * @param outSig This is the array where the output signal is
     * placed. It should be long enough to contain the output signal.
     *
     * @param outOff This is the index in outSig of the element where
     * to put the first output sample.
     *
     * @param outStep This is the step, or interleave factor, of the
     * output samples in the outSig array.
     *
     * @see SynWTFilter#synthetize_lpf
     *
     *
     *
     *
     * */
    public abstract
        void synthetize_lpf(int[] lowSig, int lowOff, int lowLen, int lowStep,
                        int[] highSig, int highOff, int highLen, int highStep,
                        int[] outSig, int outOff, int outStep);

    /**
     * The general version of the synthetize_lpf() method, it just calls
     * the specialized version. See the description of the synthetize_lpf()
     * method of the SynWTFilter class for more details.
     *
     * @param lowSig This is the array that contains the low-pass
     * input signal. It must be an int[].
     *
     * @param lowOff This is the index in lowSig of the first sample to
     * filter.
     *
     * @param lowLen This is the number of samples in the low-pass
     * input signal to filter.
     *
     * @param lowStep This is the step, or interleave factor, of the
     * low-pass input signal samples in the lowSig array.
     *
     * @param highSig This is the array that contains the high-pass
     * input signal. Itmust be an int[].
     *
     * @param highOff This is the index in highSig of the first sample to
     * filter.
     *
     * @param highLen This is the number of samples in the high-pass
     * input signal to filter.
     *
     * @param highStep This is the step, or interleave factor, of the
     * high-pass input signal samples in the highSig array.
     *
     * @param outSig This is the array where the output signal is
     * placed. It should be and int[] and long enough to contain the
     * output signal.
     *
     * @param outOff This is the index in outSig of the element where
     * to put the first output sample.
     *
     * @param outStep This is the step, or interleave factor, of the
     * output samples in the outSig array.
     *
     * @see SynWTFilter#synthetize_lpf
     *
     *
     *
     *
     * */
    public
        void synthetize_lpf(Object lowSig, int lowOff, int lowLen, int lowStep,
                        Object highSig, int highOff, int highLen, int highStep,
                        Object outSig, int outOff, int outStep) {

        synthetize_lpf((int[])lowSig, lowOff, lowLen, lowStep,
                   (int[])highSig, highOff, highLen, highStep,
                   (int[])outSig, outOff, outStep);
        }

    /**
     * A specific version of the synthetize_hpf() method that works on int
     * data. See the general description of the synthetize_hpf() method in the
     * SynWTFilter class for more details.
     *
     * @param lowSig This is the array that contains the low-pass
     * input signal.
     *
     * @param lowOff This is the index in lowSig of the first sample to
     * filter.
     *
     * @param lowLen This is the number of samples in the low-pass
     * input signal to filter.
     *
     * @param lowStep This is the step, or interleave factor, of the
     * low-pass input signal samples in the lowSig array.
     *
     * @param highSig This is the array that contains the high-pass
     * input signal.
     *
     * @param highOff This is the index in highSig of the first sample to
     * filter.
     *
     * @param highLen This is the number of samples in the high-pass
     * input signal to filter.
     *
     * @param highStep This is the step, or interleave factor, of the
     * high-pass input signal samples in the highSig array.
     *
     * @param outSig This is the array where the output signal is
     * placed. It should be long enough to contain the output signal.
     *
     * @param outOff This is the index in outSig of the element where
     * to put the first output sample.
     *
     * @param outStep This is the step, or interleave factor, of the
     * output samples in the outSig array.
     *
     * @see SynWTFilter#synthetize_hpf
     *
     *
     *
     *
     * */
    public abstract
        void synthetize_hpf(int[] lowSig, int lowOff, int lowLen, int lowStep,
                        int[] highSig, int highOff, int highLen, int highStep,
                        int[] outSig, int outOff, int outStep);

    /**
     * The general version of the synthetize_hpf() method, it just calls
     * the specialized version. See the description of the synthetize_hpf()
     * method of the SynWTFilter class for more details.
     *
     * @param lowSig This is the array that contains the low-pass
     * input signal. It must be an int[].
     *
     * @param lowOff This is the index in lowSig of the first sample to
     * filter.
     *
     * @param lowLen This is the number of samples in the low-pass
     * input signal to filter.
     *
     * @param lowStep This is the step, or interleave factor, of the
     * low-pass input signal samples in the lowSig array.
     *
     * @param highSig This is the array that contains the high-pass
     * input signal. Itmust be an int[].
     *
     * @param highOff This is the index in highSig of the first sample to
     * filter.
     *
     * @param highLen This is the number of samples in the high-pass
     * input signal to filter.
     *
     * @param highStep This is the step, or interleave factor, of the
     * high-pass input signal samples in the highSig array.
     *
     * @param outSig This is the array where the output signal is
     * placed. It should be and int[] and long enough to contain the
     * output signal.
     *
     * @param outOff This is the index in outSig of the element where
     * to put the first output sample.
     *
     * @param outStep This is the step, or interleave factor, of the
     * output samples in the outSig array.
     *
     * @see SynWTFilter#synthetize_hpf
     *
     *
     *
     *
     * */
    public
        void synthetize_hpf(Object lowSig, int lowOff, int lowLen, int lowStep,
                        Object highSig, int highOff, int highLen, int highStep,
                        Object outSig, int outOff, int outStep) {

        synthetize_hpf((int[])lowSig, lowOff, lowLen, lowStep,
                   (int[])highSig, highOff, highLen, highStep,
                   (int[])outSig, outOff, outStep);
        }

    /**
     * Returns the type of data on which this filter works, as defined
     * in the DataBlk interface, which is always TYPE_INT for this
     * class.
     *
     * @return The type of data as defined in the DataBlk interface.
     *
     * @see jj2000.j2k.image.DataBlk
     *
     *
     * */
    public int getDataType() {
        return DataBlk.TYPE_INT;
        }

    }


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"
    jcr:primaryType="cq:Page">
    <jcr:content
        cq:lastModified="{Date}2013-11-06T14:24:19.356-05:00"
        cq:lastModifiedBy="admin"
        cq:template="/libs/cq/cloudserviceconfigs/templates/servicepage"
        jcr:description="Easily add Web Fonts to your site."
        jcr:primaryType="cq:PageContent"
        jcr:title="Typekit"
        sling:resourceType="cq/cloudserviceconfigs/components/servicepage"
        componentReference="acs-commons/components/utilities/typekit"
        description="Easily add Web Fonts to your site."
        serviceAdminUrl="http://typekit.com"
        serviceUrl="http://typekit.com"
        thumbnailPath="/apps/acs-commons/templates/utilities/typekit/thumbnail.png"/>
</jcr:root>

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import FilterPopups from './filter/popUps';

class PopupsWrapper extends React.Component {
    render(){
        return(
            <FilterPopups />
        );
    }
}

export default PopupsWrapper;


text:
package com.cwjcsu.common;

import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Resources {
	private static final Logger logger = Logger.getLogger("COMMON");

	public static void close(Closeable resource) {
		try {
			if (resource != null)
				resource.close();
		} catch (IOException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}

	public static void close(ObjectOutput output) {
		try {
			if (output != null)
				output.close();
		} catch (IOException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}

	public static void close(ObjectInput input) {
		try {
			if (input != null)
				input.close();
		} catch (IOException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}

	public static void close(Connection connection) {
		try {
			if (connection != null)
				connection.close();
		} catch (SQLException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}

	public static void close(Statement statement) {
		try {
			if (statement != null)
				statement.close();
		} catch (SQLException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}

	public static void close(ResultSet resultSet) {
		try {
			if (resultSet != null)
				resultSet.close();
		} catch (SQLException e) {
			logger.log(Level.WARNING, e.getMessage(), e);
		}
	}

	public static void close(Process process) {
		if (process != null) {
			close(process.getErrorStream());
			close(process.getInputStream());
			close(process.getOutputStream());
			process.destroy();
		}
	}

	private Resources() {
		// Hide
	}
}


text:
from django.apps import AppConfig

class FilesConfig(AppConfig):
    name = 'files'

    def ready(self):
        Product = self.get_model('')
        watson.register(Product.objects.exclude(productimage=None))


text:
// Copyright 2021 Phyronnaz

#pragma once

#include "CoreMinimal.h"
#include "VoxelMultiplayer/VoxelMultiplayerInterfaceWithSocket.h"
#include "VoxelMultiplayerTcp.generated.h"

class FSocket;
class FTcpListener;
struct FIPv4Endpoint;
class FVoxelMultiplayerTcpServer;
class FVoxelMultiplayerTcpClient;

// TCP interface, only accepts IPv4
UCLASS()
class VOXEL_API UVoxelMultiplayerTcpInterface : public UVoxelMultiplayerInterface
{
	GENERATED_BODY()

public:
	/**
	 * Connect to a TCP server
	 * @param	Ip		The IPv4 of the server
	 * @param	Port	The port of the server
	 */
	UFUNCTION(BlueprintCallable, Category = "Voxel|Multiplayer|Tcp")
	bool ConnectToServer(FString& OutError, const FString& Ip = TEXT("127.0.0.1"), int32 Port = 10000);

	/**
	 * Start a TCP server
	 * @param	Ip		The IPv4 to accept connection on. 0.0.0.0 to accept all
	 * @param	Port	The port of the server
	 */
	UFUNCTION(BlueprintCallable, Category = "Voxel|Multiplayer|Tcp")
	bool StartServer(FString& OutError, const FString& Ip = TEXT("0.0.0.0"), int32 Port = 10000);

};


text:
#import <WebKitLegacy/WebEditingDelegate.h>

@class DOMHTMLElement;

@interface NSObject (WebViewEditingDelegatePrivate)
#if !TARGET_OS_IPHONE
- (BOOL)webView:(WebView *)webView shouldShowDeleteInterfaceForElement:(DOMHTMLElement *)element;
- (void)webView:(WebView *)webView didWriteSelectionToPasteboard:(NSPasteboard *)pasteboard;
#else
- (NSArray *)supportedPasteboardTypesForCurrentSelection;
- (DOMDocumentFragment *)documentFragmentForPasteboardItemAtIndex:(NSInteger)index;
#endif
- (BOOL)webView:(WebView *)webView shouldMoveRangeAfterDelete:(DOMRange *)range replacingRange:(DOMRange *)rangeToBeReplaced;
@end


text:
self.importScripts('js/analytics-helper.js');

importScripts(
  'node_modules/sw-offline-google-analytics/offline-google-analytics-import.js'
);
goog.offlineGoogleAnalytics.initialize();

(function() {
  'use strict';

  self.addEventListener('notificationclose', function(e) {
    var notification = e.notification;
    var primaryKey = notification.data.primaryKey;
    console.log('Closed notification: ' + primaryKey);
    e.waitUntil(
      sendAnalyticsEvent('close', 'notification')
    );
  });

  self.addEventListener('notificationclick', function(e) {
    var notification = e.notification;
    var primaryKey = notification.data.primaryKey;
    notification.close();
    var action = e.action;
    if (action === 'delay') {
      // Notificaion delay logic could go here in a real app
      e.waitUntil(
        sendAnalyticsEvent('delay', 'notification')
      );
    } else if (action === 'buy') {
      // Purchase logic could go here in a real app
      e.waitUntil(
        sendAnalyticsEvent('purchase', 'notification')
      );
    } else {
      e.waitUntil(
        Promise.all([
          clients.openWindow('pages/page' + primaryKey + '.html'),
          sendAnalyticsEvent('click', 'notification')
        ])
      );
    }
  });

  self.addEventListener('push', function(e) {
    var options = {
      body: 'This notification was generated from a push!',
      icon: 'images/notification-flat.png',
      vibrate: [100, 50, 100],
      data: {
        dateOfArrival: Date.now(),
        primaryKey: '-push-notification'
      },
      actions: [
        {action: 'buy', title: 'Buy on sale!',
          icon: 'images/checkmark.png'},
        {action: 'delay', title: 'Not right now',
          icon: 'images/xmark.png'},
      ]
    };
    e.waitUntil(Promise.all([
        self.registration.showNotification('Hello world!', options),
        sendAnalyticsEvent('recieved', 'push')
      ])
    );
  });
})();


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

// System.IO.Stream
struct Stream_t219029575;

#include "mscorlib_System_Object837106420.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.IO.Stream
struct  Stream_t219029575  : public Il2CppObject
{
public:

public:
};

struct Stream_t219029575_StaticFields
{
public:
	// System.IO.Stream System.IO.Stream::Null
	Stream_t219029575 * ___Null_0;

public:
	inline static int32_t get_offset_of_Null_0() { return static_cast<int32_t>(offsetof(Stream_t219029575_StaticFields, ___Null_0)); }
	inline Stream_t219029575 * get_Null_0() const { return ___Null_0; }
	inline Stream_t219029575 ** get_address_of_Null_0() { return &___Null_0; }
	inline void set_Null_0(Stream_t219029575 * value)
	{
		___Null_0 = value;
		Il2CppCodeGenWriteBarrier(&___Null_0, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
const placeKitten = createPluginHandler(function(props) {
  const GREY_TITLE = 'Black & white';
  const initOpts = props.newImgFrame;

  const elements = [
    new Label({
      value: 'Width:'
    }),
    new TextField({
      name: 'width',
      value: initOpts.width
    }),
    new Label({
      value: 'Height:'
    }),
    new TextField({
      name: 'height',
      value: initOpts.height
    }),
    new Label({
      value: 'Type:'
    }),
    new PopUpButton({
      name: 'type',
      items: ['Color', GREY_TITLE]
    })
  ];

  const onConfirm = createConfirmHandler({
    api: props.api,
    group: props.target.group,
    host: 'placekitten.com',
    initOpts: initOpts,
    urlBuilder: function(parts) {
      const base = `${parts.protocol}${parts.host}`;
      // Cast as a string because the value coming back is an object
      const type = (String(parts.allParts.type) === GREY_TITLE) ? '/g' : '';
      return `${base}${type}/${parts.width}/${parts.height}`;
    }
  });

  new Alert({
    message: 'Place Kitten Options',
    info: 'Customize the kewl kitten image that will be created.',
    iconUrl: props.api.resourceNamed('placekitten.icns'),
    onConfirm: onConfirm
  }).append(elements).runModal();
});


text:
package com.kevinshine.beyondmediaplayer.utils;

import java.net.URLEncoder;
import java.util.regex.Pattern;

import jcifs.smb.SmbFile;

/**
 * Created by gary on 16-1-8.
 */
public class SmbUtil {
    private static Pattern pattern = Pattern.compile("^.*\\.(?i)(mp3|wma|wav|aac|ogg|m4a|flac|mp4|avi|mpg|mpeg|3gp|3gpp|mkv|flv|rmvb)$");

    public static String getSmbServerUrl(String[] auth, boolean anonym) {
        String smbFilePath;
        try {
            String yourPeerIP = auth[0], domain = "";
            smbFilePath = "smb://" + (anonym ? "" : (URLEncoder.encode(auth[1] + ":" + auth[2], "UTF-8") + "@")) + yourPeerIP + "/";
            return smbFilePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getNameFromPath(String path){
        if(path == null || path.length() <2)
            return null;
        int slash = path.lastIndexOf('/');
        if(slash == -1)
            return path;
        else
            return path.substring(slash+1);
    }

    public static boolean isStreamMedia(SmbFile file) {
        return pattern.matcher(file.getName()).matches();
    }

    public boolean isSmb(String path) {
        return path != null && path.startsWith("smb:/");
    }
}


text:
@import UIKit;
#import "ZHDatePickerAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([ZHDatePickerAppDelegate class]));
    }
}


text:
class Charting
  class << self
    extend Forwardable
    delegate [
      :backend,               # charting backend name; FIXME: remove this method
      :render_format,
      :format,                # format for Ruport renderer
      :load_helpers,
      :data_ok?,
      :sample_chart,
      :chart_names_for_select,
      :chart_themes_for_select,
      :serialized,
      :deserialized,
      :js_load_statement      # javascript statement to reload charts
    ] => :instance
  end

  # discovery
  #
  #
  def self.instance
    @instance ||= new
  end

  private

  def self.new
    self == Charting ? detect_available_plugin.new : super
  end

  def self.detect_available_plugin
    subclasses.select(&:available?).max_by(&:priority)
  end
end

# load all plugins
Dir.glob(File.join(File.dirname(__FILE__), "charting/*.rb")).each { |f| require_dependency f }


text:
namespace asio {
namespace experimental {
namespace detail {

// Base class for all channel operations. A function pointer is used instead of
// virtual functions to avoid the associated overhead.
class channel_operation ASIO_INHERIT_TRACKED_HANDLER
{
public:
  template <typename Executor, typename = void>
  class handler_work_base;

  template <typename Handler, typename IoExecutor, typename = void>
  class handler_work;

  void destroy()
  {
    func_(this, destroy_op, 0);
  }

protected:
  enum action
  {
    destroy_op = 0,
    complete_op = 1,
    cancel_op = 2,
    close_op = 3
  };

  typedef void (*func_type)(channel_operation*, action, void*);

  channel_operation(func_type func)
    : next_(0),
      func_(func),
      cancellation_key_(0)
  {
  }

  // Prevents deletion through this type.
  ~channel_operation()
  {
  }

  friend class asio::detail::op_queue_access;
  channel_operation* next_;
  func_type func_;

public:
  // The operation key used for targeted cancellation.
  void* cancellation_key_;
};

template <typename Executor, typename>
class channel_operation::handler_work_base
{
public:
  handler_work_base(int, const Executor& ex)
    : executor_(asio::prefer(ex, execution::outstanding_work.tracked))
  {
  }

  template <typename Function, typename Handler>
  void post(Function& function, Handler& handler)
  {
    typename associated_allocator<Handler>::type allocator =
      (get_associated_allocator)(handler);

    execution::execute(
        asio::prefer(
          asio::require(executor_, execution::blocking.never),
          execution::allocator(allocator)),
        ASIO_MOVE_CAST(Function)(function));
  }

private:
  typename decay<
      typename prefer_result<Executor,
        execution::outstanding_work_t::tracked_t
      >::type
    >::type executor_;
};

#if !defined(ASIO_NO_TS_EXECUTORS)

template <typename Executor>
class channel_operation::handler_work_base<Executor,
    typename enable_if<
      !execution::is_executor<Executor>::value
    >::type>
{
public:
  handler_work_base(int, const Executor& ex)
    : work_(ex)
  {
  }

  template <typename Function, typename Handler>
  void post(Function& function, Handler& handler)
  {
    typename associated_allocator<Handler>::type allocator =
      (get_associated_allocator)(handler);

    work_.get_executor().post(
        ASIO_MOVE_CAST(Function)(function), allocator);
  }

private:
  executor_work_guard<Executor> work_;
};

#endif // !defined(ASIO_NO_TS_EXECUTORS)

template <typename Handler, typename IoExecutor, typename>
class channel_operation::handler_work :
  channel_operation::handler_work_base<IoExecutor>,
  channel_operation::handler_work_base<
      typename associated_executor<Handler, IoExecutor>::type, IoExecutor>
{
public:
  typedef channel_operation::handler_work_base<IoExecutor> base1_type;

  typedef channel_operation::handler_work_base<
      typename associated_executor<Handler, IoExecutor>::type, IoExecutor>
    base2_type;

  handler_work(Handler& handler, const IoExecutor& io_ex) ASIO_NOEXCEPT
    : base1_type(0, io_ex),
      base2_type(0, (get_associated_executor)(handler, io_ex))
  {
  }

  template <typename Function>
  void complete(Function& function, Handler& handler)
  {
    base2_type::post(function, handler);
  }
};

template <typename Handler, typename IoExecutor>
class channel_operation::handler_work<
    Handler, IoExecutor,
    typename enable_if<
      is_same<
        typename associated_executor<Handler,
          IoExecutor>::asio_associated_executor_is_unspecialised,
        void
      >::value
    >::type> : handler_work_base<IoExecutor>
{
public:
  typedef channel_operation::handler_work_base<IoExecutor> base1_type;

  handler_work(Handler&, const IoExecutor& io_ex) ASIO_NOEXCEPT
    : base1_type(0, io_ex)
  {
  }

  template <typename Function>
  void complete(Function& function, Handler& handler)
  {
    base1_type::post(function, handler);
  }
};

} // namespace detail
} // namespace experimental
} // namespace asio

#include "asio/detail/pop_options.hpp"

#endif // ASIO_EXPERIMENTAL_DETAIL_CHANNEL_OPERATION_HPP


text:
Imagine this scenario, I let the users set this in the Admin panel:
```
Copyright {{year}} by Upstatement, LLC. All Rights Reserved
```
But on the site I want it to render as:
```
Copyright 2013 by Upstatement, LLC. All Rights Reserved
```
Ready? There are a bunch of ways, but my favorite is:

#### In your PHP file
```php
$data['year'] = date('Y');
$data['copyright'] = get_option("footer_message"); //"Copyright {{year}} by Upstatement, LLC. All Rights Reserved"
render_twig('footer.twig', $data);
```

#### In your HTML file (let's say **footer.twig**)
```html
{% include template_from_string(copyright) %}
```

## Includes
### Simple include
```
{% include "footer.twig" %}
```
#### Notes
* Make sure your file actually exists or you're going to have a bad time
* Timber will look in your ```child-theme/views``` directory first, then ```timber/views``` directory
* Don't forget the quote marks!

### Dynamic includes
Use a variable to determine the included file!
```html
{% include ['blocks/block-'~block.slug~'.twig', 'blocks/blog.twig'] ignore missing %}
```

#### Huh?
* You're telling Twig to include an array of files
* Same rules as above
* ~ (tilda) is what twig uses to concatenate a string with your variable


text:
package io.quarkus.runtime;

/**
 * Usually, QuarkusMock mocking replaces a "delegating instance" of a client proxy.
 *
 * In some cases, e.g. for REST Client Reactive, a CDI bean is a wrapper over a delegate.
 * This interface allows to replace the delegate instead of the delegating instance of the proxy.
 */
public interface MockedThroughWrapper {
    void setMock(Object mock);

    void clearMock();
}


text:
package com.aic.appengine;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import twitter.SentAnalysis;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class SentimentServlet extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		ServletContext context=getServletContext();

		String searchText = req.getParameter("searchText");
		String start = req.getParameter("start");
		String end = req.getParameter("end");

		SentAnalysis analysis = new SentAnalysis(searchText, start, end, 1, 1, context.getResource("/WEB-INF/classifier.txt").getPath());
		analysis.run();
		System.out.println("result: " + analysis.getResult());

		resp.setContentType("text/plain");
		resp.getWriter().println(analysis.getResult());

	}
}


text:
class CreateAssets < ActiveRecord::Migration
  def self.up
    create_table :assets do |t|
      t.integer :user_id, :null => false
      t.string :title
      t.string :upload_file_name
      t.string :upload_content_type
      t.integer :upload_file_size
      t.datetime :upload_updated_at
      t.timestamps
    end
  end

  def self.down
    drop_table :assets
  end
end


text:
package us.codecraft.tinyioc.aop;

/**
 * @author yihua.huang@dianping.com
 */
public class ProxyFactory extends AdvisedSupport implements AopProxy {

	@Override
	public Object getProxy() {
		return createAopProxy().getProxy();
	}

	protected final AopProxy createAopProxy() {
		return new Cglib2AopProxy(this);
	}
}


text:
<!-- Copyright (C) 2013 Menny Even-Danan

     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.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:padding="6dp">

    <ImageView
        android:id="@+id/app_icon"
        android:scaleType="centerInside"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:adjustViewBounds="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp"/>

    <TextView
        android:id="@+id/app_name"
        style="@android:style/TextAppearance.Medium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/app_icon"
        android:layout_alignParentTop="true"/>

    <TextView
        android:id="@+id/app_version"
        style="@android:style/TextAppearance.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/version_text"
        android:layout_below="@id/app_name"
        android:layout_toRightOf="@id/app_icon"/>

    <TextView
        android:id="@+id/app_copyright"
        style="@android:style/TextAppearance.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/copyright_text"
        android:layout_below="@id/app_icon"
        android:layout_alignParentLeft="true"/>

</RelativeLayout>


text:
package http

import (
	"context"
	"fmt"
	"net"
	"net/url"
	"sort"
	"sync"
	"testing"
	"time"
)

var (
	DefaultUserAgent                  = defaultUserAgent
	NewLoggingConn                    = newLoggingConn
	ExportAppendTime                  = appendTime
	ExportRefererForURL               = refererForURL
	ExportServerNewConn               = (*Server).newConn
	ExportCloseWriteAndWait           = (*conn).closeWriteAndWait
	ExportErrRequestCanceled          = errRequestCanceled
	ExportErrRequestCanceledConn      = errRequestCanceledConn
	ExportErrServerClosedIdle         = errServerClosedIdle
	ExportServeFile                   = serveFile
	ExportScanETag                    = scanETag
	ExportHttp2ConfigureServer        = http2ConfigureServer
	Export_shouldCopyHeaderOnRedirect = shouldCopyHeaderOnRedirect
	Export_writeStatusLine            = writeStatusLine
	Export_is408Message               = is408Message
)

const MaxWriteWaitBeforeConnReuse = maxWriteWaitBeforeConnReuse

func init() {
	// We only want to pay for this cost during testing.
	// When not under test, these values are always nil
	// and never assigned to.
	testHookMu = new(sync.Mutex)

	testHookClientDoResult = func(res *Response, err error) {
		if err != nil {
			if _, ok := err.(*url.Error); !ok {
				panic(fmt.Sprintf("unexpected Client.Do error of type %T; want *url.Error", err))
			}
		} else {
			if res == nil {
				panic("Client.Do returned nil, nil")
			}
			if res.Body == nil {
				panic("Client.Do returned nil res.Body and no error")
			}
		}
	}
}

func CondSkipHTTP2(t *testing.T) {
	if omitBundledHTTP2 {
		t.Skip("skipping HTTP/2 test when nethttpomithttp2 build tag in use")
	}
}

var (
	SetEnterRoundTripHook = hookSetter(&testHookEnterRoundTrip)
	SetRoundTripRetried   = hookSetter(&testHookRoundTripRetried)
)

func SetReadLoopBeforeNextReadHook(f func()) {
	testHookMu.Lock()
	defer testHookMu.Unlock()
	unnilTestHook(&f)
	testHookReadLoopBeforeNextRead = f
}

// SetPendingDialHooks sets the hooks that run before and after handling
// pending dials.
func SetPendingDialHooks(before, after func()) {
	unnilTestHook(&before)
	unnilTestHook(&after)
	testHookPrePendingDial, testHookPostPendingDial = before, after
}

func SetTestHookServerServe(fn func(*Server, net.Listener)) { testHookServerServe = fn }

func NewTestTimeoutHandler(handler Handler, ctx context.Context) Handler {
	return &timeoutHandler{
		handler:     handler,
		testContext: ctx,
		// (no body)
	}
}

func ResetCachedEnvironment() {
	resetProxyConfig()
}

func (t *Transport) NumPendingRequestsForTesting() int {
	t.reqMu.Lock()
	defer t.reqMu.Unlock()
	return len(t.reqCanceler)
}

func (t *Transport) IdleConnKeysForTesting() (keys []string) {
	keys = make([]string, 0)
	t.idleMu.Lock()
	defer t.idleMu.Unlock()
	for key := range t.idleConn {
		keys = append(keys, key.String())
	}
	sort.Strings(keys)
	return
}

func (t *Transport) IdleConnKeyCountForTesting() int {
	t.idleMu.Lock()
	defer t.idleMu.Unlock()
	return len(t.idleConn)
}

func (t *Transport) IdleConnStrsForTesting() []string {
	var ret []string
	t.idleMu.Lock()
	defer t.idleMu.Unlock()
	for _, conns := range t.idleConn {
		for _, pc := range conns {
			ret = append(ret, pc.conn.LocalAddr().String()+"/"+pc.conn.RemoteAddr().String())
		}
	}
	sort.Strings(ret)
	return ret
}

func (t *Transport) IdleConnStrsForTesting_h2() []string {
	var ret []string
	noDialPool := t.h2transport.(*http2Transport).ConnPool.(http2noDialClientConnPool)
	pool := noDialPool.http2clientConnPool

	pool.mu.Lock()
	defer pool.mu.Unlock()

	for k, cc := range pool.conns {
		for range cc {
			ret = append(ret, k)
		}
	}

	sort.Strings(ret)
	return ret
}

func (t *Transport) IdleConnCountForTesting(scheme, addr string) int {
	t.idleMu.Lock()
	defer t.idleMu.Unlock()
	key := connectMethodKey{"", scheme, addr, false}
	cacheKey := key.String()
	for k, conns := range t.idleConn {
		if k.String() == cacheKey {
			return len(conns)
		}
	}
	return 0
}

func (t *Transport) IdleConnWaitMapSizeForTesting() int {
	t.idleMu.Lock()
	defer t.idleMu.Unlock()
	return len(t.idleConnWait)
}

func (t *Transport) IsIdleForTesting() bool {
	t.idleMu.Lock()
	defer t.idleMu.Unlock()
	return t.closeIdle
}

func (t *Transport) QueueForIdleConnForTesting() {
	t.queueForIdleConn(nil)
}

// PutIdleTestConn reports whether it was able to insert a fresh
// persistConn for scheme, addr into the idle connection pool.
func (t *Transport) PutIdleTestConn(scheme, addr string) bool {
	c, _ := net.Pipe()
	key := connectMethodKey{"", scheme, addr, false}

	if t.MaxConnsPerHost > 0 {
		// Transport is tracking conns-per-host.
		// Increment connection count to account
		// for new persistConn created below.
		t.connsPerHostMu.Lock()
		if t.connsPerHost == nil {
			t.connsPerHost = make(map[connectMethodKey]int)
		}
		t.connsPerHost[key]++
		t.connsPerHostMu.Unlock()
	}

	return t.tryPutIdleConn(&persistConn{
		t:        t,
		conn:     c,                   // dummy
		closech:  make(chan struct{}), // so it can be closed
		cacheKey: key,
	}) == nil
}

// PutIdleTestConnH2 reports whether it was able to insert a fresh
// HTTP/2 persistConn for scheme, addr into the idle connection pool.
func (t *Transport) PutIdleTestConnH2(scheme, addr string, alt RoundTripper) bool {
	key := connectMethodKey{"", scheme, addr, false}

	if t.MaxConnsPerHost > 0 {
		// Transport is tracking conns-per-host.
		// Increment connection count to account
		// for new persistConn created below.
		t.connsPerHostMu.Lock()
		if t.connsPerHost == nil {
			t.connsPerHost = make(map[connectMethodKey]int)
		}
		t.connsPerHost[key]++
		t.connsPerHostMu.Unlock()
	}

	return t.tryPutIdleConn(&persistConn{
		t:        t,
		alt:      alt,
		cacheKey: key,
	}) == nil
}

// All test hooks must be non-nil so they can be called directly,
// but the tests use nil to mean hook disabled.
func unnilTestHook(f *func()) {
	if *f == nil {
		*f = nop
	}
}

func hookSetter(dst *func()) func(func()) {
	return func(fn func()) {
		unnilTestHook(&fn)
		*dst = fn
	}
}

func ExportHttp2ConfigureTransport(t *Transport) error {
	t2, err := http2configureTransports(t)
	if err != nil {
		return err
	}
	t.h2transport = t2
	return nil
}

func (s *Server) ExportAllConnsIdle() bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	for c := range s.activeConn {
		st, unixSec := c.getState()
		if unixSec == 0 || st != StateIdle {
			return false
		}
	}
	return true
}

func (s *Server) ExportAllConnsByState() map[ConnState]int {
	states := map[ConnState]int{}
	s.mu.Lock()
	defer s.mu.Unlock()
	for c := range s.activeConn {
		st, _ := c.getState()
		states[st] += 1
	}
	return states
}

func (r *Request) WithT(t *testing.T) *Request {
	return r.WithContext(context.WithValue(r.Context(), tLogKey{}, t.Logf))
}

func ExportSetH2GoawayTimeout(d time.Duration) (restore func()) {
	old := http2goAwayTimeout
	http2goAwayTimeout = d
	return func() { http2goAwayTimeout = old }
}

func (r *Request) ExportIsReplayable() bool { return r.isReplayable() }

// ExportCloseTransportConnsAbruptly closes all idle connections from
// tr in an abrupt way, just reaching into the underlying Conns and
// closing them, without telling the Transport or its persistConns
// that it's doing so. This is to simulate the server closing connections
// on the Transport.
func ExportCloseTransportConnsAbruptly(tr *Transport) {
	tr.idleMu.Lock()
	for _, pcs := range tr.idleConn {
		for _, pc := range pcs {
			pc.conn.Close()
		}
	}
	tr.idleMu.Unlock()
}

// ResponseWriterConnForTesting returns w's underlying connection, if w
// is a regular *response ResponseWriter.
func ResponseWriterConnForTesting(w ResponseWriter) (c net.Conn, ok bool) {
	if r, ok := w.(*response); ok {
		return r.conn.rwc, true
	}
	return nil, false
}


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2002, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Robert D. Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////

package gnu.trove.decorator;

import gnu.trove.map.TLongCharMap;
import gnu.trove.iterator.TLongCharIterator;

import java.io.*;
import java.util.*;

//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////

/**
 * Wrapper class to make a TLongCharMap conform to the <tt>java.util.Map</tt> API.
 * This class simply decorates an underlying TLongCharMap and translates the Object-based
 * APIs into their Trove primitive analogs.
 *

 * Note that wrapping and unwrapping primitive values is extremely inefficient.  If
 * possible, users of this class should override the appropriate methods in this class
 * and use a table of canonical values.
 *

 * Created: Mon Sep 23 22:07:40 PDT 2002
 *
 * @author Eric D. Friedman
 * @author Robert D. Eden
 * @author Jeff Randall
 */
public class TLongCharMapDecorator extends AbstractMap<Long, Character>
	implements Map<Long, Character>, Externalizable, Cloneable {

	static final long serialVersionUID = 1L;

    /** the wrapped primitive map */
    protected TLongCharMap _map;

    /**
     * FOR EXTERNALIZATION ONLY!!
     */
    public TLongCharMapDecorator() {}

    /**
     * Creates a wrapper that decorates the specified primitive map.
     *
     * @param map the <tt>TLongCharMap</tt> to wrap.
     */
    public TLongCharMapDecorator( TLongCharMap map ) {
        super();
        this._map = map;
    }

    /**
     * Returns a reference to the map wrapped by this decorator.
     *
     * @return the wrapped <tt>TLongCharMap</tt> instance.
     */
    public TLongCharMap getMap() {
        return _map;
    }

    /**
     * Inserts a key/value pair into the map.
     *
     * @param key   an Object value
     * @param value an Object value
     * @return the previous value associated with <tt>key</tt>,
     *         or Character(0) if none was found.
     */
    public Character put( Long key, Character value ) {
        long k;
        char v;
        if ( key == null ) {
            k = _map.getNoEntryKey();
        } else {
            k = unwrapKey( key );
        }
        if ( value == null ) {
            v = _map.getNoEntryValue();
        } else {
            v = unwrapValue( value );
        }
        char retval = _map.put( k, v );
        if ( retval == _map.getNoEntryValue() ) {
            return null;
        }
        return wrapValue( retval );
    }

    /**
     * Retrieves the value for <tt>key</tt>
     *
     * @param key an Object value
     * @return the value of <tt>key</tt> or null if no such mapping exists.
     */
    public Character get( Object key ) {
        long k;
        if ( key != null ) {
            if ( key instanceof Long ) {
                k = unwrapKey( key );
            } else {
                return null;
            }
        } else {
            k = _map.getNoEntryKey();
        }
        char v = _map.get( k );
        // There may be a false positive since primitive maps
        // cannot return null, so we have to do an extra
        // check here.
        if ( v == _map.getNoEntryValue() ) {
            return null;
        } else {
            return wrapValue( v );
        }
    }

    /**
     * Empties the map.
     */
    public void clear() {
        this._map.clear();
    }

    /**
     * Deletes a key/value pair from the map.
     *
     * @param key an Object value
     * @return the removed value, or null if it was not found in the map
     */
    public Character remove( Object key ) {
        long k;
        if ( key != null ) {
            if ( key instanceof Long ) {
                k = unwrapKey( key );
            } else {
                return null;
            }
        } else {
            k = _map.getNoEntryKey();
        }
        char v = _map.remove( k );
        // There may be a false positive since primitive maps
        // cannot return null, so we have to do an extra
        // check here.
        if ( v == _map.getNoEntryValue() ) {
            return null;
        } else {
            return wrapValue( v );
        }
    }

    /**
     * Returns a Set view on the entries of the map.
     *
     * @return a Set value
     */
    public Set<Map.Entry<Long,Character>> entrySet() {
        return new AbstractSet<Map.Entry<Long,Character>>() {
            public int size() {
                return _map.size();
            }

            public boolean isEmpty() {
                return TLongCharMapDecorator.this.isEmpty();
            }

            public boolean contains( Object o ) {
                if (o instanceof Map.Entry) {
                    Object k = ( ( Map.Entry ) o ).getKey();
                    Object v = ( ( Map.Entry ) o ).getValue();
                    return TLongCharMapDecorator.this.containsKey(k)
                            && TLongCharMapDecorator.this.get(k).equals(v);
                } else {
                    return false;
                }
            }

            public Iterator<Map.Entry<Long,Character>> iterator() {
                return new Iterator<Map.Entry<Long,Character>>() {
                    private final TLongCharIterator it = _map.iterator();

                    public Map.Entry<Long,Character> next() {
                        it.advance();
                        long ik = it.key();
                        final Long key = (ik == _map.getNoEntryKey()) ? null : wrapKey( ik );
                        char iv = it.value();
                        final Character v = (iv == _map.getNoEntryValue()) ? null : wrapValue( iv );
                        return new Map.Entry<Long,Character>() {
                            private Character val = v;

                            public boolean equals( Object o ) {
                                return o instanceof Map.Entry
                                        && ( ( Map.Entry ) o ).getKey().equals(key)
                                        && ( ( Map.Entry ) o ).getValue().equals(val);
                            }

                            public Long getKey() {
                                return key;
                            }

                            public Character getValue() {
                                return val;
                            }

                            public int hashCode() {
                                return key.hashCode() + val.hashCode();
                            }

                            public Character setValue( Character value ) {
                                val = value;
                                return put( key, value );
                            }
                        };
                    }

                    public boolean hasNext() {
                        return it.hasNext();
                    }

                    public void remove() {
                        it.remove();
                    }
                };
            }

            public boolean add( Map.Entry<Long,Character> o ) {
                throw new UnsupportedOperationException();
            }

            public boolean remove( Object o ) {
                boolean modified = false;
                if ( contains( o ) ) {
                    //noinspection unchecked
                    Long key = ( ( Map.Entry<Long,Character> ) o ).getKey();
                    _map.remove( unwrapKey( key ) );
                    modified = true;
                }
                return modified;
            }

            public boolean addAll( Collection<? extends Map.Entry<Long, Character>> c ) {
                throw new UnsupportedOperationException();
            }

            public void clear() {
                TLongCharMapDecorator.this.clear();
            }
        };
    }

    /**
     * Checks for the presence of <tt>val</tt> in the values of the map.
     *
     * @param val an Object value
     * @return a boolean value
     */
    public boolean containsValue( Object val ) {
        return val instanceof Character && _map.containsValue( unwrapValue( val ) );
    }

    /**
     * Checks for the present of <tt>key</tt> in the keys of the map.
     *
     * @param key an Object value
     * @return a boolean value
     */
    public boolean containsKey( Object key ) {
        if ( key == null ) return _map.containsKey( _map.getNoEntryKey() );
        return key instanceof Long && _map.containsKey( unwrapKey( key ) );
    }

    /**
     * Returns the number of entries in the map.
     *
     * @return the map's size.
     */
    public int size() {
        return this._map.size();
    }

    /**
     * Indicates whether map has any entries.
     *
     * @return true if the map is empty
     */
    public boolean isEmpty() {
        return size() == 0;
    }

    /**
     * Copies the key/value mappings in <tt>map</tt> into this map.
     * Note that this will be a deep copy, as storage is by
     * primitive value.
     *
     * @param map a Map value
     */
    public void putAll( Map<? extends Long, ? extends Character> map ) {
        Iterator<? extends Entry<? extends Long,? extends Character>> it =
            map.entrySet().iterator();
        for ( int i = map.size(); i-- > 0; ) {
            Entry<? extends Long,? extends Character> e = it.next();
            this.put( e.getKey(), e.getValue() );
        }
    }

    /**
     * Wraps a key
     *
     * @param k key in the underlying map
     * @return an Object representation of the key
     */
    protected Long wrapKey( long k ) {
        return Long.valueOf( k );
    }

    /**
     * Unwraps a key
     *
     * @param key wrapped key
     * @return an unwrapped representation of the key
     */
    protected long unwrapKey( Object key ) {
        return ( ( Long ) key ).longValue();
    }

    /**
     * Wraps a value
     *
     * @param k value in the underlying map
     * @return an Object representation of the value
     */
    protected Character wrapValue( char k ) {
        return Character.valueOf( k );
    }

    /**
     * Unwraps a value
     *
     * @param value wrapped value
     * @return an unwrapped representation of the value
     */
    protected char unwrapValue( Object value ) {
        return ( ( Character ) value ).charValue();
    }

    // Implements Externalizable
    public void readExternal( ObjectInput in )
        throws IOException, ClassNotFoundException {

        // VERSION
        in.readByte();

        // MAP
        _map = ( TLongCharMap ) in.readObject();
    }

    // Implements Externalizable
    public void writeExternal( ObjectOutput out ) throws IOException {
        // VERSION
        out.writeByte(0);

        // MAP
        out.writeObject( _map );
    }

} // TLongCharHashMapDecorator


text:
var poolConfig = {
  user: process.env.DATA_BASE_USER,
  database: process.env.DATA_BASE,
  password: process.env.DATA_BASE_PASSWORD, //env var: PGPASSWORD
  host: process.env.DATA_BASE_HOST, // Server hosting the postgres database
  ssl: true,
  // port: 5432,
  max: 10, // max number of clients in the pool
  idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};

module.exports = {
  pg: poolConfig
};


text:
using System.Web.Mvc;

namespace RestfulRouting.Documentation.Controllers
{
    public class HomeController : ApplicationController
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}


text:
package org.roaringbitmap.spe150271.roaring;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.roaringbitmap.realdata.wrapper.BitmapIterator;
import org.roaringbitmap.spe150271.roaring.state.RealDataBenchmarkState;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class RealDataBenchmarkOr {

  @Benchmark
  public int pairwiseOr(RealDataBenchmarkState bs) {
    int total = 0;
    for (int k = 0; k + 1 < bs.bitmaps.size(); ++k) {
      total += bs.bitmaps.get(k).or(bs.bitmaps.get(k + 1)).cardinality();
    }
    return total;
  }

  @Benchmark
  public int pairwiseOr_NoCardinality(RealDataBenchmarkState bs) {
    int total = 0;
    for (int k = 0; k + 1 < bs.bitmaps.size(); ++k) {
      BitmapIterator i = bs.bitmaps.get(k).or(bs.bitmaps.get(k + 1)).iterator();
      if (i.hasNext()) {
        total += i.next();
      }
    }
    return total;
  }

}


text:
package org.apache.drill.exec.store.easy.json.parser;

import java.util.Map;

import org.apache.drill.common.map.CaseInsensitiveMap;
import org.apache.drill.shaded.guava.com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonToken;

/**
 * Parses a JSON object: { name : value ... }
 *

 * The object value may the root object (the row), a top-level
 * field or may be the element of an array. The event methods are called when
 * an object is started and ended, as well as when a new field is discovered.
 *

 * Creates a map of known fields. Each time a field is parsed,
 * looks up the field in the map. If not found, the value is "sniffed"
 * to determine its type, and a matching parser and listener created.
 * Thereafter, the previous parser is reused.
 *

 * The object listener provides semantics. One key decision is whether
 * to project a field or not. An unprojected field is parsed with
 * a "dummy" parser that "free-wheels" over all valid JSON structures.
 * Otherwise, the listener is given whatever type information that the
 * parser can discover when creating the field.
 *

 * Work is divided between this class, which discovers fields, and
 * the listeners which determine the meaning of field values. A field,
 * via a properly-defined listener, can accept one or more different
 * value kinds.
 *

 * The parser accepts JSON tokens as they appear in the file. The
 * question of whether those tokens make sense is left to the listeners.
 * The listeners decide if the tokens make sense for a particular column.
 * The listener should provide a clear error if a particular token is not
 * valid for a given listener.
 *
 *
Fields

 *
 * The structure of an object is:
 *

 *
{@code ObjectListener} which represents the object (tuple) as a whole.
 * Each field, indexed by name, is represented as a

 *
{@code ValueListener} which represents the value "slot". That value
 * can be scalar, or can be structured, in which case the value listener
 * contains either a

 *
{@code ArrayListener} for an array, or a

 *
{@code ObjectListener} for a nested object (tuple).

 *

 *
 *
Nulls

 *
 * Null values are handled at the semantic, not syntax level. If the
 * first appearance of a field contains a null value, then the parser can
 * provide no hints about the expected field type. The listener must
 * implement a solution such as referring to a schema, waiting for a
 * non-null value to appear, etc.
 *

 * Since the parser classes handle syntax, they are blissfully ignorant
 * of any fancy logic needed for null handling. Each field is
 * represented by a field parser whether that field is null or not.
 * It is the listener that may have to swap out one mechanism for
 * another as types are discovered.
 *
 *
Complex Types

 *
 * Parsers handle arrays and objects using a two-level system. Each field
 * always is driven by a field parser. If the field is discovered to be an
 * array, then we add an array parser to the field parser to handle array
 * contents. The same is true of objects.
 *

 * Both objects and arrays are collections of values, and a value can
 * optionally contain an array or object. (JSON allows any given field
 * name to map to both objects and arrays in different rows. The parser
 * structure reflects this syntax. The listeners can enforce more
 * relational-like semantics).
 *

 * If an array is single-dimension, then the field parse contains an array
 * parser which contains another value parser for the array contents. If
 * the array is multi-dimensional, there will be multiple array/value
 * parser pairs: one for each dimension.
 */
public abstract class ObjectParser extends AbstractElementParser {
  protected static final Logger logger = LoggerFactory.getLogger(ObjectParser.class);

  private final Map<String, ElementParser> members = CaseInsensitiveMap.newHashMap();

  public ObjectParser(JsonStructureParser structParser) {
    super(structParser);
  }

  @VisibleForTesting
  public ElementParser fieldParser(String key) {
    return members.get(key);
  }

  /**
   * Called at the start of a set of values for an object. That is, called
   * when the structure parser accepts the { token.
   */
  protected void onStart() { }

  /**
   * The structure parser has just encountered a new field for this
   * object. This method returns a parser for the field, along with
   * an optional listener to handle events within the field. The field typically
   * uses a value parser create by the {@link FieldParserFactory} class.
   * However, special cases (such as Mongo extended types) can create a
   * custom parser.
   *

   * If the field is not projected, the method should return a dummy parser
   * from {@link FieldParserFactory#ignoredFieldParser()}.
   * The dummy parser will "free-wheel" over whatever values the
   * field contains. (This is one way to avoid structure errors in a JSON file:
   * just ignore them.) Otherwise, the parser will look ahead to guess the
   * field type and will call one of the "add" methods, each of which should
   * return a value listener for the field itself.
   *

   * A normal field will respond to the structure of the JSON file as it
   * appears. The associated value listener receives events for the
   * field value. The value listener may be asked to create additional
   * structure, such as arrays or nested objects.
   *

   * Parse position: { ... field : ^ ? for a newly-seen field.
   * Constructs a value parser and its listeners by looking ahead
   * some number of tokens to "sniff" the type of the value. For
   * example:
   *

   *
{@code foo: <value>} - Field value

   *
{@code foo: [ <value> ]} - 1D array value

   *
{@code foo: [ [<value> ] ]} - 2D array value

   *
Etc.

   *

   *

   * There are two cases in which no type estimation is possible:
   *

   *
{@code foo: null}

   *
{@code foo: []}

   *

   *
   * @param key name of the field
   * @param tokenizer an instance of a token iterator
   * @return a parser for the newly-created field
   */
  protected abstract ElementParser onField(String key, TokenIterator tokenizer);

  /**
   * Called at the end of a set of values for an object. That is, called
   * when the structure parser accepts the } token.
   */
  protected void onEnd() { }

  /**
   * Parses { ^ ... }
   *
   * @param tokenizer an instance of a token iterator
   */
  @Override
  public void parse(TokenIterator tokenizer) {
    onStart();

    // Parse (field: value)* }
    top: while (true) {
      JsonToken token = tokenizer.requireNext();
      // Position: { (key: value)* ? ^
      switch (token) {
        case END_OBJECT:
          // Position: { (key: value)* } ^
          break top;

        case FIELD_NAME:
          // Position: { (key: value)* key: ^
          parseMember(tokenizer);
          break;

        default:
          // Position: { (key: value)* ~(key | }) ^
          // Invalid JSON.
          // Actually, we probably won't get here, the JSON parser
          // itself will throw an exception.
          throw errorFactory().syntaxError(token);
      }
    }
    onEnd();
  }

  /**
   * Parse a field. Two cases. First, this is a field we've already seen. If so,
   * look up the parser for that field and use it. If this is the first time
   * we've seen the field, "sniff" tokens to determine field type, create a
   * parser, then parse.
   *
   * @param tokenizer an instance of a token iterator
   */
  private void parseMember(TokenIterator tokenizer) {
    // Position: key: ^ ?
    final String key = tokenizer.textValue().trim();
    ElementParser fieldParser = members.get(key);
    if (fieldParser == null) {
      // New key; sniff the value to determine the parser to use
      // (which also tell us the kind of column to create in Drill.)
      // Position: key: ^
      fieldParser = detectValueParser(key, tokenizer);
      members.put(key, fieldParser);
    }
    // Parse the field value.
    // Position: key: ^ value ...
    fieldParser.parse(tokenizer);
  }

  /**
   * If the column is not projected, create a dummy parser to "free wheel" over
   * the value. Otherwise, look ahead a token or two to determine the the type
   * of the field. Then the caller will backtrack to parse the field.
   *
   * @param key name of the field
   * @return parser for the field
   */
  private ElementParser detectValueParser(String key, TokenIterator tokenizer) {
    if (key.isEmpty()) {
      throw errorFactory().structureError(
          "Drill does not allow empty keys in JSON key/value pairs");
    }
    ElementParser fieldParser = onField(key, tokenizer);
    if (fieldParser == null) {
      logger.warn("No JSON element parser returned for field {}, assuming unprojected", key);
      return DummyValueParser.INSTANCE;
    } else {
      return fieldParser;
    }
  }

  public ElementParser replaceFieldParser(String key, ElementParser fieldParser) {
    members.put(key, fieldParser);
    return fieldParser;
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.storageimportexport.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;

/** Resource collection API of BitLockerKeys. */
public interface BitLockerKeys {
    /**
     * Returns the BitLocker Keys for all drives in the specified job.
     *
     * @param jobName The name of the import/export job.
     * @param resourceGroupName The resource group name uniquely identifies the resource group within the user
     *     subscription.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.storageimportexport.models.ErrorResponseException thrown if the request is
     *     rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return getBitLockerKeys response.
     */
    PagedIterable<DriveBitLockerKey> list(String jobName, String resourceGroupName);

    /**
     * Returns the BitLocker Keys for all drives in the specified job.
     *
     * @param jobName The name of the import/export job.
     * @param resourceGroupName The resource group name uniquely identifies the resource group within the user
     *     subscription.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.storageimportexport.models.ErrorResponseException thrown if the request is
     *     rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return getBitLockerKeys response.
     */
    PagedIterable<DriveBitLockerKey> list(String jobName, String resourceGroupName, Context context);
}


text:
clean:
	find . -name flymake_* -delete

test: clean
	go test -v .

test-grep: clean
	go test -v . -check.f=$(e)

cover: clean
	go test -v .  -coverprofile=/tmp/coverage.out
	go tool cover -html=/tmp/coverage.out


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

namespace Orleans.LogConsistency
{
    ///
    /// Interface for diagnostics.
    ///
    public interface ILogConsistencyDiagnostics
    {
        /// Turns on the statistics collection for this log-consistent grain.
        void EnableStatsCollection();

        /// Turns off the statistics collection for this log-consistent grain.
        void DisableStatsCollection();

        /// Gets the collected statistics for this log-consistent grain.
        LogConsistencyStatistics GetStats();

    }

    ///
    /// A collection of statistics for grains using log-consistency. See <see cref="LogConsistentGrain{T}"/>
    ///
    public class LogConsistencyStatistics
    {
        ///
        /// A map from event names to event counts
        ///
        public Dictionary<String, long> EventCounters;
        ///
        /// A list of all measured stabilization latencies
        ///
        public List<int> StabilizationLatenciesInMsecs;
    }
}


text:
<?php

defined( 'ABSPATH' ) or exit;

/**
 * Export Email Class
 *
 * Helper class for emailing exported file
 *
 * @since 3.1.0
 */
class WC_Customer_Order_CSV_Export_Method_Email implements WC_Customer_Order_CSV_Export_Method {

	/** @var string temporary filename to be deleted */
	private $temp_filename;

	/** @var string email recipients */
	private $email_recipients;

	/** @var string email subject */
	private $email_subject;

	/** @var string email message */
	private $email_message;

	/** @var string email id */
	private $email_id;

	/**
	 * Initialize the export method
	 *
	 * @since 4.0.0
	 * @param array $args {
	 *     An array of arguments.
	 *
	 *     @type string $email_recipients Email recipients
	 *     @type string $email_subject Email subject
	 *     @type string $email_message Email message
	 *     @type string $email_id Email ID
	 * }
	 */
	 public function __construct( $args ) {

		$this->email_recipients = $args['email_recipients'];
		$this->email_subject    = $args['email_subject'];
		$this->email_message    = $args['email_message'];
		$this->email_id         = $args['email_id'];
	}

	/**
	 * Emails the admin with the exported file as an attachment
	 *
	 * @since 3.1.0
	 * @param string $filename the attachment file path
	 * @throws SV_WC_Plugin_Exception wp_mail errors
	 * @return bool whether the mail was sent successfully or not
	 */
	public function perform_action( $file_path ) {

		if ( empty( $file_path ) ) {
			throw new SV_WC_Plugin_Exception( __( 'Missing file path', 'woocommerce-customer-order-csv-export' ) );
		}

		// init email args
		$mailer  = WC()->mailer();
		$to      = ( $email = $this->email_recipients ) ? $email : get_option( 'admin_email' );
		$subject = $this->email_subject;
		$message = $this->email_message;

		// Allow actors to change the email headers.
		$headers      = apply_filters( 'woocommerce_email_headers', "Content-Type: text/plain\r\n", $this->email_id );
		$attachments  = array( $file_path );

		// hook into `wp_mail_failed` and throw errors as exceptions
		add_action( 'wp_mail_failed', array( $this, 'handle_wp_mail_error' ) );

		// send email
		$result = $mailer->send( $to, $subject, $message, $headers, $attachments );

		// unhook from wp_mail_failed
		remove_action( 'wp_mail_failed', array( $this, 'handle_wp_mail_error' ) );

		return $result;
	}

	/**
	 * Handle wp_mail_failed errors, by throwing them as exceptions
	 *
	 * @since 4.0.0
	 * @param \WP_Error $error
	 * @throws \Exception
	 */
	public function handle_wp_mail_error( WP_Error $error ) {

		// unhook from wp_mail_failed
		remove_action( 'wp_mail_failed', array( $this, 'handle_wp_mail_error' ) );

		throw new SV_WC_Plugin_Exception( $error->get_error_message() );
	}

}


text:
require 'bundler/setup'
require 'harness/action_controller'
require 'minitest/unit'
require 'minitest/autorun'

class MiniTest::Unit::TestCase
  def setup
    Harness.config.collector = Harness::FakeCollector.new
    Harness.config.queue = Harness::SyncQueue.new
  end

  def assert_timer(name)
    refute_empty timers
    timer = timers.find { |t| t.name == name }
    assert timer, "Timer #{name} not logged!"
  end

  def assert_increment(name)
    refute_empty increments
    increment = increments.find { |i| i.name == name }
    assert increment, "Increment #{name} not logged!"
  end

  def assert_decrement(name)
    refute_empty decrements
    decrement = decrements.find { |i| i.name == name }
    assert decrement, "decrement #{name} not logged!"
  end

  def assert_gauge(name)
    refute_empty gauges
    gauge = gauges.find { |g| g.name == name }
    assert gauge, "gauge #{name} not logged!"
  end

  def instrument(name, data = {}, &block)
    ActiveSupport::Notifications.instrument name, data, &block
  end

  def collector
    Harness.config.collector
  end

  def timers
    collector.timers
  end

  def increments
    collector.increments
  end

  def decrements
    collector.decrements
  end

  def counters
    collector.counters
  end

  def gauges
    collector.gauges
  end
end


text:
"""
An RPC load balancer class using ZeroMQ as a transport and
the standard Python threading API for concurrency.

Authors
-------
* Alexander Glyzov
"""

#-----------------------------------------------------------------------------
#  Copyright (C) 2014. Alexander Glyzov
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file LICENSE distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from ..base import RPCLoadBalancerBase

#-----------------------------------------------------------------------------
# RPC Load Balancer
#-----------------------------------------------------------------------------

class GreenRPCLoadBalancer(RPCLoadBalancerBase):

    def __init__(self, *ar, **kw):
        super(GreenRPCLoadBalancer, self).__init__(*ar, **kw)

        # start greenlets
        submit = self.executor.submit

        self.req_balancer   = submit(self._req_balancer)
        self.ans_forwarder  = submit(self._ans_forwarder)
        self.peer_refresher = submit(self._peer_refresher)

    def _req_balancer(self):
        """ Request balancer -- forwards client requests to peer workers
            balancing their load by tracking number of running tasks
        """
        recv_request  = self.inp_sock.recv_multipart
        send_requests = self.send_requests
        exit_ev       = self._exit_ev
        logger        = self.logger

        # receive loop
        while not exit_ev.is_set():
            try:
                request = recv_request()
                #logger.debug('recv: %r', request)
            except Exception, err:
                logger.warning(err)
                break

            if request[0] == b'QUIT':
                logger.debug('req_balancer received a QUIT signal')
                break

            if len(request) < 6 or b'|' not in request:
                logger.warning('skipping bad request: %r', request)
                continue

            send_requests(request)

        logger.debug('greenlet exited')

    def _ans_forwarder(self):
        """ Forwards worker answers back to the client
        """
        recv_answer = self.out_sock.recv_multipart
        send_answer = self.send_answer
        exit_ev     = self._exit_ev
        logger      = self.logger

        while not exit_ev.is_set():
            try:
                answer = recv_answer()
                #logger.debug('received: %r', answer)
            except Exception, err:
                self.logger.warning(err)
                break

            if answer[0] == b'QUIT':
                logger.debug('ans_forwarder received a QUIT signal')
                break

            if len(answer) < 5 or b'|' not in answer:
                logger.warning('skipping bad answer: %r', answer)
                continue

            try:
                send_answer(answer)
            except Exception, err:
                logger.warning(err)
                break

        logger.debug('greenlet exited')


text:
///////////////////////////////////////////////////////////////////////
// Portions of this code was ported from glob-js by Kevin Thompson.
// https://github.com/kthompson/glob-js
///////////////////////////////////////////////////////////////////////

using System.Collections.Generic;
using System.Linq;

namespace Cake.Core.IO.Globbing.Nodes
{
    internal sealed class SegmentNode : Node
    {
        private readonly List<Node> _items;

        public override bool IsWildcard
        {
            get { return _items.Any(x => x.IsWildcard); }
        }

        public SegmentNode(List<Node> items)
        {
            _items = items;
        }

        public override string Render()
        {
            return string.Join(string.Empty, _items.Select(x => x.Render()));
        }
    }
}


text:
#ifndef _DOCUMENT_PROCESSOR_
#define _DOCUMENT_PROCESSOR_

#include "statcalc-data-types.h"
#include "lemmatizer.h"
#include "ISentenceSplitter.h"
#include "RegExp.h"

using namespace Tokenization;
using lemmatizer::ILemmatizer;
using _sentence_splitter::ISentenceSplitter;

namespace statcalc
{

/**
 * @class	DocumentProcessor
 * @brief	Class for converting documents to bag-of-words format and storing others good statistics...
 */
class DocumentProcessor
{
public:
    /**
     * @brief Default constructor for document processor
     * @param[in] i_tokenizer is shared pointer to object tokenizer
     * @param[in] i_lemmatizer is shared pointer to object lemmatizer
     */
    DocumentProcessor(shared_ptr<ITokenizer> i_tokenizer, shared_ptr<ILemmatizer> i_lemmatizer, shared_ptr<ISentenceSplitter> i_splitter);

    /**
     * @brief main function for converting document from plain text to bag of words
     * @param[in] i_document is document for procesing
     * @param[out] o_docBOW structure for storing result
     * @return true in case of success, false otherwise
     */
    bool processDocument(std::shared_ptr<Tools::Document> i_document, StatCalc &i_statcalc);

    /**
     * @overload processDocument(const vector<vector<DisambiguatedData> >& i_doc, WordIntStat& o_docBOW);
     * @param[in] i_doc is already disambiguated data for processing
     * @param[out] o_docBOW structure for storing result
     * @return true in case of success, false otherwise
     */
    bool processDocument(const vector<vector<DisambiguatedData> >& i_doc, StatCalc &i_statcalc);

    /**
     * @brief docBOW is getter for bag-of-words form of document
     * @return m_docBOW
     */
    unordered_map<int,int>& docBOW(void)
    {
        return m_docBOW;
    }

    /**
     * @brief cleaning m_docBOW and m_docPlain
     */
    void clean(void);

private:
    void processSentence_(wstring& currentSentence, StatCalc &i_statcalc);

    unordered_map<int,int> m_docBOW;
    RegExpTools m_reTools;
    shared_ptr<ITokenizer> m_tokenizer;
    shared_ptr<ILemmatizer> m_lemmatizer;
    shared_ptr<ISentenceSplitter> m_splitter;
};

}
#endif //_DOCUMENT_PROCESSOR_


text:
'use strict';

var hljs = require('highlight.js');

module.exports = function (hljsOptions) {
  hljs.configure(hljsOptions);

  return function (example) {
    if (hljsOptions.highlightAuto) {
      return hljs.highlightAuto(example).value;
    }
    return hljs.highlight('js', example).value;
  };
};


text:
@interface TravelViewController : UIViewController

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuite xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd" name="org.json.simple.parser.YylexTest" time="0.001" tests="1" errors="0" skipped="0" failures="0">
  <properties>
    <property name="gopherProxySet" value="false"/>
    <property name="awt.toolkit" value="sun.lwawt.macosx.LWCToolkit"/>
    <property name="file.encoding.pkg" value="sun.io"/>
    <property name="java.specification.version" value="1.8"/>
    <property name="sun.cpu.isalist" value=""/>
    <property name="sun.jnu.encoding" value="UTF-8"/>
    <property name="java.class.path" value="/Users/kovacsadam/bme/json-simple/target/test-classes:/Users/kovacsadam/bme/json-simple/target/classes:/Users/kovacsadam/.m2/repository/junit/junit/4.10/junit-4.10.jar:/Users/kovacsadam/.m2/repository/org/hamcrest/hamcrest-core/1.1/hamcrest-core-1.1.jar:"/>
    <property name="java.vm.vendor" value="Oracle Corporation"/>
    <property name="sun.arch.data.model" value="64"/>
    <property name="java.vendor.url" value="http://java.oracle.com/"/>
    <property name="user.timezone" value=""/>
    <property name="user.country.format" value="HU"/>
    <property name="java.vm.specification.version" value="1.8"/>
    <property name="os.name" value="Mac OS X"/>
    <property name="user.country" value="US"/>
    <property name="sun.java.launcher" value="SUN_STANDARD"/>
    <property name="sun.boot.library.path" value="/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib"/>
    <property name="sun.java.command" value="/Users/kovacsadam/bme/json-simple/target/surefire/surefirebooter1571419513995184241.jar /Users/kovacsadam/bme/json-simple/target/surefire 2017-09-23T17-16-11_607-jvmRun1 surefire4896023408336710371tmp surefire_08795162943925228109tmp"/>
    <property name="http.nonProxyHosts" value="local|*.local|169.254/16|*.169.254/16"/>
    <property name="surefire.test.class.path" value="/Users/kovacsadam/bme/json-simple/target/test-classes:/Users/kovacsadam/bme/json-simple/target/classes:/Users/kovacsadam/.m2/repository/junit/junit/4.10/junit-4.10.jar:/Users/kovacsadam/.m2/repository/org/hamcrest/hamcrest-core/1.1/hamcrest-core-1.1.jar:"/>
    <property name="sun.cpu.endian" value="little"/>
    <property name="user.home" value="/Users/kovacsadam"/>
    <property name="user.language" value="en"/>
    <property name="java.specification.vendor" value="Oracle Corporation"/>
    <property name="java.home" value="/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre"/>
    <property name="basedir" value="/Users/kovacsadam/bme/json-simple"/>
    <property name="file.separator" value="/"/>
    <property name="line.separator" value="
"/>
    <property name="java.vm.specification.vendor" value="Oracle Corporation"/>
    <property name="java.specification.name" value="Java Platform API Specification"/>
    <property name="java.awt.graphicsenv" value="sun.awt.CGraphicsEnvironment"/>
    <property name="surefire.real.class.path" value="/Users/kovacsadam/bme/json-simple/target/surefire/surefirebooter1571419513995184241.jar"/>
    <property name="sun.boot.class.path" value="/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/sunrsasign.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/classes"/>
    <property name="sun.management.compiler" value="HotSpot 64-Bit Tiered Compilers"/>
    <property name="ftp.nonProxyHosts" value="local|*.local|169.254/16|*.169.254/16"/>
    <property name="java.runtime.version" value="1.8.0_144-b01"/>
    <property name="user.name" value="kovacsadam"/>
    <property name="path.separator" value=":"/>
    <property name="os.version" value="10.11.6"/>
    <property name="java.endorsed.dirs" value="/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/endorsed"/>
    <property name="java.runtime.name" value="Java(TM) SE Runtime Environment"/>
    <property name="file.encoding" value="UTF-8"/>
    <property name="java.vm.name" value="Java HotSpot(TM) 64-Bit Server VM"/>
    <property name="localRepository" value="/Users/kovacsadam/.m2/repository"/>
    <property name="java.vendor.url.bug" value="http://bugreport.sun.com/bugreport/"/>
    <property name="java.io.tmpdir" value="/var/folders/y6/rb7yrjz90ml02cqdj5yy462h0000gn/T/"/>
    <property name="java.version" value="1.8.0_144"/>
    <property name="user.dir" value="/Users/kovacsadam/bme/json-simple"/>
    <property name="os.arch" value="x86_64"/>
    <property name="java.vm.specification.name" value="Java Virtual Machine Specification"/>
    <property name="java.awt.printerjob" value="sun.lwawt.macosx.CPrinterJob"/>
    <property name="sun.os.patch.level" value="unknown"/>
    <property name="java.library.path" value="/Users/kovacsadam/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:."/>
    <property name="java.vm.info" value="mixed mode"/>
    <property name="java.vendor" value="Oracle Corporation"/>
    <property name="java.vm.version" value="25.144-b01"/>
    <property name="java.ext.dirs" value="/Users/kovacsadam/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java"/>
    <property name="sun.io.unicode.encoding" value="UnicodeBig"/>
    <property name="java.class.version" value="52.0"/>
    <property name="socksNonProxyHosts" value="local|*.local|169.254/16|*.169.254/16"/>
  </properties>
  <testcase name="testYylex" classname="org.json.simple.parser.YylexTest" time="0.001"/>
</testsuite>


text:
/* @flow */

import context from "./context";
import request from "./request";
import response from "./response";
import cookies from "./cookies";
import http from "./http";
import util from "./util";
import server from "./server";

import Emitter from 'events';
import compose from 'koa-compose';
import statuses from 'statuses';
import accepts from 'accepts';
import Stream from 'stream';
import only from 'only';

class Application extends Emitter {
  proxy: boolean = false;
  middleware: Array<KoaMiddlewareType> = [];

  constructor() {
    super();

    this.proxy = false;
    this.middleware = [];
    this.subdomainOffset = 2;
    this.env = process.env.NODE_ENV || 'development';
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
    this.listening = false;
  }

  listen() {
    this.composedMiddleware = compose(this.middleware);
    if (!this.listeners('error').length) this.on('error', this.onerror);
    this.listening = true;
    return server.listen.apply(server, arguments);
  }

  /**
  * Return JSON representation.
  * We only bother showing settings.
  *
  * @return {Object}
  * @api public
  */

  toJSON() {
    return only(this, [
      'subdomainOffset',
      'proxy',
      'env'
    ]);
  }

  /**
  * Inspect implementation.
  *
  * @return {Object}
  * @api public
  */

  inspect() {
    return this.toJSON();
  }

  /**
  * Use the given middleware `fn`.
  *
  * @param {Function} fn
  * @return {Application} self
  * @api public
  */

  use(fn) {
    this.middleware.push(fn);
    return this;
  }

  _createAnchor(url) {
    var a = document.createElement("a");
    a.href = url;
    return a;
  }

  httpGet(url) {
    const anchor = _createAnchor(url);

    const request = {};
    request.url = url;
    request.method = "GET";
    request.path = anchor.pathname;
    request.host = anchor.host;
    request.hostname = anchor.hostname;
    request.protocol = location.protocol;
    request.search = anchor.search;

    return runMiddleware(request, {});
  }

  /*
  Handle a request coming via PageJS client-side routing mechanism
  The incoming context will be a PageJS context, which needs to be converted to a KoaJS context.
  */
  handleIsotropyXMLHttpRequest(request) {
    var req = new NativeRequest({
      method: request.method,
      url: request.url,
      headers: request.requestHeaders || {}
    });

    //koa will use lower case for these headers
    if (request.requestHeaders["Content-Type"]) {
      req.headers["content-type"] = request.requestHeaders["Content-Type"];
    }

    var res = new NativeResponse();
    this.requestListener.call(this.app, req, res);

    req.emit("data", request.requestBody);
    req.emit("end");

    var self = this;
    res.on("end", function(body) {
      request.respond(self.status, self.headers, body);
    });
  };

  /*
  Handle a request coming via PageJS client-side routing mechanism
  The incoming context will be a PageJS context, which needs to be converted to a KoaJS context.
  */
  handlePageJSRequest(pageJSContext) {
    var req = new NativeRequest({
      method: "GET",
      url: pageJSContext.path,
      headers: {}
    });
    var res = new NativeResponse();
    this.requestListener.call(this.app, req, res);
  }

  /**
  * Return a request handler callback
  * for node's native http server.
  *
  * @return {Function}
  * @api public
  */

  runMiddleware(req, res) {
    res.statusCode = 404;
    const ctx = this.createContext(req, res);
    onFinished(res, ctx.onerror);
    return this.composedMiddleware(ctx).then(() => respond(ctx)).catch(ctx.onerror);
  }

  /**
  * Initialize a new context.
  *
  * @api private
  */

  createContext(req, res) {
    const context = Object.create(this.context);
    const request = context.request = Object.create(this.request);
    const response = context.response = Object.create(this.response);
    context.app = request.app = response.app = this;
    context.req = request.req = response.req = req;
    context.res = request.res = response.res = res;
    request.ctx = response.ctx = context;
    request.response = response;
    response.request = request;
    context.onerror = context.onerror.bind(context);
    context.originalUrl = request.originalUrl = req.url;
    context.cookies = new Cookies(req, res, this.keys);
    context.accept = request.accept = accepts(req);
    context.state = {};
    return context;
  }

  /**
  * Default error handler.
  *
  * @param {Error} err
  * @api private
  */

  onerror(err) {
    assert(err instanceof Error, `non-error thrown: ${err}`);

    if (404 == err.status || err.expose) return;
    if (this.silent) return;

    const msg = err.stack || err.toString();
    console.error();
    console.error(msg.replace(/^/gm, '  '));
    console.error();
  }

};

/**
* Response helper.
*/

function respond(ctx) {
  // allow bypassing koa
  if (false === ctx.respond) return;

  const res = ctx.res;
  if (res.headersSent || !ctx.writable) return;

  let body = ctx.body;
  const code = ctx.status;

  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    ctx.body = null;
    return res.end();
  }

  if ('HEAD' == ctx.method) {
    if (isJSON(body)) ctx.length = Buffer.byteLength(JSON.stringify(body));
    return res.end();
  }

  // status body
  if (null == body) {
    ctx.type = 'text';
    body = ctx.message || String(code);
    ctx.length = Buffer.byteLength(body);
    return res.end(body);
  }

  // responses
  if (Buffer.isBuffer(body)) return res.end(body);
  if ('string' == typeof body) return res.end(body);
  if (body instanceof Stream) return body.pipe(res);

  // body: json
  body = JSON.stringify(body);
  ctx.length = Buffer.byteLength(body);
  res.end(body);
}

export default Application;


text:
require 'gooddata/commands/user'

describe GoodData::Command::User do
  before(:each) do
    @client = ConnectionHelper.create_default_connection
  end

  after(:each) do
    @client.disconnect
  end

  it "Is Possible to create GoodData::Command::Membership instance" do
    cmd = GoodData::Command::User.new()
    cmd.should be_a(GoodData::Command::User)
  end

  describe "#show" do
    it "Shows profile" do
      GoodData::Command::User.show(:client => @client)
    end
  end
end


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;

    /// <summary>
    /// The type WorkbookFunctionsOct2BinRequestBody.
    /// </summary>
    [DataContract]
    public partial class WorkbookFunctionsOct2BinRequestBody
    {

        /// <summary>
        /// Gets or sets Number.
        /// </summary>
        [DataMember(Name = "number", EmitDefaultValue = false, IsRequired = false)]
        public Newtonsoft.Json.Linq.JToken Number { get; set; }

        /// <summary>
        /// Gets or sets Places.
        /// </summary>
        [DataMember(Name = "places", EmitDefaultValue = false, IsRequired = false)]
        public Newtonsoft.Json.Linq.JToken Places { get; set; }

    }
}


text:
<?php

namespace Laravel\Spark\Http\Controllers\Auth;

use App\User;
use Validator;
use Exception;
use Carbon\Carbon;
use Laravel\Spark\Spark;
use Illuminate\Http\Request;
use Stripe\Coupon as StripeCoupon;
use Illuminate\Support\Facades\DB;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Spark\Subscriptions\Plan;
use Laravel\Spark\Events\User\Registered;
use Laravel\Spark\Events\User\Subscribed;
use Laravel\Spark\InteractsWithSparkHooks;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Laravel\Spark\Contracts\Repositories\UserRepository;
use Laravel\Spark\Contracts\Repositories\TeamRepository;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Laravel\Spark\Contracts\Auth\Subscriber as SubscriberContract;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins, ValidatesRequests, InteractsWithSparkHooks;

    /**
     * The user repository instance.
     *
     * @var \Laravel\Spark\Contracts\Repositories\UserRepository
     */
    protected $users;

    /**
     * The team repository instance.
     *
     * @var \Laravel\Spark\Contracts\Repositories\TeamRepository
     */
    protected $teams;

    /**
     * The URI for the login route.
     *
     * @var string
     */
    protected $loginPath = '/login';

    /**
     * Create a new authentication controller instance.
     *
     * @param  \Laravel\Spark\Contracts\Repositories\UserRepository  $users
     * @param  \Laravel\Spark\Contracts\Repositories\TeamRepository  $teams
     * @return void
     */
    public function __construct(UserRepository $users, TeamRepository $teams)
    {
        $this->users = $users;
        $this->teams = $teams;
        $this->plans = Spark::plans();

        $this->middleware('guest', ['except' => 'getLogout']);
    }

    /**
     * Show the application login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getLogin()
    {
        return view('spark::auth.authenticate');
    }

    /**
     * Send the post-authentication response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @return \Illuminate\Http\Response
     */
    protected function authenticated(Request $request, Authenticatable $user)
    {
        if (Spark::supportsTwoFactorAuth() && Spark::twoFactorProvider()->isEnabled($user)) {
            return $this->logoutAndRedirectToTokenScreen($request, $user);
        }

        return redirect()->intended($this->redirectPath());
    }

    /**
     * Generate a redirect response to the two-factor token screen.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $users
     * @return \Illuminate\Http\Response
     */
    protected function logoutAndRedirectToTokenScreen(Request $request, Authenticatable $user)
    {
        Auth::logout();

        $request->session()->put('spark:auth:id', $user->id);

        return redirect('login/token');
    }

    /**
     * Show the two-factor authentication token verification form.
     *
     * @return \Illuminate\Http\Response
     */
    public function getToken()
    {
        return session('spark:auth:id') ? view('spark::auth.token') : redirect('login');
    }

    /**
     * Verify the two-factor authentication token.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postToken(Request $request)
    {
        $this->validate($request, ['token' => 'required']);

        if (! session('spark:auth:id')) {
            return redirect('login');
        }

        $model = config('auth.model');

        $user = (new $model)->findOrFail(
            $request->session()->pull('spark:auth:id')
        );

        if (Spark::twoFactorProvider()->tokenIsValid($user, $request->token)) {
            Auth::login($user);

            return redirect()->intended($this->redirectPath());
        } else {
            return back();
        }
    }

    /**
     * Show the application registration form.
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function getRegister(Request $request)
    {
        if (Spark::forcingPromotion() && ! $request->query('coupon')) {
            if (count($request->query()) > 0) {
                return redirect($request->fullUrl().'&coupon='.Spark::forcedPromotion());
            } else {
                return redirect($request->fullUrl().'?coupon='.Spark::forcedPromotion());
            }
        }

        if (count($this->plans->paid()) > 0) {
            return view('spark::auth.registration.subscription');
        } else {
            return view('spark::auth.registration.simple');
        }
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postRegister(Request $request)
    {
        $withSubscription = count($this->plans->paid()) > 0 &&
                            $this->plans->find($request->plan) &&
                            $this->plans->find($request->plan)->price > 0;

        return $this->register($request, $withSubscription);
    }

    /**
     * Handle a registration request for the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $withSubscription
     * @return \Illuminate\Http\Response
     */
    protected function register(Request $request, $withSubscription = false)
    {
        $this->validateRegistration($request, $withSubscription);

        $user = $this->users->createUserFromRegistrationRequest(
            $request, $withSubscription
        );

        if ($request->team_name) {
            $team = $this->teams->create($user, ['name' => $request->team_name]);
        }

        if ($request->invitation) {
            $this->teams->attachUserToTeamByInvitation($request->invitation, $user);
        }

        event(new Registered($user));

        if ($withSubscription) {
            event(new Subscribed($user));
        }

        Auth::login($user);

        return response()->json(['path' => $this->redirectPath()]);
    }

    /**
     * Validate the new registration.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $withSubscription
     * @return void
     */
    protected function validateRegistration(Request $request, $withSubscription = false)
    {
        if (Spark::$validateRegistrationsWith) {
            $this->callCustomValidator(
                Spark::$validateRegistrationsWith, $request, [$withSubscription]
            );
        } else {
            $this->validateDefaultRegistration($request, $withSubscription);
        }
    }

    /**
     * Validate a new registration using the default rules.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  bool  $withSubscription
     * @return void
     */
    protected function validateDefaultRegistration(Request $request, $withSubscription)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:6',
            'terms' => 'required|accepted',
        ]);

        if ($withSubscription) {
            $validator->mergeRules('stripe_token', 'required');

            if ($request->coupon) {
                $validator->after(function ($validator) use ($request) {
                    $this->validateCoupon($validator, $request);
                });
            }
        }

        if ($validator->fails()) {
            $this->throwValidationException($request, $validator);
        }
    }

    /**
     * Validate that the provided coupon actually exists on Stripe.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @param  \Illuminate\Http\Request  $request
     * @return void
     */
    protected function validateCoupon($validator, Request $request)
    {
        try {
            $coupon = StripeCoupon::retrieve(
                $request->coupon, ['api_key' => config('services.stripe.secret')]
            );

            if ($coupon && $coupon->valid) {
                return;
            }
        } catch (Exception $e) {
            //
        }

        $validator->errors()->add('coupon', 'The provided coupon code is invalid.');
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function getLogout(Request $request)
    {
        $request->session()->flush();

        Auth::logout();

        return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
    }

    /**
     * Get the post register / login redirect path.
     *
     * @return string
     */
    public function redirectPath()
    {
        return Spark::$afterAuthRedirectTo;
    }
}


text:
import roxotAnalytic from 'modules/roxotAnalyticsAdapter';
import { expect } from 'chai';
let events = require('src/events');
let adaptermanager = require('src/adaptermanager');
let constants = require('src/constants.json');

describe('Roxot Prebid Analytic', function () {
  describe('enableAnalytics', function () {
    beforeEach(() => {
      sinon.spy(roxotAnalytic, 'track');
    });

    afterEach(() => {
      roxotAnalytic.track.restore();
    });
    it('should catch all events', function () {
      adaptermanager.registerAnalyticsAdapter({
        code: 'roxot',
        adapter: roxotAnalytic
      });

      adaptermanager.enableAnalytics({
        provider: 'roxot',
        options: {
          publisherIds: ['test_roxot_prebid_analytid_publisher_id']
        }
      });

      events.emit(constants.EVENTS.AUCTION_INIT, {});
      events.emit(constants.EVENTS.AUCTION_END, {});
      events.emit(constants.EVENTS.BID_REQUESTED, {});
      events.emit(constants.EVENTS.BID_RESPONSE, {});
      events.emit(constants.EVENTS.BID_WON, {});

      sinon.assert.callCount(roxotAnalytic.track, 5);
    });
  });
  describe('build utm tag data', () => {
    beforeEach(() => {
      localStorage.setItem('roxot_analytics_utm_source', 'utm_source');
      localStorage.setItem('roxot_analytics_utm_medium', 'utm_medium');
      localStorage.setItem('roxot_analytics_utm_campaign', '');
      localStorage.setItem('roxot_analytics_utm_term', '');
      localStorage.setItem('roxot_analytics_utm_content', '');
      localStorage.setItem('roxot_analytics_utm_timeout', Date.now());
    });
    it('should build utm data from local storage', () => {
      let utmTagData = roxotAnalytic.buildUtmTagData();
      expect(utmTagData.utm_source).to.equal('utm_source');
      expect(utmTagData.utm_medium).to.equal('utm_medium');
      expect(utmTagData.utm_campaign).to.equal('');
      expect(utmTagData.utm_term).to.equal('');
      expect(utmTagData.utm_content).to.equal('');
    });
  });
});


text:
let flowFactory: ng.flow.FlowFactory;
flowFactory.create({} as any as flowjs.FlowOptions);


text:
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import StaticPool

# Database
engine = create_engine('sqlite:///files/chats.db', convert_unicode=True,
                        connect_args= {'check_same_thread': False},
                        poolclass=StaticPool)
db_session = scoped_session(sessionmaker(autocommit=False,
                                        autoflush=False,
                                        bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
  # import all modules here that might define models so that
  # they will be registered properly on the metadata.  Otherwise
  # you will have to import them first before calling init_db()
  import scraper.models
  Base.metadata.create_all(bind=engine)