text:
#ifndef __HAL_CAMERA_HARDWARE_H__
#define __HAL_CAMERA_HARDWARE_H__

/*
 * Contains declaration of a class CameraHardware that encapsulates functionality
 * common to all V4L2Cameras ("fake", "webcam", "video file", etc.).
 * Instances of this class (for each V4L2Camera) are created during the
 * construction of the HALCameraFactory instance.
 * This class serves as an entry point for all camera API calls that defined
 * by camera_device_ops_t API.
 */

#include <utils/Mutex.h>

#include <videodev2.h>
#include <camera/CameraParameters.h>
#include <FaceDetectionApi.h>

#include "V4L2CameraDevice.h"
#include "PreviewWindow.h"
#include "CallbackNotifier.h"
#include "CCameraConfig.h"

namespace android {

#define KEY_CAMERA_HAL_VERSION			"camera-hal-version"
#define KEY_CAPTURE_SIZE_WIDTH			"capture-size-width"
#define KEY_CAPTURE_SIZE_HEIGHT			"capture-size-height"
#define KEY_PREVIEW_CAPTURE_SIZE_WIDTH	"preview_capture-size-width"
#define KEY_PREVIEW_CAPTURE_SIZE_HEIGHT	"preview_capture-size-height"

#define KEY_PICTURE_MODE				"picture-mode"
#define PICTURE_MODE_NORMAL				"normal"
#define PICTURE_MODE_CONTINUOUS			"continuous"
#define PICTURE_MODE_CONTINUOUS_FAST	"continuous-fast"
#define KEY_CANCEL_CONTINUOUS_PICTURE	"cancel_continuous_picture"		// "true" for stopping
#define KEY_CONTINUOUS_PICTURE_PATH		"continuous-picture-path"

#define KEY_SNAP_PATH					"snap-path"

/* Encapsulates functionality common to all V4L2Cameras.
 *
 * Note that HALCameraFactory instantiates object of this class just once,
 * when HALCameraFactory instance gets constructed. Connection to /
 * disconnection from the actual camera device is handled by calls to connectDevice(),
 * and closeCamera() methods of this class that are ivoked in response to
 * hw_module_methods_t::open, and camera_device::close callbacks.
 */
class CameraHardware : public camera_device {
public:
    /* Constructs CameraHardware instance.
     * Param:
     *  module - V4L2Camera HAL module descriptor.
     */
    CameraHardware(struct hw_module_t* module, CCameraConfig* pCameraCfg);

    /* Destructs CameraHardware instance. */
    virtual ~CameraHardware();

    /****************************************************************************
     * Public API
     ***************************************************************************/

public:
    /* Initializes CameraHardware instance.
     * Return:
     *  NO_ERROR on success, or an appropriate error status on failure.
     */
    virtual status_t Initialize();

    /* Entry point for notifications that occur in camera device.
     * Param:
     *  err - CAMERA_ERROR_XXX error code.
     */
    virtual void onCameraDeviceError(int err);

    /****************************************************************************
     * Camera API implementation
     ***************************************************************************/

public:
    /* Creates connection to the V4L2Camera device.
     * This method is called in response to hw_module_methods_t::open callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t connectCamera(hw_device_t** device);

    /* Closes connection to the V4L2Camera.
     * This method is called in response to camera_device::close callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t closeCamera();

    /****************************************************************************
     * Camera API implementation.
     * These methods are called from the camera API callback routines.
     ***************************************************************************/

protected:
    /* Actual handler for camera_device_ops_t::set_preview_window callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t setPreviewWindow(struct preview_stream_ops *window);

    /* Actual handler for camera_device_ops_t::set_callbacks callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void setCallbacks(camera_notify_callback notify_cb,
                              camera_data_callback data_cb,
                              camera_data_timestamp_callback data_cb_timestamp,
                              camera_request_memory get_memory,
                              void* user);

    /* Actual handler for camera_device_ops_t::enable_msg_type callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void enableMsgType(int32_t msg_type);

    /* Actual handler for camera_device_ops_t::disable_msg_type callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void disableMsgType(int32_t msg_type);

    /* Actual handler for camera_device_ops_t::msg_type_enabled callback.
     * NOTE: When this method is called the object is locked.
     * Return:
     *  0 if message(s) is (are) disabled, != 0 if enabled.
     */
    virtual int isMsgTypeEnabled(int32_t msg_type);

    /* Actual handler for camera_device_ops_t::start_preview callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t startPreview();

    /* Actual handler for camera_device_ops_t::stop_preview callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void stopPreview();

    /* Actual handler for camera_device_ops_t::preview_enabled callback.
     * NOTE: When this method is called the object is locked.
     * Return:
     *  0 if preview is disabled, != 0 if enabled.
     */
    virtual int isPreviewEnabled();

    /* Actual handler for camera_device_ops_t::store_meta_data_in_buffers callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t storeMetaDataInBuffers(int enable);

    /* Actual handler for camera_device_ops_t::start_recording callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t startRecording();

    /* Actual handler for camera_device_ops_t::stop_recording callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void stopRecording();

    /* Actual handler for camera_device_ops_t::recording_enabled callback.
     * NOTE: When this method is called the object is locked.
     * Return:
     *  0 if recording is disabled, != 0 if enabled.
     */
    virtual int isRecordingEnabled();

    /* Actual handler for camera_device_ops_t::release_recording_frame callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void releaseRecordingFrame(const void* opaque);

    /* Actual handler for camera_device_ops_t::auto_focus callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t setAutoFocus();

    /* Actual handler for camera_device_ops_t::cancel_auto_focus callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t cancelAutoFocus();

    /* Actual handler for camera_device_ops_t::take_picture callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t takePicture();

    /* Actual handler for camera_device_ops_t::cancel_picture callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t cancelPicture();

    /* Actual handler for camera_device_ops_t::set_parameters callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t setParameters(const char* parms);

    /* Actual handler for camera_device_ops_t::get_parameters callback.
     * NOTE: When this method is called the object is locked.
     * Return:
     *  Flattened parameters string. The caller will free the buffer allocated
     *  for the string by calling camera_device_ops_t::put_parameters callback.
     */
    virtual char* getParameters();

    /* Actual handler for camera_device_ops_t::put_parameters callback.
     * Called to free the string returned from camera_device_ops_t::get_parameters
     * callback. There is nothing more to it: the name of the callback is just
     * misleading.
     * NOTE: When this method is called the object is locked.
     */
    virtual void putParameters(char* params);

    /* Actual handler for camera_device_ops_t::send_command callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2);

    /* Actual handler for camera_device_ops_t::release callback.
     * NOTE: When this method is called the object is locked.
     */
    virtual void releaseCamera();

    /* Actual handler for camera_device_ops_t::dump callback.
     * NOTE: When this method is called the object is locked.
     * Note that failures in this method are reported as negave EXXX statuses.
     */
    virtual status_t dumpCamera(int fd);

    /****************************************************************************
     * Preview management.
     ***************************************************************************/

protected:
public:
    /* Starts preview.
     * Note that when this method is called mPreviewWindow may be NULL,
     * indicating that framework has an intention to start displaying video
     * frames, but didn't create the preview window yet.
     * Return:
     *  NO_ERROR on success, or an appropriate error status on failure.
     */
    virtual status_t doStartPreview();

    /* Stops preview.
     * This method reverts DoStartPreview.
     * Return:
     *  NO_ERROR on success, or an appropriate error status on failure.
     */
    virtual status_t doStopPreview();

	status_t doTakePicture();
	status_t doTakePictureEnd();

    /****************************************************************************
     * Private API.
     ***************************************************************************/

protected:
    /* Cleans up camera when released. */
    virtual status_t cleanupCamera();

    /****************************************************************************
     * Camera API callbacks as defined by camera_device_ops structure.
     * See hardware/libhardware/include/hardware/camera.h for information on
     * each of these callbacks. Implemented in this class, these callbacks simply
     * dispatch the call into an instance of CameraHardware class defined by the
     * 'camera_device' parameter.
     ***************************************************************************/

private:
    static int set_preview_window(struct camera_device* dev,
                                   struct preview_stream_ops* window);

    static void set_callbacks(struct camera_device* dev,
                              camera_notify_callback notify_cb,
                              camera_data_callback data_cb,
                              camera_data_timestamp_callback data_cb_timestamp,
                              camera_request_memory get_memory,
                              void* user);

    static void enable_msg_type(struct camera_device* dev, int32_t msg_type);

    static void disable_msg_type(struct camera_device* dev, int32_t msg_type);

    static int msg_type_enabled(struct camera_device* dev, int32_t msg_type);

    static int start_preview(struct camera_device* dev);

    static void stop_preview(struct camera_device* dev);

    static int preview_enabled(struct camera_device* dev);

    static int store_meta_data_in_buffers(struct camera_device* dev, int enable);

    static int start_recording(struct camera_device* dev);

    static void stop_recording(struct camera_device* dev);

    static int recording_enabled(struct camera_device* dev);

    static void release_recording_frame(struct camera_device* dev,
                                        const void* opaque);

    static int auto_focus(struct camera_device* dev);

    static int cancel_auto_focus(struct camera_device* dev);

    static int take_picture(struct camera_device* dev);

    static int cancel_picture(struct camera_device* dev);

    static int set_parameters(struct camera_device* dev, const char* parms);

    static char* get_parameters(struct camera_device* dev);

    static void put_parameters(struct camera_device* dev, char* params);

    static int send_command(struct camera_device* dev,
                            int32_t cmd,
                            int32_t arg1,
                            int32_t arg2);

    static void release(struct camera_device* dev);

    static int dump(struct camera_device* dev, int fd);

    static int close(struct hw_device_t* device);

    /****************************************************************************
     * Data members
     ***************************************************************************/

protected:
    /* Locks this instance for parameters, state, etc. change. */
    Mutex                           mObjectLock;

    /* Camera parameters. */
    CameraParameters                mParameters;

    /* Preview window. */
    PreviewWindow                   mPreviewWindow;

    /* Callback notifier. */
    CallbackNotifier                mCallbackNotifier;

	V4L2CameraDevice *   			mV4L2CameraDevice;

private:
    /* Registered callbacks implementing camera API. */
    static camera_device_ops_t      mDeviceOps;

