text:
#ifndef MUMBLE_MUMBLE_AUDIOWIZARD_H_
#define MUMBLE_MUMBLE_AUDIOWIZARD_H_

#include <QtCore/QtGlobal>
#if QT_VERSION >= 0x050000
# include <QtWidgets/QWizard>
# include <QtWidgets/QWizardPage>
#else
# include <QtGui/QWizard>
# include <QtGui/QWizardPage>
#endif

#include "AudioStats.h"
#include "AudioOutput.h"
#include "GlobalShortcut.h"
#include "Settings.h"

class CompletablePage : public QWizardPage {
		Q_OBJECT
	protected:
		bool bComplete;
	public:
		CompletablePage(QWizard *p = NULL);
		void setComplete(bool);
		bool isComplete() const Q_DECL_OVERRIDE;
};

#include "ui_AudioWizard.h"

class AudioWizard: public QWizard, public Ui::AudioWizard {
	private:
		Q_OBJECT
		Q_DISABLE_COPY(AudioWizard)
	protected:
		bool bTransmitChanged;

		QGraphicsScene *qgsScene;
		QGraphicsItem *qgiSource;
		AudioOutputSample *aosSource;
		float fAngle;
		float fX, fY;

		Settings sOldSettings;

		QTimer *ticker;

		bool bInit;
		bool bDelay;
		bool bLastActive;

		QPixmap qpTalkingOn, qpTalkingOff;

		int iMaxPeak;
		int iTicks;

		void restartAudio();
		void playChord();

		bool eventFilter(QObject *, QEvent *) Q_DECL_OVERRIDE;
	public slots:
		void on_qcbInput_activated(int);
		void on_qcbInputDevice_activated(int);
		void on_qcbOutput_activated(int);
		void on_qcbOutputDevice_activated(int);
		void on_qsOutputDelay_valueChanged(int);
		void on_qsMaxAmp_valueChanged(int);
		void on_Ticker_timeout();
		void on_qsVAD_valueChanged(int);
		void on_qrAmplitude_clicked(bool);
		void on_qrSNR_clicked(bool);
		void on_qrPTT_clicked(bool);
		void on_qcbEcho_clicked(bool);
		void on_qcbHeadphone_clicked(bool);
		void on_qcbPositional_clicked(bool);
		void on_qcbAttenuateOthers_clicked(bool);
		void on_qcbHighContrast_clicked(bool);
		void on_skwPTT_keySet(bool, bool);
		void on_qrbQualityUltra_clicked();
		void on_qrbQualityBalanced_clicked();
		void on_qrbQualityLow_clicked();
		void on_qrbQualityCustom_clicked();
		void showPage(int);
		void updateTriggerWidgets(bool);
	public:
		AudioWizard(QWidget *parent);
		void reject() Q_DECL_OVERRIDE;
		void accept() Q_DECL_OVERRIDE;
		bool validateCurrentPage() Q_DECL_OVERRIDE;
		virtual int nextId() const Q_DECL_OVERRIDE;
};

#endif


text:
/**
 * This class is used to send requests to the server using {@link Ext.direct.Manager Ext.Direct}. When a
 * request is made, the transport mechanism is handed off to the appropriate
 * {@link Ext.direct.RemotingProvider Provider} to complete the call.
 *
 * # Specifying the function
 *
 * This proxy expects a Direct remoting method to be passed in order to be able to complete requests.
 * This can be done by specifying the {@link #directFn} configuration. This will use the same direct
 * method for all requests. Alternatively, you can provide an {@link #api} configuration. This
 * allows you to specify a different remoting method for each CRUD action.
 *
 * # Parameters
 *
 * This proxy provides options to help configure which parameters will be sent to the server.
 * By specifying the {@link #paramsAsHash} option, it will send an object literal containing each
 * of the passed parameters. The {@link #paramOrder} option can be used to specify the order in which
 * the remoting method parameters are passed.
 *
 * # Example Usage
 *
 *     Ext.define('User', {
 *         extend: 'Ext.data.Model',
 *         fields: ['firstName', 'lastName'],
 *         proxy: {
 *             type: 'direct',
 *             directFn: MyApp.getUsers,
 *             paramOrder: 'id' // Tells the proxy to pass the id as the first parameter to the remoting method.
 *         }
 *     });
 *     User.load(1);
 */
Ext.define('Ext.data.proxy.Direct', {
    /* Begin Definitions */

    extend: 'Ext.data.proxy.Server',
    alternateClassName: 'Ext.data.DirectProxy',

    alias: 'proxy.direct',

    requires: ['Ext.direct.Manager'],

    /* End Definitions */

    /**
     * @cfg {String/String[]} paramOrder
     * Defaults to undefined. A list of params to be executed server side.  Specify the params in the order in
     * which they must be executed on the server-side as either (1) an Array of String values, or (2) a String
     * of params delimited by either whitespace, comma, or pipe. For example, any of the following would be
     * acceptable:
     *
     *     paramOrder: ['param1','param2','param3']
     *     paramOrder: 'param1 param2 param3'
     *     paramOrder: 'param1,param2,param3'
     *     paramOrder: 'param1|param2|param'
     */
    paramOrder: undefined,

    /**
     * @cfg {Boolean} paramsAsHash
     * Send parameters as a collection of named arguments.
     * Providing a {@link #paramOrder} nullifies this configuration.
     */
    paramsAsHash: true,

    /**
     * @cfg {Function} directFn
     * Function to call when executing a request.  directFn is a simple alternative to defining the api configuration-parameter
     * for Store's which will not implement a full CRUD api.
     */
    directFn : undefined,

    /**
     * @cfg {Object} api
     * The same as {@link Ext.data.proxy.Server#api}, however instead of providing urls, you should provide a direct
     * function call.
     */

    /**
     * @cfg {Object} extraParams
     * Extra parameters that will be included on every read request. Individual requests with params
     * of the same name will override these params when they are in conflict.
     */

    // private
    paramOrderRe: /[\s,|]/,

    constructor: function(config){
        var me = this;

        Ext.apply(me, config);
        if (Ext.isString(me.paramOrder)) {
            me.paramOrder = me.paramOrder.split(me.paramOrderRe);
        }
        me.callParent(arguments);
    },

    doRequest: function(operation, callback, scope) {
        var me = this,
            writer = me.getWriter(),
            request = me.buildRequest(operation, callback, scope),
            fn = me.api[request.action]  || me.directFn,
            args = [],
            params = request.params,
            paramOrder = me.paramOrder,
            method,
            i = 0,
            len;

        //<debug>
        if (!fn) {
            Ext.Error.raise('No direct function specified for this proxy');
        }
        //</debug>

        if (operation.allowWrite()) {
            request = writer.write(request);
        }

        if (operation.action == 'read') {
            // We need to pass params
            method = fn.directCfg.method;

            if (method.ordered) {
                if (method.len > 0) {
                    if (paramOrder) {
                        for (len = paramOrder.length; i < len; ++i) {
                            args.push(params[paramOrder[i]]);
                        }
                    } else if (me.paramsAsHash) {
                        args.push(params);
                    }
                }
            } else {
                args.push(params);
            }
        } else {
            args.push(request.jsonData);
        }

        Ext.apply(request, {
            args: args,
            directFn: fn
        });
        args.push(me.createRequestCallback(request, operation, callback, scope), me);
        fn.apply(window, args);
    },

    /*
     * Inherit docs. We don't apply any encoding here because
     * all of the direct requests go out as jsonData
     */
    applyEncoding: function(value){
        return value;
    },

    createRequestCallback: function(request, operation, callback, scope){
        var me = this;

        return function(data, event){
            me.processResponse(event.status, operation, request, event, callback, scope);
        };
    },

    // inherit docs
    extractResponseData: function(response){
        return Ext.isDefined(response.result) ? response.result : response.data;
    },

    // inherit docs
    setException: function(operation, response) {
        operation.setException(response.message);
    },

    // inherit docs
    buildUrl: function(){
        return '';
    }
});

redpajama_set_name: RedPajamaGithub


text:
'use strict';

angular.module('core').run(['$rootScope', 'CheckAuth', function($rootScope, CheckAuth) {
	// setting up English as default

	$rootScope.lang = 'en';

	// checking authorization when state changes
	$rootScope.$on('$stateChangeStart', function(event, stateTo) {
		if(stateTo.url.indexOf('admin') !== -1) {
			CheckAuth();
		}
	});
}]);


text:
set(install_command_env)
if (UNIX AND NOT APPLE)
  set(install_command_env env LD_LIBRARY_PATH=<INSTALL_DIR>/lib)
endif()

set(process_environment)
if (UNIX AND NOT APPLE)
  set (process_environment PROCESS_ENVIRONMENT
    LD_LIBRARY_PATH "<INSTALL_DIR>/lib")
endif()

add_external_project(cython
  DEPENDS python
  CONFIGURE_COMMAND ""
  BUILD_COMMAND
    env
        CPPFLAGS=-I<INSTALL_DIR>/include
        LDFLAGS=-L<INSTALL_DIR>/lib
    ${pv_python_executable} setup.py build
  BUILD_IN_SOURCE 1
  INSTALL_COMMAND
    ${install_command_env}
  ${pv_python_executable} setup.py install
     --prefix=<INSTALL_DIR>
  ${process_environment}
)


text:
API Documentation
=================

Kolide Fleet is powered by a Go API server which serves three types of endpoints:

- Endpoints starting with `/api/v1/osquery/` are osquery TLS server API endpoints. All of these endpoints are used for talking to osqueryd agents and that's it.
- Endpoints starting with `/api/v1/kolide/` are endpoints to interact with the Fleet data model (packs, queries, scheduled queries, labels, hosts, etc) as well as application endpoints (configuring settings, logging in, session management, etc).
- All other endpoints are served the React single page application bundle. The React app uses React Router to determine whether or not the URI is a valid route and what to do.

Only osquery agents should interact with the osquery API, but we'd like to support the eventual use of the Fleet API extensively. The API is not very well documented at all right now, but we have plans to:

