text:
package com.frameworkexample.android.network;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import com.frameworkexample.android.network.utils.NetWorkUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;

public class HttpClientUtil
{
    final  static String TAG = "HttpClientUtil";
    final static int TIMEOUT = 35 * 1000;
    final static int USER_BINDING_TIMEOUT = 121 * 1000;

    private static HttpClient httpClient = null;

    // 解决javax.net.ssl.SSLPeerUnverifiedException no peer certificate
    public static HttpClient getNewHttpClient(Context context)
    {
        try
        {
        	if(httpClient ==null)
        	{
        		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                 trustStore.load(null, null);
                 SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
                 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                 HttpParams params = new BasicHttpParams();
                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
                 HttpProtocolParams.setContentCharset(params, "UTF-8");
                 HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
                 HttpConnectionParams.setSoTimeout(params, TIMEOUT);
                 SchemeRegistry registry = new SchemeRegistry();
                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                 registry.register(new Scheme("https", sf, 443));
                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
                 httpClient = new DefaultHttpClient(ccm,params);
        	}
        	  httpClient = setNetWork(context, httpClient);
        } catch (Exception e)
        {
            Log.e(TAG, "HttpClientUtil   getNewHttpClient Exception " + e.getMessage());
        }
        return httpClient;
    }

    public static HttpRes proxyHttpGet(Context context, String url,String json,String sign) throws Exception
    {
        HttpGet httpGet = null;
        HttpRes res = null;
        try
        {
        	json=URLEncoder.encode(json,"UTF-8");
        	url+="?" + "p" + "=" + json
        	+ "&" + "sign" + "=" + sign;
        	//Log.w(TAG,"httpGet -->"+url);
        	httpGet = new HttpGet(url);
            httpClient = getNewHttpClient(context);
            HttpResponse response = httpClient.execute(httpGet);
            if (response != null)
            {
                StatusLine line = response.getStatusLine();
                if (line != null)
                {
                    int resCode = line.getStatusCode();
                    if (resCode == HttpStatus.SC_OK)
                    {
                    	res = new HttpRes();
                    	res.setEntity(response.getEntity());
                    	res.setHttpGet(httpGet);
                    }
                }
            }
        } catch (Exception e)
        {
            if(httpGet != null)
            {
                httpGet.abort();
            }
            Log.e(TAG, "get() Exception -- " + e.toString());
            e.printStackTrace();
            res=null;
        } finally
        {

            if( httpClient!=null)
            {
                httpClient.getConnectionManager().closeExpiredConnections();
            }
        }
        return res;
    }
    public static HttpRes proxyHttpDelete(Context context,String url ,String json,String sign)
    {
    	HttpDelete httpDelete=null;
    	HttpResponse response=null;
    	HttpRes res=null;
    	try{
        	json=URLEncoder.encode(json,"UTF-8");
        	url+="?" + "p" + "=" + json
        	+ "&" + "sign" + "=" + sign;
    		httpDelete=new HttpDelete(url);
    		httpClient=getNewHttpClient(context);
            response = httpClient.execute(httpDelete);
            if (response != null)
            {
                StatusLine line = response.getStatusLine();
                if (line != null)
                {
                    int resCode = line.getStatusCode();
                    Log.w(TAG," httpClientUtil resCode"+resCode);
                    if (resCode == HttpStatus.SC_OK)
                    {
                    	res = new HttpRes();
                    	res.setEntity(response.getEntity());
                    }
                }
            }
    	}catch(Exception e)
    	{
            e.printStackTrace();
            res =null;
            if(httpDelete != null)
            {
            	httpDelete.abort();
            }
    	}finally
        {
            if( httpClient!=null)
            {
                httpClient.getConnectionManager().closeExpiredConnections();
            }
        }
		return res;
    }