    /****************************************************************************
     * Common keys
     ***************************************************************************/

public:
    static const char FACING_KEY[];
    static const char ORIENTATION_KEY[];
    static const char RECORDING_HINT_KEY[];

     /****************************************************************************
     * Common string values
     ***************************************************************************/

    /* Possible values for FACING_KEY */
    static const char FACING_BACK[];
    static const char FACING_FRONT[];

	// -------------------------------------------------------------------------
	// extended interfaces here <***** star *****>
	// -------------------------------------------------------------------------
public:
	status_t setCameraHardwareInfo(HALCameraInfo * halInfo);
	void initDefaultParameters();

	void notifyPictureMsg(const void* frame);

	void setNewCrop(Rect * rect);
	int setAutoFocusMode();
	int setAutoFocusCtrl(int af_ctrl, void *areas);
	int getCurrentFaceFrame(void * frame);
	int faceDetection(camera_frame_metadata_t *face);

    int parse_focus_areas(const char * str);
	bool checkFocusArea(const char * area);
	bool checkFocusMode(const char * mode);

	bool commandThread();
	bool autoFocusThread();

	void setVideoCaptureSize(int video_w, int video_h);
	void getCurrentOriention(int * oriention);

	bool isCameraIdle();

protected:
	CCameraConfig * 				mCameraConfig;

	HALCameraInfo					mHalCameraInfo;

    Mutex                           mCameraIdleLock;
	bool							mIsCameraIdle;

	bool							mFirstSetParameters;
	bool							mIsSupportFocus;
	bool							mIsSupportEffect;
	bool							mIsSupportFlash;
	bool							mIsSupportScene;
	bool							mIsSupportWhiteBlance;
	bool							mIsSupportExposure;

	int								mFullSizeWidth;
	int								mFullSizeHeight;
	int								mCaptureWidth;
	int								mCaptureHeight;
	int								mVideoCaptureWidth;
	int								mVideoCaptureHeight;
	bool							mUseHwEncoder;

	char							mCallingProcessName[128];

	FaceDetectionDev *				mFaceDetection;

	Rect							mFrameRectCrop;		// current frame buffer crop for focus
	char							mFocusAreasStr[32];
	struct v4l2_pix_size			mFocusAreas;

	typedef enum CMD_QUEUE_t{
		CMD_QUEUE_SET_COLOR_EFFECT 	= 0,
		CMD_QUEUE_SET_WHITE_BALANCE,
		CMD_QUEUE_SET_FLASH_MODE,
		CMD_QUEUE_SET_FOCUS_MODE,
		CMD_QUEUE_SET_FOCUS_AREA,
		CMD_QUEUE_SET_EXPOSURE_COMPENSATION,

		CMD_QUEUE_START_FACE_DETECTE,
		CMD_QUEUE_STOP_FACE_DETECTE,

		CMD_QUEUE_TAKE_PICTURE,
		CMD_QUEUE_PICTURE_MSG,
		CMD_QUEUE_STOP_CONTINUOUSSNAP,

		CMD_QUEUE_SET_FOCUS_STATUS,

		CMD_QUEUE_MAX
	}CMD_QUEUE;

	OSAL_QUEUE						mQueueCommand;

	typedef struct Queue_Element_t {
		CMD_QUEUE cmd;
		int data;
	}Queue_Element;

	Queue_Element					mQueueElement[CMD_QUEUE_MAX];

	class DoCommandThread : public Thread {
        CameraHardware* mCameraHardware;
		ThreadState		mThreadStatus;
    public:
        DoCommandThread(CameraHardware* hw) :
			Thread(false),
			mCameraHardware(hw),
			mThreadStatus(THREAD_STATE_NULL) {
		}
        void startThread() {
			mThreadStatus = THREAD_STATE_RUNNING;
			run("CameraCommandThread", PRIORITY_NORMAL);
        }
		void stopThread() {
			mThreadStatus = THREAD_STATE_EXIT;
        }
		ThreadState getThreadStatus() {
			return mThreadStatus;
		}
		bool isThreadStarted() {
			return (mThreadStatus == THREAD_STATE_PAUSED) || (mThreadStatus == THREAD_STATE_RUNNING);
		}
        virtual bool threadLoop() {
			return mCameraHardware->commandThread();
        }
    };
	sp<DoCommandThread>				mCommandThread;

	pthread_mutex_t 				mCommandMutex;
	pthread_cond_t					mCommandCond;

	class DoAutoFocusThread : public Thread {
        CameraHardware* mCameraHardware;
		ThreadState		mThreadStatus;
    public:
        DoAutoFocusThread(CameraHardware* hw) :
			Thread(false),
			mCameraHardware(hw),
			mThreadStatus(THREAD_STATE_NULL) {
		}
        void startThread() {
			mThreadStatus = THREAD_STATE_RUNNING;
			run("CameraAutoFocusThread", PRIORITY_NORMAL);
        }
		void stopThread() {
			mThreadStatus = THREAD_STATE_EXIT;
        }
		ThreadState getThreadStatus() {
			return mThreadStatus;
		}
		bool isThreadStarted() {
			return (mThreadStatus == THREAD_STATE_PAUSED) || (mThreadStatus == THREAD_STATE_RUNNING);
		}
        virtual bool threadLoop() {
			return mCameraHardware->autoFocusThread();
        }
    };
	sp<DoAutoFocusThread>			mAutoFocusThread;

	pthread_mutex_t 				mAutoFocusMutex;
	pthread_cond_t					mAutoFocusCond;

public:
	typedef enum FocusStatus_t {
		FOCUS_STATUS_IDLE		= 0x0,
		FOCUS_STATUS_SUCCESS	= 0x1,
		FOCUS_STATUS_FAIL		= 0x2,
		FOCUS_STATUS_DONE		= FOCUS_STATUS_SUCCESS | FOCUS_STATUS_FAIL,
		FOCUS_STATUS_BUSY		= 0x4,
	}FocusStatus;

protected:
	FocusStatus						mFocusStatus;
	bool							mIsSingleFocus;

	int								mOriention;

	int								mZoomRatio;
};

}; /* namespace android */

#endif  /* __HAL_CAMERA_HARDWARE_H__ */


text:
import scala.concurrent.duration.*
import scala.language.postfixOps

object Test extends App {
  List(
    (60 minutes,    1 hour),
    (2000 millis,   2 seconds),
    (2000 micros,   2 millis),
    (2000 nanos,    2 micros),
    (2000000 nanos, 2 millis),
    (48 hours,      2 days),
    (5 seconds,     5 seconds),
    (1 second,      1 second)
  ) foreach {
    case (x, expected) =>
      val actual = x.toCoarsest
      assert(actual.unit == expected.unit, s"$actual, $expected")
      assert(actual.length == expected.length, s"$actual, $expected")
  }

  List(
    45 minutes,
    500 millis,
    1500 millis,
    23 hours,
    40 days
  ) foreach (x => assert(x == x.toCoarsest, x))
}

redpajama_set_name: RedPajamaGithub


text:
package Vent;

import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.SwingConstants;

public final class Clases implements ActionListener {

    Frame a;
    Label b, c, i;
    TextField j, g;
    Button h;

    public void Compooent() {
        b = new Label("Sumando 1");
        b.setBounds(10, 50, 100, 20);

        c = new Label("Sumando 2");
        c.setBounds(10, 100, 100, 20);
        Font myFont = new Font("Serif", Font.ITALIC, 15);
        c.setFont(myFont);
        c.setForeground(Color.CYAN);

        j = new TextField();
        j.setBounds(150, 50, 100, 20);

        g = new TextField();
        g.setBounds(150, 100, 100, 20);

        i = new Label();
        i.setBounds((300 - 100) / 2, 200, 200, 30);

        h = new Button("Sumar");
        h.setBounds((300 - 100) / 2, 160, 100, 30);
        h.addActionListener(this);

    }

    public void FrameCre(String title) {
        a = new Frame(title);
        a.setSize(300, 400);
        a.setBackground(Color.PINK);
        a.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        }
        );

        a.setLayout(null);
        a.add(b);
        a.add(c);
        a.add(j);
        a.add(g);
        a.add(h);
        a.add(i);

        a.setLocationRelativeTo(null);
        a.setResizable(false);
        a.setVisible(true);
    }

    public Clases(String title) {
        Compooent();
        FrameCre(title);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(h)) {
            i.setText("la suma es " + (Integer.parseInt(g.getText()) + Integer.parseInt(j.getText())));
        }
    }

}


text:
using content::BrowserThread;

namespace drive {

namespace {

// OAuth2 scopes for Drive API.
const char kDriveScope[] = "https://www.googleapis.com/auth/drive";
const char kDriveAppsReadonlyScope[] =
    "https://www.googleapis.com/auth/drive.apps.readonly";

}  // namespace

DriveAPIService::DriveAPIService()
    : profile_(NULL),
      runner_(NULL) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

DriveAPIService::~DriveAPIService() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (runner_.get()) {
    runner_->operation_registry()->RemoveObserver(this);
    runner_->auth_service()->RemoveObserver(this);
  }
}

void DriveAPIService::Initialize(Profile* profile) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  profile_ = profile;

  std::vector<std::string> scopes;
  scopes.push_back(kDriveScope);
  scopes.push_back(kDriveAppsReadonlyScope);
  runner_.reset(new google_apis::OperationRunner(profile, scopes));
  runner_->Initialize();

  runner_->auth_service()->AddObserver(this);
  runner_->operation_registry()->AddObserver(this);
}

void DriveAPIService::AddObserver(google_apis::DriveServiceObserver* observer) {
  observers_.AddObserver(observer);
}

void DriveAPIService::RemoveObserver(
    google_apis::DriveServiceObserver* observer) {
  observers_.RemoveObserver(observer);
}

bool DriveAPIService::CanStartOperation() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  return HasRefreshToken();
}

void DriveAPIService::CancelAll() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  runner_->CancelAll();
}

bool DriveAPIService::CancelForFilePath(const FilePath& file_path) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return operation_registry()->CancelForFilePath(file_path);
}

google_apis::OperationProgressStatusList
DriveAPIService::GetProgressStatusList() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  return operation_registry()->GetProgressStatusList();
}

void DriveAPIService::Authenticate(
    const google_apis::AuthStatusCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  runner_->Authenticate(callback);
}