- Generate and publish detailed documentation via a tool built using [test2doc](https://github.com/adams-sarah/test2doc) (or similar).
- Release a JavaScript Fleet API client library (which would be derived from the [current](https://github.com/kolide/fleet/blob/master/frontend/kolide/index.js) JavaScript API client).
- Commit to a stable, standardized API format.

## Fleetctl

Many of the operations that a user may wish to perform with an API are currently best performed via the [fleetctl](../cli/README.md) tooling. These CLI tools allow updating of the osquery configuration entities, as well as performing live queries.

## Current API

The general idea with the current API is that there are many entities throughout the Fleet application, such as:

- Queries
- Packs
- Labels
- Hosts

Each set of objects follows a similar REST access pattern.

- You can `GET /api/v1/kolide/packs` to get all packs
- You can `GET /api/v1/kolide/packs/1` to get a specific pack.
- You can `DELETE /api/v1/kolide/packs/1` to delete a specific pack.
- You can `POST /api/v1/kolide/packs` (with a valid body) to create a new pack.
- You can `PATCH /api/v1/kolide/packs/1` (with a valid body) to modify a specific pack.

Queries, packs, scheduled queries, labels, invites, users, sessions all behave this way. Some objects, like invites, have additional HTTP methods for additional functionality. Some objects, such as scheduled queries, are merely a relationship between two other objects (in this case, a query and a pack) with some details attached.

All of these objects are put together and distributed to the appropriate osquery agents at the appropriate time. At this time, the best source of truth for the API is the [HTTP handler file](https://github.com/kolide/fleet/blob/master/server/service/handler.go) in the Go application. The REST API is exposed via a transport layer on top of an RPC service which is implemented using a micro-service library called [Go Kit](https://github.com/go-kit/kit). If using the Fleet API is important to you right now, being familiar with Go Kit would definitely be helpful.


text:
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;

namespace LineSharp.Functions
{
    internal class Net
    {
        internal static bool ValidateSsl(object sender,
            X509Certificate certificate,
            X509Chain chain,
            SslPolicyErrors sslPolicyErrors)
        {
            //Validate the certificate, no extra auth. required
            return true;
        }

        internal static string GetLocalIpAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }
    }
}


text:
package com.plugin.commons.ui.pkbk;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.plugin.R;
import com.plugin.commons.ComApp;
import com.plugin.commons.CoreContants;
import com.plugin.commons.helper.ComUtil;
import com.plugin.commons.helper.DialogUtil;
import com.plugin.commons.helper.DialogUtil.OnAlertSureOnclick;
import com.plugin.commons.helper.FileUtils;
import com.plugin.commons.helper.FuncUtil;
import com.plugin.commons.helper.SituoHttpAjax;
import com.plugin.commons.model.CommonModel;
import com.plugin.commons.model.DialogObj;
import com.plugin.commons.model.PhotoAndVideoModel;
import com.plugin.commons.model.RspResultModel;
import com.plugin.commons.service.PaiKeBoKeService;
import com.plugin.commons.service.PaiKeBoKeServiceImpl;
import com.plugin.commons.ui.base.BaseActivity;
import com.plugin.commons.view.DialogOptionSelect;
import com.zq.types.StBaseType;

/**
 * @author zhang
 *	上传拍照信息
 */
public class UploadVideoActivity extends BaseActivity implements OnClickListener{

	LinearLayout ll_show_imgs;
	Button btn_right;
	ImageView im_ph_1;
	ImageView im_ph_2;
	ImageView im_ph_3;
	ImageView im_ph_4;
	ImageView im_ph_5;
	ImageView im_ph_6;
	ImageView im_ph_7;
	ImageView im_ph_8;
	ImageView im_ph_9;
	private List<PhotoAndVideoModel>  phtModel=new ArrayList<PhotoAndVideoModel>();
	private List<Bitmap> bitMapList=new ArrayList<Bitmap>();
	private int maxPhtos=9;
	private EditText ed_title;
	private Button btn_photo;
	private LinearLayout ll_photo;
	private RelativeLayout rl_up_video;
	private ArrayList<DialogObj> dlglist;
	private PaiKeBoKeService pkSv;
	private CommonModel cmmodel;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_video);

		ComUtil.customeTitle(this,"播客上传",true);
		cmmodel=(CommonModel) getIntent().getExtras().get(CoreContants.PARAMS_MSG);
		pkSv =new PaiKeBoKeServiceImpl();
		initViews();
		initDisplay();
	}

	private void initDisplay(){
		dlglist =new ArrayList<DialogObj>();
		DialogObj dobj=new DialogObj("1", "拍视频");
		DialogObj dobj2=new DialogObj("2", "在视频库中选择");
		dlglist.add(dobj);
		dlglist.add(dobj2);
	}

	private void initViews(){
		btn_right = (Button)this.findViewById(R.id.btn_title_right);
		btn_right.setBackgroundDrawable(this.getResources().getDrawable(ComApp.getInstance().appStyle.btn_dialogsure_selector));
		btn_right.setVisibility(View.VISIBLE);
		this.ed_title=(EditText) this.findViewById(R.id.et_upload_title);
		ll_photo=(LinearLayout) this.findViewById(R.id.ll_photo);
		rl_up_video=(RelativeLayout) this.findViewById(R.id.rl_up_video);

		im_ph_1=(ImageView) this.findViewById(R.id.im_ph_1);
		im_ph_1.setOnClickListener(this);
		im_ph_2=(ImageView) this.findViewById(R.id.im_ph_2);
		im_ph_2.setOnClickListener(this);
		im_ph_3=(ImageView) this.findViewById(R.id.im_ph_3);
		im_ph_3.setOnClickListener(this);
		im_ph_4=(ImageView) this.findViewById(R.id.im_ph_4);
		im_ph_4.setOnClickListener(this);
		im_ph_5=(ImageView) this.findViewById(R.id.im_ph_5);
		im_ph_5.setOnClickListener(this);
		im_ph_6=(ImageView) this.findViewById(R.id.im_ph_6);
		im_ph_6.setOnClickListener(this);
		im_ph_7=(ImageView) this.findViewById(R.id.im_ph_7);
		im_ph_7.setOnClickListener(this);
		im_ph_8=(ImageView) this.findViewById(R.id.im_ph_8);
		im_ph_8.setOnClickListener(this);
		im_ph_9=(ImageView) this.findViewById(R.id.im_ph_9);
		im_ph_9.setOnClickListener(this);

		btn_photo = (Button) this.findViewById(R.id.btn_photo);
		btn_photo.setBackgroundDrawable(this.getResources().getDrawable(ComApp.getInstance().appStyle.boke_btn_selector));
		ll_show_imgs=(LinearLayout) this.findViewById(R.id.ll_show_imgs);
		btn_photo.setOnClickListener(new View.OnClickListener() {
			private DialogObj mSelectItem;//已选项目
			@Override
			public void onClick(View arg0) {

				DialogOptionSelect dlg = new DialogOptionSelect(UploadVideoActivity.this,new DialogOptionSelect.PickDialogcallback() {

					@Override
					public void onItemSelect(DialogObj selectItem) {

						if("1".equals(selectItem.getCode())){//从相机拍照获取相片
							takeVideo();
						}else{//从视频库中获取
							getVideoFromlib();
						}
					}
				},dlglist,mSelectItem);
				dlg.show();
			}
		});

		btn_right.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				cmmodel.setTitle(ed_title.getText().toString());
				if(FuncUtil.isEmpty(cmmodel.getTitle())){
					DialogUtil.showToast(UploadVideoActivity.this, "请填写标题!");
					return;
				}
				DialogUtil.showProgressDialog(UploadVideoActivity.this);
				SituoHttpAjax.ajax(new SituoHttpAjax.SituoAjaxCallBack() {

					@Override
					public StBaseType requestApi() {

						int index=0;
						FileInputStream ins1=null;
						FileInputStream ins2=null;
						FileInputStream ins3=null;
						FileInputStream ins4=null;
						FileInputStream ins5=null;
						FileInputStream ins6=null;
						FileInputStream ins7=null;
						FileInputStream ins8=null;
						FileInputStream ins9=null;
						try {
							for(PhotoAndVideoModel pkmodel:phtModel){//暂时只能上传一个视频
								index++;
								if(index%9==1){
									cmmodel.setVideoname(FileUtils.getPathName(pkmodel.getFilePath()));
									cmmodel.setVidio(getFileIns(pkmodel.getFilePath(),ins1));
									cmmodel.setVideoFile(pkmodel.getFilePath());
								}
							}
							RspResultModel rsp =pkSv.pushVideo(cmmodel);
							return rsp;
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}finally{
							try{
								if(ins1!=null)
									ins1.close();
								if(ins2!=null)
									ins2.close();
								if(ins3!=null)
									ins3.close();
								if(ins4!=null)
									ins4.close();
								if(ins5!=null)
									ins5.close();
								if(ins6!=null)
									ins6.close();
								if(ins7!=null)
									ins7.close();
								if(ins8!=null)
									ins8.close();
								if(ins9!=null)
									ins9.close();
							}catch(Exception e){
								e.printStackTrace();
							}
						}
						return null;
					}
					@Override
					public void callBack(StBaseType baseType) {
						DialogUtil.closeProgress(UploadVideoActivity.this);
						RspResultModel result = (RspResultModel)baseType;
						if(ComUtil.checkRsp(UploadVideoActivity.this, result)){
							DialogUtil.showToast(UploadVideoActivity.this, "上传播客信息成功");
						}else{
							DialogUtil.showToast(UploadVideoActivity.this, "上传播客信息失败");
						}
					}
				});
			}
		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		log.info(requestCode+";"+resultCode);
		try {

			if (CoreContants.REQUEST_CODE_TAKE_VIDEO == requestCode) {
				if (null != data) {
					log.info("处理video");
					Uri uri = data.getData();
					if (uri == null) {
						return;
					} else {
						// 视频捕获并保存到指定的fileUri意图
						Cursor c = getContentResolver().query(uri,
								new String[] { MediaStore.MediaColumns.DATA },
								null, null, null);
						if (c != null && c.moveToFirst()) {
							String filePath = c.getString(0);
							PhotoAndVideoModel ph=new PhotoAndVideoModel();
							ph.setFilePath(filePath);
							phtModel.add(ph);
							refreshImageView(filePath);
						}

					}
				}
			}else{
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				// 选择的图片不为空,获取图片的路径 并跳转到确认页面
				if (cursor != null) {
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					cursor.moveToFirst();
					String path = cursor.getString(column_index);
					if (path != null) {
						log.info("显示图片");
						final String file = ComUtil.saveImage(this, path,480,640);
						PhotoAndVideoModel ph=new PhotoAndVideoModel();
						ph.setFilePath(path);
						phtModel.add(ph);
						refreshImageView(file);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			DialogUtil.showToast(this, "获取视频失败");
			return;
		}
	}

	@Override
	public void onClick(final View v) {

		 DialogUtil.showConfirmAlertDialog(this, "确定删除该视频?","删除视频提示", new OnAlertSureOnclick() {

			@Override
			public void onAlertSureOnclick() {
				PhotoAndVideoModel tem = null;
				for(PhotoAndVideoModel ph:phtModel){
					if(ph.getId().equals(v.getId()+"")){
						tem=ph;
						break;
					}
				}
				phtModel.remove(tem);
				FileUtils.deleteFile(tem.getFilePath());
				v.setVisibility(View.GONE);
			}
		});
	}

	/**
	 * 刷新图片
	 * @param file
	 */
	private  void refreshImageView(String file){
		int index=0;
		for(PhotoAndVideoModel p:phtModel){
			Bitmap bitmap = ComUtil.getVideoThumbnail(p.getFilePath(),100,100,MediaStore.Images.Thumbnails.MINI_KIND);
			bitMapList.add(bitmap);
			if(bitmap!=null){
				if(index==0){
					im_ph_1.setImageBitmap(bitmap);
					im_ph_1.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_1+"");
					if(rl_up_video!=null){
						rl_up_video.setVisibility(View.VISIBLE);
					}
				}
				if(index==1){
					im_ph_2.setImageBitmap(bitmap);
					im_ph_2.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_2+"");
				}
				if(index==2){
					im_ph_3.setImageBitmap(bitmap);
					im_ph_3.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_3+"");
				}
				if(index==3){
					im_ph_4.setImageBitmap(bitmap);
					im_ph_4.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_4+"");
				}
				if(index==4){
					im_ph_5.setImageBitmap(bitmap);
					im_ph_5.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_5+"");
				}
				if(index==5){
					im_ph_6.setImageBitmap(bitmap);
					im_ph_6.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_6+"");
				}
				if(index==6){
					im_ph_7.setImageBitmap(bitmap);
					im_ph_7.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_7+"");
				}
				if(index==7){
					im_ph_8.setImageBitmap(bitmap);
					im_ph_8.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_8+"");
				}
				if(index==8){
					im_ph_9.setImageBitmap(bitmap);
					im_ph_9.setVisibility(View.VISIBLE);
					p.setId(R.id.im_ph_9+"");
				}
				index++;
			}
		}
	}

	/**
	 * 录影
	 */
	private void takeVideo(){
		// TODO Auto-generated method stub
		if(phtModel.size()==maxPhtos){
			DialogUtil.showToast(UploadVideoActivity.this, "每次只允许上次1个视频");
			return ;
		}
		ComUtil.takeVideo(this);
	}

	/**
	 * 选择视频
	 */
	private void getVideoFromlib(){
		if(phtModel.size()==maxPhtos){
			DialogUtil.showToast(UploadVideoActivity.this, "每次只允许上次1个视频");
			return ;
		}
		ComUtil.getVideoFromLib(this);
	}

	@Override
	protected void onStop() {
		for(Bitmap bmap:bitMapList){
			if(bmap!=null){
				bmap.recycle();
				bmap=null;
			}
		}
		super.onStop();
	}

	private FileInputStream getFileIns(String fileName,FileInputStream ins) throws Exception{
		if(!FuncUtil.isEmpty(fileName)){
			File imageFile = new File(fileName);
			ins = new FileInputStream(imageFile);
			log.info("文件大小:"+ins.available()/1024+"KB");
			return ins;
		}
		return null;
	}
}