    public static HttpRes proxyHttpPost(Context context, String url, String json,String sign)
    {
    	String logHeader = "url : "+ url +" json : "+ json ;
        HttpPost httpPost = null;
        HttpResponse response = null;
        httpClient = getNewHttpClient(context);
        HttpRes res = null;
        try
        {
            httpPost = new HttpPost(url);
            httpPost.addHeader("Accept", "application/json, */*; q=0.01");
            httpPost.addHeader("Accept-Encoding", "gzip,deflate");
            Object obj = httpClient.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);
            boolean proxyFlag = (obj != null);
            if(proxyFlag)
            {
            	//2013-03-05 解决使用代理服务器时发生服务器未响应错误
                //原因: Expect:100-Continue 默认设置,导致客户端与服务器交互时先验证
                //参见: http://www.cnblogs.com/cxd4321/archive/2012/01/30/2331621.html
                //HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
               /*httpPost.setHeader("Connection", "Close");*/
            }else
            {
            	//httpPost.setHeader("Connection", "Keep-Alive");
            }
            //httpPost.setHeader("Connection", "close");
            /***/
            /***/
            httpPost = addParams(httpPost, json,sign);
            response = httpClient.execute(httpPost);
            if (response != null)
            {
                StatusLine line = response.getStatusLine();
                Log.i(TAG, logHeader+ " proxyHttpPost StatusLine------->" + line);
                if (line != null)
                {
                    int resCode = line.getStatusCode();
                    Log.i(TAG, logHeader + "proxyHttpPost resCode -- >" + resCode );
                    if (resCode >199&&resCode<300)
                    {
                    	res = new HttpRes();
                    	res.setEntity(response.getEntity());
                    	res.setHttpPost(httpPost);
                    }
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            Log.e(TAG, logHeader + " proxyHttpPost connect : " + url + " Exception  " + e.getMessage());
            res =null;
            if(httpPost != null)
            {
            	httpPost.abort();
            }
        }finally
        {
        	if(res == null && httpPost != null)
        	{
        		httpPost.abort();
        	}
        	if( httpClient!=null)
        	{
        		httpClient.getConnectionManager().closeExpiredConnections();
        	}
        }
        return res;
    }

    /**
     * 使用中...
     */
    public static HttpRes proxyHttpPostFile(Context context, String url, String json,String sign,
    		Bundle reqExtras)
    {
        if (null == reqExtras || reqExtras.isEmpty()) {
        	return null;
        }

    	String logHeader = "proxyHttpPostFile url : "+ url +" json : "+ json ;
        HttpPost httpPost = null;
        HttpResponse response = null;
        httpClient = getNewHttpClient(context);
        HttpRes res = null;
        try
        {
            httpPost = new HttpPost(url);
            final Charset cs = Charset.forName("UTF-8");
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart(new FormBodyPart("p", new StringBody(json, cs)));
            entity.addPart(new FormBodyPart("sign", new StringBody(sign)));
            //entity.addPart("p", new StringBody(json, Charset.forName("UTF-8")));
            //entity.addPart("sign", new StringBody(sign));
            for (String key : reqExtras.keySet()) {
            	ByteArrayOutputStream out = null;
            	FileInputStream in = null;
            	try {
            		File file = new File(reqExtras.getString(key));
                	if (file.exists()) {
                		out = new ByteArrayOutputStream();
                		in = new FileInputStream(file);
                		int len = -1;
                		byte buf[] = new byte[512];
                		while (-1 != (len = in.read(buf))) {
                			out.write(buf, 0 , len);
                		}
                		out.flush();
                		ByteArrayBody picBody = new ByteArrayBody(out.toByteArray(),
                				MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg"), file.getName());
            	        entity.addPart(new FormBodyPart(key, picBody));
                	}
				} catch (Exception e) {
					Log.e(TAG, "proxyHttpPostFile Exception: " + e.getMessage());
				} finally {
					if (null != in) {
						try {
							in.close();
						} catch (Exception e_in) { }
					}
					if (null != out) {
						try {
							out.close();
						} catch (Exception e_out) { }
					}
				}
			}
            httpPost.setEntity(entity);

            httpPost.addHeader("Accept", "application/json, image/*, */*; q=0.01");
            httpPost.addHeader("Accept-Encoding", "gzip,deflate");
            Object obj = httpClient.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);
            boolean proxyFlag = (obj != null);
            if(proxyFlag)
            {
            	//2013-03-05 解决使用代理服务器时发生服务器未响应错误
                //原因: Expect:100-Continue 默认设置,导致客户端与服务器交互时先验证
                //参见: http://www.cnblogs.com/cxd4321/archive/2012/01/30/2331621.html
                //HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
               /*httpPost.setHeader("Connection", "Close");*/
            }else
            {
            	//httpPost.setHeader("Connection", "Keep-Alive");
            }
            //httpPost.setHeader("Connection", "close");
            /***/
            /***/
            //httpPost = addParams(httpPost, json,sign);
            response = httpClient.execute(httpPost);
            if (response != null)
            {
                StatusLine line = response.getStatusLine();
                Log.i(TAG, logHeader+ " proxyHttpPostFile StatusLine------->" + line);
                if (line != null)
                {
                    int resCode = line.getStatusCode();
                    Log.i(TAG, logHeader + "proxyHttpPostFile resCode -- >" + resCode );
                    if (resCode >= HttpStatus.SC_OK && resCode < 300)
                    {
                    	res = new HttpRes();
                    	res.setEntity(response.getEntity());
                    	res.setHttpPost(httpPost);
                    }
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            Log.e(TAG, logHeader + " proxyHttpPostFile connect : " + url + " Exception  " + e.getMessage());
            res =null;
            if(httpPost != null)
            {
            	httpPost.abort();
            }
        }finally
        {
        	if(res == null && httpPost != null)
        	{
        		httpPost.abort();
        	}
        	if( httpClient!=null)
        	{
        		httpClient.getConnectionManager().closeExpiredConnections();
        	}
        }
        return res;
    }

    /**
     * 使用中...
     */
    public static HttpRes proxyHttpPutFile(Context context, String url, String json,String sign,
    		Bundle reqExtras)
    {
        if (null == reqExtras || reqExtras.isEmpty()) {
        	return null;
        }

    	String logHeader = "proxyHttpPostFile url : "+ url +" json : "+ json ;
        HttpPut httpPut = null;
        HttpResponse response = null;
        httpClient = getNewHttpClient(context);
        HttpRes res = null;
        try
        {
        	httpPut = new HttpPut(url);
            final Charset cs = Charset.forName("UTF-8");
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart(new FormBodyPart("p", new StringBody(json, cs)));
            entity.addPart(new FormBodyPart("sign", new StringBody(sign)));
            //entity.addPart("p", new StringBody(json, Charset.forName("UTF-8")));
            //entity.addPart("sign", new StringBody(sign));
            for (String key : reqExtras.keySet()) {
            	ByteArrayOutputStream out = null;
            	FileInputStream in = null;
            	try {
            		File file = new File(reqExtras.getString(key));
                	if (file.exists()) {
                		out = new ByteArrayOutputStream();
                		in = new FileInputStream(file);
                		int len = -1;
                		byte buf[] = new byte[512];
                		while (-1 != (len = in.read(buf))) {
                			out.write(buf, 0 , len);
                		}
                		out.flush();
                		ByteArrayBody picBody = new ByteArrayBody(out.toByteArray(),
                				MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg"), file.getName());
            	        entity.addPart(new FormBodyPart(key, picBody));
                	}
				} catch (Exception e) {
					Log.e(TAG, "proxyHttpPostFile Exception: " + e.getMessage());
				} finally {
					if (null != in) {
						try {
							in.close();
						} catch (Exception e_in) { }
					}
					if (null != out) {
						try {
							out.close();
						} catch (Exception e_out) { }
					}
				}
			}
            httpPut.setEntity(entity);

            httpPut.addHeader("Accept", "application/json, image/*, */*; q=0.01");
            httpPut.addHeader("Accept-Encoding", "gzip,deflate");
            Object obj = httpClient.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);
            boolean proxyFlag = (obj != null);
            if(proxyFlag)
            {
            	//2013-03-05 解决使用代理服务器时发生服务器未响应错误
                //原因: Expect:100-Continue 默认设置,导致客户端与服务器交互时先验证
                //参见: http://www.cnblogs.com/cxd4321/archive/2012/01/30/2331621.html
                //HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), false);
               /*httpPost.setHeader("Connection", "Close");*/
            }else
            {
            	//httpPost.setHeader("Connection", "Keep-Alive");
            }
            //httpPost.setHeader("Connection", "close");
            /***/
            /***/
            //httpPost = addParams(httpPost, json,sign);
            response = httpClient.execute(httpPut);
            if (response != null)
            {
                StatusLine line = response.getStatusLine();
                Log.i(TAG, logHeader+ " proxyHttpPostFile StatusLine------->" + line);
                if (line != null)
                {
                    int resCode = line.getStatusCode();
                    Log.i(TAG, logHeader + "proxyHttpPostFile resCode -- >" + resCode );
                    if (resCode >= HttpStatus.SC_OK && resCode < 300)
                    {
                    	res = new HttpRes();
                    	res.setEntity(response.getEntity());
                    	res.setHttpPut(httpPut);
                    }
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            Log.e(TAG, logHeader + " proxyHttpPostFile connect : " + url + " Exception  " + e.getMessage());
            res =null;
            if(httpPut != null)
            {
            	httpPut.abort();
            }
        }finally
        {
        	if(res == null && httpPut != null)
        	{
        		httpPut.abort();
        	}
        	if( httpClient!=null)
        	{
        		httpClient.getConnectionManager().closeExpiredConnections();
        	}
        }
        return res;
    }

    private static HttpClient setNetWork(Context context, HttpClient client)
    {
        String netType = NetworkManager.getNetWorkType((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE));
        if (!NetWorkUtils.WIFI_STATE.equalsIgnoreCase(netType))
        {
            if (!NetWorkUtils.isOPhone())
            {
                Map<String, Object> map = NetworkManager.getProxy();
                if (map != null && !map.isEmpty())
                {
                	if(android.os.Build.VERSION.SDK_INT <=7)
                	{
                		 String proxyHost = (String) map.get(NetworkManager.PROXY_HOST);
                         int proxyPort = (Integer) map.get(NetworkManager.PROXY_PORT);
                         HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                         client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                	}
                }
                else
                {
                    // cmnet set proxy
                    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
                }
            }

        }
        else if (NetWorkUtils.WIFI_STATE.equalsIgnoreCase(netType))
        {
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
        }
        return client;

    }

    private static HttpPost addParams(HttpPost httpPost, String json,String sign)
    {
        UrlEncodedFormEntity urlEncode = null;
        List<NameValuePair> params = null;
        try
        {
        	Log.i(TAG, "addParams httpPost------>" + httpPost);
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("p", json));
            params.add(new BasicNameValuePair("sign",sign));
            Log.i(TAG, "params size " + params.size());
            urlEncode = new UrlEncodedFormEntity(params, "utf-8");
            httpPost.setEntity(urlEncode);

        } catch (Exception e)
        {
            Log.e(TAG, "addParams Exception " + e.getMessage());
        } finally
        {
              if (params != null)
              {
            	  params.clear();
            	  params = null;
               }
              if (urlEncode != null) {
              urlEncode = null;
              }

        }
        return httpPost;
    }

    @SuppressWarnings("unused")
	private static HttpDelete addParams(HttpDelete httpDelete, String json,String sign)
    {
        UrlEncodedFormEntity urlEncode = null;
        List<NameValuePair> params = null;
        try
        {
        	Log.i(TAG, "addParams httpDelete------>" + httpDelete);
            params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("p", json));
            params.add(new BasicNameValuePair("sign",sign));
            Log.i(TAG, "params size " + params.size());
            urlEncode = new UrlEncodedFormEntity(params, "utf-8");
           // HttpParams params=new
           //httpDelete.setParams(params);
          //httpDelete.setEntity(urlEncode);

        } catch (Exception e)
        {
            Log.e(TAG, "httpDelete  addParams Exception " + e.getMessage());
        } finally
        {
              if (params != null)
              {
            	  params.clear();
            	  params = null;
               }
              if (urlEncode != null) {
              urlEncode = null;
              }

        }
        return httpDelete;
    }

//    public static boolean downloadZipFile(Context context, String url, String zipPath, String json) throws Exception
//    {
//    	HttpPost httpPost = null;
//    	HttpResponse httpResponse = null;
//    	HttpEntity entity = null;
//    	InputStream in = null;
//    	FileOutputStream out = null;
//    	File file = null;
//    	try {
//    			file = new File(zipPath);
//    		    httpClient = getNewHttpClient(context);
//    		    httpPost = new HttpPost(url);
//    		    httpResponse = httpClient.execute(addParams(httpPost, json));
//    	        int responseCode = httpResponse.getStatusLine().getStatusCode();
//    	        if (responseCode == HttpStatus.SC_OK)
//    	        {
//    	            // 获取响应实体
//    	        	entity = httpResponse.getEntity();
//
//		            long contentlength = entity.getContentLength();
//		            Log.d(TAG, "Zip contentlength:" + contentlength);
//		            if (!(contentlength > 0))
//		            {
//			             Log.d(TAG, "Zip File is not exist");
//			             return false;
//		            }
//
//    	            in = entity.getContent();
//
//    	            out = new FileOutputStream(file);
//
//    	            byte[] bytes = new byte[4096];
//    	            int c;
//
//    	            Log.v(TAG, "server msb file:begin: \n");
//    	            while ((c = in.read(bytes)) != -1)
//    	            {
//    	                String content = new String(bytes, 0, c);
//    	                Log.v(TAG, content);
//    	                out.write(bytes, 0, c);
//    	            }
//    	            out.flush();
//    	            if(contentlength == file.length()){
//    	            	return true;
//    	            }else{
//    	            	if(null != file && file.exists()){
//    	            		file.delete();
//    	            	}
//
//    	            }
//    	        }
//
//    	        return true;
//
//		} catch (Exception e) {
//			Log.e(TAG, " downloadZipFile exception : " + e.getMessage());
//			e.printStackTrace();
//			if(null != file && file.exists()){
//         		file.delete();
//         	}
//			if (httpPost != null) {
//				httpPost.abort();
//			}
//
//		} finally{
//			 if(null != out){
//				 out.close();
//			 }
//			 if(null != in){
//				 in.close();
//			 }
//			 if (entity != null) {
//					entity.consumeContent();
//			 }
//			 if (httpPost != null) {
//					httpPost.abort();
//				}
//			 if (httpClient != null)
//             {
//                 httpClient.getConnectionManager().closeExpiredConnections();
//             }
//		}
//        return false;
//    }

    @SuppressWarnings("finally")
    public static File downloadImageFile(Context context, String url, File file)
    {
        HttpEntity entity = null;
        InputStream conIn = null;
        DataInputStream in = null;
        OutputStream out = null;
        httpClient = getNewHttpClient(context);
        HttpGet httpGet = null;
        long totalSize = 0;
        try
        {
        	long startTime = System.currentTimeMillis();
        	Log.i("downImage", url+ " downImage start-----"+startTime);
        	httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            Log.i("downImage", url + " downloadImageFile httpResponse --->" + httpResponse);
            if (httpResponse != null)
            {
            	long endTime = System.currentTimeMillis();
            	Log.i("downImage", url + " downImage end-----"+endTime +" use time :"+((endTime-startTime)/1000));
                StatusLine line = httpResponse.getStatusLine();
                Log.i("downImage", url+ " downloadImageFile line --->" + line);
                if (line != null)
                {
                    int responseCode = line.getStatusCode();
                    if (responseCode == HttpStatus.SC_OK)
                    {
                        entity = httpResponse.getEntity();
                        if (entity != null)
                        {
                            conIn = entity.getContent();
                            totalSize = entity.getContentLength();
                            in = new DataInputStream(conIn);
                            out = new FileOutputStream(file);
                            byte[] buffer = new byte[1024];
                            int byteread = 0;
                            while ((byteread = in.read(buffer)) != -1)
                            {
                                out.write(buffer, 0, byteread);
                            }
                        }
                        else
                        {
                            if (file != null)
                            {
                                file.delete();
                                file = null;
                            }
                        }

                    }
                    else
                    {
                    	Log.i("downImage", url + " downLoadImage Server return error, response code = " + responseCode);
                        if (file != null)
                        {
                            file.delete();
                            file = null;
                        }
                    }
                }
                else
                {
                    if (file != null)
                    {
                        file.delete();
                        file = null;
                    }
                    Log.i("downImage", url + " Server return error, StatusLine  " + line);
                }

            }
            else
            {
                if (file != null)
                {
                    file.delete();
                    file = null;
                }
                Log.i("downImage", url + " Server return error, httpResponse  " + httpResponse);
            }

        } catch (Exception e)
        {
        	Log.e("downImage", url + " downImage Exception -----"+e.getMessage());
            if (file != null)
            {
                file.delete();
                file = null;
            }
            if(httpGet != null)
            {
            	httpGet.abort();
            }
        } finally
        {
        	if(file != null)
        	{
        		if(file.length() != totalSize)
        		{
        			file.delete();
        		}
        	}
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
                if (conIn != null)
                {
                    conIn.close();
                }
                if (entity != null)
                {
                    entity.consumeContent();
                }
                if(httpGet != null)
                {
                	httpGet.abort();
                	httpGet = null;
                }
                if(httpClient != null)
                {
                	httpClient.getConnectionManager().closeExpiredConnections();
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            return file;
        }
    }

//    @SuppressWarnings("finally")
//    public static File downloadFile(Context context, String url, String json, File file)
//    {
//        HttpEntity entity = null;
//        InputStream conIn = null;
//        DataInputStream in = null;
//        OutputStream out = null;
//        httpClient = getNewHttpClient(context);
//        HttpPost httpPost = null;
//        try
//        {
//
//            httpPost = new HttpPost(url);
//            HttpResponse httpResponse = httpClient.execute(addParams(httpPost, json));
//            int responseCode = httpResponse.getStatusLine().getStatusCode();
//            if (responseCode == HttpStatus.SC_OK)
//            {
//                entity = httpResponse.getEntity();
//                conIn = entity.getContent();
//
//                in = new DataInputStream(conIn);
//                out = new FileOutputStream(file);
//                byte[] buffer = new byte[1024];
//                int byteread = 0;
//                while ((byteread = in.read(buffer)) != -1)
//                {
//                    out.write(buffer, 0, byteread);
//                }
//            }
//            else
//            {
//            	Log.i(TAG, "Server return error, response code = " + responseCode);
//                if (file != null)
//                {
//                    file.delete();
//                    file = null;
//                }
//            }
//        } catch (Exception e)
//        {
//            Log.e(TAG, e.getMessage()+"");
//            if (file != null)
//            {
//                file.delete();
//                file = null;
//            }
//            if(httpPost != null)
//            {
//            	httpPost.abort();
//            }
//        } finally
//        {
//            try
//            {
//                if (out != null)
//                {
//                    out.close();
//                }
//                if (in != null)
//                {
//                    in.close();
//                }
//                if (conIn != null)
//                {
//                    conIn.close();
//                }
//                if (entity != null)
//                {
//                    entity.consumeContent();
//                }
//                if(httpPost != null)
//                {
//                	httpPost.abort();
//                }
//                if(httpClient != null)
//                {
//                	httpClient.getConnectionManager().closeExpiredConnections();
//                }
//            } catch (Exception e)
//            {
//                e.printStackTrace();
//            }
//            return file;
//        }
//    }

}


text:
package org.apereo.cas.ws.idp.web;

import org.apereo.cas.ws.idp.WSFederationConstants;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import java.util.UUID;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link WSFederationRequestTests}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@Tag("WSFederation")
public class WSFederationRequestTests {

    @Test
    public void verifyOperation() {
        val id = UUID.randomUUID().toString();
        val request = new MockHttpServletRequest();
        request.addParameter(WSFederationConstants.WTREALM, id);
        request.addParameter(WSFederationConstants.WREPLY, id);
        request.addParameter(WSFederationConstants.WREQ, id);
        request.addParameter(WSFederationConstants.WCTX, id);
        request.addParameter(WSFederationConstants.WREFRESH, id);
        request.addParameter(WSFederationConstants.WHR, id);
        request.addParameter(WSFederationConstants.WRESULT, id);
        request.addParameter(WSFederationConstants.RELAY_STATE, id);
        request.addParameter(WSFederationConstants.SAML_RESPONSE, id);
        request.addParameter(WSFederationConstants.STATE, id);
        request.addParameter(WSFederationConstants.CODE, id);
        request.addParameter(WSFederationConstants.WA, id);

        assertNotNull(WSFederationRequest.of(request));
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace boost;

void test_typedefed_wchar_t_runtime()
{
#ifndef BOOST_LCAST_NO_WCHAR_T
#ifdef BOOST_MSVC
    BOOST_STATIC_ASSERT((boost::is_same<wchar_t, unsigned short>::value));

    BOOST_CHECK_EQUAL(boost::lexical_cast<int>(L'A'), 65);
    BOOST_CHECK_EQUAL(boost::lexical_cast<int>(L'B'), 66);

    BOOST_CHECK_EQUAL(boost::lexical_cast<wchar_t>(L"65"), 65);
    BOOST_CHECK_EQUAL(boost::lexical_cast<wchar_t>(L"66"), 66);
#endif
#endif
    BOOST_CHECK(1);
}

unit_test::test_suite *init_unit_test_suite(int, char *[])
{
    unit_test::test_suite *suite =
        BOOST_TEST_SUITE("lexical_cast typedefed wchar_t runtime test");
    suite->add(BOOST_TEST_CASE(&test_typedefed_wchar_t_runtime));

    return suite;
}


text:
<?
$UserID = $LoggedUser['ID'];
$TagID = db_string($_GET['tagid']);
$GroupID = db_string($_GET['groupid']);
$Way = db_string($_GET['way']);

if (!is_number($TagID) || !is_number($GroupID)) {
	error(404);
}
if (!in_array($Way, array('up', 'down'))) {
	error(404);
}

$DB->query("
	SELECT TagID
	FROM torrents_tags_votes
	WHERE TagID = '$TagID'
		AND GroupID = '$GroupID'
		AND UserID = '$UserID'
		AND Way = '$Way'");
if (!$DB->has_results()) {
	if ($Way == 'down') {
		$Change = 'NegativeVotes = NegativeVotes + 1';
	} else {
		$Change = 'PositiveVotes = PositiveVotes + 2';
	}
	$DB->query("
		UPDATE torrents_tags
		SET $Change
		WHERE TagID = '$TagID'
			AND GroupID = '$GroupID'");
	$DB->query("
		INSERT INTO torrents_tags_votes
			(GroupID, TagID, UserID, Way)
		VALUES
			('$GroupID', '$TagID', '$UserID', '$Way')");
	$Cache->delete_value("torrents_details_$GroupID"); // Delete torrent group cache
}
header('Location: '.$_SERVER['HTTP_REFERER']);
?>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Bootstrap 101 Template</title>

  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">


text:
OTTO WG Minutes 12/2/15
STATUS: No-Quorum

## Voting Members Attending:
 - Mike Schwartz
 - Keith Hazelton

## Non-voting members
 - Alan Karp

Quorum was not reached, so we kept the discussion abbreviated.

# JSON-LD Signature discussion

Mike did some research last week on JSON-LD signatures, and it looks encouraging.
In particular, there is an approach to convert JSON-LD to RDF, and then to
normalize and sign the RDF. See the working group drafts here:
 [http://json-ld.org/spec/latest](http://json-ld.org/spec/latest)

What is the difference betwen Canonicalization and normalization?

[https://en.wikipedia.org/wiki/Canonicalization](Wikipedia definition):
  In computer science, canonicalization (sometimes standardization or normalization) is a process
  for converting data that has more than one possible representation into a "standard", "normal",
  or canonical form. This can be done to compare different representations for equivalence, to count
  the number of distinct data structures, to improve the efficiency of various algorithms by
  eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

Alan mentioned that dealing with whitespace was a particular challenge in efforts to
normalize RDF. Tools had different conventions, and people would adjust whitespace for
readability.

Manu Sporny, one of the editors will be a special guest next week. We can pose this question to him.

Please watch this quick video by Manu on JSON-LD signatures:
 https://youtu.be/QdUZaYeQblY

He is also working on an effort to use JSON-LD signautres to enable personal
identification: OpenCreds:
 http://opencreds.org

As we may not have the benefits of Manu's expertise in the future, if you have any questions
about JSON-LD, please prepare them for next week. Also please attend!

## Next Meeting - Weds 12/9 8am PT : Special Guest Manu Sporny

**Next MEETING 12/9 **

Screen Sharing: [https://global.gotomeeting.com/join/162399285](https://global.gotomeeting.com/join/162399285)

 - Audio: Skype: +99051000000481
 - North America Toll: +1 (805) 309-2350
 - Alternate Toll: +1 (714) 551-9842
 - International Toll: http://www.turbobridge.com/international.html

 - Conference ID: 613-2898

    Command Menu: 0 Plays menu of Keypad Commands *3 Promote to Host (if non-host) *5 Raise your hand
    *6 Mute yourself (toggle on/off) *# Private roll call of participants *\ Mute music-on-hold (toggle on/off)

    TurboPhone (beta): https://www.turbobridge.com/join.html Works with Internet Explorer on Windows only

    SIP Access (using IP phone or soft phone) sip:bridge@turbobridge.com
    SIP URL details: https://www.turbobridge.com/help/Index.html?context=180


text:
Installation (DE)
=================

Sämtliche Komponenten für eMonitor liegen für verschiedene Betriebssysteme vor und können somit auf nahezu jeder
Platform installiert werden. Nachfolgend ist die Installation für Linux und Windows-Systeme beschrieben.

Installation unter Linux
------------------------

Nach der Installation von Python 2.x sind folgende Schritte erforderlich:

1. Laden der Quellen von Github
::

 > git clone https://github.com/seiferta/eMonitor.git emonitor
 > cd emonitor
 > pip install -r requirements.txt

2. Installation von ImageMagick (Wird zur Umwandlung von PDF-Dateien nach PNG benötigt)
::

 > apt-get install imagemagick

3. Installation von ghostview (wird zur Umwandlung der PDF-Dateien benötigt)
::

 > apt-get install ghostview

4. Installation von Ghostscript (gsprint wird zum Ausdruck der PDF-Alarmansicht benötigt)
::

 > apt-get install ghostscript

5. Installation von tesseract (OCR-Software)
::

 > apt-get install tesseract-ocr tesseract-ocr-deu

Installation unter Windows
--------------------------

Nach der Installation von Python 2.x sind folgende Schritte erforderlich:
(Falls pip nicht direkt installiert werden kann, unter https://bootstrap.pypa.io/get-pip.py liegt ein Script, mit dem man pip direkt mit python installieren kann, eine Anleitung ist unter https://pip.pypa.io/en/latest/installing.html zu finden)

1. Laden der Quellen von Github
::

 > git clone https://github.com/seiferta/eMonitor.git emonitor
 > cd emonitor

Unter Windows kann man mit pip einige Python-Pakete nicht direkt installieren:

- Pillow: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pillow
- Reportlab: http://www.lfd.uci.edu/~gohlke/pythonlibs/#reportlab

2. Anschließend folgt dann die Installation der restlichen Python-Abhängigkeiten mit pip
::

 > pip install -r requirements.txt

3. Folgende weitere Softwarepakete bzw. Teile davon werden noch benötigt:
- ImageMagick: convert.exe http://www.imagemagick.org/script/binary-releases.php
- GhostView: gsprint.exe http://pages.cs.wisc.edu/~ghost/gsview/get50.htm
- GhostScript: http://www.ghostscript.com/download/gsdnld.html
- Tesseract: tesseract.exe http://tesseract-ocr.googlecode.com/files/tesseract-ocr-3.02-win32-portable.zip

Installation als Windows-Service
````````````````````````````````

eMonitor kann unter Windows als Dienst installiert werden, der automatisch beim Starten des Rechners aktiviert wird.
Dazu sind ein paar Dinge zu beachten:

* Dateipfade dürfen keine Netzwerklaufwerke sein, die per Zuordnung einem Buchstaben zugeordnet sind. Es sind
  ausschließlich UNC-Pfade zu verwenden.

* Der Benutzer, unter dem der Dienst läuft, muss Zugriff auf die Verzeichnisse haben

Installation:
::

 > cd emonitor
 > python service.py install

Anschließend kann der Dienst über die Dienste-Verwaltung konfiguriert werden.

Konfiguration und Hilfe
-----------------------

Parameter für convert (PDF -> PNG)
::

 > 32-bit[basepath]/bin/convert/convert32.exe -depth 32 -density 250 [incomepath][filename] -quality 100 [tmppath]
 > 64-bit[basepath]/bin/convert/convert64.exe -resize 200% -depth 32 -density 200 [incomepath][filename] -quality 100 [tmppath]

Parameter für tesseract (OCR)
::

 > 32-bit[basepath]/bin/tesseract/tesseract.exe [incomepath][filename] [tmppath] -l deu -psm  6 quiet custom
 > 64-bit[basepath]/bin/tesseract/tesseract.exe [incomepath][filename] [tmppath] -l deu -psm 6 quiet custom


text:
package jp.co.dzl.example.akka.api.di

import akka.actor.ActorSystem
import scaldi.Module

class AkkaModule extends Module {
  bind[ActorSystem] toNonLazy ActorSystem("akka-api-gateway-example")
}


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.

.. include:: ../../../common.defs

.. _developer-plugins-http-transformations:

HTTP Transformations
********************

Transform plugins examine or transform HTTP message body content. For
example, transform plugins can:

-  Append text to HTML documents

-  Compress images

-  Do virus checking (on client ``POST`` data or server response data)

-  Do content-based filtering (filter out HTML documents that contain
   certain terms or expressions)

This chapter explains how to write transform plugins. The following
examples are discussed in detail:

.. toctree::
   :maxdepth: 2

   sample-null-transformation-plugin.en
   append-transform-plugin.en
   sample-buffered-null-transformation-plugin.en

.. _WritingContentTransformPlugin:

Writing Content Transform Plugins
=================================

Content transformation plugins transform HTTP response content (such as
images or HTML documents) and HTTP request content (such as client
``POST`` data). Because the data stream to be transformed is of variable
length, these plugins must use a mechanism that passes data from buffer
to buffer *and* checks to see if the end of the data stream is reached.
This mechanism is provided by virtual connections (``VConnection``\ s)
and virtual IO descriptors (``VIO``\ s).

A ``VConnection`` is an abstraction for a data pipe that allows its
users to perform asynchronous reads and writes without knowing the
underlying implementation. A transformation is a specific type of
``VConnection``. A **transformation** connects an input data source and
an output data sink; this feature enables it to view and modify all the
data passing through it.

Transformations can be chained together, one after the other, so that
multiple transformations can be performed on the same content. The
``VConnection`` type, ``TSVConn``, is actually a subclass of ``TSCont``,
which means that ``VConnection``\ s (and transformations) are
continuations. ``VConnection``\ s and transformations can thus exchange
events, informing one another that data is available for reading or
writing, or that the end of a data stream is reached.

A ``VIO`` is a description of an IO operation that is in progress.
Every ``VConnection`` has an associated *input VIO* and an associated
*output VIO*. When ``VConnection``\ s are transferring data to one
another, one ``VConnection``'s input ``VIO`` is another
``VConnection``'s output ``VIO``. A ``VConnection``'s input ``VIO`` is
also called its **write ``VIO``** because the input ``VIO`` refers to a
write operation performed on the ``VConnection`` itself. Similarly, the
output ``VIO`` is also called the **read ``VIO``**. For transformations,
which are designed to pass data in one direction, you can picture the
relationship between the transformation ``VConnection`` and its
``VIO``\ s as follows:

.. _transformationAndItsVIOs:

.. figure:: /static/images/sdk/vconnection.jpg
   :alt: A Transformation and its VIOs
   :align: center

   **A Transformation and its VIOs**

Because the Traffic Server API places transformations directly in the
response or request data stream, the transformation ``VConnection`` is
responsible only for reading the data from the input buffer,
transforming it, and then writing it to the output buffer. The upstream
``VConnection`` writes the incoming data to the transformation's input
buffer. In the figure above, :ref:`TransformationAndItsVIOs`, the input ``VIO`` describes the
progress of the upstream ``VConnection``'s write operation on the
transformation, while the output ``VIO`` describes the progress of the
transformation's write operation on the output (downstream)
``VConnection``. The **nbytes** value in the ``VIO`` is the total number
of bytes to be written. The **ndone** value is the current progress, or
the number of bytes that have been written at a specific point in time.

When writing a transformation plugin, you must understand implementation
as well as the use of ``VConnection``\ s. The *implementor's side*
refers to how to implement a ``VConnection`` that others can use. At
minimum, a transform plugin creates a transformation that sits in the
data stream and must be able to handle the events that the upstream and
downstream ``VConnection``\ s send to it. The *user's side* refers to
how to use a ``VConnection`` to read or write data. At the very least,
transformations output (write) data.

.. _transformations:

Transformations
---------------

VIOs
----

A ``VIO`` or virtual IO is a description of an in progress IO
operation. The ``VIO`` data structure is used by ``VConnection`` users
to determine how much progress has been made on a particular IO
operation, and to reenable an IO operation when it stalls due to buffer
space. ``VConnection`` implementors use ``VIO``\ s to determine the
buffer for an IO operation, how much work to do on the IO operation, and
which continuation to call back when progress on the IO operation is
made.

The ``TSVIO`` data structure itself is opaque, but it might have been
defined as follows:

.. code-block:: c

   typedef struct {
      TSCont continuation;
      TSVConn vconnection;
      TSIOBufferReader reader;
      TSMutex mutex;
      int nbytes;
      int ndone;
   } *TSVIO;

IO Buffers
----------

The **IO buffer** data structure is the building block of the
``VConnection`` abstraction. An IO buffer is composed of a list of
buffer blocks which, in turn, point to buffer data. Both the *buffer
block* (``TSIOBufferBlock``) and *buffer data* (``TSIOBufferData``) data
structures are reference counted so they can reside in multiple buffers
at the same time. This makes it extremely efficient to copy data from
one IO buffer to another using ``TSIOBufferCopy``, since Traffic Server
only needs to copy pointers and adjust reference counts appropriately
(instead of actually copying any data).

The IO buffer abstraction provides for a single writer and multiple
readers. In order for the readers to have no knowledge of each other,
they manipulate IO buffers through the\ ``TSIOBufferReader`` data
structure. Since only a single writer is allowed, there is no
corresponding ``TSIOBufferWriter`` data structure. The writer simply
modifies the IO buffer directly.

Transaction Data Sink
~~~~~~~~~~~~~~~~~~~~~

The hook `TS_HTTP_RESPONSE_CLIENT_HOOK` is a hook that supports a special type of transformation, one with only input and no output.
Although the transformation doesn't provide data back to Traffic Server it can do anything else with the data, such as writing it
to another output device or process. It must, however, consume all the data for the transaction. There are two primary use cases.

#. Tap in to the transaction to provide the data for external processing.
#. Maintain the transaction.

For the latter it is important to note that if all consumers of a transaction (primarily the user agent) shut down the transaction is also
terminated, including the connection to the origin server. A data sink transform, unlike a standard transform, is considered to be a consumer
and will keep the transaction and the origin server connection up. This is useful when the transaction is in some way expensive and should
run to completion even if the user agent disconnects. Examples would be a standard transform that is expensive to initiate, or expensive
origin server connections that should be :ts:cv:`shared <proxy.config.http.server_session_sharing.match>`.

There is an `example plugin <https://github.com/apache/trafficserver/blob/master/example/txn-data-sink/txn-data-sink.c>`_ that demonstrates
this used as a pure data sink to keep the transaction up regardless of whether the user agent disconnects.


text:
<?php

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package		app.Controller
 * @link		http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */

class AppController extends Controller {

	public $components = array('Session', 'Auth');

	public function beforeFilter() {
		parent::beforeFilter();

		// Handle basic auth for API.
		if (isset($this->request->params['ext']) && $this->request->params['ext'] == 'json') {
				$this->Auth->authenticate = array('Basic' => array(
						'fields' => array('username' => 'email')
				));

				if (!$this->Auth->login()) {
						$data = array (
								'status' => 400,
								'message' => $this->Auth->authError,
						);
						$this->set('data', $data);
						$this->set('_serialize', 'data');

						$this->viewClass = 'Json';
						$this->render();
				}
		}

		$this->set('logged_in', $this->Auth->loggedIn());
	}

	public function isAuthorized($user) {
		return true;
	}
}


text:
local BackGround = require "entities.background"
local background = BackGround()
local imgTitle = love.graphics.newImage("assets/images/endtitle.png")

local credits = {}
local pegCount
local score

function credits:enter(self, pegsCollected, totalScore)
   -- Create and set a default 55 point font
   titleFont = love.graphics.newFont(55)

   -- Create and set a default 30 point font
   creditFont = love.graphics.newFont(30)

   pegCount = pegsCollected
   score = totalScore
   Sound.playChris()
end

function credits:update(dt)
end

function credits:draw()
   love.graphics.setColor(0, 40, 60)
   background:draw()

   love.graphics.setColor(200, 255, 200)
   love.graphics.draw(imgTitle, Constants.SCREEN_WIDTH/8 , 0)

   -- Use the larger title font
   love.graphics.setFont(titleFont)
   love.graphics.setColor(50, 200, 150)
   percentage = pegCount / Constants.NUM_STARTING_PEGS
   if percentage > .75 then
      love.graphics.print("You Win!", 75, Constants.SCREEN_HEIGHT * .4)
   else
      love.graphics.print("You Lose!", 75, Constants.SCREEN_HEIGHT * .4)
   end
   love.graphics.print("Score: " .. score, 75, 350)

   -- Use the credit font
   love.graphics.setFont(creditFont)
   love.graphics.setColor(50, 200, 150)

   love.graphics.print("You collected:\n" .. pegCount .. " out of " .. 65 .. " pegs", 75, 500)

   love.graphics.print("Marc Zych!", 500, 350)
   love.graphics.print("Katherine Blizard!", 550, 400)
   love.graphics.print("Taylor Arnicar!", 600, 450)
   love.graphics.print("Chris Patton!", 650, 500)
   love.graphics.print("Thomas Soria!", 700, 550)

   love.graphics.print("(Press any key to restart)", 325, 650)
end

function credits:keypressed(key, unicode)
   Gamestate.switch(States.title)
end

return credits


text:
package net.erel.maven.plugins.mojo;

import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.project.MavenProject;

public abstract class PGXAbstractReleaseMojo extends CommandLineExecutorAbstractMojo {

	protected DefaultArtifactVersion defaultArtifactVersion;

	@Component
	protected MavenProject project;

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		this.defaultArtifactVersion = new DefaultArtifactVersion(project.getVersion());
	}

	String getNextRCVersion() {
		return null;
	}

	String getNextVersion() {
		return null;
	}

}


text:
package org.xtuml.bp.cli;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.ui.PlatformUI;

import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.debug.ui.launch.VerifierLaunchConfiguration;

public class ExecuteWorkbenchAdvisor extends BPCLIWorkbenchAdvisor {
	ILaunchConfiguration launchConfig = null;
	private final String mode = ILaunchManager.DEBUG_MODE;

	protected ExecuteWorkbenchAdvisor(BPCLIPreferences prefs) throws CoreException, BPCLIException {
		super(prefs);
		debug = cmdLine.getBooleanValue("-debugCLI");
		String specifiedLaunchName = cmdLine.getStringValue("-launch");
		ILaunchConfiguration[] cfgs = getVerifierLaunchConfigs();
		for(int i = 0; i < cfgs.length; i++){
	        final String cfgName = cfgs[i].getName();

	        if(cfgName.equals(specifiedLaunchName)) {
                if (debug) {
                    System.out.println("Located and configured to use the specified launch configuration: " + specifiedLaunchName);
                }
	        	launchConfig = cfgs[i];
	        }
	    }

		if (launchConfig == null) {
            if (debug) {
                System.out.println("No launch config named \"" + specifiedLaunchName + "\" was found");
            }
			throw new BPCLIException("No launch config named \"" + specifiedLaunchName + "\" was found");
		}
	}

	public static ILaunchConfiguration[] getVerifierLaunchConfigs() throws CoreException {
		ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
		ILaunchConfigurationType veriferLaunchType =  manager.getLaunchConfigurationType(VerifierLaunchConfiguration.LAUNCH_ID);
		ILaunchConfiguration[] cfgs = manager.getLaunchConfigurations(veriferLaunchType);
		return cfgs;
	}

	@Override
	public void postStartup() {
		super.postStartup();
		Thread runner = new Thread(new Runnable() {

			@Override
			public void run() {
				launchConfiguration();
			}
		});
		runner.setName("BP CLI Execution");
		runner.start();
	}

	private void launchConfiguration() {
		try {
			ILaunch launch = launchConfig.launch(mode, null);
			if (launch.canTerminate()) {
				while (!launch.isTerminated() ) {
					Thread.sleep(100);
				}
			}
		} catch (CoreException e) {
			BPCLIPreferences.logError("Error encountered during launch of "
					+ launchConfig.getName(), e);
		} catch (InterruptedException e) {
			BPCLIPreferences.logError("Could not sleep execution thread", e);
		} finally {
			System.out.println("Execution complete.  Exiting.");
			// Unless running in debug exit after the build
			if (!debug) {
				PlatformUI.getWorkbench().getDisplay().asyncExec(
						new Runnable() {

							@Override
							public void run() {
								PlatformUI.getWorkbench().close();
							}
						});
			}
		}
	}

}


text: ALTER TABLE `#__extensions` CHANGE `enabled` `enabled` TINYINT(3) NOT NULL DEFAULT '0';


text:
layout: page
title: Robles Cloud Studios Dinner
date: 2016-05-24
author: Kenneth Proctor
tags: weekly links, java
status: published
summary: Aliquam et luctus metus. Donec luctus rhoncus nisl eu.
banner: images/banner/wedding.jpg
booking:
  startDate: 01/19/2017
  endDate: 01/21/2017
  ctyhocn: DAYVNHX
  groupCode: RCSD
published: true
---
Mauris sit amet malesuada massa. Aliquam consectetur non tellus ac sagittis. Integer quis magna velit. Proin faucibus, dolor vitae dictum semper, felis diam condimentum augue, et condimentum risus augue sagittis quam. Integer non sem vitae turpis rhoncus auctor. Praesent sed magna ante. Phasellus lorem erat, tempor eu lorem eget, auctor mollis nulla. In sollicitudin pharetra lorem in facilisis. Nam aliquam sed tortor eu eleifend. Suspendisse diam velit, mollis ornare odio ultricies, cursus porttitor lacus. Curabitur interdum mi sed diam dictum, vel congue mi rutrum. Sed efficitur diam tortor, nec viverra libero laoreet non. Suspendisse molestie leo id turpis dapibus, consequat pellentesque ante tristique. Aliquam est ligula, varius quis libero non, interdum elementum neque. Curabitur ornare vulputate pellentesque.

* Cras ornare felis et faucibus suscipit
* Etiam et tortor sollicitudin eros rhoncus egestas
* Integer sit amet nisi nec magna eleifend fermentum sed et risus
* Fusce sit amet felis nec risus aliquam facilisis
* Vivamus pulvinar lacus ac nunc laoreet, sed dictum tellus blandit.

Vivamus sollicitudin pharetra massa, auctor elementum massa mollis vel. Morbi non lectus et ex bibendum dictum sit amet sed nibh. Nunc ornare elementum nisi vel iaculis. Aenean luctus pulvinar nibh, in dictum orci semper efficitur. Nullam ac sapien quis magna commodo fringilla a eget metus. Duis eget purus eget ipsum iaculis sagittis. Curabitur sollicitudin mauris lectus, ut congue odio suscipit eu. Proin at sem sit amet est tempus commodo. Integer eu consequat magna, id aliquet leo. Aenean sem lacus, elementum nec tellus a, maximus consectetur elit. Pellentesque justo odio, suscipit a leo et, iaculis gravida justo. Nullam accumsan orci ac neque efficitur tempor. Morbi facilisis lectus ligula. Fusce aliquet pretium nisl, ac dictum purus pellentesque vitae.


text:
namespace {

static const FilePath::CharType kStartFile[] =
    FILE_PATH_LITERAL("run.html");

const char kRunV8Benchmark[] = "run-v8-benchmark";

class V8BenchmarkTest : public UIPerfTest {
 public:
  typedef std::map<std::string, std::string> ResultsMap;

  V8BenchmarkTest() : reference_(false) {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  void RunTest() {
    FilePath::StringType start_file(kStartFile);
    FilePath test_path = GetV8BenchmarkDir();
    test_path = test_path.Append(start_file);
    GURL test_url(net::FilePathToFileURL(test_path));

    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());
    ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS, tab->NavigateToURL(test_url));

    // Wait for the test to finish.
    ASSERT_TRUE(WaitUntilTestCompletes(tab.get(), test_url));

    PrintResults(tab.get());
  }

 protected:
  bool reference_;  // True if this is a reference build.

 private:
  // Return the path to the V8 benchmark directory on the local filesystem.
  FilePath GetV8BenchmarkDir() {
    FilePath test_dir;
    PathService::Get(chrome::DIR_TEST_DATA, &test_dir);
    return test_dir.AppendASCII("v8_benchmark");
  }

  bool WaitUntilTestCompletes(TabProxy* tab, const GURL& test_url) {
    return WaitUntilCookieValue(tab, test_url, "__done",
                                TestTimeouts::large_test_timeout_ms(), "1");
  }

  bool GetScore(TabProxy* tab, std::string* score) {
    std::wstring score_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send(automation.GetScore());",
        &score_wide);

    // Note that we don't use ASSERT_TRUE here (and in some other places) as it
    // doesn't work inside a function with a return type other than void.
    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    score->assign(WideToUTF8(score_wide));
    return true;
  }

  bool GetResults(TabProxy* tab, ResultsMap* results) {
    std::wstring json_wide;
    bool succeeded = tab->ExecuteAndExtractString(L"",
        L"window.domAutomationController.send("
        L"    JSON.stringify(automation.GetResults()));",
        &json_wide);

    EXPECT_TRUE(succeeded);
    if (!succeeded)
      return false;

    std::string json = WideToUTF8(json_wide);
    return JsonDictionaryToMap(json, results);
  }

  void PrintResults(TabProxy* tab) {
    std::string score;
    ASSERT_TRUE(GetScore(tab, &score));

    ResultsMap results;
    ASSERT_TRUE(GetResults(tab, &results));

    std::string trace_name = reference_ ? "score_ref" : "score";
    std::string unit_name = "score (bigger is better)";

    perf_test::PrintResult("score", "", trace_name, score, unit_name, true);

    ResultsMap::const_iterator it = results.begin();
    for (; it != results.end(); ++it)
      perf_test::PrintResult(it->first, "", trace_name, it->second, unit_name,
                             false);
  }

  DISALLOW_COPY_AND_ASSIGN(V8BenchmarkTest);
};

class V8BenchmarkReferenceTest : public V8BenchmarkTest {
 public:
  V8BenchmarkReferenceTest() : V8BenchmarkTest() {
    reference_ = true;
  }

  void SetUp() {
    UseReferenceBuild();
    V8BenchmarkTest::SetUp();
  }
};

TEST_F(V8BenchmarkTest, Perf) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunV8Benchmark))
    return;

  RunTest();
}

// Bug 87162: Disable Perf for ChromeOS
#if defined(OS_CHROMEOS)
#define MAYBE_Perf DISABLED_Perf
#else
#define MAYBE_Perf Perf
#endif

TEST_F(V8BenchmarkReferenceTest, MAYBE_Perf) {
  if (!CommandLine::ForCurrentProcess()->HasSwitch(kRunV8Benchmark))
    return;

  RunTest();
}

}  // namespace


text:
from app import app
app.run()


text:
package com.dangdang.config.service.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 主题通用实现
 *
 * @author Yuxuan Wang
 *
 */
public abstract class AbstractSubject implements ISubject {

	/**
	 * 观察者列表
	 */
	private final List<IObserver> watchers = new ArrayList<>();

	@Override
	public void register(final IObserver watcher) {
		if(watcher == null) {
			throw new IllegalArgumentException("watcher cannot be null");
		}
		watchers.add(watcher);
	}

	@Override
	public void notify(final String key, final String value) {
		for (final IObserver watcher : watchers) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					watcher.notified(key, value);
				}
			}).start();
		}
	}

}


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

<TITLE>
JvmBugs (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.util

Class JvmBugs

java.lang.Object
  org.apache.poi.util.JvmBugs

public class JvmBugs
extends java.lang.Object

Constructor Summary

JvmBugs()

Method Summary

static boolean
hasLineBreakMeasurerBug()

          The LineBreakMeasurer is used for calculating text bounds.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

JvmBugs

public JvmBugs()

Method Detail

hasLineBreakMeasurerBug

public static boolean hasLineBreakMeasurerBug()

The LineBreakMeasurer is used for calculating text bounds.
 The last official JDK 6 version (1.6.0_45) and also JDK 7 (1.7.0_21)
 for Windows are affected. For JDK 7 - update to a more recent version.
 For JDK 6 - replace the fontmanager.dll with the previous release.

 For performance reasons, this method only checks for a windows jvm
 with version 1.6.0_45 and 1.7.0_21.

 Set system property "org.apache.poi.JvmBugs.LineBreakMeasurer.ignore" to "true"
 to bypass this check and use the normal fonts.

Returns:
true, if jvm is bugged, caller code should use Lucida Sans
 instead of Calibri and Lucida Bright instead of Cambria
See Also:
Workaround for XSLF,
Workaround for XSSF and HSSF,
POI Bug #54904,
JDK Bug #6501991,
LineBreakMeasurerTest

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
      <title>Wallaby-Multipurpose Responsive Email Template</title>

                        If you cannot read this email, please click here

                        Hi Ron,

Heading 4

Heading 3

Heading 2

Heading 1

list item 1

list item 2

list item 3

                        Congrats on achieving statistical significance (stat. sig.) on 3 of your 6 total teacher and student questionnaires (as of December 6). Great job you're almost there!

                        Please see the image below on how to find the most up-to-date information for your schools through your clarity3.brightbytes.net login. Please keep in mind that the system updates every night at midnight, so you won't see your responses until the next day.

                        Please let us know if you have any questions. For support issues and immediate assistance, please contact us at support@brightbytes.net or at (877) 433-4036.

                        Best,

                        Aglae

                        Aglae Velasco Shaw

                        Project Manager

                        aglae@brightbytes.net | www.BrightBytes.net

                        (415) 652-3952 | www.calendly.com/aglae

                        You're receiving this email because you are a valued member of the Clarity™ family.

                        © 2014 BrightBytes.  All Rights Reserved.  Unsubscribe.

                        490 2nd St. Suite 302, San Francisco, CA 94107


text:
A small configuration helper for the Raspberry Pi.

See the [Adafruit Pi Finder](https://github.com/adafruit/Adafruit-Pi-Finder) and
[Occidentalis](https://github.com/adafruit/Adafruit-Occidentalis) for more info.


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>Local Notifications (Toasts)</title>
	<meta name="keywords" content="local notifications background toast" />

	<link href="//Microsoft.WinJS.2.0/css/ui-light.css" rel="stylesheet" />

	<link href="toasts.css" rel="stylesheet" />

			<button data-win-control="WinJS.UI.BackButton"></button>

				Local Notifications (Toasts)

Concept

Here we're going to fire a local notification with a toast. You can also schedule it for later at a desired time. Type some text and hit 'Fire' or select the time you want the notification to go off and hit 'Schedule'.

						<input id="toastText" />
						<button id="now">Fire now</button>
						or schedule for

						<button id="schedule">Schedule</button>

						<button id="clear">Clear all scheduled notifications</button>

						<button id="clearMessages" style="visibility:hidden">Clear messages</button>


text:
package migrations

var migration_v0062 = map[string][]string{
	"mysql": {
		`CALL drop_terminal_guid_unique_index();`,
	},
	"postgres": {},
}


text:
module Elements
  module SpecHelper

    def descriptor(name, attributes={}, &block)
      @descriptor = Elements::ElementBuilder.create(name, attributes, &block)
    end

    def property(name, type, attributes={}, &block)
      @property = Elements::ElementBuilder.new(@descriptor).property(name, type, attributes, &block)
      @property.save!
      @property
    end

    def compile(descriptor=@descriptor)
      @klass = Elements::Compiler.new(descriptor).compile
    end

  end
end


text:
<?php

use yii\helpers\Html;
use yii\widgets\DetailView;

/* @var $this yii\web\View */
/* @var $model common\models\CustomerCreditProcessHis */

$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Customer Credit Process His'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

    <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'apply_id',
            'manager_id',
            'result_id',
            'remark:ntext',
            'create_time:datetime',
            'update_time:datetime',
            'status',
            'order',
        ],
    ]) ?>


text:
#ifndef APE_IFILEMATERIAL_H
#define APE_IFILEMATERIAL_H

#include "apeMaterial.h"

namespace ape
{
	class IFileMaterial : public Material
	{
	protected:
		IFileMaterial(std::string name) : Material(name, Entity::MATERIAL_FILE) {}

		virtual ~IFileMaterial() {};

	public:
		virtual void setFileName (std::string fileName) = 0;

		virtual std::string getfFileName () = 0;

		virtual void setAsSkyBox() = 0;

		virtual void setTexture(ape::TextureWeakPtr texture) = 0;

		virtual ape::TextureWeakPtr getTexture() = 0;
	};

	typedef std::weak_ptr<IFileMaterial> FileMaterialWeakPtr;
}

#endif


text:
This framework is use with:

[Sketch-Flex-Layout](http://github.com/hrescak/Sketch-Flex-Layout)

[Sketch](http://bohemiancoding.com)


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Give extends StdCommand
{
	public Give(){}

	private String[] access={"GIVE","GI"};
	public String[] getAccessWords(){return access;}
	public boolean execute(MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException
	{
		if(commands.size()<2)
		{
			mob.tell("Give what to whom?");
			return false;
		}
		commands.removeElementAt(0);
		if(commands.size()<2)
		{
			mob.tell("To whom should I give that?");
			return false;
		}

		MOB recipient=mob.location().fetchInhabitant((String)commands.lastElement());
		if((recipient==null)||(!CMLib.flags().canBeSeenBy(recipient,mob)))
		{
			mob.tell("I don't see anyone called "+(String)commands.lastElement()+" here.");
			return false;
		}
		commands.removeElementAt(commands.size()-1);
		if((commands.size()>0)&&(((String)commands.lastElement()).equalsIgnoreCase("to")))
			commands.removeElementAt(commands.size()-1);

		int maxToGive=CMLib.english().calculateMaxToGive(mob,commands,true,mob,false);
        if(maxToGive<0) return false;

		String thingToGive=CMParms.combine(commands,0);
		int addendum=1;
		String addendumStr="";
		Vector V=new Vector();
		boolean allFlag=(commands.size()>0)?((String)commands.elementAt(0)).equalsIgnoreCase("all"):false;
		if(thingToGive.toUpperCase().startsWith("ALL.")){ allFlag=true; thingToGive="ALL "+thingToGive.substring(4);}
		if(thingToGive.toUpperCase().endsWith(".ALL")){ allFlag=true; thingToGive="ALL "+thingToGive.substring(0,thingToGive.length()-4);}
        boolean onlyGoldFlag=mob.hasOnlyGoldInInventory();
        Item giveThis=CMLib.english().bestPossibleGold(mob,null,thingToGive);
        if(giveThis!=null)
        {
            if(((Coins)giveThis).getNumberOfCoins()<CMLib.english().numPossibleGold(mob,thingToGive))
                return false;
            if(CMLib.flags().canBeSeenBy(giveThis,mob))
                V.addElement(giveThis);
        }
		boolean doBugFix = true;
        if(V.size()==0)
		while(doBugFix || ((allFlag)&&(addendum<=maxToGive)))
		{
			doBugFix=false;
			giveThis=mob.fetchCarried(null,thingToGive+addendumStr);
			if((giveThis==null)
			&&(V.size()==0)
			&&(addendumStr.length()==0)
			&&(!allFlag))
			{
				giveThis=mob.fetchWornItem(thingToGive);
				if(giveThis!=null)
				{
					if((!(giveThis).amWearingAt(Wearable.WORN_HELD))&&(!(giveThis).amWearingAt(Wearable.WORN_WIELD)))
					{
						mob.tell("You must remove that first.");
						return false;
					}
					CMMsg newMsg=CMClass.getMsg(mob,giveThis,null,CMMsg.MSG_REMOVE,null);
					if(mob.location().okMessage(mob,newMsg))
						mob.location().send(mob,newMsg);
					else
						return false;
				}
			}
            if((allFlag)&&(!onlyGoldFlag)&&(giveThis instanceof Coins)&&(thingToGive.equalsIgnoreCase("all")))
                giveThis=null;
            else
            {
    			if(giveThis==null) break;
    			if(CMLib.flags().canBeSeenBy(giveThis,mob))
    				V.addElement(giveThis);
            }
            addendumStr="."+(++addendum);
		}

		if(V.size()==0)
			mob.tell("You don't seem to be carrying that.");
		else
		for(int i=0;i<V.size();i++)
		{
			giveThis=(Item)V.elementAt(i);
			CMMsg newMsg=CMClass.getMsg(mob,recipient,giveThis,CMMsg.MSG_GIVE,"<S-NAME> give(s) <O-NAME> to <T-NAMESELF>.");
			if(mob.location().okMessage(mob,newMsg))
				mob.location().send(mob,newMsg);
			if(giveThis instanceof Coins)
				((Coins)giveThis).putCoinsBack();
			if(giveThis instanceof RawMaterial)
				((RawMaterial)giveThis).rebundle();
		}
		return false;
	}
    public double combatActionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCOMCMDTIME),100.0);}
    public double actionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCMDTIME),100.0);}
	public boolean canBeOrdered(){return true;}

}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="profiteer">
        <note>
            Frames file for 'profiteer' based on sentences in wsj.  No Verbnet entry.
        </note>

        <roleset id="profiteer.01" name="take excessive profits, be a pirate" vncls="-">
            <roles>
                <role descr="pirate" n="0"/>
            </roles>

            <example name="the one example">
                <inflection aspect="perfect" form="participle" person="third" tense="present" voice="active"/>
                <text>
                    ``Let's not forget this is the same company that *trace* has been
                    profiteering with this drug for 2 1/2 years,'' Mr. Weiss added.
                </text>
                <arg n="0">*trace*</arg>
                <arg n="M" f="RCL">that ->  the same company</arg>
                <rel>profiteering</rel>
                <arg f="MNR" n="M">with this drug</arg>
                <arg f="TMP" n="M">for 2 1/2 years</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