void DriveAPIService::GetDocuments(
    const GURL& url,
    int64 start_changestamp,
    const std::string& search_query,
    const std::string& directory_resource_id,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (search_query.empty())
    GetChangelist(url, start_changestamp, callback);
  else
    GetFilelist(url, search_query, callback);

  return;
  // TODO(kochi): Implement !directory_resource_id.empty() case.
  NOTREACHED();
}

void DriveAPIService::GetFilelist(
    const GURL& url,
    const std::string& search_query,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  runner_->StartOperationWithRetry(
      new google_apis::GetFilelistOperation(operation_registry(),
                                            url,
                                            search_query,
                                            callback));
}

void DriveAPIService::GetChangelist(
    const GURL& url,
    int64 start_changestamp,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  runner_->StartOperationWithRetry(
      new google_apis::GetChangelistOperation(operation_registry(),
                                              url,
                                              start_changestamp,
                                              callback));
}

void DriveAPIService::GetDocumentEntry(
    const std::string& resource_id,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  runner_->StartOperationWithRetry(new google_apis::GetFileOperation(
      operation_registry(),
      resource_id,
      callback));
}

void DriveAPIService::GetAccountMetadata(
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  runner_->StartOperationWithRetry(
      new google_apis::GetAboutOperation(operation_registry(), callback));
}

void DriveAPIService::GetApplicationInfo(
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  runner_->StartOperationWithRetry(
      new google_apis::GetApplistOperation(operation_registry(), callback));
}

void DriveAPIService::DownloadDocument(
    const FilePath& virtual_path,
    const FilePath& local_cache_path,
    const GURL& document_url,
    google_apis::DocumentExportFormat format,
    const google_apis::DownloadActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::DownloadFile(
      const FilePath& virtual_path,
      const FilePath& local_cache_path,
      const GURL& document_url,
      const google_apis::DownloadActionCallback& download_action_callback,
      const google_apis::GetContentCallback& get_content_callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::DeleteDocument(
    const GURL& document_url,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::CreateDirectory(
    const GURL& parent_content_url,
    const FilePath::StringType& directory_name,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::CopyDocument(
    const std::string& resource_id,
    const FilePath::StringType& new_name,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::RenameResource(
    const GURL& resource_url,
    const FilePath::StringType& new_name,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::AddResourceToDirectory(
    const GURL& parent_content_url,
    const GURL& resource_url,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::RemoveResourceFromDirectory(
    const GURL& parent_content_url,
    const GURL& resource_url,
    const std::string& resource_id,
    const google_apis::EntryActionCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::InitiateUpload(
    const google_apis::InitiateUploadParams& params,
    const google_apis::InitiateUploadCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::ResumeUpload(
    const google_apis::ResumeUploadParams& params,
    const google_apis::ResumeUploadCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

void DriveAPIService::AuthorizeApp(
    const GURL& resource_url,
    const std::string& app_ids,
    const google_apis::GetDataCallback& callback) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // TODO(kochi): Implement this.
  NOTREACHED();
}

bool DriveAPIService::HasAccessToken() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  return runner_->auth_service()->HasAccessToken();
}

bool DriveAPIService::HasRefreshToken() const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  return runner_->auth_service()->HasRefreshToken();
}

google_apis::OperationRegistry* DriveAPIService::operation_registry() const {
  return runner_->operation_registry();
}

void DriveAPIService::OnOAuth2RefreshTokenChanged() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (CanStartOperation()) {
    FOR_EACH_OBSERVER(
        google_apis::DriveServiceObserver, observers_,
        OnReadyToPerformOperations());
  }
}

void DriveAPIService::OnProgressUpdate(
    const google_apis::OperationProgressStatusList& list) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  FOR_EACH_OBSERVER(
      google_apis::DriveServiceObserver, observers_, OnProgressUpdate(list));
}

void DriveAPIService::OnAuthenticationFailed(
    google_apis::GDataErrorCode error) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  FOR_EACH_OBSERVER(
      google_apis::DriveServiceObserver, observers_,
      OnAuthenticationFailed(error));
}

}  // namespace drive


text:
package com.senla.rakickaya.courseplanner.api.beans;

import java.util.List;

public interface IStudent extends IEntity {
	public String getNameStudent();

	public void setCourses(List<ICourse> courses);

	public List<ICourse> getCourses();
}


text:
@echo off
setlocal
if not defined PLAYWRIGHT_NODEJS_PATH (
  set PLAYWRIGHT_NODEJS_PATH=%~dp0\node.exe
)
"""%PLAYWRIGHT_NODEJS_PATH%""" "%~dp0\package\lib\cli\cli.js" %*


text:
package tv.niuwa.live.wxapi;

import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import tv.niuwa.live.pay.Constants;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{

	private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.pay_result);

    	api = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
        api.handleIntent(getIntent(), this);
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		//LogUtils.i("onPayFinish" + resp.errCode);
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			switch (resp.errCode){
				case 0:
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					//builder.setTitle("支付成功");
					builder.setMessage("支付成功");
					builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int i) {
							WXPayEntryActivity.this.finish();
						}
					});
					builder.show();
					break;
				default:
					AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
					//builder.setTitle("支付成功");
					builder1.setMessage("支付失败");
					builder1.setNegativeButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int i) {
							WXPayEntryActivity.this.finish();
						}
					});
					builder1.show();
					break;
			}
		}
	}
}


text:
1. What is it?

    Chromed Bird is a general purpose Chromium twitter extension.