text:
package searchinsertposition

func searchInsert(nums []int, target int) int {
	low, high := 0, len(nums)-1
	// find the target using binary search.
	for low <= high {
		mid := (low + high) / 2
		if nums[mid] == target {
			return mid
		} else if nums[mid] > target {
			high = mid - 1
		} else {
			low = mid + 1
		}
	}
	return low
}


text:
package testdata

const PathStringRequestBuildCode = `// BuildMethodPathStringRequest instantiates a HTTP request object with method
// and path set to call the "ServicePathString" service "MethodPathString"
// endpoint
func (c *Client) BuildMethodPathStringRequest(ctx context.Context, v interface{}) (*http.Request, error) {
	var (
		p string
	)
	{
		p, ok := v.(*servicepathstring.MethodPathStringPayload)
		if !ok {
			return nil, goahttp.ErrInvalidType("ServicePathString", "MethodPathString", "*servicepathstring.MethodPathStringPayload", v)
		}
		if p.P != nil {
			p = *p.P
		}
	}
	u := &url.URL{Scheme: c.scheme, Host: c.host, Path: MethodPathStringServicePathStringPath(p)}
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, goahttp.ErrInvalidURL("ServicePathString", "MethodPathString", u.String(), err)
	}
	if ctx != nil {
		req = req.WithContext(ctx)
	}

	return req, nil
}
`

const PathStringRequiredRequestBuildCode = `// BuildMethodPathStringValidateRequest instantiates a HTTP request object with
// method and path set to call the "ServicePathStringValidate" service
// "MethodPathStringValidate" endpoint
func (c *Client) BuildMethodPathStringValidateRequest(ctx context.Context, v interface{}) (*http.Request, error) {
	var (
		p string
	)
	{
		p, ok := v.(*servicepathstringvalidate.MethodPathStringValidatePayload)
		if !ok {
			return nil, goahttp.ErrInvalidType("ServicePathStringValidate", "MethodPathStringValidate", "*servicepathstringvalidate.MethodPathStringValidatePayload", v)
		}
		p = p.P
	}
	u := &url.URL{Scheme: c.scheme, Host: c.host, Path: MethodPathStringValidateServicePathStringValidatePath(p)}
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, goahttp.ErrInvalidURL("ServicePathStringValidate", "MethodPathStringValidate", u.String(), err)
	}
	if ctx != nil {
		req = req.WithContext(ctx)
	}

	return req, nil
}
`

const PathStringDefaultRequestBuildCode = `// BuildMethodPathStringDefaultRequest instantiates a HTTP request object with
// method and path set to call the "ServicePathStringDefault" service
// "MethodPathStringDefault" endpoint
func (c *Client) BuildMethodPathStringDefaultRequest(ctx context.Context, v interface{}) (*http.Request, error) {
	var (
		p string
	)
	{
		p, ok := v.(*servicepathstringdefault.MethodPathStringDefaultPayload)
		if !ok {
			return nil, goahttp.ErrInvalidType("ServicePathStringDefault", "MethodPathStringDefault", "*servicepathstringdefault.MethodPathStringDefaultPayload", v)
		}
		p = p.P
	}
	u := &url.URL{Scheme: c.scheme, Host: c.host, Path: MethodPathStringDefaultServicePathStringDefaultPath(p)}
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, goahttp.ErrInvalidURL("ServicePathStringDefault", "MethodPathStringDefault", u.String(), err)
	}
	if ctx != nil {
		req = req.WithContext(ctx)
	}

	return req, nil
}
`

const PathObjectRequestBuildCode = `// BuildMethodPathObjectRequest instantiates a HTTP request object with method
// and path set to call the "ServicePathObject" service "MethodPathObject"
// endpoint
func (c *Client) BuildMethodPathObjectRequest(ctx context.Context, v interface{}) (*http.Request, error) {
	var (
		id string
	)
	{
		p, ok := v.(*servicepathobject.MethodPathObjectPayload)
		if !ok {
			return nil, goahttp.ErrInvalidType("ServicePathObject", "MethodPathObject", "*servicepathobject.MethodPathObjectPayload", v)
		}
		if p.ID != nil {
			id = *p.ID
		}
	}
	u := &url.URL{Scheme: c.scheme, Host: c.host, Path: MethodPathObjectServicePathObjectPath(id)}
	req, err := http.NewRequest("PUT", u.String(), nil)
	if err != nil {
		return nil, goahttp.ErrInvalidURL("ServicePathObject", "MethodPathObject", u.String(), err)
	}
	if ctx != nil {
		req = req.WithContext(ctx)
	}

	return req, nil
}
`


text:
(function() {
    "use strict";

var q = require('q'),
    db = require('./db'),
    collection = "messages";

var singleton = { };

singleton.find = function(id) {
    return db.find(collection, id);
};

singleton.save = function(message) {
    return db.save(collection, message);
};

singleton.findAllForConversation = function(conversationId) {
    return db.findMany(collection, { conversationId: conversationId });
};

singleton.clearTests = function() {
    return db.clear(collection, { isTest: true})
};

module.exports = singleton;

}());


text:
module FirstOrderA where

import FirstOrderB
import FirstOrderC


text:
using std::vector;
using std::unordered_map;

#include <dnn/util/ptr.h>
#include <dnn/util/log/log.h>

namespace dnn {
class TimeSeries;

namespace shapelets {

class Dataset {
public:
    Dataset(vector<Ptr<TimeSeries>> &_ts);
    ~Dataset();
    size_t N() const {
        return ts_set.size();
    }
    size_t C() const {
        return class_counts.size();
    }

    const unordered_map<size_t, size_t>& class_hist() const {
        return class_counts;
    }

    bool operator == (const Dataset &d) const;
    bool operator != (const Dataset &d) const;

    const double& entropy() const {
        return _entropy;
    }
    Ptr<TimeSeries> operator() (const size_t &i) const {
        return ts_set[i];
    }
    vector<Ptr<TimeSeries>>::iterator begin() {
        return ts_set.begin();
    }
    vector<Ptr<TimeSeries>>::iterator end() {
        return ts_set.end();
    }
    vector<Ptr<TimeSeries>>::const_iterator begin() const {
        return ts_set.cbegin();
    }
    vector<Ptr<TimeSeries>>::const_iterator end() const {
        return ts_set.cend();
    }
    const size_t& getTsLabelId(const size_t &i);

    static double calcEntropy(const unordered_map<size_t, size_t> &_class_counts, const size_t &N);

    template <typename K>
    static void pushIntoHist(unordered_map<K, size_t> &hist, const K& v) {
        auto p = hist.find(v);
        if(p == hist.end()) {
            hist.insert(std::make_pair(v, 1));
        } else {
            ++(p->second);
        }
    }

private:
    double _entropy;
    unordered_map<size_t, size_t> class_counts;
    unordered_map<string, size_t> class_ids;
    vector<Ptr<TimeSeries>> ts_set;
};

}
}