import {Component} from '@angular/core'

@Component({
  selector: 'd-ftufw',
  template: `
    This is a dummy component for Ftufw

    `,
})
export class Ftufw {
    msg: string = 'nothing to say';
    doNothing(evt: any) {}
}


text:
<template>

		  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
			Toggle Navigation

		  </button>

				${row.title}

3

			<form class="navbar-form navbar-right">
            	<input type="text" class="form-control" placeholder="Search...">
          	</form>

</template>


text:
import {Category} from './category';
import {PageProp} from '../models/pageprop';
export class Page {
  _id:string;
  __v:number;
  title: string;
  categories: Category[] = [];
  pageProps: PageProp[] = [];
  markdown: string;
  updatedAt: Date;
  createdAt: Date;
}


text:
import sys
import subprocess
import argparse
import shutil
import logging.config
from threading import Thread, Event
from collections import namedtuple

from django.conf import settings
from django.core.mail import send_mail, mail_admins
from django.template.loader import render_to_string
from django.core.exceptions import ImproperlyConfigured
from django.db import connection, OperationalError

import path

from frog import getRoot
from frog.models import VideoQueue, SiteConfig

try:
    FROG_FFMPEG = getattr(settings, "FROG_FFMPEG")
    FROG_FFPROBE = getattr(settings, "FROG_FFPROBE")
    FROG_VIDEO_TEMP = getattr(settings, "FROG_VIDEO_TEMP")