2. Installing

    Check the [download page](http://cezarsa.github.com/chromed_bird/)

3. Compatibility

    Currently only Dev channel releases of Google Chrome support extensions. Check [http://dev.chromium.org/getting-involved/dev-channel](http://dev.chromium.org/getting-involved/dev-channel).

4. Features

    * Follow your timelines and navigate through your tweets
    * Notify user through icon changes whenever new tweets arrive
    * Compose, reply, and RT tweets
    * Read / unread tweets tracking
    * OAuth authentication
    * Tweets caching to avoid hitting Twitter's API rate limit (Only hit Twitter after 1 minute or when fetching uncached tweets)
    * It uses Chromium autoupdate feature, so you won't be left behind

6. License

    This project uses the very simple and permissive MIT license. Check the LICENSE file.


text:
class UserFilesController < ApplicationController
  before_action :set_user_file, only: [:show, :edit, :update, :destroy]

  # GET /user_files
  # GET /user_files.json
  def index
    @user_files = UserFile.all
  end

  # GET /user_files/1
  # GET /user_files/1.json
  def show
  end

  # GET /user_files/new
  def new
    @call = UserFile.new
  end

  # GET /user_files/1/edit
  def edit
  end

  # POST /user_files
  # POST /user_files.json
  def create
    @user_file = UserFile.new(call_params)

    respond_to do |format|
      if @user_file.save
        format.html { redirect_to @user_file, notice: 'UserFile was successfully created.' }
        format.json { render :show, status: :created, location: @user_file }
      else
        format.html { render :new }
        format.json { render json: @user_file.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /user_files/1
  # PATCH/PUT /user_files/1.json
  def update
    respond_to do |format|
      if @user_file.update(call_params)
        format.html { redirect_to @user_file, notice: 'UserFile was successfully updated.' }
        format.json { render :show, status: :ok, location: @user_file }
      else
        format.html { render :edit }
        format.json { render json: @user_file.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /user_files/1
  # DELETE /user_files/1.json
  def destroy
    @user_file.destroy
    respond_to do |format|
      format.html { redirect_to user_files_url, notice: 'UserFile was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user_file
      @user_file = UserFile.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def call_params
      params.require(:user_file).permit(:subscriber, :filename, :start_date, :end_date)
    end
end


text:
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
 *  Main authors:
 *     Christian Schulte <schulte@gecode.org>
 *
 *  Copyright:
 *     Christian Schulte, 2008
 *
 *  Last modified:
 *     $Date: 2013-03-11 14:47:11 +0100 (må, 11 mar 2013) $ by $Author: schulte $
 *     $Revision: 13490 $
 *
 *  This file is part of Gecode, the generic constraint
 *  development environment:
 *     http://www.gecode.org
 *
 *  Permission is hereby granted, free of charge, to any person obtaining
 *  a copy of this software and associated documentation files (the
 *  "Software"), to deal in the Software without restriction, including
 *  without limitation the rights to use, copy, modify, merge, publish,
 *  distribute, sublicense, and/or sell copies of the Software, and to
 *  permit persons to whom the Software is furnished to do so, subject to
 *  the following conditions:
 *
 *  The above copyright notice and this permission notice shall be
 *  included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

namespace Gecode {

  /// Initialize integer set with integer arguments
  template<>
  class IntSetInit<IntArgs> {
  public:
    static void init(IntSet& s, const IntArgs& i) {
      if (i.size() > 0)
        s.init(&i[0],i.size());
    }
  };

}

// STATISTICS: int-var


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

#ifndef _NIBOOLINTERPOLATOR_H_
#define _NIBOOLINTERPOLATOR_H_

//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//

#include "NiKeyBasedInterpolator.h"

// Include structures
#include "../Ref.h"
namespace Niflib {

// Forward define of referenced NIF objects
class NiBoolData;
class NiBoolInterpolator;
typedef Ref<NiBoolInterpolator> NiBoolInterpolatorRef;

/*! Unknown. */
class NiBoolInterpolator : public NiKeyBasedInterpolator {
public:
	/*! Constructor */
	NIFLIB_API NiBoolInterpolator();

	/*! Destructor */
	NIFLIB_API virtual ~NiBoolInterpolator();

	/*!
	 * A constant value which uniquly identifies objects of this type.
	 */
	NIFLIB_API static const Type TYPE;

	/*!
	 * A factory function used during file reading to create an instance of this type of object.
	 * \return A pointer to a newly allocated instance of this type of object.
	 */
	NIFLIB_API static NiObject * Create();

	/*!
	 * Summarizes the information contained in this object in English.
	 * \param[in] verbose Determines whether or not detailed information about large areas of data will be printed out.
	 * \return A string containing a summary of the information within the object in English.  This is the function that Niflyze calls to generate its analysis, so the output is the same.
	 */
	NIFLIB_API virtual string asString( bool verbose = false ) const;

	/*!
	 * Used to determine the type of a particular instance of this object.
	 * \return The type constant for the actual type of the object.
	 */
	NIFLIB_API virtual const Type & GetType() const;

	//--BEGIN MISC CUSTOM CODE--//

	/*!
	 * Gets the boolean value stored in this object.  Perhaps this is the current interpolated value, the value when posed, or at time index 0.
	 * \return The boolean value stored in this object.
	 */
	NIFLIB_API bool GetBoolValue() const;

	/*!
	 * Sets the boolean value stored in this object.  Perhaps this is the current interpolated value, the value when posed, or at time index 0.
	 * \param[in] value The new boolean value to store in this object.
	 */
	NIFLIB_API void SetBoolValue( bool value );

	/*!
	 * Gets the NiBoolData object that this interpolator links to, if any.
	 * \return The NiBoolData object that this interpolator links to, or NULL if one is not linked.
	 */
	NIFLIB_API Ref<NiBoolData > GetData() const;

	/*!
	 * Sets the NiBoolData object that this interpolator links to, if any.
	 * \return The NiBoolData object that this interpolator should now link to, or NULL to clear the current one.
	 */
	NIFLIB_API void SetData( NiBoolData * value );

	/*!
	 * This function will adjust the times in all the keys stored in the data
	 * objects referenced by this interpolator such that phase will equal 0 and
	 * frequency will equal one.  In other words, it will cause the key times
	 * to be in seconds starting from zero.
	 * \param[in] phase The phase shift to remove from any keys stored in this
	 * object.
	 * \param[in] frequency The frequency to normalize to 1.0 for any keys
	 * stored in this object
	 */
	NIFLIB_API virtual void NormalizeKeys( float phase, float frequency );

	//--END CUSTOM CODE--//
protected:
	/*! Value when posed?  At time 0? */
	bool boolValue;
	/*! Refers to a NiBoolData object. */
	Ref<NiBoolData > data;
public:
	/*! NIFLIB_HIDDEN function.  For internal use only. */
	NIFLIB_HIDDEN virtual void Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info );
	/*! NIFLIB_HIDDEN function.  For internal use only. */
	NIFLIB_HIDDEN virtual void Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const;
	/*! NIFLIB_HIDDEN function.  For internal use only. */
	NIFLIB_HIDDEN virtual void FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info );
	/*! NIFLIB_HIDDEN function.  For internal use only. */
	NIFLIB_HIDDEN virtual list<NiObjectRef> GetRefs() const;
	/*! NIFLIB_HIDDEN function.  For internal use only. */
	NIFLIB_HIDDEN virtual list<NiObject *> GetPtrs() const;
};

//--BEGIN FILE FOOT CUSTOM CODE--//
//--END CUSTOM CODE--//

} //End Niflib namespace
#endif


text:
package org.locationtech.geowave.core.geotime.store.query;

import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.locationtech.geowave.core.geotime.store.GeotoolsFeatureDataAdapter;
import org.locationtech.geowave.core.geotime.util.GeometryUtils;
import org.locationtech.geowave.core.geotime.util.IndexOptimizationUtils;
import org.locationtech.geowave.core.store.api.Index;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.filter.Filter;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SpatialQuery extends AbstractVectorConstraints<ExplicitSpatialQuery> {
  private static final Logger LOGGER = LoggerFactory.getLogger(SpatialQuery.class);

  public SpatialQuery() {
    super();
  }

  public SpatialQuery(final ExplicitSpatialQuery delegateConstraints) {
    super(delegateConstraints);
  }

  @Override
  protected ExplicitSpatialQuery newConstraints() {
    return new ExplicitSpatialQuery();
  }

  @Override
  protected boolean isSupported(final Index index, final GeotoolsFeatureDataAdapter adapter) {
    return IndexOptimizationUtils.hasAtLeastSpatial(index);
  }

  @Override
  protected Filter getFilter(final GeotoolsFeatureDataAdapter adapter, final Index index) {
    return getFilter(adapter, index, delegateConstraints);
  }

  protected static Filter getFilter(
      final GeotoolsFeatureDataAdapter adapter,
      final Index index,
      final ExplicitSpatialQuery delegateConstraints) {
    final GeometryDescriptor geomDesc = adapter.getFeatureType().getGeometryDescriptor();
    final CoordinateReferenceSystem indexCrs = GeometryUtils.getIndexCrs(index);
    return GeometryUtils.geometryToSpatialOperator(
        transformToAdapter(indexCrs, delegateConstraints),
        geomDesc.getLocalName(),
        indexCrs);
  }

  private static Geometry transformToAdapter(
      final CoordinateReferenceSystem adapterCrs,
      final ExplicitSpatialQuery delegateConstraints) {
    final Geometry queryGeometry = delegateConstraints.getQueryGeometry();
    if (adapterCrs == null) {
      return queryGeometry;
    }
    final String indexCrsStr = GeometryUtils.getCrsCode(adapterCrs);
    if (indexCrsStr == null) {
      return queryGeometry;
    }
    if (GeometryUtils.crsMatches(delegateConstraints.getCrsCode(), indexCrsStr)
        || (queryGeometry == null)) {
      return queryGeometry;
    } else {
      CoordinateReferenceSystem crs = delegateConstraints.getCrs();
      if (crs == null) {
        String crsCode = delegateConstraints.getCrsCode();

        if ((crsCode == null) || crsCode.isEmpty()) {
          crsCode = GeometryUtils.DEFAULT_CRS_STR;
        }

        try {
          crs = CRS.decode(crsCode, true);
        } catch (final FactoryException e) {
          LOGGER.warn("Unable to decode spatial query crs", e);
        }
      }
      try {
        final MathTransform transform = CRS.findMathTransform(crs, adapterCrs, true);
        // transform geometry
        return JTS.transform(queryGeometry, transform);
      } catch (final FactoryException e) {
        LOGGER.warn("Unable to create coordinate reference system transform", e);
      } catch (MismatchedDimensionException | TransformException e) {
        LOGGER.warn("Unable to transform query geometry into index CRS", e);
      }
    }
    return queryGeometry;
  }
}


text:
<resources>
    <string name="app_name">NearbyConStreamDemo</string>
</resources>


text:
#include <windows.h>

#include "LuaDll.h"
#include "DebugBackend.h"

HINSTANCE g_hInstance = NULL;

BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD reason, LPVOID reserved)
{
    g_hInstance = hInstance;

    if (reason == DLL_PROCESS_ATTACH)
    {
        if (!DebugBackend::Get().Initialize(hInstance))
        {
            return FALSE;
        }
    }
    else if (reason == DLL_PROCESS_DETACH)
    {
		std::string stack = TraceStack();
		DebugBackend::Get().Message(stack.c_str());
        DebugBackend::Destroy();
    }

    return TRUE;

}


text:
package griffon.plugins.preferences.util;

import griffon.plugins.preferences.PreferencesManager;

/**
 * @author Andres Almiray
 */
public class PreferencesManagerHolder {
    private static PreferencesManager preferencesManager;

    public static PreferencesManager getPreferencesManager() {
        return preferencesManager;
    }

    public static void setPreferencesManager(PreferencesManager preferencesManager) {
        PreferencesManagerHolder.preferencesManager = preferencesManager;
    }
}


text:
define([
    '../jsonForm',
    'jquery',
    'underscore',
    'handlebars',
    'marketplace'
], function (JsonForm, $, _, Handlebars, Marketplace) {

    var FormFieldTypes = JsonForm.FormFieldTypes,
        ArrayInputField = FormFieldTypes.get('array'),
        TextInputField = FormFieldTypes.get('text'),
        EmailInputField = FormFieldTypes.get('email'),
        TelephoneInputField = FormFieldTypes.get('tel'),
        Select2InputField = FormFieldTypes.get('select2'),
        HiddenInputField = FormFieldTypes.get('hidden'),
        contactTypes = Marketplace.contactTypes;

    var ContactsInputField = function (options) {
        this.init('intents', options);
    };

    _.extend(ContactsInputField.prototype, ArrayInputField.prototype, {

        constructor: ContactsInputField,

        template: Handlebars.compile(
            '
' +
                '
+Add
' +
            '
'
        ),

        itemTemplate: Handlebars.compile(
            '
' +
                '
' +
                    '
Type*
' +
                    '
Name*
' +
                    '
Organization
' +
                '
' +
                '
' +
                    '
Email*
' +
                    '
Secure Phone*
' +
                    '
Unsecure Phone*
' +
                '
' +
                '{{#unless disabled}}' +
                    '
-
' +
                '{{/unless}}' +
            '
'
        ),

        index: 0,

        idFields: null,
        typeFields: null,
        nameFields: null,
        organizationFields: null,
        emailFields: null,
        securePhoneFields: null,
        unsecurePhoneFields: null,

        init: function (type, options) {
            ArrayInputField.prototype.init.call(this, type, options);
            this.idFields = [];
            this.typeFields = [];
            this.nameFields = [];
            this.organizationFields = [];
            this.emailFields = [];
            this.securePhoneFields = [];
            this.unsecurePhoneFields = [];
        },

        addItem: function (contact, contacts, disabled) {
            var me = this,
                $item = $(this.itemTemplate(_.extend({
                    disabled: disabled
                }, contact))),
                index = this.index,
                typeField, nameField, organizationField, emailField, securePhoneField, unsecurePhoneField, idField;

            nameField = new TextInputField({
                attrs: {
                    name: 'contacts[' + index + '][name]',
                    required: true,
                    maxlength: 100,
                    value: contact.name || ''
                }
            }).render();

            organizationField = new TextInputField({
                attrs: {
                    name: 'contacts[' + index + '][organization]',
                    maxlength: 100,
                    value: contact.organization || ''
                }
            }).render();

            emailField = new EmailInputField({
                attrs: {
                    name: 'contacts[' + index + '][email]',
                    required: true,
                    maxlength: 100,
                    value: contact.email || ''
                }
            }).render();

            securePhoneField = new TelephoneInputField({
                attrs: {
                    name: 'contacts[' + index + '][securePhone]',
                    required: contact.unsecurePhone ? false : true,
                    maxlength: 50,
                    value: contact.securePhone || ''
                }
            }).render();

            unsecurePhoneField = new TelephoneInputField({
                attrs: {
                    name: 'contacts[' + index + '][unsecurePhone]',
                    required: contact.securePhone ? false : true,
                    maxlength: 50,
                    value: contact.unsecurePhone || ''
                }
            }).render();

            typeField = new Select2InputField({
                data: contactTypes,
                attrs: {
                    name: 'contacts[' + index + '][type][id]',
                    required: true,
                    value: contact.type ? contact.type.id : '',
                    disabled: disabled
                }
            }).render();

            if(contact && contact.id) {
                idField = new HiddenInputField({
                    attrs: {
                        name: 'contacts[' + index + '][id]',
                        value: contact && contact.attrs || ''
                    }
                }).render();
            }

            $item.find('.type-field').append(typeField.$el);
            $item.find('.name-field').append(nameField.$el);
            $item.find('.organization-field').append(organizationField.$el);
            $item.find('.email-field').append(emailField.$el);
            $item.find('.secure-phone-field').append(securePhoneField.$el);
            $item.find('.unsecure-phone-field').append(unsecurePhoneField.$el);
            idField && $item.append(idField.$el);

            this.$el.find('.btn-field-add').before($item);

            this.index++;
            this.typeFields.push(typeField);
            this.nameFields.push(nameField);
            this.organizationFields.push(organizationField);
            this.emailFields.push(emailField);
            this.securePhoneFields.push(securePhoneField);
            this.unsecurePhoneFields.push(unsecurePhoneField);
            idField && this.idFields.push(idField);
        },

        addItems: function () {
            var me = this,
                contacts = this.options.attrs.value || [],
                requiredContactTypes = _.where(contactTypes, {required: true}),
                typesRendered = {};

            if(contacts.length === 0) {
                _.forEach(requiredContactTypes, function (ct) {
                    // no values exist, disable all required types
                    me.addItem({
                        type: {
                            id: ct.id,
                            title: ct.title,
                            required: ct.required
                        }
                    }, contacts, true);
                });
            }
            else {
                _.forEach(contacts, function (contact, i) {
                    var type = contact.type;
                    // disable this contact's type from changing if contact type is required and
                    // at least one of contact of that type is not yet renderd
                    me.addItem(contact, contacts, type.required && !typesRendered[type.id]);

                    // update the flag to keep track of which types have rendered
                    typesRendered[type.id] = true;
                });
            }
        },

        onAddClick: function () {
            this.addItem({});
        },

        remove: function () {
            _.invoke(this.idFields, 'remove');
            _.invoke(this.nameFields, 'remove');
            _.invoke(this.organizationFields, 'remove');
            _.invoke(this.emailFields, 'remove');
            _.invoke(this.securePhoneFields, 'remove');
            _.invoke(this.unsecurePhoneFields, 'remove');
            return ArrayInputField.prototype.remove.call(this);
        }

    });

    $(document).on('keyup', '.array-items.contacts input[name*="securePhone"]', _.debounce(function (evt) {
        var input = this,
            $input = $(input),
            value = $input.val(),
            isUnsecurePhone = _.contains($input.attr('name'), 'unsecurePhone'),
            $sibling = $input.parent().siblings(isUnsecurePhone ? '.secure-phone-field' : '.unsecure-phone-field').find('input'),
            siblingValue = $sibling.val();

        if(value || siblingValue) {
            $sibling.removeAttr('required').valid();
        }
        else {
            $input.attr('required', true).valid();
            $sibling.attr('required', true).valid();
        }
    }, 200));

    FormFieldTypes.register('contacts', ContactsInputField);

    return ContactsInputField;

});


text:
#ifndef __F_FIELD_H__
#define __F_FIELD_H__ 1

#include <string.h>
#include "constant_time.h"

#include "p521.h"
#define FIELD_LIT_LIMB_BITS  58
#define FIELD_BITS           521
#define field_t              p521_t
#define field_mul            p521_mul
#define field_sqr            p521_sqr
#define field_add_RAW        p521_add_RAW
#define field_sub_RAW        p521_sub_RAW
#define field_mulw           p521_mulw
#define field_bias           p521_bias
#define field_isr            p521_isr
#define field_inverse        p521_inverse
#define field_weak_reduce    p521_weak_reduce
#define field_strong_reduce  p521_strong_reduce
#define field_serialize      p521_serialize
#define field_deserialize    p521_deserialize

#endif /* __F_FIELD_H__ */


text:
module Graphics.D3D11Binding.Interface.DxgiSwapChain where
import Data.Word

import Foreign.Storable
import Foreign.Marshal.Alloc
import Foreign.Ptr

import Graphics.Win32
import Graphics.D3D11Binding.GUID
import Graphics.D3D11Binding.Types

import Graphics.D3D11Binding.Interface.Unknown

foreign import stdcall "Present" c_present
  :: Ptr IDxgiSwapChain -> Word32 -> Word32 -> IO HRESULT

foreign import stdcall "GetBuffer" c_getBuffer
  :: Ptr IDxgiSwapChain -> Word32 -> Ptr GUID -> Ptr (Ptr ()) -> IO HRESULT

class (UnknownInterface interface) => DxgiSwapChainInterface interface where
  present :: Ptr interface -> Word32 -> Word32 -> IO HRESULT
  present this syncInterval flags = c_present (castPtr this) syncInterval flags
  getBuffer :: (HasGUID surface) => Ptr interface -> Word32 -> IO (Either HRESULT (Ptr surface))
  getBuffer this buffer = alloca $ \surface -> alloca $ \pGuid -> do
    let guid = getGUID surface
    poke pGuid guid
    hr <- c_getBuffer (castPtr this) buffer pGuid (castPtr surface)
    if hr < 0 then return (Left hr)
    else do
      peekSurface <- peek surface
      return (Right peekSurface)

data IDxgiSwapChain = IDxgiSwapChain
instance UnknownInterface IDxgiSwapChain
instance DxgiSwapChainInterface IDxgiSwapChain


text:
title: About
----------------------

Hello,

My name is Danny Gratzer, I am a sophomore at Carnegie Mellon
University. I can be found haunting a coffee shop with a laptop and a
cup of black coffee.

## CS Stuff
I like functional type theory and compilers. I also enjoy a good bit of
math, mostly abstract algebra or logic. I like writing Haskell, SML, Coq or Agda.

## Projects
I have a few projects most of which are licensed permissively under
the MIT license. They can all be found on my
[bitbucket](http://www.bitbucket.org/jozefg) account. The more
interesting ones have also found a home on
[github](http://www.github.com/jozefg).

If you feel the urge to contribute to any of these, please email :)

## Find Me
I'm active on a few sites, usually under the handle jozefg.
You can find me on twitter as [dannygratzer](https://twitter.com/dannygratzer).


text:
package weka.classifiers.bayes.net;

import weka.core.FastVector;

// Referenced classes of package weka.classifiers.bayes.net:
//            EditableBayesNet

class this._cls0 extends this._cls0 {

    static final long serialVersionUID = 1L;
    final EditableBayesNet this$0;

    public void redo() {
        try {
            spaceVertical(m_nodes);
        }
        catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    public String getUndoMsg() {
        return (new StringBuilder()).append("Returning ").append(m_nodes.size()).append(" from spaceng vertically.").toString();
    }

    public String getRedoMsg() {
        return (new StringBuilder()).append("Spaceng ").append(m_nodes.size()).append(" nodes vertically.").toString();
    }

    public weka.classifiers.bayes.net.EditableBayesNet.spaceVerticalAction(FastVector fastvector) {
        this$0 = EditableBayesNet.this;
        super(EditableBayesNet.this, fastvector);
    }
}


text:
/* This file can define __ASSUME_* macros checked by certain source files.
   Almost none of these are used outside of sysdeps/unix/sysv/linux code.
   But those referring to POSIX-level features like O_* flags can be.  */

#include <fcntl.h>

/* If a system defines the O_CLOEXEC constant but it is sometimes ignored,
   it must override this file to define __ASSUME_O_CLOEXEC conditionally
   (or not at all) to indicate when O_CLOEXEC actually works.  */
#ifdef O_CLOEXEC
# define __ASSUME_O_CLOEXEC	1
#endif


text:
To install and run this application you should have:
    -  Python (2.7 or 3.2+), tested with Python 2.7.9.;
    -  python-pip;
    -  virtualenv (preferred).

Execute following steps to run application:
    0. Clone this reporsitory and open its folder;
    1. Create new virtual env. (or skip this step)
        `virtualenv venv`;
    2. Install all required packages
        `pip install -r requirements/development.txt`;
    3. Activate virtualenv
        `source venv/bin/activate`;
    4. Copy `secrets_sample.py` file in same folder and rename it to `secrets.py`
            - open `secrets.py` file
            - Fill SECRET_KEY variable with randomly generated string,
            - Fill DB name with a needed data,
    5. Apply migrations
        `python src/manage.py migrate`
    6. Run application (by default at localhost:8000)
        `python src/manage.py runserver`


text:
package net.runelite.client.plugins.screenmarkers;

import java.awt.Color;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ScreenMarker
{
	private long id;
	private String name;
	private int borderThickness;
	private Color color;
	private Color fill;
	private boolean visible;
	private boolean labelled;
}


text:
package org.apache.geronimo.deployment.cli;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.util.Properties;

import org.apache.geronimo.common.DeploymentException;
import org.apache.geronimo.crypto.EncryptionManager;
import org.apache.geronimo.deployment.plugin.ConfigIDExtractor;

/**
 * Various helpers for deployment.
 *
 * @version $Rev$ $Date$
 */
public class DeployUtils extends ConfigIDExtractor {

    public final static String DEFAULT_HOST = "localhost";
    public final static Integer DEFAULT_PORT = 1099;

    private final static String DEFAULT_URI = "deployer:geronimo:jmx";
    private final static String DEFAULT_SECURE_URI = "deployer:geronimo:jmxs";

    private static final String KEYSTORE_TRUSTSTORE_PASSWORD_FILE =
        "org.apache.geronimo.keyStoreTrustStorePasswordFile";

    private static final String DEFAULT_TRUSTSTORE_KEYSTORE_LOCATION =
        "/var/security/keystores/geronimo-default";

    private static final String GERONIMO_HOME =
        "org.apache.geronimo.home.dir";

    private static final String GERONIMO_SERVER =
        "org.apache.geronimo.server.dir";

    private static final String DEFAULT_KEYSTORE_TRUSTSTORE_PASSWORD_FILE =
        System.getProperty(GERONIMO_SERVER) + "/var/config/config-substitutions.properties";

    /**
     * Split up an output line so it indents at beginning and end (to fit in a
     * typical terminal) and doesn't break in the middle of a word.
     *
     * @param source The unformatted String
     * @param indent The number of characters to indent on the left
     * @param width  The maximum width of the entire line in characters,
     *               including indent (indent 10 with endCol 70 results
     *               in 60 "usable" characters).
     */
    public static String reformat(String source, int indent, int width) {
        int endCol = width;
        if (endCol == 0) {
            endCol = DEFAULT_WIDTH;
        }
        if (endCol - indent < 10) {
            throw new IllegalArgumentException("Need at least 10 spaces for " +
                "printing, but indent=" + indent + " and endCol=" + endCol);
        }
        StringBuilder buf = new StringBuilder((int) (source.length() * 1.1));
        String prefix = indent == 0 ? "" : buildIndent(indent);
        try {
            BufferedReader in = new BufferedReader(new StringReader(source));
            String line;
            int pos;
            while ((line = in.readLine()) != null) {
                if (buf.length() > 0) {
                    buf.append('\n');
                }
                while (line.length() > 0) {
                    line = prefix + line;
                    if (line.length() > endCol) {
                        pos = line.lastIndexOf(' ', endCol);
                        if (pos < indent) {
                            pos = line.indexOf(' ', endCol);
                            if (pos < indent) {
                                pos = line.length();
                            }
                        }
                        buf.append(line.substring(0, pos)).append('\n');
                        if (pos < line.length() - 1) {
                            line = line.substring(pos + 1);
                        } else {
                            break;
                        }
                    } else {
                        buf.append(line).append("\n");
                        break;
                    }
                }
            }
        } catch (IOException e) {
            throw (AssertionError) new AssertionError("This should be impossible").initCause(e);
        }
        return buf.toString();
    }

    private final static int DEFAULT_WIDTH = 76;

    public static void println(String line, int indent, ConsoleReader consoleReader) throws IOException {
        // we don't have sophisticated shell information available with the karaf shell, so just write out
        // the information as a line

        if (indent != 0) {
            consoleReader.printString(buildIndent(indent));
        }
        // just write the line
        consoleReader.println(line);
    }

    public static void printTo(String string, int col, ConsoleReader consoleReader) throws IOException {
        consoleReader.printString(string);
        for (int i = string.length(); i < col; i++) {
            consoleReader.printString(" ");
        }
    }

    private static String buildIndent(int indent) {
        StringBuilder buf = new StringBuilder(indent);
        for (int i = 0; i < indent; i++) {
            buf.append(' ');
        }
        return buf.toString();
    }

    public static String getConnectionURI(String host, Integer port, boolean secure) {
        if (host == null) {
            host = DEFAULT_HOST;
        }
        if (port == null) {
            port = DEFAULT_PORT;
        }
        String uri = (secure) ? DEFAULT_SECURE_URI : DEFAULT_URI;
        uri += "://" + host + ":" + port;
        return uri;
    }

    public static SavedAuthentication readSavedCredentials(String uri) throws IOException {
        SavedAuthentication auth = null;
        InputStream in;

        // First check for .geronimo-deployer on class path (e.g. packaged in deployer.jar)
        in = DeployUtils.class.getResourceAsStream("/.geronimo-deployer");
        // If not there, check in home directory
        if (in == null) {
            File authFile = new File(System.getProperty("user.home"), ".geronimo-deployer");
            if (authFile.exists() && authFile.canRead()) {
                try {
                    in = new BufferedInputStream(new FileInputStream(authFile));
                } catch (FileNotFoundException e) {
                    // ignore
                }
            }
        }

        if (in != null) {
            try {
                Properties props = new Properties();
                props.load(in);
                String encrypted = props.getProperty("login." + uri);
                if (encrypted != null) {
                    if (encrypted.startsWith("{Plain}")) {
                        int pos = encrypted.indexOf("/");
                        String user = encrypted.substring(7, pos);
                        String password = encrypted.substring(pos + 1);
                        auth = new SavedAuthentication(uri, user, password.toCharArray());
                    } else {
                        Object o = EncryptionManager.decrypt(encrypted);
                        if (o == encrypted) {
                            throw new IOException("Unknown encryption used in saved login file");
                        } else {
                            auth = (SavedAuthentication) o;
                        }
                    }
                }
            } catch (IOException e) {
                throw new IOException("Unable to read authentication from saved login file: " + e.getMessage());
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    // ingore
                }
            }
        }

        return auth;
    }

    public final static class SavedAuthentication implements Serializable {

        private static final long serialVersionUID = -3127576258038677899L;

        private String uri;
        private String user;
        private char[] password;

        public SavedAuthentication(String uri, String user, char[] password) {
            this.uri = uri;
            this.user = user;
            this.password = password;
        }

        public String getURI() {
            return this.uri;
        }

        public String getUser() {
            return this.user;
        }

        public char[] getPassword() {
            return this.password;
        }
    }

    public static void setSecurityProperties() throws DeploymentException {
        try {
            Properties props = new Properties();
            FileInputStream fstream = new FileInputStream(System.getProperty(KEYSTORE_TRUSTSTORE_PASSWORD_FILE, DEFAULT_KEYSTORE_TRUSTSTORE_PASSWORD_FILE));
            props.load(fstream);
            fstream.close();

            String keyStorePassword = (String) EncryptionManager.decrypt(props.getProperty("keyStorePassword"));
            String trustStorePassword = (String) EncryptionManager.decrypt(props.getProperty("trustStorePassword"));

            String keyStore = System.getProperty("javax.net.ssl.keyStore", System.getProperty(GERONIMO_HOME) + DEFAULT_TRUSTSTORE_KEYSTORE_LOCATION);
            String trustStore = System.getProperty("javax.net.ssl.trustStore", System.getProperty(GERONIMO_HOME) + DEFAULT_TRUSTSTORE_KEYSTORE_LOCATION);

            System.setProperty("javax.net.ssl.keyStore", keyStore);
            System.setProperty("javax.net.ssl.trustStore", trustStore);
            System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
            System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
        } catch (IOException e) {
            throw new DeploymentException("Unable to set KeyStorePassword and TrustStorePassword.", e);
        }
    }
}


text:
using content::BrowserThread;

namespace electron {

namespace {

// Convert string to lower case and escape it.
std::string MakePartitionName(const std::string& input) {
  return net::EscapePath(base::ToLowerASCII(input));
}

}  // namespace

// static
AtomBrowserContext::BrowserContextMap AtomBrowserContext::browser_context_map_;

AtomBrowserContext::AtomBrowserContext(const std::string& partition,
                                       bool in_memory,
                                       const base::DictionaryValue& options)
    : base::RefCountedDeleteOnSequence<AtomBrowserContext>(
          base::ThreadTaskRunnerHandle::Get()),
      in_memory_pref_store_(nullptr),
      storage_policy_(new SpecialStoragePolicy),
      in_memory_(in_memory),
      weak_factory_(this) {
  user_agent_ = AtomBrowserClient::Get()->GetUserAgent();

  // Read options.
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache);
  options.GetBoolean("cache", &use_cache_);

  base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize),
                    &max_cache_size_);

  if (!base::PathService::Get(DIR_USER_DATA, &path_)) {
    base::PathService::Get(DIR_APP_DATA, &path_);
    path_ = path_.Append(base::FilePath::FromUTF8Unsafe(GetApplicationName()));
    base::PathService::Override(DIR_USER_DATA, path_);
  }

  if (!in_memory && !partition.empty())
    path_ = path_.Append(FILE_PATH_LITERAL("Partitions"))
                .Append(base::FilePath::FromUTF8Unsafe(
                    MakePartitionName(partition)));

  content::BrowserContext::Initialize(this, path_);

  // Initialize Pref Registry.
  InitPrefs();

  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    proxy_config_monitor_ = std::make_unique<ProxyConfigMonitor>(prefs_.get());
    io_handle_ =
        new URLRequestContextGetter::Handle(weak_factory_.GetWeakPtr());
  }

  cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this);

  BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this);
}