text:
/*
 * crypto_kem/try.c version 20180227
 * D. J. Bernstein
 * Public domain.
 * Auto-generated by trygen.py; do not edit.
 */

#include "crypto_kem.h"
#include "try.h"

const char *primitiveimplementation = crypto_kem_implementation;

#define TUNE_BYTES 1536
#ifdef SMALL
#define MAXTEST_BYTES 128
#else
#define MAXTEST_BYTES 4096
#endif
#ifdef SMALL
#define LOOPS 8
#else
#define LOOPS 64
#endif

static unsigned char *p;
static unsigned char *s;
static unsigned char *k;
static unsigned char *c;
static unsigned char *t;
static unsigned char *p2;
static unsigned char *s2;
static unsigned char *k2;
static unsigned char *c2;
static unsigned char *t2;
#define plen crypto_kem_PUBLICKEYBYTES
#define slen crypto_kem_SECRETKEYBYTES
#define klen crypto_kem_BYTES
#define clen crypto_kem_CIPHERTEXTBYTES
#define tlen crypto_kem_BYTES

void preallocate(void)
{
#ifdef RAND_R_PRNG_NOT_SEEDED
  RAND_status();
#endif
}

void allocate(void)
{
  unsigned long long alloclen = 0;
  if (alloclen < TUNE_BYTES) alloclen = TUNE_BYTES;
  if (alloclen < MAXTEST_BYTES) alloclen = MAXTEST_BYTES;
  if (alloclen < crypto_kem_PUBLICKEYBYTES) alloclen = crypto_kem_PUBLICKEYBYTES;
  if (alloclen < crypto_kem_SECRETKEYBYTES) alloclen = crypto_kem_SECRETKEYBYTES;
  if (alloclen < crypto_kem_BYTES) alloclen = crypto_kem_BYTES;
  if (alloclen < crypto_kem_CIPHERTEXTBYTES) alloclen = crypto_kem_CIPHERTEXTBYTES;
  if (alloclen < crypto_kem_BYTES) alloclen = crypto_kem_BYTES;
  p = alignedcalloc(alloclen);
  s = alignedcalloc(alloclen);
  k = alignedcalloc(alloclen);
  c = alignedcalloc(alloclen);
  t = alignedcalloc(alloclen);
  p2 = alignedcalloc(alloclen);
  s2 = alignedcalloc(alloclen);
  k2 = alignedcalloc(alloclen);
  c2 = alignedcalloc(alloclen);
  t2 = alignedcalloc(alloclen);
}

void predoit(void)
{
  crypto_kem_keypair(p,s);
}

void doit(void)
{
  crypto_kem_enc(c,k,p);
  crypto_kem_dec(t,c,s);
}

void test(void)
{
  unsigned long long loop;

  for (loop = 0;loop < LOOPS;++loop) {

    output_prepare(p2,p,plen);
    output_prepare(s2,s,slen);
    if (crypto_kem_keypair(p,s) != 0) fail("crypto_kem_keypair returns nonzero");
    checksum(p,plen);
    checksum(s,slen);
    output_compare(p2,p,plen,"crypto_kem_keypair");
    output_compare(s2,s,slen,"crypto_kem_keypair");

    output_prepare(c2,c,clen);
    output_prepare(k2,k,klen);
    memcpy(p2,p,plen);
    double_canary(p2,p,plen);
    if (crypto_kem_enc(c,k,p) != 0) fail("crypto_kem_enc returns nonzero");
    checksum(c,clen);
    checksum(k,klen);
    output_compare(c2,c,clen,"crypto_kem_enc");
    output_compare(k2,k,klen,"crypto_kem_enc");
    input_compare(p2,p,plen,"crypto_kem_enc");

    output_prepare(t2,t,tlen);
    memcpy(c2,c,clen);
    double_canary(c2,c,clen);
    memcpy(s2,s,slen);
    double_canary(s2,s,slen);
    if (crypto_kem_dec(t,c,s) != 0) fail("crypto_kem_dec returns nonzero");
    if (memcmp(t,k,klen) != 0) fail("crypto_kem_dec does not match k");
    checksum(t,tlen);
    output_compare(t2,t,tlen,"crypto_kem_dec");
    input_compare(c2,c,clen,"crypto_kem_dec");
    input_compare(s2,s,slen,"crypto_kem_dec");

    double_canary(t2,t,tlen);
    double_canary(c2,c,clen);
    double_canary(s2,s,slen);
    if (crypto_kem_dec(t2,c2,s2) != 0) fail("crypto_kem_dec returns nonzero");
    if (memcmp(t2,t,tlen) != 0) fail("crypto_kem_dec is nondeterministic");

    double_canary(t2,t,tlen);
    double_canary(c2,c,clen);
    double_canary(s2,s,slen);
    if (crypto_kem_dec(c2,c2,s) != 0) fail("crypto_kem_dec with c=t overlap returns nonzero");
    if (memcmp(c2,t,tlen) != 0) fail("crypto_kem_dec does not handle c=t overlap");
    memcpy(c2,c,clen);
    if (crypto_kem_dec(s2,c,s2) != 0) fail("crypto_kem_dec with s=t overlap returns nonzero");
    if (memcmp(s2,t,tlen) != 0) fail("crypto_kem_dec does not handle s=t overlap");
    memcpy(s2,s,slen);
  }
}


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

using System;
using Microsoft.Azure.Management.Search;
using Microsoft.Azure.Test;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Microsoft.Azure.Search.Tests.Utilities
{
    public abstract class SearchTestBase<TTestFixture> : TestBase where TTestFixture : new()
    {
        protected TTestFixture Data { get; private set; }

        protected static SearchManagementClient GetSearchManagementClient()
        {
            return GetServiceClient<SearchManagementClient>(new CSMTestEnvironmentFactory());
        }

        protected void Run(Action testBody)
        {
            const int TestNameStackFrameDepth = 4;
            using (var undoContext = UndoContext.Current)
            {
                undoContext.Start(TestNameStackFrameDepth);

                Data = new TTestFixture();

                Func<JsonSerializerSettings> oldDefault = JsonConvert.DefaultSettings;

                // This should ensure that the SDK doesn't depend on global JSON.NET settings.
                JsonConvert.DefaultSettings = () =>
                    new JsonSerializerSettings() { Converters = new[] { new InvalidJsonConverter() } };

                try
                {
                    testBody();
                }
                finally
                {
                    JsonConvert.DefaultSettings = oldDefault;
                }
            }
        }

        private class InvalidJsonConverter : JsonConverter
        {
            private const string ErrorMessage = "Some part of the SDK is using JsonConvert.DefaultSettings!";

            public override bool CanConvert(Type objectType)
            {
                throw new InvalidOperationException(ErrorMessage);
            }

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                throw new InvalidOperationException(ErrorMessage);
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                throw new InvalidOperationException(ErrorMessage);
            }
        }
    }
}


text:
import os

from ansiblelint.rules import AnsibleLintRule
from ansiblelint.utils import get_first_cmd_arg

try:
    from ansible.module_utils.parsing.convert_bool import boolean
except ImportError:
    try:
        from ansible.utils.boolean import boolean
    except ImportError:
        try:
            from ansible.utils import boolean
        except ImportError:
            from ansible import constants
            boolean = constants.mk_boolean

class CommandsInsteadOfArgumentsRule(AnsibleLintRule):
    id = '302'
    shortdesc = 'Using command rather than an argument to e.g. file'
    description = (
        'Executing a command when there are arguments to modules '
        'is generally a bad idea'
    )
    severity = 'VERY_HIGH'
    tags = ['command-shell', 'resources', 'ANSIBLE0007']
    version_added = 'historic'

    _commands = ['command', 'shell', 'raw']
    _arguments = {'chown': 'owner', 'chmod': 'mode', 'chgrp': 'group',
                  'ln': 'state=link', 'mkdir': 'state=directory',
                  'rmdir': 'state=absent', 'rm': 'state=absent'}

    def matchtask(self, file, task):
        if task["action"]["__ansible_module__"] in self._commands:
            first_cmd_arg = get_first_cmd_arg(task)
            if not first_cmd_arg:
                return

            executable = os.path.basename(first_cmd_arg)
            if executable in self._arguments and \
                    boolean(task['action'].get('warn', True)):
                message = "{0} used in place of argument {1} to file module"
                return message.format(executable, self._arguments[executable])


text:
/// <reference path="fourslash.ts" />

//// module m { export enum Color { Red } }
//// var /**/t = m.Color.Red + 1;

goTo.marker();
verify.quickInfoExists();
verify.quickInfoIs('(var) t: number');


text:
var expect = require('chai').expect;
var sinon = require('sinon');
var request = require('supertest');
var Books = require('../../../app/data/json/books').Books;

describe('API: books', function () {
    var server;
    var booksData;

    before(function () {
        booksData = [
            {
                id: '1',
                name: 'Sample Book 1',
                author: 'George Washington',
                publishedDate: new Date(),
                cover: 'blank.jpg'
            },
            {
                id: '2',
                name: 'Sample Book 2',
                author: 'Abraham Lincoln',
                publishedDate: new Date(),
                cover: 'blank.jpg'
            },
            {
                id: '3',
                name: 'Sample Book 3',
                author: 'Johnny Appleseed',
                publishedDate: new Date(),
                cover: 'blank.jpg'
            }
        ];
    });

    beforeEach(function (done) {
        delete require.cache[require.resolve('../../../server')];
        server = require('../../../server');
        done();
    });

    afterEach(function (done) {
        server.close(done);
    });

    describe('GET /books', function () {
        var getAllStub;

        before(function () {
            getAllStub = sinon.stub(Books.prototype, 'getAll', () => {
                return new Promise((resolve, reject) => {
                    resolve(booksData);
                })
            });
        });

        after(function () {
            getAllStub.restore();
        });

        it('should return a list of all books', function (done) {
            request(server).get('/api/books')
                .expect(200, (err, resp) => {
                    expect(resp.body).to.not.be.empty;

                    var bkArr = resp.body;
                    expect(bkArr).to.have.lengthOf(3);
                    done();
                });
        });
    });

    describe('GET /books/:id', function () {
        var getStub;

        before(function () {
            getStub = sinon.stub(Books.prototype, 'get', (id) => {
                return new Promise((resolve, reject) => {
                    var book = booksData.filter((b) => { return b.id == id; })[0];
                    resolve(book);
                })
            });
        });

        after(function () {
            getStub.restore();
        });

        it('should return a single book', function (done) {
            request(server).get('/api/books/1')
                .expect(200, (err, resp) => {
                    expect(resp.body).to.not.be.empty;

                    var bk = resp.body;
                    expect(bk).to.not.be.instanceOf(Array);
                    expect(bk.author).to.equal('George Washington');
                    done();
                });
        });

        it('should return null', function (done) {
            request(server).get('/api/books/5')
                .expect(200, (err, resp) => {
                    expect(resp.body).to.be.empty;
                    done();
                });
        });
    });

});