except AttributeError:
    raise ImproperlyConfigured(
        "FROG_FFMPEG and FROG_FFPROBE and FROG_VIDEO_TEMP are required"
    )

FROG_SCRUB_DURATION = getattr(settings, "FROG_SCRUB_DURATION", 60)
FROG_FFMPEG_ARGS = getattr(
    settings,
    "FROG_FFMPEG_ARGS",
    "-vcodec libx264 -b:v {0}k -pix_fmt yuv420p -movflags faststart -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 -acodec aac -b:a {1}k -ac 2 -y",
)

TIMEOUT = 1
QualitySetting = namedtuple("QualitySetting", ("video", "audio"))
ROOT = getRoot()
LOGGER = logging.getLogger("video_worker")
QUALITY = {
    "low": QualitySetting(1250, 56),
    "medium": QualitySetting(2500, 56),
    "high": QualitySetting(10000, 128),
}

class VideoThread(Thread):
    def __init__(
        self,
        quality="medium",
        alwaysconvert=False,
        emailuser=False,
        *args,
        **kwargs
    ):
        super(VideoThread, self).__init__(*args, **kwargs)
        self.daemon = True
        self.stop_event = Event()

        self._quality = quality
        self._alwaysconvert = alwaysconvert
        self._emailuser = emailuser

        LOGGER.info(
            "Options quality={}, alwaysconvert={}, emailuser={}".format(
                self._quality, self._alwaysconvert, self._emailuser
            )
        )

    def stop(self):
        self.stop_event.set()

    def run(self):
        while not self.stop_event.is_set():
            try:
                item = VideoQueue.objects.filter(
                    status=VideoQueue.QUEUED
                ).first()
            except OperationalError:
                # Reset the connection to the db
                connection.close()
                item = None

            if not item:
                self.stop_event.wait(TIMEOUT)
                continue

            LOGGER.info("Working on %s", item.video.guid)

            try:
                video = item.video

                # -- Set the video to processing
                LOGGER.info("Processing video: %s" % video.guid)
                item.status = VideoQueue.PROCESSING
                item.message = "Processing video..."
                item.save()

                sourcepath = ROOT / video.source.name

                # -- Get the video information
                videodata = video.info()
                isH264 = (
                    "h264" in videodata["codec"] and sourcepath.ext == ".mp4"
                )

                tempfile = path.Path(FROG_VIDEO_TEMP) / "{}.mp4".format(
                    video.hash
                )
                outfile = sourcepath.parent / "{}.mp4".format(video.hash)

                # -- Further processing is needed if not h264 or needs to be scrubbable
                if not isH264 or self._alwaysconvert:
                    LOGGER.info("Converting video: %s" % video.guid)
                    item.message = "Converting to MP4..."
                    item.save()

                    args = FROG_FFMPEG_ARGS
                    cmd = [FROG_FFMPEG, "-i", str(sourcepath)]
                    width = (
                        item.video.width - 1
                        if item.video.width % 2
                        else item.video.width
                    )
                    height = (
                        item.video.height - 1
                        if item.video.height % 2
                        else item.video.height
                    )

                    if width != item.video.width or height != item.video.height:
                        cmd += [
                            "-filter:v",
                            "crop={0}:{1}:0:0".format(width, height),
                        ]
                    cmd += args.format(*QUALITY[self._quality]).split(" ")
                    cmd += [str(tempfile)]

                    LOGGER.debug(cmd)
                    subprocess.call(cmd)

                    video.video = outfile.replace("\\", "/").replace(ROOT, "")
                    shutil.move(tempfile, outfile)
                else:
                    # -- No further processing
                    video.video = video.source.name

                # -- Set the video to the result
                item.delete()
                video.save()

                if self._emailuser:
                    # -- Email User
                    emailUser(video)
            except Exception as err:
                LOGGER.error(str(err))
                if self._emailuser:
                    emailUser(item.video, err)
                mail_admins("Video Processing Failure", str(err))
                item.status = VideoQueue.ERROR
                item.save()