AtomBrowserContext::~AtomBrowserContext() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  NotifyWillBeDestroyed(this);
  ShutdownStoragePartitions();

  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    io_handle_->ShutdownOnUIThread();
  } else {
    BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
                              std::move(resource_context_));
  }

  // Notify any keyed services of browser context destruction.
  BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
      this);
}

void AtomBrowserContext::InitPrefs() {
  auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences"));
  base::ThreadRestrictions::ScopedAllowIO allow_io;
  PrefServiceFactory prefs_factory;
  scoped_refptr<JsonPrefStore> pref_store =
      base::MakeRefCounted<JsonPrefStore>(prefs_path);
  pref_store->ReadPrefs();  // Synchronous.
  prefs_factory.set_user_prefs(pref_store);

  auto registry = WrapRefCounted(new PrefRegistrySimple);

  registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,
                                 base::FilePath());
  base::FilePath download_dir;
  base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir);
  registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
                                 download_dir);
  registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);
  InspectableWebContentsImpl::RegisterPrefs(registry.get());
  MediaDeviceIDSalt::RegisterPrefs(registry.get());
  ZoomLevelDelegate::RegisterPrefs(registry.get());
  PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get());

  prefs_ = prefs_factory.Create(
      registry.get(),
      std::make_unique<PrefStoreDelegate>(weak_factory_.GetWeakPtr()));
  prefs_->UpdateCommandLinePrefStore(new ValueMapPrefStore);
}