text:
package models.daos.slick

import models.User
import play.api.db.slick._
import play.api.db.slick.Config.driver.simple._
import models.daos.slick.DBTableDefinitions._
import com.mohiva.play.silhouette.api.LoginInfo
import scala.concurrent.Future
import java.util.UUID
import play.Logger
import models.daos.UserDAO

/**
 * Give access to the user object using Slick
 */
class UserDAOSlick extends UserDAO {

  import play.api.Play.current

  /**
   * Finds a user by its login info.
   *
   * @param loginInfo The login info of the user to find.
   * @return The found user or None if no user for the given login info could be found.
   */
  def find(loginInfo: LoginInfo) = {
    DB withSession { implicit session =>
      Future.successful {
        slickLoginInfos.filter(
          x => x.providerID === loginInfo.providerID && x.providerKey === loginInfo.providerKey
        ).firstOption match {
          case Some(info) =>
            slickUserLoginInfos.filter(_.loginInfoId === info.id).firstOption match {
              case Some(userLoginInfo) =>
                slickUsers.filter(_.id === userLoginInfo.userID).firstOption match {
                  case Some(user) =>
                    Some(User(UUID.fromString(user.userID), loginInfo, user.firstName, user.lastName, user.fullName, user.email, user.avatarURL))
                  case None => None
                }
              case None => None
            }
          case None => None
        }
      }
    }
  }

  /**
   * Finds a user by its user ID.
   *
   * @param userID The ID of the user to find.
   * @return The found user or None if no user for the given ID could be found.
   */
  def find(userID: UUID) = {
    DB withSession { implicit session =>
      Future.successful {
        slickUsers.filter(
          _.id === userID.toString
        ).firstOption match {
          case Some(user) =>
            slickUserLoginInfos.filter(_.userID === user.userID).firstOption match {
              case Some(info) =>
                slickLoginInfos.filter(_.id === info.loginInfoId).firstOption match {
                  case Some(loginInfo) =>
                    Some(User(UUID.fromString(user.userID), LoginInfo(loginInfo.providerID, loginInfo.providerKey), user.firstName, user.lastName, user.fullName, user.email, user.avatarURL))
                  case None => None
                }
              case None => None
            }
          case None => None
        }
      }
    }
  }

  /**
   * Saves a user.
   *
   * @param user The user to save.
   * @return The saved user.
   */
  def save(user: User) = {
    DB withSession { implicit session =>
      Future.successful {
        val dbUser = DBUser(user.userID.toString, user.firstName, user.lastName, user.fullName, user.email, user.avatarURL)
        slickUsers.filter(_.id === dbUser.userID).firstOption match {
          case Some(userFound) => slickUsers.filter(_.id === dbUser.userID).update(dbUser)
          case None => slickUsers.insert(dbUser)
        }
        var dbLoginInfo = DBLoginInfo(None, user.loginInfo.providerID, user.loginInfo.providerKey)
        // Insert if it does not exist yet
        slickLoginInfos.filter(info => info.providerID === dbLoginInfo.providerID && info.providerKey === dbLoginInfo.providerKey).firstOption match {
          case None => slickLoginInfos.insert(dbLoginInfo)
          case Some(info) => Logger.debug("Nothing to insert since info already exists: " + info)
        }
        dbLoginInfo = slickLoginInfos.filter(info => info.providerID === dbLoginInfo.providerID && info.providerKey === dbLoginInfo.providerKey).first
        // Now make sure they are connected
        slickUserLoginInfos.filter(info => info.userID === dbUser.userID && info.loginInfoId === dbLoginInfo.id).firstOption match {
          case Some(info) =>
            // They are connected already, we could as well omit this case ;)
          case None =>
            slickUserLoginInfos += DBUserLoginInfo(dbUser.userID, dbLoginInfo.id.get)
        }
        user // We do not change the user => return it
      }
    }
  }
}


text:
"""This module contains the mappers to compute the Hessian/gradients in a distributed fashion

Copyright (c) 2017 The ADMML Authors.

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

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

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

"""

from math import exp

import numpy as np

def mapHv(algoParam, vector, w, mu):
    """Map function to compute the appropriate Hessian/Gradient based on
    ``algoParam['LOSS']`` and ``algoParam['PROBLEM']``.

    Parameters
    ----------
    algoParam : dict
        This contains the algorithm parameters for ML/ADMM algorithm.
        The default can be set as: ``algoParam = setDefaultAlgoParams()``.
        Here ``algoParam['LOSS']`` and ``algoParam['PROBLEM']``  should be
        specified
    vector : numpy.ndarray
        Data sample (a row of data matrix) which contributes to Hessian/Gradient
    w : numpy.ndarray
        weight vector at the current internal newtonian iteration.
    mu : float
        The :math:`\\mu` value only for Huber/Pseudo-Huber Loss. Else it's None.

    Returns
    -------
    H_i : numpy.ndarray
        The i-th sample's contribution to the Hessian
    v_i : numpy.ndarray
        The i-th sample's contribution to the gradient

    """
    if algoParam['LOSS'] == 'logistic' and algoParam['PROBLEM'] == 'binary':
        return _mapHv_logistic_binary(vector, w)

    elif algoParam['LOSS'] == 'hinge' and algoParam['PROBLEM'] == 'binary':  # SHALL BE PROVIDED IN NEXT VERSION
        raise ValueError('ERROR: Currently Unsupported.')

    elif algoParam['LOSS'] == 'sq_hinge' and algoParam['PROBLEM'] == 'binary':
        return _mapHv_sq_hinge_binary(vector, w, algoParam['D'])

    elif algoParam['LOSS'] == 'smooth_hinge' and algoParam['PROBLEM'] == 'binary':
        return _mapHv_smooth_hinge_binary(vector, w, algoParam['D'])

    elif algoParam['LOSS'] == 'pseudo_huber' and algoParam['PROBLEM'] == 'regression':
        return _mapHv_pseudo_huber_regression(vector, w, mu)

    elif algoParam['LOSS'] == 'huber' and algoParam['PROBLEM'] == 'regression':
        return _mapHv_huber_regression(vector, w, mu)

    else:
        raise ValueError('ERROR: Unsupported Loss Function.')

def _mapHv_logistic_binary(vector, w):
    """COMPUTE DISTRIBUTED HESSIAN/GRADIENT

    Parameters
    ----------
    vector : numpy.ndarray
        Data sample (a row of data matrix) which contributes to Hessian/Gradient
    w : numpy.ndarray
        weight vector at the current internal newtonian iteration.

    Returns
    -------
    H_i : numpy.ndarray
        The i-th sample's contribution to the Hessian
    v_i : numpy.ndarray
        The i-th sample's contribution to the gradient

    """
    y = vector[0]
    x = vector[1:]
    eta = y * (np.dot(x, w))
    p = 1 / (1 + exp(-eta))
    v_i = -y * (1 - p) * x
    H_i = (1 - p) * p * (np.outer(x, x))
    return H_i, v_i

def _mapHv_sq_hinge_binary(vector, w, D):
    """COMPUTE DISTRIBUTED HESSIAN/GRADIENT

    Parameters
    ----------
    vector : numpy.ndarray
        Data sample (a row of data matrix) which contributes to Hessian/Gradient
    w : numpy.ndarray
        weight vector at the current internal newtonian iteration.
    D : int
        the dimension of the sample

    Returns
    -------
    H_i : numpy.ndarray
        The i-th sample's contribution to the Hessian
    v_i : numpy.ndarray
        The i-th sample's contribution to the gradient

    """
    y = vector[0]
    x = vector[1:]
    z = y * (np.dot(w, x))

    if z >= 1.0:
        H_i = np.zeros([D, D])
        v_i = np.zeros(D)

    else:
        H_i = np.outer(x, x)
        v_i = (-y * (1.0 - z)) * x

    return H_i, v_i

def _mapHv_smooth_hinge_binary(vector, w, D):
    """COMPUTE DISTRIBUTED HESSIAN/GRADIENT (DO NOT USE!!)

    Parameters
    ----------
    vector : numpy.ndarray
        Data sample (a row of data matrix) which contributes to Hessian/Gradient
    w : numpy.ndarray
        weight vector at the current internal newtonian iteration.
    D : int
        the dimension of the sample

    Returns
    -------
    H_i : numpy.ndarray
        The i-th sample's contribution to the Hessian
    v_i : numpy.ndarray
        The i-th sample's contribution to the gradient

    """
    y = vector[0]
    x = vector[1:]
    z = y * (np.dot(w, x))

    if z >= 1.0:
        H_i = np.zeros([D, D])
        v_i = np.zeros(D)

    elif 0.0 < z < 1.0:
        H_i = np.outer(x, x)
        v_i = (-y * (1.0 - z)) * x

    else:
        H_i = np.zeros([D, D])
        v_i = -y * x

    return H_i, v_i

def _mapHv_pseudo_huber_regression(vector, w, mu):
    """COMPUTE DISTRIBUTED HESSIAN/GRADIENT

    Parameters
    ----------
    vector : numpy.ndarray
        Data sample (a row of data matrix) which contributes to Hessian/Gradient
    w : numpy.ndarray
        weight vector at the current internal newtonian iteration.
    mu : float
        The :math:`\\mu` value only for Pseudo-Huber Loss.

    Returns
    -------
    H_i : numpy.ndarray
        The i-th sample's contribution to the Hessian
    v_i : numpy.ndarray
        The i-th sample's contribution to the gradient

    """
    y = vector[0]
    x = vector[1:]
    s = (y - np.dot(x, w))
    v_i = -(s / np.sqrt(mu ** 2 + s ** 2)) * x
    H_i = ((mu ** 2) / np.sqrt(mu ** 2 + s ** 2) ** 3) * np.outer(x, x)
    return H_i, v_i