def emailUser(video, error=None):
    """Emails the author of the video that it has finished processing"""
    config = SiteConfig.getSiteConfig()
    html = render_to_string(
        "frog/video_email.html",
        {
            "user": video.author,
            "error": error,
            "video": video,
            "SITE_URL": config.site_url,
        },
    )
    subject, from_email, to = (
        "Video Processing Finished{}".format(error or ""),
        "noreply@frogmediaserver.com",
        video.author.email,
    )
    text_content = "This is an important message."
    html_content = html

    send_mail(
        subject, text_content, from_email, [to], html_message=html_content
    )

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--quality", default="medium")
    parser.add_argument(
        "--always-convert", action="store_true", dest="alwaysconvert"
    )
    parser.add_argument("--email-user", action="store_true", dest="emailuser")

    args = parser.parse_args()

    LOGGER.info("Starting Worker")
    try:
        thread = VideoThread(
            quality=args.quality,
            alwaysconvert=args.alwaysconvert,
            emailuser=args.emailuser,
        )
        thread.start()
        thread.join()
    except Exception as err:
        LOGGER.error(err)

if __name__ == "__main__":
    main()


text:
if(!dojo._hasResource["dojox.gfx.silverlight"]){
dojo._hasResource["dojox.gfx.silverlight"]=true;
dojo.provide("dojox.gfx.silverlight");
dojo.require("dojox.gfx._base");
dojo.require("dojox.gfx.shape");
dojo.require("dojox.gfx.path");
dojo.experimental("dojox.gfx.silverlight");
dojox.gfx.silverlight.dasharray={solid:"none",shortdash:[4,1],shortdot:[1,1],shortdashdot:[4,1,1,1],shortdashdotdot:[4,1,1,1,1,1],dot:[1,3],dash:[4,3],longdash:[8,3],dashdot:[4,3,1,3],longdashdot:[8,3,1,3],longdashdotdot:[8,3,1,3,1,3]};
dojox.gfx.silverlight.fontweight={normal:400,bold:700};
dojox.gfx.silverlight.caps={butt:"Flat",round:"Round",square:"Square"};
dojox.gfx.silverlight.joins={bevel:"Bevel",round:"Round"};
dojox.gfx.silverlight.fonts={serif:"Times New Roman",times:"Times New Roman","sans-serif":"Arial",helvetica:"Arial",monotone:"Courier New",courier:"Courier New"};
dojox.gfx.silverlight.hexColor=function(_1){
var c=dojox.gfx.normalizeColor(_1),t=c.toHex(),a=Math.round(c.a*255);
a=(a<0?0:a>255?255:a).toString(16);
return "#"+(a.length<2?"0"+a:a)+t.slice(1);
};
dojo.extend(dojox.gfx.Shape,{setFill:function(_2){
var p=this.rawNode.getHost().content,r=this.rawNode,f;
if(!_2){
this.fillStyle=null;
this._setFillAttr(null);
return this;
}
if(typeof (_2)=="object"&&"type" in _2){
switch(_2.type){
case "linear":
this.fillStyle=f=dojox.gfx.makeParameters(dojox.gfx.defaultLinearGradient,_2);
var _3=p.createFromXaml("<LinearGradientBrush/>");
_3.mappingMode="Absolute";
_3.startPoint=f.x1+","+f.y1;
_3.endPoint=f.x2+","+f.y2;
dojo.forEach(f.colors,function(c){
var t=p.createFromXaml("<GradientStop/>");
t.offset=c.offset;
t.color=dojox.gfx.silverlight.hexColor(c.color);
_3.gradientStops.add(t);
});
this._setFillAttr(_3);
break;
case "radial":
this.fillStyle=f=dojox.gfx.makeParameters(dojox.gfx.defaultRadialGradient,_2);
var _4=p.createFromXaml("<RadialGradientBrush/>"),c=dojox.gfx.matrix.multiplyPoint(dojox.gfx.matrix.invert(this._getAdjustedMatrix()),f.cx,f.cy),pt=c.x+","+c.y;
_4.mappingMode="Absolute";
_4.gradientOrigin=pt;
_4.center=pt;
_4.radiusX=_4.radiusY=f.r;
dojo.forEach(f.colors,function(c){
var t=p.createFromXaml("<GradientStop/>");
t.offset=c.offset;
t.color=dojox.gfx.silverlight.hexColor(c.color);
_4.gradientStops.add(t);
});
this._setFillAttr(_4);
break;
case "pattern":
this.fillStyle=null;
this._setFillAttr(null);
break;
}
return this;
}
this.fillStyle=f=dojox.gfx.normalizeColor(_2);
var _5=p.createFromXaml("<SolidColorBrush/>");
_5.color=f.toHex();
_5.opacity=f.a;
this._setFillAttr(_5);
return this;
},_setFillAttr:function(f){
this.rawNode.fill=f;
},setStroke:function(_6){
var p=this.rawNode.getHost().content,r=this.rawNode;
if(!_6){
this.strokeStyle=null;
r.stroke=null;
return this;
}
if(typeof _6=="string"||dojo.isArray(_6)||_6 instanceof dojo.Color){
_6={color:_6};
}
var s=this.strokeStyle=dojox.gfx.makeParameters(dojox.gfx.defaultStroke,_6);
s.color=dojox.gfx.normalizeColor(s.color);
if(s){
var _7=p.createFromXaml("<SolidColorBrush/>");
_7.color=s.color.toHex();
_7.opacity=s.color.a;
r.stroke=_7;
r.strokeThickness=s.width;
r.strokeStartLineCap=r.strokeEndLineCap=r.strokeDashCap=dojox.gfx.silverlight.caps[s.cap];
if(typeof s.join=="number"){
r.strokeLineJoin="Miter";
r.strokeMiterLimit=s.join;
}else{
r.strokeLineJoin=dojox.gfx.silverlight.joins[s.join];
}
var da=s.style.toLowerCase();
if(da in dojox.gfx.silverlight.dasharray){
da=dojox.gfx.silverlight.dasharray[da];
}
if(da instanceof Array){
da=dojo.clone(da);
var i;
if(s.cap!="butt"){
for(i=0;i<da.length;i+=2){
--da[i];
if(da[i]<1){
da[i]=1;
}
}
for(i=1;i<da.length;i+=2){
++da[i];
}
}
r.strokeDashArray=da.join(",");
}else{
r.strokeDashArray=null;
}
}
return this;
},_getParentSurface:function(){
var _8=this.parent;
for(;_8&&!(_8 instanceof dojox.gfx.Surface);_8=_8.parent){
}
return _8;
},_applyTransform:function(){
var tm=this._getAdjustedMatrix(),r=this.rawNode;
if(tm){
var p=this.rawNode.getHost().content,m=p.createFromXaml("<MatrixTransform/>"),mm=p.createFromXaml("<Matrix/>");
mm.m11=tm.xx;
mm.m21=tm.xy;
mm.m12=tm.yx;
mm.m22=tm.yy;
mm.offsetX=tm.dx;
mm.offsetY=tm.dy;
m.matrix=mm;
r.renderTransform=m;
}else{
r.renderTransform=null;
}
return this;
},setRawNode:function(_9){
_9.fill=null;
_9.stroke=null;
this.rawNode=_9;
},_moveToFront:function(){
var c=this.parent.rawNode.children,r=this.rawNode;
c.remove(r);
c.add(r);
return this;
},_moveToBack:function(){
var c=this.parent.rawNode.children,r=this.rawNode;
c.remove(r);
c.insert(0,r);
return this;
},_getAdjustedMatrix:function(){
return this.matrix;
}});
dojo.declare("dojox.gfx.Group",dojox.gfx.Shape,{constructor:function(){
dojox.gfx.silverlight.Container._init.call(this);
},setRawNode:function(_a){
this.rawNode=_a;
}});
dojox.gfx.Group.nodeType="Canvas";
dojo.declare("dojox.gfx.Rect",dojox.gfx.shape.Rect,{setShape:function(_b){
this.shape=dojox.gfx.makeParameters(this.shape,_b);
this.bbox=null;
var r=this.rawNode,n=this.shape;
r.width=n.width;
r.height=n.height;
r.radiusX=r.radiusY=n.r;
return this._applyTransform();
},_getAdjustedMatrix:function(){
var m=this.matrix,s=this.shape,d={dx:s.x,dy:s.y};
return new dojox.gfx.Matrix2D(m?[m,d]:d);
}});
dojox.gfx.Rect.nodeType="Rectangle";
dojo.declare("dojox.gfx.Ellipse",dojox.gfx.shape.Ellipse,{setShape:function(_c){
this.shape=dojox.gfx.makeParameters(this.shape,_c);
this.bbox=null;
var r=this.rawNode,n=this.shape;
r.width=2*n.rx;
r.height=2*n.ry;
return this._applyTransform();
},_getAdjustedMatrix:function(){
var m=this.matrix,s=this.shape,d={dx:s.cx-s.rx,dy:s.cy-s.ry};
return new dojox.gfx.Matrix2D(m?[m,d]:d);
}});
dojox.gfx.Ellipse.nodeType="Ellipse";
dojo.declare("dojox.gfx.Circle",dojox.gfx.shape.Circle,{setShape:function(_d){
this.shape=dojox.gfx.makeParameters(this.shape,_d);
this.bbox=null;
var r=this.rawNode,n=this.shape;
r.width=r.height=2*n.r;
return this._applyTransform();
},_getAdjustedMatrix:function(){
var m=this.matrix,s=this.shape,d={dx:s.cx-s.r,dy:s.cy-s.r};
return new dojox.gfx.Matrix2D(m?[m,d]:d);
}});
dojox.gfx.Circle.nodeType="Ellipse";
dojo.declare("dojox.gfx.Line",dojox.gfx.shape.Line,{setShape:function(_e){
this.shape=dojox.gfx.makeParameters(this.shape,_e);
this.bbox=null;
var r=this.rawNode,n=this.shape;
r.x1=n.x1;
r.y1=n.y1;
r.x2=n.x2;
r.y2=n.y2;
return this;
}});
dojox.gfx.Line.nodeType="Line";
dojo.declare("dojox.gfx.Polyline",dojox.gfx.shape.Polyline,{setShape:function(_f,_10){
if(_f&&_f instanceof Array){
this.shape=dojox.gfx.makeParameters(this.shape,{points:_f});
if(_10&&this.shape.points.length){
this.shape.points.push(this.shape.points[0]);
}
}else{
this.shape=dojox.gfx.makeParameters(this.shape,_f);
}
this.bbox=null;
this._normalizePoints();
var p=this.shape.points,rp=[];
for(var i=0;i<p.length;++i){
rp.push(p[i].x,p[i].y);
}
this.rawNode.points=rp.join(",");
return this;
}});
dojox.gfx.Polyline.nodeType="Polyline";
dojo.declare("dojox.gfx.Image",dojox.gfx.shape.Image,{setShape:function(_11){
this.shape=dojox.gfx.makeParameters(this.shape,_11);
this.bbox=null;
var r=this.rawNode,n=this.shape;
r.width=n.width;
r.height=n.height;
r.source=n.src;
return this._applyTransform();
},_getAdjustedMatrix:function(){
var m=this.matrix,s=this.shape,d={dx:s.x,dy:s.y};
return new dojox.gfx.Matrix2D(m?[m,d]:d);
},setRawNode:function(_12){
this.rawNode=_12;
}});
dojox.gfx.Image.nodeType="Image";
dojo.declare("dojox.gfx.Text",dojox.gfx.shape.Text,{setShape:function(_13){
this.shape=dojox.gfx.makeParameters(this.shape,_13);
this.bbox=null;
var r=this.rawNode,s=this.shape;
r.text=s.text;
r.textDecorations=s.decoration==="underline"?"Underline":"None";
r["Canvas.Left"]=-10000;
r["Canvas.Top"]=-10000;
if(!this._delay){
this._delay=window.setTimeout(dojo.hitch(this,"_delayAlignment"),10);
}
return this;
},_delayAlignment:function(){
var r=this.rawNode,s=this.shape,w=r.actualWidth,h=r.actualHeight,x=s.x,y=s.y-h*0.75;
switch(s.align){
case "middle":
x-=w/2;
break;
case "end":
x-=w;
break;
}
this._delta={dx:x,dy:y};
r["Canvas.Left"]=0;
r["Canvas.Top"]=0;
this._applyTransform();
delete this._delay;
},_getAdjustedMatrix:function(){
var m=this.matrix,d=this._delta,x;
if(m){
x=d?[m,d]:m;
}else{
x=d?d:{};
}
return new dojox.gfx.Matrix2D(x);
},setStroke:function(){
return this;
},_setFillAttr:function(f){
this.rawNode.foreground=f;
},setRawNode:function(_14){
this.rawNode=_14;
},getTextWidth:function(){
return this.rawNode.actualWidth;
}});
dojox.gfx.Text.nodeType="TextBlock";
dojo.declare("dojox.gfx.Path",dojox.gfx.path.Path,{_updateWithSegment:function(_15){
dojox.gfx.Path.superclass._updateWithSegment.apply(this,arguments);
var p=this.shape.path;
if(typeof (p)=="string"){
this.rawNode.data=p?p:null;
}
},setShape:function(_16){
dojox.gfx.Path.superclass.setShape.apply(this,arguments);
var p=this.shape.path;
this.rawNode.data=p?p:null;
return this;
}});
dojox.gfx.Path.nodeType="Path";
dojo.declare("dojox.gfx.TextPath",dojox.gfx.path.TextPath,{_updateWithSegment:function(_17){
},setShape:function(_18){
},_setText:function(){
}});
dojox.gfx.TextPath.nodeType="text";
dojox.gfx.silverlight.surfaces={};
dojox.gfx.silverlight.nullFunc=function(){
};
dojo.declare("dojox.gfx.Surface",dojox.gfx.shape.Surface,{constructor:function(){
dojox.gfx.silverlight.Container._init.call(this);
},destroy:function(){
window[this._onLoadName]=dojox.gfx.silverlight.nullFunc;
delete dojox.gfx.silverlight.surfaces[this.rawNode.name];
this.inherited(arguments);
},setDimensions:function(_19,_1a){
this.width=dojox.gfx.normalizedLength(_19);
this.height=dojox.gfx.normalizedLength(_1a);
var p=this.rawNode&&this.rawNode.getHost();
if(p){
p.width=_19;
p.height=_1a;
}
return this;
},getDimensions:function(){
var p=this.rawNode&&this.rawNode.getHost();
var t=p?{width:p.content.actualWidth,height:p.content.actualHeight}:null;
if(t.width<=0){
t.width=this.width;
}
if(t.height<=0){
t.height=this.height;
}
return t;
}});
dojox.gfx.createSurface=function(_1b,_1c,_1d){
if(!_1c&&!_1d){
var pos=d.position(_1b);
_1c=_1c||pos.w;
_1d=_1d||pos.h;
}
if(typeof _1c=="number"){
_1c=_1c+"px";
}
if(typeof _1d=="number"){
_1d=_1d+"px";
}
var s=new dojox.gfx.Surface();
_1b=dojo.byId(_1b);
s._parent=_1b;
var t=_1b.ownerDocument.createElement("script");
t.type="text/xaml";
t.id=dojox.gfx._base._getUniqueId();
t.text="<?xml version='1.0'?><Canvas xmlns='http://schemas.microsoft.com/client/2007' Name='"+dojox.gfx._base._getUniqueId()+"'/>";
_1b.parentNode.insertBefore(t,_1b);
s._nodes.push(t);
var obj,_1e=dojox.gfx._base._getUniqueId(),_1f="__"+dojox.gfx._base._getUniqueId()+"_onLoad";
s._onLoadName=_1f;
window[_1f]=function(_20){
if(!s.rawNode){
s.rawNode=dojo.byId(_1e).content.root;
dojox.gfx.silverlight.surfaces[s.rawNode.name]=_1b;
s.onLoad(s);
}
};
if(dojo.isSafari){
obj="<embed type='application/x-silverlight' id='"+_1e+"' width='"+_1c+"' height='"+_1d+" background='transparent'"+" source='#"+t.id+"'"+" windowless='true'"+" maxFramerate='60'"+" onLoad='"+_1f+"'"+" onError='__dojoSilverlightError'"+" /><iframe style='visibility:hidden;height:0;width:0'/>";
}else{
obj="<object type='application/x-silverlight' data='data:application/x-silverlight,' id='"+_1e+"' width='"+_1c+"' height='"+_1d+"'>"+"<param name='background' value='transparent' />"+"<param name='source' value='#"+t.id+"' />"+"<param name='windowless' value='true' />"+"<param name='maxFramerate' value='60' />"+"<param name='onLoad' value='"+_1f+"' />"+"<param name='onError' value='__dojoSilverlightError' />"+"</object>";
}
_1b.innerHTML=obj;
var _21=dojo.byId(_1e);
if(_21.content&&_21.content.root){
s.rawNode=_21.content.root;
dojox.gfx.silverlight.surfaces[s.rawNode.name]=_1b;
}else{
s.rawNode=null;
s.isLoaded=false;
}
s._nodes.push(_21);
s.width=dojox.gfx.normalizedLength(_1c);
s.height=dojox.gfx.normalizedLength(_1d);
return s;
};
__dojoSilverlightError=function(_22,err){
var t="Silverlight Error:\n"+"Code: "+err.ErrorCode+"\n"+"Type: "+err.ErrorType+"\n"+"Message: "+err.ErrorMessage+"\n";
switch(err.ErrorType){
case "ParserError":
t+="XamlFile: "+err.xamlFile+"\n"+"Line: "+err.lineNumber+"\n"+"Position: "+err.charPosition+"\n";
break;
case "RuntimeError":
t+="MethodName: "+err.methodName+"\n";
if(err.lineNumber!=0){
t+="Line: "+err.lineNumber+"\n"+"Position: "+err.charPosition+"\n";
}
break;
}
console.error(t);
};
dojox.gfx.silverlight.Font={_setFont:function(){
var f=this.fontStyle,r=this.rawNode,fw=dojox.gfx.silverlight.fontweight,fo=dojox.gfx.silverlight.fonts,t=f.family.toLowerCase();
r.fontStyle=f.style=="italic"?"Italic":"Normal";
r.fontWeight=f.weight in fw?fw[f.weight]:f.weight;
r.fontSize=dojox.gfx.normalizedLength(f.size);
r.fontFamily=t in fo?fo[t]:f.family;
if(!this._delay){
this._delay=window.setTimeout(dojo.hitch(this,"_delayAlignment"),10);
}
}};
dojox.gfx.silverlight.Container={_init:function(){
dojox.gfx.shape.Container._init.call(this);
},add:function(_23){
if(this!=_23.getParent()){
dojox.gfx.shape.Container.add.apply(this,arguments);
this.rawNode.children.add(_23.rawNode);
}
return this;
},remove:function(_24,_25){
if(this==_24.getParent()){
var _26=_24.rawNode.getParent();
if(_26){
_26.children.remove(_24.rawNode);
}
dojox.gfx.shape.Container.remove.apply(this,arguments);
}
return this;
},clear:function(){
this.rawNode.children.clear();
return dojox.gfx.shape.Container.clear.apply(this,arguments);
},_moveChildToFront:dojox.gfx.shape.Container._moveChildToFront,_moveChildToBack:dojox.gfx.shape.Container._moveChildToBack};
dojo.mixin(dojox.gfx.shape.Creator,{createObject:function(_27,_28){
if(!this.rawNode){
return null;
}
var _29=new _27();
var _2a=this.rawNode.getHost().content.createFromXaml("<"+_27.nodeType+"/>");
_29.setRawNode(_2a);
_29.setShape(_28);
this.add(_29);
return _29;
}});
dojo.extend(dojox.gfx.Text,dojox.gfx.silverlight.Font);
dojo.extend(dojox.gfx.Group,dojox.gfx.silverlight.Container);
dojo.extend(dojox.gfx.Group,dojox.gfx.shape.Creator);
dojo.extend(dojox.gfx.Surface,dojox.gfx.silverlight.Container);
dojo.extend(dojox.gfx.Surface,dojox.gfx.shape.Creator);
(function(){
var _2b=dojox.gfx.silverlight.surfaces;
var _2c=function(s,a){
var ev={target:s,currentTarget:s,preventDefault:function(){
},stopPropagation:function(){
}};
if(a){
try{
ev.ctrlKey=a.ctrl;
ev.shiftKey=a.shift;
var p=a.getPosition(null);
ev.x=ev.offsetX=ev.layerX=p.x;
ev.y=ev.offsetY=ev.layerY=p.y;
var _2d=_2b[s.getHost().content.root.name];
var t=dojo.position(_2d);
ev.clientX=t.x+p.x;
ev.clientY=t.y+p.y;
}
catch(e){
}
}
return ev;
};
var _2e=function(s,a){
var ev={keyCode:a.platformKeyCode,ctrlKey:a.ctrl,shiftKey:a.shift};
return ev;
};
var _2f={onclick:{name:"MouseLeftButtonUp",fix:_2c},onmouseenter:{name:"MouseEnter",fix:_2c},onmouseleave:{name:"MouseLeave",fix:_2c},onmouseover:{name:"MouseEnter",fix:_2c},onmouseout:{name:"MouseLeave",fix:_2c},onmousedown:{name:"MouseLeftButtonDown",fix:_2c},onmouseup:{name:"MouseLeftButtonUp",fix:_2c},onmousemove:{name:"MouseMove",fix:_2c},onkeydown:{name:"KeyDown",fix:_2e},onkeyup:{name:"KeyUp",fix:_2e}};
var _30={connect:function(_31,_32,_33){
var _34,n=_31 in _2f?_2f[_31]:{name:_31,fix:function(){
return {};
}};
if(arguments.length>2){
_34=this.getEventSource().addEventListener(n.name,function(s,a){
dojo.hitch(_32,_33)(n.fix(s,a));
});
}else{
_34=this.getEventSource().addEventListener(n.name,function(s,a){
_32(n.fix(s,a));
});
}
return {name:n.name,token:_34};
},disconnect:function(_35){
this.getEventSource().removeEventListener(_35.name,_35.token);
}};
dojo.extend(dojox.gfx.Shape,_30);
dojo.extend(dojox.gfx.Surface,_30);
dojox.gfx.equalSources=function(a,b){
return a&&b&&a.equals(b);
};
})();
}