void AtomBrowserContext::SetUserAgent(const std::string& user_agent) {
  user_agent_ = user_agent;
}

net::URLRequestContextGetter* AtomBrowserContext::CreateRequestContext(
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector protocol_interceptors) {
  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    return io_handle_
        ->CreateMainRequestContextGetter(protocol_handlers,
                                         std::move(protocol_interceptors))
        .get();
  } else {
    NOTREACHED();
    return nullptr;
  }
}

net::URLRequestContextGetter* AtomBrowserContext::CreateMediaRequestContext() {
  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    return io_handle_->GetMainRequestContextGetter().get();
  } else {
    NOTREACHED();
    return nullptr;
  }
}

net::URLRequestContextGetter* AtomBrowserContext::GetRequestContext() {
  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    return GetDefaultStoragePartition(this)->GetURLRequestContext();
  } else {
    NOTREACHED();
    return nullptr;
  }
}

network::mojom::NetworkContextPtr AtomBrowserContext::GetNetworkContext() {
  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    return io_handle_->GetNetworkContext();
  } else {
    NOTREACHED();
    return nullptr;
  }
}

base::FilePath AtomBrowserContext::GetPath() {
  return path_;
}

bool AtomBrowserContext::IsOffTheRecord() {
  return in_memory_;
}