def _mapHv_huber_regression(vector, w, mu):
    """COMPUTE DISTRIBUTED HESSIAN/GRADIENT

    Parameters
    ----------
    vector : numpy.ndarray
        Data sample (a row of data matrix) which contributes to Hessian/Gradient
    w : numpy.ndarray
        weight vector at the current internal newtonian iteration.
    mu : float
        The :math:`\\mu` value only for Huber Loss.

    Returns
    -------
    H_i : numpy.ndarray
        The i-th sample's contribution to the Hessian
    v_i : numpy.ndarray
        The i-th sample's contribution to the gradient

    """

    def trimg(s, mu):
        return max(-mu, min(mu, s))

    def trimH(s, mu):
        return float(abs(s) <= mu)

    y = vector[0]
    x = vector[1:]
    s = (y - np.dot(x, w))
    v_i = -trimg(s, mu) * x
    H_i = trimH(s, mu) * np.outer(x, x)
    return H_i, v_i


text:
namespace Dsp.Web.Characters
{
    public class ResetLocation
    {
        public ResetLocationType Type { get; set; }
    }

    public enum ResetLocationType
    {
        Home = 0,
        RuludeGardens = 1
    }
}


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

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

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

"""

import os
from resource_management import *
from resource_management.core.resources.system import Execute
from resource_management.libraries.functions import Direction
from resource_management.libraries.functions.format import format
from resource_management.libraries.script.script import Script

class KafkaUpgrade(Script):

  def copy_kerberos_param(self,env):
    import params
    kafka_run_path = "/usr/iop/4.1.0.0/kafka/bin/kafka-run-class.sh"
    if params.upgrade_direction is not None and params.upgrade_direction == Direction.UPGRADE:
      Execute(("sed", "-i", "s/\$CLASSPATH \$KAFKA_OPTS/\$CLASSPATH \$KAFKA_OPTS \$KAFKA_KERBEROS_PARAMS/", kafka_run_path), logoutput=True)

if __name__ == "__main__":
  KafkaUpgrade().execute()


text:
package org.apache.felix.ipojo.runtime.core;

import org.apache.felix.ipojo.ComponentFactory;
import org.apache.felix.ipojo.PrimitiveInstanceDescription;
import org.apache.felix.ipojo.architecture.Architecture;
import org.apache.felix.ipojo.runtime.core.services.FooService;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;

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

import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

public class TestManagedServiceFactoryTestForImmediate extends Common {

    private ComponentFactory factory;

    @Before
    public void setUp() {
        factory = (ComponentFactory) ipojoHelper.getFactory("CA-ImmConfigurableProvider");
    }

    @Test
    public void testCreationAndReconfiguration() {
        Configuration configuration = null;
        try {
            configuration = admin.createFactoryConfiguration("CA-ImmConfigurableProvider", "?");
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Dictionary props = configuration.getProperties();
        if (props == null) {
            props = new Properties();
        }
        props.put("message", "message");

        try {
            configuration.update(props);
        } catch (IOException e) {
            fail(e.getMessage());
        }

        String pid = configuration.getPid();

        // Wait for the processing of the first configuration.
        grace();

        //  The instance should be created, wait for the architecture service
        osgiHelper.waitForService(Architecture.class.getName(), "(architecture.instance=" + pid + ")", 1000);
        Architecture architecture = (Architecture) osgiHelper.getServiceObject(Architecture.class.getName(), "(architecture.instance=" + pid + ")");

        assertEquals("Check object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        FooService fs = (FooService) osgiHelper.getServiceObject(FooService.class.getName(), "(instance.name=" + pid + ")");
        Properties p = fs.fooProps();
        String mes = p.getProperty("message");
        int count = (Integer) p.get("count");
        //architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Assert Message", "message", mes);
        assertEquals("Assert count", 1, count);
        assertEquals("Check 1 object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        props.put("message", "message2");
        try {
            configuration.update(props);
            // Update the configuration ...
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        fs = (FooService) osgiHelper.getServiceObject(FooService.class.getName(), "(instance.name=" + pid + ")");
        p = fs.fooProps();
        mes = p.getProperty("message");
        count = (Integer) p.get("count");
        //architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Assert Message", "message2", mes);
        assertEquals("Assert count", 2, count);
        assertEquals("Check 1 object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        try {
            configuration.delete();
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        ServiceReference ref = osgiHelper.getServiceReference(FooService.class.getName(), "(instance.name=" + pid + ")");
        assertNull("Check unavailability", ref);
    }

    @Test
    public void testCreationAndReconfiguration2() {
        //The reconfiguration happens before the service invocation
        Configuration configuration = null;
        try {
            configuration = admin.createFactoryConfiguration("CA-ImmConfigurableProvider", "?");
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Dictionary props = configuration.getProperties();
        if (props == null) {
            props = new Properties();
        }
        props.put("message", "message");

        try {
            configuration.update(props);
        } catch (IOException e) {
            fail(e.getMessage());
        }

        String pid = configuration.getPid();
        System.out.println("PID : " + pid);

        // Wait for the processing of the first configuration.
        grace();

        //  The instance should be created, wait for the architecture service
        osgiHelper.waitForService(Architecture.class.getName(), "(architecture.instance=" + pid + ")", 1000);
        Architecture architecture = (Architecture) osgiHelper.getServiceObject(Architecture.class.getName(), "(architecture.instance=" + pid + ")");

        assertEquals("Check object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        props.put("message", "message2");
        try {
            configuration.update(props);
            // Update the configuration ...
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        //architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Check object -2", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        //Invoke
        FooService fs = (FooService) osgiHelper.getServiceObject(FooService.class.getName(), "(instance.name=" + pid + ")");
        Properties p = fs.fooProps();
        String mes = p.getProperty("message");
        int count = ((Integer) p.get("count")).intValue();
        // architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Assert Message", "message2", mes);
        assertEquals("Assert count", 2, count);
        assertEquals("Check 1 object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        try {
            configuration.delete();
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        ServiceReference ref = osgiHelper.getServiceReference(FooService.class.getName(), "(instance.name=" + pid + ")");
        assertNull("Check unavailability", ref);
    }

    @Test
    public void testDelayedCreationAndReconfiguration() {
        factory.stop();
        Configuration configuration = null;
        try {
            configuration = admin.createFactoryConfiguration("CA-ImmConfigurableProvider", "?");
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Dictionary props = configuration.getProperties();
        if (props == null) {
            props = new Properties();
        }
        props.put("message", "message");

        try {
            configuration.update(props);
        } catch (IOException e) {
            fail(e.getMessage());
        }

        String pid = configuration.getPid();

        // Wait for the processing of the first configuration.
        grace();

        assertNull("check no instance", osgiHelper.getServiceObject(Architecture.class.getName(), "(architecture.instance=" + pid + ")"));

        factory.start();

        // Wait for the processing of the first configuration.
        grace();

        //  The instance should be created, wait for the architecture service
        osgiHelper.waitForService(Architecture.class.getName(), "(architecture.instance=" + pid + ")", 1000);
        Architecture architecture = (Architecture) osgiHelper.getServiceObject(Architecture.class.getName(), "(architecture.instance=" + pid + ")");

        assertEquals("Check object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        FooService fs = (FooService) osgiHelper.getServiceObject(FooService.class.getName(), "(instance.name=" + pid + ")");
        Properties p = fs.fooProps();
        String mes = p.getProperty("message");
        int count = (Integer) p.get("count");
        //architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Assert Message", "message", mes);
        assertEquals("Assert count", 1, count);
        assertEquals("Check 1 object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        props.put("message", "message2");
        try {
            configuration.update(props);
            // Update the configuration ...
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        fs = (FooService) osgiHelper.getServiceObject(FooService.class.getName(), "(instance.name=" + pid + ")");
        p = fs.fooProps();
        mes = p.getProperty("message");
        count = (Integer) p.get("count");
        // architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Assert Message", "message2", mes);
        //assertEquals("Assert count", 2, count);
        // This test was removed as the result can be 3.
        assertEquals("Check 1 object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        try {
            configuration.delete();
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        ServiceReference ref = osgiHelper.getServiceReference(FooService.class.getName(), "(instance.name=" + pid + ")");
        assertNull("Check unavailability", ref);
    }

    @Test
    public void testDelayedCreationAndReconfiguration2() {
        factory.stop();
        //The reconfiguration happens before the service invocation
        Configuration configuration = null;
        try {
            configuration = admin.createFactoryConfiguration("CA-ImmConfigurableProvider", "?");
        } catch (IOException e) {
            fail(e.getMessage());
        }
        Dictionary props = configuration.getProperties();
        if (props == null) {
            props = new Properties();
        }
        props.put("message", "message");

        try {
            configuration.update(props);
        } catch (IOException e) {
            fail(e.getMessage());
        }

        String pid = configuration.getPid();

        // Wait for the processing of the first configuration.
        grace();

        assertNull("check no instance", osgiHelper.getServiceObject(Architecture.class.getName(), "(architecture.instance=" + pid + ")"));

        factory.start();

        // Wait for the processing of the first configuration.
        grace();

        //  The instance should be created, wait for the architecture service
        osgiHelper.waitForService(Architecture.class.getName(), "(architecture.instance=" + pid + ")", 1000);
        Architecture architecture = (Architecture) osgiHelper.getServiceObject(Architecture.class.getName(), "(architecture.instance=" + pid + ")");

        assertEquals("Check object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        props.put("message", "message2");
        try {
            configuration.update(props);
            // Update the configuration ...
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        //architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Check object -1", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        //Invoke
        FooService fs = (FooService) osgiHelper.getServiceObject(FooService.class.getName(), "(instance.name=" + pid + ")");
        Properties p = fs.fooProps();
        String mes = p.getProperty("message");
        int count = (Integer) p.get("count");
        // architecture = (Architecture) osgiHelper.getServiceObject( Architecture.class.getName(), "(architecture.instance="+pid+")");

        assertEquals("Assert Message", "message2", mes);
        assertEquals("Assert count", 2, count);
        assertEquals("Check 1 object", 1, ((PrimitiveInstanceDescription) architecture.getInstanceDescription()).getCreatedObjects().length);

        try {
            configuration.delete();
            grace();
        } catch (Exception e) {
            fail(e.getMessage());
        }

        ServiceReference ref = osgiHelper.getServiceReference(FooService.class.getName(), "(instance.name=" + pid + ")");
        assertNull("Check unavailability", ref);
    }

}


text:
package com.mysema.codegen;

import static com.mysema.codegen.Symbols.ASSIGN;
import static com.mysema.codegen.Symbols.COMMA;
import static com.mysema.codegen.Symbols.DOT;
import static com.mysema.codegen.Symbols.QUOTE;
import static com.mysema.codegen.Symbols.SEMICOLON;
import static com.mysema.codegen.Symbols.SPACE;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

import com.google.common.base.Function;
import com.mysema.codegen.model.Parameter;
import com.mysema.codegen.model.Type;

/**
 * JavaWriter is the default implementation of the CodeWriter interface
 *
 * @author tiwe
 *
 */
public final class JavaWriter extends AbstractCodeWriter<JavaWriter> {

    private static final String EXTENDS = " extends ";

    private static final String IMPLEMENTS = " implements ";

    private static final String IMPORT = "import ";

    private static final String IMPORT_STATIC = "import static ";

    private static final String PACKAGE = "package ";

    private static final String PRIVATE = "private ";

    private static final String PRIVATE_FINAL = "private final ";

    private static final String PRIVATE_STATIC_FINAL = "private static final ";

    private static final String PROTECTED = "protected ";

    private static final String PROTECTED_FINAL = "protected final ";

    private static final String PUBLIC = "public ";

    private static final String PUBLIC_CLASS = "public class ";

    private static final String PUBLIC_FINAL = "public final ";

    private static final String PUBLIC_INTERFACE = "public interface ";

    private static final String PUBLIC_STATIC = "public static ";

    private static final String PUBLIC_STATIC_FINAL = "public static final ";

    private final Set<String> classes = new HashSet<String>();

    private final Set<String> packages = new HashSet<String>();

    private final Stack<Type> types = new Stack<Type>();

    public JavaWriter(Appendable appendable) {
        super(appendable, 4);
        this.packages.add("java.lang");
    }

    @Override
    public JavaWriter annotation(Annotation annotation) throws IOException {
        beginLine().append("@").appendType(annotation.annotationType());
        Method[] methods = annotation.annotationType().getDeclaredMethods();
        if (methods.length == 1 && methods[0].getName().equals("value")) {
            try {
                Object value = methods[0].invoke(annotation);
                append("(");
                annotationConstant(value);
                append(")");
            } catch (IllegalArgumentException e) {
                throw new CodegenException(e);
            } catch (IllegalAccessException e) {
                throw new CodegenException(e);
            } catch (InvocationTargetException e) {
                throw new CodegenException(e);
            }
        } else {
            boolean first = true;
            for (Method method : methods) {
                try {
                    Object value = method.invoke(annotation);
                    if (value == null || value.equals(method.getDefaultValue())) {
                        continue;
                    } else if (value.getClass().isArray()
                            && Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue())) {
                        continue;
                    } else if (!first) {
                        append(COMMA);
                    } else {
                        append("(");
                    }
                    append(method.getName()).append("=");
                    annotationConstant(value);
                } catch (IllegalArgumentException e) {
                    throw new CodegenException(e);
                } catch (IllegalAccessException e) {
                    throw new CodegenException(e);
                } catch (InvocationTargetException e) {
                    throw new CodegenException(e);
                }
                first = false;
            }
            if (!first) {
                append(")");
            }
        }
        return nl();
    }

    @Override
    public JavaWriter annotation(Class<? extends Annotation> annotation) throws IOException {
        return beginLine().append("@").appendType(annotation).nl();
    }

    @SuppressWarnings("unchecked")
    private void annotationConstant(Object value) throws IOException {
        if (value.getClass().isArray()) {
            append("{");
            boolean first = true;
            for (Object o : (Object[]) value) {
                if (!first) {
                    append(", ");
                }
                annotationConstant(o);
                first = false;
            }
            append("}");
        } else if (value instanceof Class) {
            appendType((Class) value).append(".class");
        } else if (value instanceof Number || value instanceof Boolean) {
            append(value.toString());
        } else if (value instanceof Enum) {
            Enum<?> enumValue = (Enum<?>) value;
            if (classes.contains(enumValue.getClass().getName())
                    || packages.contains(enumValue.getClass().getPackage().getName())) {
                append(enumValue.name());
            } else {
                append(enumValue.getDeclaringClass().getName()).append(DOT).append(enumValue.name());
            }
        } else if (value instanceof String) {
            String escaped = StringUtils.escapeJava(value.toString());
            append(QUOTE).append(escaped.replace("\\/", "/")).append(QUOTE);
        } else {
            throw new IllegalArgumentException("Unsupported annotation value : " + value);
        }
    }

    private JavaWriter appendType(Class<?> type) throws IOException {
        if (classes.contains(type.getName()) || packages.contains(type.getPackage().getName())) {
            append(type.getSimpleName());
        } else {
            append(type.getName());
        }
        return this;
    }

    @Override
    public JavaWriter beginClass(Type type) throws IOException {
        return beginClass(type, null);
    }

    @Override
    public JavaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException {
        packages.add(type.getPackageName());
        beginLine(PUBLIC_CLASS, type.getGenericName(false, packages, classes));
        if (superClass != null) {
            append(EXTENDS).append(superClass.getGenericName(false, packages, classes));
        }
        if (interfaces.length > 0) {
            append(IMPLEMENTS);
            for (int i = 0; i < interfaces.length; i++) {
                if (i > 0) {
                    append(COMMA);
                }
                append(interfaces[i].getGenericName(false, packages, classes));
            }
        }
        append(" {").nl().nl();
        goIn();
        types.push(type);
        return this;
    }

    @Override
    public <T> JavaWriter beginConstructor(Collection<T> parameters,
            Function<T, Parameter> transformer) throws IOException {
        types.push(types.peek());
        beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters, transformer)
                .append(" {").nl();
        return goIn();
    }

    @Override
    public JavaWriter beginConstructor(Parameter... parameters) throws IOException {
        types.push(types.peek());
        beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters).append(" {").nl();
        return goIn();
    }

    @Override
    public JavaWriter beginInterface(Type type, Type... interfaces) throws IOException {
        packages.add(type.getPackageName());
        beginLine(PUBLIC_INTERFACE, type.getGenericName(false, packages, classes));
        if (interfaces.length > 0) {
            append(EXTENDS);
            for (int i = 0; i < interfaces.length; i++) {
                if (i > 0) {
                    append(COMMA);
                }
                append(interfaces[i].getGenericName(false, packages, classes));
            }
        }
        append(" {").nl().nl();
        goIn();
        types.push(type);
        return this;
    }

    private JavaWriter beginMethod(String modifiers, Type returnType, String methodName,
            Parameter... args) throws IOException {
        types.push(types.peek());
        beginLine(
                modifiers, returnType.getGenericName(true, packages, classes), SPACE, methodName)
                .params(args).append(" {").nl();
        return goIn();
    }

    @Override
    public <T> JavaWriter beginPublicMethod(Type returnType, String methodName,
            Collection<T> parameters, Function<T, Parameter> transformer) throws IOException {
        return beginMethod(PUBLIC, returnType, methodName, transform(parameters, transformer));
    }

    @Override
    public JavaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args)
            throws IOException {
        return beginMethod(PUBLIC, returnType, methodName, args);
    }

    @Override
    public <T> JavaWriter beginStaticMethod(Type returnType, String methodName,
            Collection<T> parameters, Function<T, Parameter> transformer) throws IOException {
        return beginMethod(PUBLIC_STATIC, returnType, methodName,
                transform(parameters, transformer));
    }

    @Override
    public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args)
            throws IOException {
        return beginMethod(PUBLIC_STATIC, returnType, methodName, args);
    }

    @Override
    public JavaWriter end() throws IOException {
        types.pop();
        goOut();
        return line("}").nl();
    }

    @Override
    public JavaWriter field(Type type, String name) throws IOException {
        return line(type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON).nl();
    }

    private JavaWriter field(String modifier, Type type, String name) throws IOException {
        return line(
                modifier, type.getGenericName(true, packages, classes), SPACE, name, SEMICOLON)
                .nl();
    }

    private JavaWriter field(String modifier, Type type, String name, String value)
            throws IOException {
        return line(
                modifier, type.getGenericName(true, packages, classes), SPACE, name,
                ASSIGN , value, SEMICOLON).nl();
    }

    @Override
    public String getClassConstant(String className) {
        return className + ".class";
    }

    @Override
    public String getGenericName(boolean asArgType, Type type) {
        return type.getGenericName(asArgType, packages, classes);
    }

    @Override
    public String getRawName(Type type) {
        return type.getRawName(packages, classes);
    }

    @Override
    public JavaWriter imports(Class<?>... imports) throws IOException {
        for (Class<?> cl : imports) {
            classes.add(cl.getName());
            line(IMPORT, cl.getName(), SEMICOLON);
        }
        nl();
        return this;
    }

    @Override
    public JavaWriter imports(Package... imports) throws IOException {
        for (Package p : imports) {
            packages.add(p.getName());
            line(IMPORT, p.getName(), ".*;");
        }
        nl();
        return this;
    }

    @Override
    public JavaWriter importClasses(String... imports) throws IOException {
        for (String cl : imports) {
            classes.add(cl);
            line(IMPORT, cl, SEMICOLON);
        }
        nl();
        return this;
    }

    @Override
    public JavaWriter importPackages(String... imports) throws IOException {
        for (String p : imports) {
            packages.add(p);
            line(IMPORT, p, ".*;");
        }
        nl();
        return this;
    }

    @Override
    public JavaWriter javadoc(String... lines) throws IOException {
        line("/**");
        for (String line : lines) {
            line(" * ", line);
        }
        return line(" */");
    }

    @Override
    public JavaWriter packageDecl(String packageName) throws IOException {
        packages.add(packageName);
        return line(PACKAGE, packageName, SEMICOLON).nl();
    }

    private <T> JavaWriter params(Collection<T> parameters, Function<T, Parameter> transformer)
            throws IOException {
        append("(");
        boolean first = true;
        for (T param : parameters) {
            if (!first) {
                append(COMMA);
            }
            param(transformer.apply(param));
            first = false;
        }
        append(")");
        return this;
    }

    private JavaWriter params(Parameter... params) throws IOException {
        append("(");
        for (int i = 0; i < params.length; i++) {
            if (i > 0) {
                append(COMMA);
            }
            param(params[i]);
        }
        append(")");
        return this;
    }

    private JavaWriter param(Parameter parameter) throws IOException {
        append(parameter.getType().getGenericName(true, packages, classes));
        append(" ");
        append(parameter.getName());
        return this;
    }

    @Override
    public JavaWriter privateField(Type type, String name) throws IOException {
        return field(PRIVATE, type, name);
    }

    @Override
    public JavaWriter privateFinal(Type type, String name) throws IOException {
        return field(PRIVATE_FINAL, type, name);
    }

    @Override
    public JavaWriter privateFinal(Type type, String name, String value) throws IOException {
        return field(PRIVATE_FINAL, type, name, value);
    }

    @Override
    public JavaWriter privateStaticFinal(Type type, String name, String value) throws IOException {
        return field(PRIVATE_STATIC_FINAL, type, name, value);
    }

    @Override
    public JavaWriter protectedField(Type type, String name) throws IOException {
        return field(PROTECTED, type, name);
    }

    @Override
    public JavaWriter protectedFinal(Type type, String name) throws IOException {
        return field(PROTECTED_FINAL, type, name);
    }

    @Override
    public JavaWriter protectedFinal(Type type, String name, String value) throws IOException {
        return field(PROTECTED_FINAL, type, name, value);
    }

    @Override
    public JavaWriter publicField(Type type, String name) throws IOException {
        return field(PUBLIC, type, name);
    }

    @Override
    public JavaWriter publicField(Type type, String name, String value) throws IOException {
        return field(PUBLIC, type, name, value);
    }

    @Override
    public JavaWriter publicFinal(Type type, String name) throws IOException {
        return field(PUBLIC_FINAL, type, name);
    }

    @Override
    public JavaWriter publicFinal(Type type, String name, String value) throws IOException {
        return field(PUBLIC_FINAL, type, name, value);
    }

    @Override
    public JavaWriter publicStaticFinal(Type type, String name, String value) throws IOException {
        return field(PUBLIC_STATIC_FINAL, type, name, value);
    }

    @Override
    public JavaWriter staticimports(Class<?>... imports) throws IOException {
        for (Class<?> cl : imports) {
            line(IMPORT_STATIC, cl.getName(), ".*;");
        }
        return this;
    }

    @Override
    public JavaWriter suppressWarnings(String type) throws IOException {
        return line("@SuppressWarnings(\"", type, "\")");
    }

    @Override
    public CodeWriter suppressWarnings(String... types) throws IOException {
        return annotation(new MultiSuppressWarnings(types));
    }

    private <T> Parameter[] transform(Collection<T> parameters,
            Function<T, Parameter> transformer) {
        Parameter[] rv = new Parameter[parameters.size()];
        int i = 0;
        for (T value : parameters) {
            rv[i++] = transformer.apply(value);
        }
        return rv;
    }

}


text:
""" Get yearly mapped class areas