bool AtomBrowserContext::CanUseHttpCache() const {
  return use_cache_;
}

int AtomBrowserContext::GetMaxCacheSize() const {
  return max_cache_size_;
}

content::ResourceContext* AtomBrowserContext::GetResourceContext() {
  if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) {
    return io_handle_->GetResourceContext();
  } else {
    if (!resource_context_)
      resource_context_.reset(new content::ResourceContext);
    return resource_context_.get();
  }
}

std::string AtomBrowserContext::GetMediaDeviceIDSalt() {
  if (!media_device_id_salt_.get())
    media_device_id_salt_.reset(new MediaDeviceIDSalt(prefs_.get()));
  return media_device_id_salt_->GetSalt();
}

std::unique_ptr<content::ZoomLevelDelegate>
AtomBrowserContext::CreateZoomLevelDelegate(
    const base::FilePath& partition_path) {
  if (!IsOffTheRecord()) {
    return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path);
  }
  return std::unique_ptr<content::ZoomLevelDelegate>();
}

content::DownloadManagerDelegate*
AtomBrowserContext::GetDownloadManagerDelegate() {
  if (!download_manager_delegate_.get()) {
    auto* download_manager = content::BrowserContext::GetDownloadManager(this);
    download_manager_delegate_.reset(
        new AtomDownloadManagerDelegate(download_manager));
  }
  return download_manager_delegate_.get();
}

content::BrowserPluginGuestManager* AtomBrowserContext::GetGuestManager() {
  if (!guest_manager_)
    guest_manager_.reset(new WebViewManager);
  return guest_manager_.get();
}

content::PermissionControllerDelegate*
AtomBrowserContext::GetPermissionControllerDelegate() {
  if (!permission_manager_.get())
    permission_manager_.reset(new AtomPermissionManager);
  return permission_manager_.get();
}

storage::SpecialStoragePolicy* AtomBrowserContext::GetSpecialStoragePolicy() {
  return storage_policy_.get();
}

std::string AtomBrowserContext::GetUserAgent() const {
  return user_agent_;
}

AtomBlobReader* AtomBrowserContext::GetBlobReader() {
  if (!blob_reader_.get()) {
    content::ChromeBlobStorageContext* blob_context =
        content::ChromeBlobStorageContext::GetFor(this);
    blob_reader_.reset(new AtomBlobReader(blob_context));
  }
  return blob_reader_.get();
}

content::PushMessagingService* AtomBrowserContext::GetPushMessagingService() {
  return nullptr;
}

content::SSLHostStateDelegate* AtomBrowserContext::GetSSLHostStateDelegate() {
  return nullptr;
}

content::BackgroundFetchDelegate*
AtomBrowserContext::GetBackgroundFetchDelegate() {
  return nullptr;
}

content::BackgroundSyncController*
AtomBrowserContext::GetBackgroundSyncController() {
  return nullptr;
}

content::BrowsingDataRemoverDelegate*
AtomBrowserContext::GetBrowsingDataRemoverDelegate() {
  return nullptr;
}

content::ClientHintsControllerDelegate*
AtomBrowserContext::GetClientHintsControllerDelegate() {
  return nullptr;
}

ResolveProxyHelper* AtomBrowserContext::GetResolveProxyHelper() {
  if (!resolve_proxy_helper_) {
    resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this);
  }
  return resolve_proxy_helper_.get();
}

// static
scoped_refptr<AtomBrowserContext> AtomBrowserContext::From(
    const std::string& partition,
    bool in_memory,
    const base::DictionaryValue& options) {
  PartitionKey key(partition, in_memory);
  auto* browser_context = browser_context_map_[key].get();
  if (browser_context)
    return scoped_refptr<AtomBrowserContext>(browser_context);

  auto* new_context = new AtomBrowserContext(partition, in_memory, options);
  browser_context_map_[key] = new_context->GetWeakPtr();
  return scoped_refptr<AtomBrowserContext>(new_context);
}

}  // namespace electron


text:
<?php namespace Arcanesoft\Blog\Http\Controllers\Front;

use Arcanesoft\Blog\Models\Post;

/**
 * Class     PostsController
 *
 * @package  Arcanesoft\Blog\Http\Controllers\Front
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 *
 * @todo: Complete the seo feature.
 */
class PostsController extends Controller
{
    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    public function index()
    {
        $posts = Post::published()->latest()->paginate(6);

        return $this->view('blog::front.posts.index', compact('posts'));
    }

    public function show($slug)
    {
        /** @var  \Arcanesoft\Blog\Models\Post  $post */
        $post = Post::published()->where('slug', $slug)->firstOrFail();

        $this->setTitle($post->seo->title);
        $this->setDescription($post->seo->description);
        $this->setKeywords($post->seo->keywords ? $post->seo->keywords->toArray() : []);
        $this->addBreadcrumb($post->title);

        return $this->view('blog::front.posts.single', compact('post'));
    }

    public function archive($year)
    {
        $posts = Post::publishedAt($year)->latest()->paginate(6);

        return $this->view('blog::front.posts.single', compact('posts'));
    }
}


text:
var cLocal = require('../config/local'),
    fs = require('fs'),
    _ = require('lodash'),
    Promise = require('bluebird'),
    stripJsonComments = require('strip-json-comments'),
    security = require(cLocal.blueOak + 'lib/security');

var config;

function setSources(cBot) {
    cBot = cBot || {};
    cBot.configs = cBot.configs || [];

    if (!Array.isArray(cBot.configs)) {
        throw new Error('bot configuration is malformed. configs property must be an array');
    }

    return cBot;
}

function setDefaultValues() {
    config = loadFromPath(cLocal.blueOak + 'defaults.json');
}

function overrideDefaultGet(configService) {
    configService.get = function (key) {
        return config[key] || {};
    };

    return configService;
}

function merge(cBot, cOverride) {
    var configService = global.services.get('config');

    setDefaultValues();
    configService = overrideDefaultGet(configService);
    cBot = setSources(cBot);

    var i;

    for (i = 0; i < cBot.configs.length; i++) {
        config = _.merge(config, loadFromPath(cBot.configs[i]));
    }

    if (cOverride) {
        config = _.merge(config, cOverride);
    }

    if (!cBot.logging) {
        for (i = 0; i < config.logger.transports.length; i++) {
            config.logger.transports[i].options.level = 'silent';
        }
    }

    decrypt(config);

    return configService;
}

function decrypt(config) {
    if (security.containsEncryptedData(config)) {
        security.decryptObject(config, function (str) {
            return security.decrypt(str, process.env.decryptionKey);
        });
    }

    return config;
}

function loadFromPath(path) {
    var json = fs.readFileSync(path, 'utf-8');
    json = stripJsonComments(json);
    json = JSON.parse(json);

    return json;
}

module.exports = {
    merge: merge
};


text:
using System.Collections.Generic;
using ClaySharp;
using ClaySharp.Implementation;

namespace Orchard.DisplayManagement {
    /// <summary>
    /// Service that creates new instances of dynamic shape objects
    /// This may be used directly, or through the IShapeHelperFactory.
    /// </summary>
    public interface IShapeFactory : IDependency {
        IShape Create(string shapeType, INamedEnumerable<object> parameters);
        IShape Create(string shapeType, INamedEnumerable<object> parameters, IEnumerable<IClayBehavior> behaviors);
    }

    public static class ShapeFactoryExtensions {
        public static IShape Create(this IShapeFactory factory, string shapeType) {
            return factory.Create(shapeType, Arguments.Empty());
        }
    }
}


text:
<?php
/**
 * [PHPFOX_HEADER]
 */

defined('PHPFOX') or exit('NO DICE!');

/**
 *
 *
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author  		Raymond Benc
 * @package  		Module_Bulletin
 * @version 		$Id: display.class.php 1724 2010-08-16 11:14:54Z Miguel_Espinoza $
 */
class Bulletin_Component_Block_Display extends Phpfox_Component
{
	/**
	 * Class process method wnich is used to execute this component.
	 */
	public function process()
	{
		return false;

		if (!Phpfox::isUser())
		{
			return false;
		}

		$aBulletins = Phpfox::getService('bulletin.bulletin')->getBulletins(Phpfox::getUserId());

		if (empty($aBulletins))
		{
			return false;
		}
		$this->template()->assign(array(
				'sHeader' => Phpfox::getPhrase('bulletin.bulletins'),
				'aBulletins' => $aBulletins,
				'bNoExtraLinks' => true,
				'aFooter' => ((empty($aBulletins) ? array() : array(
							Phpfox::getPhrase('bulletin.view_all_bulletins') => $this->url()->makeUrl('bulletin'),
							Phpfox::getPhrase('bulletin.post_a_bulletin') => $this->url()->makeUrl('bulletin.add')
						)
					)
				)
			)
		);

		$this->template()->assign('sDeleteBlock', 'dashboard');

		return 'block';
	}

	/**
	 * Garbage collector. Is executed after this class has completed
	 * its job and the template has also been displayed.
	 */
	public function clean()
	{
		(($sPlugin = Phpfox_Plugin::get('bulletin.component_controller_index_clean')) ? eval($sPlugin) : false);
	}

	public function widget()
	{
		return true;
	}
}

?>


text:
using System;
using Csla;

namespace Invoices.DataAccess.Sql
{
    public partial class SupplierProductCollDal
    {
    }
}


text:
<?php
/**
 * Vertex.
 */
namespace GraphDS\Vertex;

/**
 * Class defining a generic, extendable vertex object.
 */
class Vertex
{
    /**
     * Variable holding the value of this vertex.
     *
     * @var mixed
     */
    protected $value;

    /**
     * Array holding references to all neighboring vertices of this vertex.
     *
     * @var Vertex[][]
     */
    public $neighbors;

    /**
     * Constructor for general Vertex object.
     */
    public function __construct()
    {
        $this->value = null;
        $this->neighbors = array();
    }

    /**
     * Gets the value associated with this vertex.
     *
     * @return mixed Value associated with this vertex
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Sets the value associated with this vertex.
     *
     * @param mixed $value Value to be associated with this vertex
     */
    public function setValue($value = null)
    {
        $this->value = $value;
    }
}


text:
package com.ibm.jaggr.core.util;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * A list builder that supports concurrency for insertion without the concurrency bottlenecks of a
 * synchronized List.
 *

 * Note that this class is thread-safe for adding elements only. It is not thread-safe for adding
 * elements concurrent with calling {@link #toList()}, with the possible result being that some
 * elements in the returned list may have un-assigned values.
 *

 * To avoid thread contention, the initial size of the list should be specified so as to avoid the
 * need to resize the internal array when its size is exceeded.
 *
 * @param <T>
 *            the type of the list element
 */
public class ConcurrentListBuilder<T> {
	private static final String sourceClass = ConcurrentListBuilder.class.getName();

	final private AtomicInteger index = new AtomicInteger(0);
	final private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
	private T[] items;

	public ConcurrentListBuilder() {
		this(32);
	}

	@SuppressWarnings("unchecked")
	public ConcurrentListBuilder(int initialSize) {
		items = (T[])new Object[initialSize];
	}

	@SuppressWarnings("unchecked")
	public ConcurrentListBuilder(Collection<T> other) {
		items = (T[])new Object[other.size()];
		for (T elem : other) {
			add(elem);
		}
	}

	/**
	 * Adds the specified element to the builder.
	 *

	 * Blocking on add operations only occurs when the list array needs to be grown.
	 *
	 * @param item
	 *            The item to add
	 * @return the index in the list to which the item was added
	 * @throws NullPointerException
	 *             on attempt to add null to the list
	 */
	public int add(T item) {
		final String sourceMethod = "add"; //$NON-NLS-1$
		if (item == null) {
			throw new NullPointerException();
		}
		Lock lock = null;
		int idx = index.getAndIncrement();
		lock = (idx >= items.length) ? rwl.writeLock() : rwl.readLock();
		SignalUtil.lock(lock, sourceClass, sourceMethod);
		try {
			if (idx >= items.length) {
				int newLength = items.length;
				while (idx >= newLength) { newLength*=2; }
				items = Arrays.copyOf(items, newLength);
			}
			items[idx] = item;
		} finally {
			lock.unlock();
		}
		return idx;
	}

	/**
	 * Returns the number of elements that have been added.
	 *
	 * @return the list size
	 */
	public int size() {
		return index.get();
	}

	/**
	 * Returns a list object for this builder.
	 *

	 * If this method is called concurrently with adding elements, then there is the potential that
	 * one or more of the list elements may have unassigned values.
	 *
	 * @return a list object for this builder.
	 */
	public List<T> toList() {
		final String sourceMethod = "toList"; //$NON-NLS-1$
		SignalUtil.lock(rwl.readLock(), sourceClass, sourceMethod);
		List<T> result = null;
		try {
			result = Arrays.asList(Arrays.copyOf(items, index.get()));
		} finally {
			rwl.readLock().unlock();
		}
		return result;
	}
}


text:
#ifndef CXXLAPACK_INTERFACE_ORM2R_H
#define CXXLAPACK_INTERFACE_ORM2R_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename IndexType>
    IndexType
    orm2r(char          side,
          char          trans,
          IndexType     m,
          IndexType     n,
          IndexType     k,
          const float   *A,
          IndexType     ldA,
          const float   *tau,
          float         *C,
          IndexType     ldC,
          float         *work);

template <typename IndexType>
    IndexType
    orm2r(char          side,
          char          trans,
          IndexType     m,
          IndexType     n,
          IndexType     k,
          const double  *A,
          IndexType     ldA,
          const double  *tau,
          double        *C,
          IndexType     ldC,
          double        *work);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_ORM2R_H


text:
require 'spec_helper'

describe "<%= file_name %>/<%= @action %>.html.<%= options[:template_engine] %>" do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
def sports
  puts "This is a sports string"
  yield("basketball", "football")
end

sports {|sport1, sport2| puts "#{sport1} and #{sport2} are sports"}

hollywood_actors = {
  "Denzel Washington" => "John Q",
  "Tom Hanks" => "Forrest Gump",
  "Leo" => "Jack"
}

movie_genres = ["comedy", "drama", "action", "biopic"]

hollywood_actors.each do |actor, character|
  puts "#{actor} is best known for his character #{character}"
end

p hollywood_actors

p movie_genres

movie_genres.map! do |genre|
  genre.upcase
end

p movie_genres

#Release 2

letter_array = ["a", "b", "c", "d"]

num_hash = {1 => "one", 2=> "two", 3 => "three"}

#method that iterates through items deleting under condition
p num_hash.delete_if {|digit, strng| digit.even?}

#method that filters data structure for items that do satisfy condition
p letter_array.keep_if {|letter| letter =="b" }

#method that does the same as line 37
p num_hash.select {|digit, strng| digit > 1}

p num_hash.reject {|digit, strng| digit > 1}

# method that removes until condition is false and then stops
p letter_array.take_while {|letter| letter != "c"}


text:
#region MIT
//
// Gorgon.
// Copyright (C) 2018 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: April 5, 2018 12:49:36 PM
//
#endregion

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Gorgon.Examples
{
    /// <summary>
    /// Updates the animation frame index for a GIF.
    /// </summary>
    class GifAnimator
    {
        #region Variables.
        // The task that updates the frame index.
        private Task _animationTask;
        // The current sychronization context.
        private readonly SynchronizationContext _syncContext;
        // Cancellation support.
        private CancellationTokenSource _cancel;
        private int _currentFrame;
        #endregion

        #region Properties.
        /// <summary>
        /// Property to return the current frame of animation.
        /// </summary>
        public int CurrentFrame
        {
            get => _currentFrame;
            private set => _currentFrame = value;
        }

        /// <summary>
        /// Property to set or return the time between each frame.
        /// </summary>
        public IReadOnlyList<int> FrameTimes
        {
            get;
            set;
        }
        #endregion

        #region Methods.
        /// <summary>
        /// Function to reset the frame index.
        /// </summary>
        public void Reset() => Interlocked.Exchange(ref _currentFrame, 0);

        /// <summary>
        /// Function to start the animation.
        /// </summary>
        /// <param name="frameChangeCallback">The callback to execute when a frame is updated.</param>
        public void Animate(Action frameChangeCallback)
        {
            if ((FrameTimes is null) || (FrameTimes.Count == 0) || (_animationTask is not null))
            {
                return;
            }

            _cancel = new CancellationTokenSource();
            CancellationToken token = _cancel.Token;

            // We'll use a background task to update the frame index.
            // We didn't set up an Idle loop in this app, so we'll just use another task to continuously execute the frame change.
            _animationTask = Task.Run(async () =>
                                      {
                                          while (!token.IsCancellationRequested)
                                          {
                                              if (frameChangeCallback is not null)
                                              {
                                                  // Always execute the callback on the main thread.
                                                  // This way we won't have to worry about cross thread stuff.
                                                  _syncContext.Post(_ => frameChangeCallback(), null);
                                              }

                                              // Gif frame times are in 1/100th of a second.  We need to scale to milliseconds.
                                              await Task.Delay(FrameTimes[CurrentFrame] * 10, token);

                                              ++CurrentFrame;

                                              if (CurrentFrame >= FrameTimes.Count)
                                              {
                                                  CurrentFrame = 0;
                                              }
                                          }
                                      }, token);
        }

        /// <summary>
        /// Function to cancel the animation.
        /// </summary>
        /// <returns>The task that is updating the animation.</returns>
        public async Task CancelAsync()
        {
            if (_animationTask is null)
            {
                return;
            }

            _cancel.Cancel();
            // We await so the animation has time to shut down gracefully.
            await _animationTask;
            _animationTask = null;
            _cancel = null;
        }
        #endregion

        #region Constructor/Finalizer.
        /// <summary>
        /// Initializes a new instance of the <see cref="GifAnimator"/> class.
        /// </summary>
        /// <param name="syncContext">The synchronize context.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="syncContext"/> parameter is <b>null</b>.</exception>
        public GifAnimator(SynchronizationContext syncContext) =>
            // We use this synchronization context to ensure that we fire the event on the main thread.
            _syncContext = syncContext ?? throw new ArgumentNullException(nameof(syncContext));
        #endregion

    }
}


text:
package org.apache.beam.sdk.function;

import java.util.function.Consumer;

/**
 * A {@link Consumer} which can throw {@link Exception}s.
 *
 * <p>Used to expand the allowed set of method references to be used by Java 8 functional
 * interfaces.
 */
@FunctionalInterface
public interface ThrowingConsumer<ExceptionT extends Exception, T> {
  void accept(T t) throws ExceptionT;
}


text:
package ru.job4j.ProjectTracker;
/**
 * Interface = Input implementation.
 * Ручной ввод.
 *
 * @author mosipov
 * @since 24.06.2017.
 * @version 1
 *
 */
public class MenuOutEception  extends RuntimeException {
	/**	Исключение при выходе из диапазона.
	*	@param msg String **param**
	*/
    public MenuOutEception(String msg) {
        super(msg);
    }

}


text:
A Wercker box that contains a Gentoo chroot with `crossdev` installed.

## But why‽

To be used as a base image for other wercker boxes containing crossdev toolchains.

See [`wercker-box-gentoo`][1] for a detailed explanation.

## `crossdev` version

The current `crossdev` version is **20141030**. If there is a newer version
available [in Portage][2], just send me a pull request and I'll merge it.

[0]: https://app.wercker.com/#applications/5495c90c07fa3ea41500d357/tab/details
[1]: https://github.com/attilaolah/wercker-box-gentoo
[2]: http://packages.gentoo.org/package/sys-devel/crossdev


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Contr. Univ. Mich. Herb. 5: 35 (1941)

#### Original name
Psathyrella michiganensis A.H. Sm.

### Remarks
null