Usage: get_yearly_area.py [options] <input> <output>

"""

from docopt import docopt
import gdal
from osgeo import ogr, osr
import os
import numpy as np
import pandas as pd

def main(raster, years, output):

    """ Main function for getting class area of a raster by year """

    # Open raster
    rast_op = gdal.Open(raster)
    array = rast_op.ReadAsArray()

    # convert to just years

    multiplier = .09 #hectares

    # Deg
    out_deg = pd.DataFrame()
    for year in years:
        out_deg[str(year)] = [0]

    out_name = output + '_strata_deg.csv'
    for year in years:
        count_year = len(array[0:3,:,:][array[0:3,:,:] == year]) * multiplier
        out_deg[str(year)] += count_year

    out_deg.to_csv(out_name)

    # Deg
    out_def = pd.DataFrame()
    for year in years:
        out_def[str(year)] = [0]

    out_name = output + '_strata_def.csv'
    for year in years:
        count_year = len(array[3:6,:,:][array[3:6,:,:] == year]) * multiplier
        out_def[str(year)] += count_year

    out_def.to_csv(out_name)

if __name__ == '__main__':
    args = docopt(__doc__, version='0.6.2')

raster=args['<input>']
output=args['<output>']
years=range(1990,2014)

main(raster, years, output)


text:
/* $Id: TestBase.java 988245 2010-08-23 18:39:35Z kwright $ */

/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.crawler.tests;

import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.crawler.system.ManifoldCF;

import java.io.*;
import java.util.*;
import org.junit.*;

/** This is a testing base class that is responsible for setting up/tearing down the agents framework. */
public class BasePostgresql extends org.apache.manifoldcf.agents.tests.BasePostgresql
{

  @Before
  public void setUp()
    throws Exception
  {
    initializeSystem();
    try
    {
      localReset();
    }
    catch (Exception e)
    {
      System.out.println("Warning: Preclean failed: "+e.getMessage());
    }
    try
    {
      localSetUp();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw e;
    }
  }

  protected void localSetUp()
    throws Exception
  {
    super.localSetUp();

    IThreadContext tc = ThreadContextFactory.make();
    IAgentManager mgr = AgentManagerFactory.make(tc);
    mgr.registerAgent("org.apache.manifoldcf.crawler.system.CrawlerAgent");
  }

  @After
  public void cleanUp()
    throws Exception
  {
    try
    {
      localCleanUp();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw e;
    }
    cleanupSystem();
  }

  protected void localCleanUp()
    throws Exception
  {
    IThreadContext tc = ThreadContextFactory.make();

    Exception currentException = null;
    try
    {
      IAgentManager mgr = AgentManagerFactory.make(tc);
      mgr.unregisterAgent("org.apache.manifoldcf.crawler.system.CrawlerAgent");
    }
    catch (Exception e)
    {
      if (currentException != null)
        currentException = e;
    }
    try
    {
      super.localCleanUp();
    }
    catch (Exception e)
    {
      if (currentException != null)
        currentException = e;
    }
    if (currentException != null)
      throw currentException;
  }

  protected void initializeSystem()
    throws Exception
  {
    super.initializeSystem();
    IThreadContext tc = ThreadContextFactory.make();
    org.apache.manifoldcf.authorities.system.ManifoldCF.localInitialize(tc);
    org.apache.manifoldcf.crawler.system.ManifoldCF.localInitialize(tc);
  }

  protected void cleanupSystem()
    throws Exception
  {
    IThreadContext tc = ThreadContextFactory.make();
    org.apache.manifoldcf.authorities.system.ManifoldCF.localCleanup(tc);
    org.apache.manifoldcf.crawler.system.ManifoldCF.localCleanup(tc);
    super.cleanupSystem();
  }

}


text:
angular.module('app').component('datepicker',{
    templateUrl: 'app/template/componentTypes/datepicker/datepicker.html',
    controller: function(modalCodeFactory){
        var ctrl = this;
        ctrl.dateValue = new Date();
        ctrl.onChange = function(){
            console.log('Date Selected: ' + ctrl.dateValue);
        }
        ctrl.showCode = function(){
            modalCodeFactory.showCode('datepicker');
        };
    }
})


text:
function setupWindow(tabUrls, callback) {
  createWindow(tabUrls, {}, function(winId, tabIds) {
    // Remove all other windows.
    var removedCount = 0;
    chrome.windows.getAll({}, function(windows) {
      for (var i in windows) {
        if (windows[i].id != winId) {
          chrome.windows.remove(windows[i].id, function() {
            removedCount++;
            if (removedCount == windows.length - 1)
              callback(winId, tabIds);
          });
        }
      }
      if (windows.length == 1)
        callback(winId, tabIds);
    });
  });
}

// Creates one window with tabs set to the urls in the array |tabUrls|.
// At least one url must be specified.
// The |callback| should look like function(windowId, tabIds) {...}.
function createWindow(tabUrls, winOptions, callback) {
  winOptions["url"] = tabUrls;
  chrome.windows.create(winOptions, function(win) {
    var newTabIds = [];
    assertTrue(win.id > 0);
    assertEq(tabUrls.length, win.tabs.length);

    for (var i = 0; i < win.tabs.length; i++)
      newTabIds.push(win.tabs[i].id);

    callback(win.id, newTabIds);
  });
}

// Waits until all tabs (yes, in every window) have status "complete".
// This is useful to prevent test overlap when testing tab events.
// |callback| should look like function() {...}.  Note that |callback| expects
// zero arguments.
function waitForAllTabs(callback) {
  // Wait for all tabs to load.
  function waitForTabs(){
    chrome.windows.getAll({"populate": true}, function(windows) {
      var ready = true;
      for (var i in windows){
        for (var j in windows[i].tabs) {
          if (windows[i].tabs[j].status != "complete") {
            ready = false;
            break;
          }
        }
        if (!ready)
          break;
      }
      if (ready)
        callback();
      else
        window.setTimeout(waitForTabs, 30);
    });
  }
  waitForTabs();
}


text:
from sms.tests.config import *
from django.test import TestCase
import sms.utils as util

class CleanNumberTestCase(TestCase):

    def testCleanNumberLeavesNumbers(self):
        self.assertEqual('12345', util.clean_number('12345'))

    def testCleanNumberRemovesNonnumbers(self):
        self.assertEqual('12345', util.clean_number('a+1aszz23!!!45'))

class SmsParserTestCase(TestCase):

    def setUp(self):
        pass

    def testSmsGetsRoute(self):
        output = util.parse_message("yesoch knows all")
        self.assertEqual(output['route'], 'yesoch')

    def testSmsLowerCasesStuff(self):
        output = util.parse_message("YESOCH knows all")
        self.assertEqual(output['route'], 'yesoch')

    def testSmsGetsArguments(self):
        output = util.parse_message("YESOCH knows all")
        self.assertEqual(output['args'], ['knows', 'all'])

from sms.models import Template
from contact.models import Contact
class GetTemplaterTestCase(TestCase):

    def setUp(self):
        self.contact = Contact.objects.create(first_name="a")

    def testDefaultsToDjangoTemplates(self):
        t2 = Template.objects.create(name="panic", text="test")
        template = util.get_templater("panic")(self.contact)
        self.assertNotIn("test", template)

    def testThenTriesModelTemplates(self):
        t2 = Template.objects.create(name="test", text="a test")
        template = util.get_templater("test")(self.contact)
        self.assertIn("a test", template)