text:
Imports Aspose.Email.Mail
Imports Aspose.Email.Mime

Namespace Aspose.Email.Examples.VisualBasic.Email.SMTP
    Class EmbeddedObjects
        Public Shared Sub Run()
            ' ExStart:EmbeddedObjects
            ' The path to the File directory.
            Dim dataDir As String = RunExamples.GetDataDir_Email()
            Dim dstEmail As String = dataDir & Convert.ToString("EmbeddedImage.msg")

            ' Create an instance of the MailMessage class and Set the addresses and Set the content
            Dim mail As New MailMessage()
            mail.From = New MailAddress("test001@gmail.com")
            mail.[To].Add("test001@gmail.com")
            mail.Subject = "This is an email"

            ' Create the plain text part It is viewable by those clients that don't support HTML
            Dim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content", Nothing, "text/plain")

            ' Create the HTML part.To embed images, we need to use the prefix 'cid' in the img src value.
            '            The cid value will map to the Content-Id of a Linked resource. Thus  will map to a LinkedResource with a ContentId of //'barcode'.

            Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.", Nothing, "text/html")

            ' Create the LinkedResource (embedded image) and Add the LinkedResource to the appropriate view
            Dim barcode As New LinkedResource(dataDir & Convert.ToString("1.jpg"), MediaTypeNames.Image.Jpeg) With { _
                .ContentId = "barcode" _
            }
            mail.LinkedResources.Add(barcode)
            mail.AlternateViews.Add(plainView)
            mail.AlternateViews.Add(htmlView)
            mail.Save(dstEmail, SaveOptions.DefaultMsgUnicode)
            ' ExEnd:EmbeddedObjects
            Console.WriteLine(Convert.ToString(Environment.NewLine + "Message saved with embedded objects successfully at ") & dstEmail)
        End Sub
    End Class
End Namespace


text:
import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import * as jQuery from 'jquery';
import { Router } from '@angular/router';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { EventService } from '../../../portal/services/event';
import { coreConfigConstant } from '../../../core/services/core-config';
import {
  FacebookService,
  InitParams,
  UIParams,
  UIResponse,
  LoginResponse
} from 'ng2-facebook-sdk';

@Component({
  // The selector is what angular internally uses
  // for `document.querySelectorAll(selector)` in our index.html
  // where, in this case, selector is the string 'event-modal'
  selector: 'event-modal',  // <event-modal></event-modal>
  // We need to tell Angular's Dependency Injection which providers are in our app.
  providers: [
    EventService
  ],
  // Our list of styles in our component. We may add more to compose many styles together
  styleUrls: ['./event-modal.style.scss'],
  // Every Angular template is first compiled by the browser before Angular runs it's compiler
  templateUrl: './event-modal.template.pug',
})

export class AdminEventModalComponent implements OnInit {
  @Input()
  public event: IEvent;
  public content: FormControl;

  constructor(
    public modalInstance: NgbActiveModal,
    private eventService: EventService,
    private toastr: ToastsManager,
    private router: Router,
    private fb: FacebookService
  ) {
    console.log('hello `event-modal` component');
    let initParams: InitParams = {
      appId: '753259471522465',
      xfbml: false,
      cookie: false,
      version: 'v2.9'
    };

    this.fb.init(initParams);

    this.content = new FormControl();
  }

  public ngOnInit(): void {
    this.content.setValue(this.event.description);
  }

  public share(): void {
    let url: string = coreConfigConstant.URL + '/#events';
    // let url: string = coreConfigConstant.URL + '/view/event/' + this.event.id;
    let el: HTMLElement = document.createElement('html');
    el.innerHTML = this.content.value;
    let images: any = el.getElementsByTagName('img');
    let image = images.length
      ? images[0].src
      : 'http://rendez-vous.lsoftwaresolutions.com/assets/images/text.png';
    let params: UIParams = {
      method: 'share_open_graph',
      action_type: 'og:share',
      action_properties: JSON.stringify({
        object: {
          'og:url': url,
          'og:title': 'Rendez Vous',
          'og:description': this.event.subject,
          'og:image': image
        }
      })
    };

    this.fb.ui(params)
      .then((res: UIResponse) => console.log(res))
      .catch((e: any) => console.error(e));
  }

  public addEvent(): void {
    this.event.description = this.content.value;
    this.modalInstance.close(this.event);
  }

  public changeContent(event: any): void {
    console.log(event);
  }
}

redpajama_set_name: RedPajamaGithub


text:
% LaTeX resume using res.cls
\documentclass[article]{res}

\usepackage[margin=0.75in]{geometry}
\addtolength{\topmargin}{-.225in}

%\usepackage{helvetica} % uses helvetica postscript font (download helvetica.sty)

%\usepackage{newcent}   % uses new century schoolbook postscript font
%\setlength{\textwidth}{5.1in} % set width of text portion
%Allows changed margins
\def\changemargin#1#2{\list{}{\rightmargin#2\leftmargin#1}\item[]}
\let\endchangemargin=\endlist

\begin{document}

% Center the name over the entire width of resume:
 \moveleft.5\hoffset\centerline{\Huge\bf Sam Kantor}
 \moveleft.5\hoffset\centerline{}
 \begin{changemargin}{-0.6cm}{0.5cm}
 {https://play.google.com/store/apps/developer?id=Sam+Kantor \hspace{43 pt} https://github.com/S-Kantor}
  \end{changemargin}
% Draw a horizontal line
\begin{changemargin}{-0.7cm}{2.5cm}
 {\noindent\rule{17cm}{0.5pt} }
 \end{changemargin}

% address begins here
% Again, the address lines must be centered over entire width of resume:

 \moveleft.5\hoffset\centerline{54 Loire Valley Avenue}
 \moveleft.5\hoffset\centerline{Thornhill, ON L4J-8R8}
 \moveleft.5\hoffset\centerline{Phone Number: (647) 713-3674}

\begin{resume}

\section{SKILLS} {\sl Proficient in:} Python, C, Racket, HTML5, CSS3, Git \\
{\sl Familiar with:} MySQL, Android, C++, \space \LaTeX \\
{\sl Platforms:} Windows, Linux (Ubuntu), Mac OS X, Arduino

\section{EDUCATION} {\sl Honours Mathematics Coop} \hfill Sept 2015 - April 2020   \\
                      % \sl will be bold italic in New Century Schoolbook (or
	              % any postscript font) and just slanted in
		      %	Computer Modern (default) font
                University of Waterloo, Waterloo, ON

\section{PROJECTS \&  EXPERIENCE} {\sl Android Developer} \hfill Sept 2014 - Present
                 \begin{itemize}  \itemsep -2pt %reduce space between items
                 \item Ontario Border Wait Times:
                 Developed an application to see the \\ delays for each of the Buffalo/ Niagara Falls bridges
                 	\begin{itemize} \itemsep -1pt
    				\item Built on Android Studio
    				\item Developed a parser to get the delay time from a live  XML feed
    				\item Used multi-threading for network requests
    				\item Built using W3C libraries for parsing
					\end{itemize}
                \item Risk Battle Simulator: Developed application for a client
                	\begin{itemize}  \itemsep -1pt
                	\item Built with Java math libraries
                	\item Ported logic from Python
					\end{itemize}
                \end{itemize}

                {\sl Hackathon project} \\
                WildHacks 2015 @ Northwestern University, IL \\
				LogBlocks. A big data visualizer for the Oculus Rift
				\begin {itemize} \itemsep -2pt
				\item Won sponsor API prize
				\item Worked on the front end development in a team of four
				\item Developed the API request script in python

				\end {itemize}

                {\sl Sales Associate} \hfill            Nov 2014 - Sept 2015 \\
                Best Buy Canada @ Richmond Hill, ON
                 \begin{itemize}  \itemsep -2pt %reduce space between items
                 \item Remarkable knowledge of customer service and experience in sales
                 \item Highest sales of insurance services in the district [in August 2015]
                 \item Promoted from seasonal employment to part time employment
                 \end{itemize}
                {\sl Web Developer} \hfill        April 2014 - Sept 2014 \\
                DECA Westmount (wcideca.com)
                  \begin{itemize} \itemsep -2pt
                   \item Worked on a team to develop custom plugins for WordPress
                   \item Contributed to the creation of a WordPress-based backend for DECA
                   \item Modified themes to fit site needs
                   \end{itemize}

\section{HOBBIES \&  ACTIVITIES}
 			Hobbies: Table Tennis, Billiards, Baseball \\
			Interests: Fantasy Hockey, Home Automation (Raspberry Pi \& Tasker), Travel
\end{resume}
\end{document}


text:
{% for page in site.pages %}
    {% if page.tags contains "about" %}
        {{ page.title }}
    {% endif %}
{% endfor %}
{% for page in site.pages %}
    {% if page.tags contains "style" %}
        {{ page.title }}
    {% endif %}
{% endfor %}


text:
<?php
/*
 * Generated by CRUDigniter v3.2
 * www.crudigniter.com
 */

class Package_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    /*
     * Get package by id
     */
    function get_package($id)
    {
        return $this->db->get_where('packages',array('packageid'=>$id))->row_array();
    }

    /*
     * Get all packages
     */
    function get_all_packages()
    {
        //$this->db->order_by('id', 'desc');
        return $this->db->get('packages')->result_array();
    }

    /*
     * function to add new package
     */
    function add_package($params)
    {
        $this->db->insert('packages',$params);
        return $this->db->insert_id();
    }

    /*
     * function to update package
     */
    function update_package($id,$params)
    {
        $this->db->where('packageid',$id);
        return $this->db->update('packages',$params);
    }

    /*
     * function to delete package
     */
    function delete_package($id)
    {
        return $this->db->delete('packages',array('packageid'=>$id));
    }
}


text:
/*
Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.
*/

'use strict'

/**
 * @param {number[]} digits
 * @return {number[]}
 */
const plusOne = function(digits) {
  let carry = true
  let i = digits.length - 1

  while (carry && (i >= 0)) {
    digits[i] = (digits[i] + 1) % 10
    carry = (digits[i] === 0);
    --i
  }

  if (carry) {
    digits.unshift(1)
  }

  return digits
}


text:
// Copyright 2013 Viewfinder. All rights reserved.
// Author: Marc Berhault
package co.viewfinder;

import co.viewfinder.proto.*;
import co.viewfinder.proto.CookieMetadataPB.CookieMetadata;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.google.protobuf.Message;
import com.loopj.android.http.*;
import java.io.InputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.MalformedURLException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.util.List;
import junit.framework.Assert;
import org.apache.http.HttpResponse;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
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.client.methods.HttpRequestBase;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.conn.ClientConnectionManager;
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.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

/**
 * Manage network interactions.
 */
public class NetworkManager {
  private static final String TAG = "viewfinder.NetworkManager";

  // Timeouts and period settings.
  private static final int HTTP_TIMEOUT_SECS = 60;

  // Threadpool settings.
  // TODO(marc): are those correct? If needed, we could use Runtime.getRuntime().availableProcessors();
  // Threadpool always keeps at least THREADPOOL_CORE_SIZE threads. If needed, it creates up to THREADPOOL_MAX_SIZE.
  // Extra idle threads get destroyed after THREADPOOL_KEEP_ALIVE_TIME (in THREADPOOL_KEEP_ALIVE_UNITS).
  private static final int THREADPOOL_CORE_SIZE = 2;
  private static final int THREADPOOL_MAX_SIZE = 4;
  private static final long THREADPOOL_KEEP_ALIVE_TIME = 10;
  private static final TimeUnit THREADPOOL_KEEP_ALIVE_UNIT = TimeUnit.SECONDS;

  private static AppState mAppState = null;

  // Pointer to the native NetworkManager.
  private final long mNativeNetworkManager;

  // Threadpool.
  private static ThreadPoolExecutor mExecutor;

  // Handler to schedule runnables on the UI thread.
  private static Handler mUIHandler;

  // Thread-safe http client.
  private static DefaultHttpClient mHttpClient;

  public NetworkManager(AppState appState, long nativePointer, boolean isProduction,
                        byte[] userCookie, byte[] xsrfCookie) {
    mAppState = appState;
    mNativeNetworkManager = nativePointer;
    mExecutor = new ThreadPoolExecutor(THREADPOOL_CORE_SIZE, THREADPOOL_MAX_SIZE,
                                       THREADPOOL_KEEP_ALIVE_TIME, THREADPOOL_KEEP_ALIVE_UNIT,
                                       new LinkedBlockingQueue<Runnable>());
    mUIHandler = new Handler(Looper.getMainLooper());
    initHttpClient(isProduction, userCookie, xsrfCookie);
  }

  public void onTerminate() {
    Log.d(TAG, "onDestroy");
  }

  private static void maybeUpdateCookies() {
    VFCookieStore store = (VFCookieStore) NetworkManager.getHttpClient().getCookieStore();
    if (!store.checkAndClearNewCookies()) {
      return;
    }

    byte[] userCookie = store.getRawUserCookie();
    byte[] xsrfCookie = store.getRawXsrfCookie();

    mAppState.setAuthCookies(userCookie, xsrfCookie);
  }

  /**
   * Custom cookie store that only keeps viewfinder cookies around.
   * TODO(marc): make this thread-safe.
   */
  public static class VFCookieStore implements CookieStore {
    private Cookie mUserCookie = null;
    private Cookie mXsrfCookie = null;
    private boolean mNewCookies = false;

    public VFCookieStore() { }

    public Cookie getUserCookie() { return mUserCookie; }
    public Cookie getXsrfCookie() { return mXsrfCookie; }

    public byte[] getRawUserCookie() {
      if (mUserCookie == null) {
        return null;
      }
      return serializeCookie(mUserCookie);
    }

    public byte[] getRawXsrfCookie() {
      if (mXsrfCookie == null) {
        return null;
      }
      return serializeCookie(mXsrfCookie);
    }

    public boolean checkAndClearNewCookies() {
      if (mNewCookies) {
        mNewCookies = false;
        return true;
      }
      return false;
    }

    private byte[] serializeCookie(Cookie cookie) {
      CookieMetadata.Builder builder = CookieMetadata.newBuilder();
      ServerUtils.maybeSetString(builder, "name", cookie.getName());
      ServerUtils.maybeSetString(builder, "value", cookie.getValue());
      ServerUtils.maybeSetString(builder, "comment", cookie.getComment());
      ServerUtils.maybeSetString(builder, "domain", cookie.getDomain());
      ServerUtils.maybeSetLong(builder, "expiry_date", cookie.getExpiryDate().getTime());
      ServerUtils.maybeSetString(builder, "path", cookie.getPath());
      ServerUtils.maybeSetInt(builder, "version", cookie.getVersion());
      builder.setIsSecure(cookie.isSecure());
      return builder.build().toByteArray();
    }

    private Cookie parseCookie(byte[] raw) {
      if (raw == null || raw.length == 0) {
        return null;
      }
      CookieMetadata cm;
      try {
        cm = CookieMetadata.parseFrom(raw);
      } catch (Exception e) {
        return null;
      }

      BasicClientCookie cookie = new BasicClientCookie(cm.getName(), cm.getValue());
      if (cm.hasComment())     cookie.setComment(cm.getComment());
      if (cm.hasDomain())      cookie.setDomain(cm.getDomain());
      if (cm.hasExpiryDate())  cookie.setExpiryDate(new Date(cm.getExpiryDate()));
      if (cm.hasPath())        cookie.setPath(cm.getPath());
      if (cm.hasVersion())     cookie.setVersion(cm.getVersion());
      if (cm.hasIsSecure())    cookie.setSecure(cm.getIsSecure());
      return cookie;
    }

    public void addRawCookie(byte[] raw) {
      Cookie c = parseCookie(raw);
      if (c != null) {
        addCookie(c);
      }
    }

    @Override
    public void addCookie(Cookie cookie) {
      String name = cookie.getName();
      if (name.equals("user")) {
        Log.i(TAG, "Got new user cookie");
        mUserCookie = cookie;
        mNewCookies = true;
      } else if (name.equals("_xsrf")) {
        Log.i(TAG, "Got new xsrf cookie");
        mXsrfCookie = cookie;
        mNewCookies = true;
      } else {
        Log.w(TAG, "Unknown cookie name: " + name);
      }
    }

    @Override
    public void clear() {
      mUserCookie = null;
      mXsrfCookie = null;
    }

    @Override
    public boolean clearExpired(Date date) {
      boolean ret = false;
      if (mUserCookie != null && mUserCookie.isExpired(date)) {
        mUserCookie = null;
        ret = true;
      }
      if (mXsrfCookie != null && mXsrfCookie.isExpired(date)) {
        mXsrfCookie = null;
      }
      return ret;
    }

    @Override
    public List<Cookie> getCookies() {
      ArrayList<Cookie> list = new ArrayList<Cookie>();
      if (mUserCookie != null) {
        list.add(mUserCookie);
      }
      if (mXsrfCookie != null) {
        list.add(mXsrfCookie);
      }
      return list;
    }
  }

  private static void initHttpClient(boolean isProduction, byte[] userCookie, byte[] xsrfCookie) {
    HttpParams params = new BasicHttpParams();

    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (isProduction) {
      registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {
      // Use a custom SSL factory when working on local backend.
      registry.register(new Scheme("https", newSslSocketFactory(), 443));
    }

    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
    mHttpClient = new DefaultHttpClient(connectionManager, params);
    HttpConnectionParams.setSoTimeout(mHttpClient.getParams(), HTTP_TIMEOUT_SECS * 1000);
    HttpConnectionParams.setConnectionTimeout(mHttpClient.getParams(), HTTP_TIMEOUT_SECS * 1000);
    // Don't handle redirects automatically.
    mHttpClient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    // Set the cookie policy. It still rejects cookies when hostnames don't match.
    mHttpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // Initialize our custom cookie store and add the user and xsrf cookies if non-null.
    VFCookieStore store = new VFCookieStore();
    store.addRawCookie(userCookie);
    store.addRawCookie(xsrfCookie);
    // New cookies come from the AppState, no need to set them again.
    store.checkAndClearNewCookies();
    mHttpClient.setCookieStore(store);
  }

  private static SSLSocketFactory newSslSocketFactory() {
    try {
      // Get an instance of the Bouncy Castle KeyStore format
      KeyStore trusted = KeyStore.getInstance("BKS");
      // Get the raw resource, which contains the keystore with
      // your trusted certificates (root and any intermediate certs)
      InputStream in = mAppState.getApplicationContext().getResources().openRawResource(R.raw.emulator_keystore);
      try {
        // Initialize the keystore with the provided trusted certificates
        // Also provide the password of the keystore
        trusted.load(in, "local_pwd".toCharArray());
      } finally {
        in.close();
      }
      // Pass the keystore to the SSLSocketFactory. The factory is responsible
      // for the verification of the server certificate.
      SSLSocketFactory sf = new SSLSocketFactory(trusted);
      // Hostname verification from certificate
      // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
      // Don't be too careful about SSL. For testing against local backends only.
      // sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      return sf;
    } catch (Exception e) {
      throw new AssertionError(e);
    }
  }

  public static DefaultHttpClient getHttpClient() {
    return mHttpClient;
  }

  // Add the runnable to the network threadpool.
  private static void dispatchNetwork(Runnable task) {
    mExecutor.execute(task);
  }

  // Run on the UI thread.
  private static void dispatchUI(Runnable task) {
    mUIHandler.post(task);
  }

  public static void sendRequest(long requestPointer, String url, String method, String body,
                                 String contentType, String contentMD5, String ifNoneMatch) {
    Log.i(TAG, "sendRequest: url=" + url + " method=" + method + " body=" + body);
    if (getHttpClient() == null) {
      // TODO(marc): figure out why the native network manager runs before our explicit dispatch.
      throw new java.lang.AssertionError("Java HTTP Client not yet initialized.");
    }

    AsyncHttpHandler mHandler = new AsyncHttpHandler(requestPointer, method, url, body,
                                                     contentType, contentMD5, ifNoneMatch);
    mHandler.execute();
  }

  public static class AsyncHttpHandler implements Runnable {
    private long mRequestPointer;
    private String mMethod;
    private String mUrl;
    private String mBody;
    private String mContentType;
    private String mContentMD5;
    private String mIfNoneMatch;
    private HttpHandler mHandler;

    public AsyncHttpHandler(long requestPointer, String method, String url, String body,
                            String contentType, String contentMD5, String ifNoneMatch) {
      mRequestPointer = requestPointer;
      mMethod = method;
      mUrl = url;
      mBody = body;
      mContentType = contentType;
      mContentMD5 = contentMD5;
      mIfNoneMatch = ifNoneMatch;
      mHandler = new HttpHandler(method, url, body, contentType, contentMD5, ifNoneMatch);
    }

    public void execute() {
      NetworkManager.dispatchNetwork(this);
    }

    @Override
    public void run() {
      mHandler.execute();

      Log.i(TAG, "got response: " + mHandler.responseCode());
      if (mHandler.responseCode() == -1) {
        // An exception was thrown. Call HandleError.
        HandleError(mRequestPointer, mHandler.exception().toString());
      } else if (mHandler.responseCode() == 301) {
        // Permanent redirect. Check that it's staging.
        Header redirectHeader = mHandler.response().getLastHeader("X-Vf-Staging-Redirect");
        if (redirectHeader == null) {
          Log.wtf(TAG, "Got redirect from backend but no X-Vf-Staging-Redirect redirect");
        }
        String redirectHost = redirectHeader.getValue();
        Log.d(TAG, "Got redirect: " + redirectHost);

        // Tell native code about the change.
        HandleRedirect(mRequestPointer, redirectHost);

        // Replace protocol://host:port from url.
        try {
          URL prevUrl = new URL(mUrl);
          URL newUrl = new URL(prevUrl.getProtocol(), redirectHost, prevUrl.getPort(), prevUrl.getFile());
          mUrl = newUrl.toString();
        } catch (MalformedURLException e) {
          Log.wtf(TAG, "Failed to parse previous URL even though we got a redirect from it: " + mUrl);
        }

        // Create new HttpHandler and execute.
        Log.d(TAG, "Reissuing request with redirect url=" + mUrl);
        mHandler = new HttpHandler(mMethod, mUrl, mBody, mContentType, mContentMD5, mIfNoneMatch);
        execute();
      } else {
        // We get the data all at once, so combine HandleData and HandleDone into a single call.
        HandleDone(mRequestPointer, mHandler.result(), mHandler.responseCode());
      }
    }
  }

  public static class HttpHandler {
    private DefaultHttpClient mClient;
    private HttpRequestBase mRequest;

    private int mResponseCode = -1;
    private String mResult = null;
    private HttpResponse mResponse = null;
    private Exception mException = null;

    // Typical for a GET request.
    public HttpHandler(String method, String url) {
      init(method, url, "", "", "", "");
    }

    // Typical for a POST request.
    public HttpHandler(String method, String url, String body, String contentType) {
      init(method, url, body, contentType, "", "");
    }

    // Typical for a PUT request.
    public HttpHandler(String method, String url, String body,
                       String contentType, String contentMD5, String ifNoneMatch) {
      init(method, url, body, contentType, contentMD5, ifNoneMatch);
    }

    private void init(String method, String url, String body,
                      String contentType, String contentMD5, String ifNoneMatch) {
      if (method.equals("GET")) {
        mRequest = new HttpGet(url);
        // GET does not have a body, or a setEntity method.
      } else if (method.equals("POST")) {
        HttpPost post = new HttpPost(url);
        try {
          if (!Utils.isEmptyOrNull(body))           post.setEntity(new StringEntity(body));
        } catch (UnsupportedEncodingException e) {
          Log.wtf(NetworkManager.TAG, "Unsupposed encoding for HttpPost.setEntity: " + body, e);
        }
        mRequest = post;
      } else if (method.equals("PUT")) {
        HttpPut put = new HttpPut(url);
        try {
          if (!Utils.isEmptyOrNull(body))           put.setEntity(new StringEntity(body));
        } catch (UnsupportedEncodingException e) {
          Log.wtf(NetworkManager.TAG, "Unsupposed encoding for HttpPut.setEntity: " + body, e);
        }
        mRequest = put;
      } else {
        Log.wtf(NetworkManager.TAG, "Unsupported HTTP method: " + method);
      }

      mClient = NetworkManager.getHttpClient();

      // Find the xsrf cookie.
      // TODO(marc): we should really do manual cookie handling and re-login when expired.
      String xsrfValue = getCookieValue(mClient.getCookieStore(), "_xsrf");
      if (!Utils.isEmptyOrNull(xsrfValue))      mRequest.setHeader("X-Xsrftoken", xsrfValue);

      // Set extra headers.
      if (!Utils.isEmptyOrNull(contentType))    mRequest.setHeader("Content-Type", contentType);
      if (!Utils.isEmptyOrNull(contentMD5))     mRequest.setHeader("Content-MD5", contentMD5);
      if (!Utils.isEmptyOrNull(ifNoneMatch))    mRequest.setHeader("If-None-Match", ifNoneMatch);
    }

    public String result() {
      return mResult;
    }

    public int responseCode() {
      return mResponseCode;
    }

    public HttpResponse response() {
      return mResponse;
    }

    public Exception exception() {
      return mException;
    }

    private String getCookieValue(CookieStore store, String name) {
      List<Cookie> cookies = store.getCookies();
      for (int i = 0; i < cookies.size(); ++i) {
        Cookie cookie = cookies.get(i);
        if (cookie.getName().equals(name)) {
          return cookie.getValue();
        }
      }
      return null;
    }

    public void execute() {
      Assert.assertNull(mResult);
      Assert.assertNull(mResponse);
      Assert.assertNull(mException);
      try {
        // Issue request.
        mResponse = mClient.execute(mRequest);

        // Extract status code and data.
        // TODO(marc): do we care about the rest of the StatusLine? (protocol version and reason phrase).
        mResponseCode = mResponse.getStatusLine().getStatusCode();
        HttpEntity entity = mResponse.getEntity();
        if (entity != null) {
          mResult = EntityUtils.toString(entity);
        }

        // Check if cookies have changed and push them down to native.
        maybeUpdateCookies();
      } catch (IOException e) {
        Log.e(NetworkManager.TAG, "Problem issuing request", e);
        mException = e;
      }
    }
  }

  /**
   * Callback for the Auth requests. Run on the UI thread.
   * Implement run() in instances.
   */
  public static class AuthResponseCallback implements Runnable {
    protected int mStatusCode;
    protected int mErrorId;
    protected String mErrorMsg;

    public AuthResponseCallback() { }

    public void done(int statusCode, int errorId, String errorMsg) {
      mStatusCode = statusCode;
      mErrorId = errorId;
      mErrorMsg = errorMsg;
    }

    @Override
    public void run() { }
  }

  // Singleton gatekeeper for auth requests. TODO: should this be in UI code?
  private static boolean mHasInflightAuthRequest = false;

  private void startAuthRequest() {
    if (mHasInflightAuthRequest) {
      Log.wtf(TAG, "We already have an in-flight auth request.");
    }
    mHasInflightAuthRequest = true;
  }

  public void sendAuthLogin(String identity, String password, AuthResponseCallback callback) {
    startAuthRequest();

    // TODO(marc): maybe pass NULL instead of empty string here and fix native side to check for it.
    // TODO(marc): proper identity management instead of AddIdentityPrefix.
    // TODO(marc): name formatting.
    AuthViewfinder(mNativeNetworkManager, "login", Utils.AddIdentityPrefix(identity),
                   password, "", "", "", true, callback);
  }

  public void sendAuthRegister(String identity, String first, String last, String password,
                               AuthResponseCallback callback) {
    startAuthRequest();

    String name = ContactManager.ConstructFullName(first, last);
    AuthViewfinder(mNativeNetworkManager, "register", Utils.AddIdentityPrefix(identity),
                   password, first, last, name, true, callback);
  }

  public void sendAuthReset(String identity, AuthResponseCallback callback) {
    startAuthRequest();

    AuthViewfinder(mNativeNetworkManager, "login_reset", Utils.AddIdentityPrefix(identity),
                   "", "", "", "", true, callback);
  }

  public void sendAuthVerify(String identity, String accessToken, AuthResponseCallback callback) {
    startAuthRequest();

    VerifyViewfinder(mNativeNetworkManager, Utils.AddIdentityPrefix(identity),
                     accessToken, true, callback);
  }

  public void sendChangePassword(String oldPassword, String newPassword, AuthResponseCallback callback) {
    startAuthRequest();

    ChangePassword(mNativeNetworkManager, oldPassword, newPassword, callback);
  }

  public static void authDone(Object callback, int statusCode, int errorId, String errorMsg) {
    if (!mHasInflightAuthRequest) {
      Log.wtf(TAG, "authDone() called but no in-flight auth requests.");
    }
    AuthResponseCallback cb = (AuthResponseCallback) callback;
    // Set variables for callback object.
    cb.done(statusCode, errorId, errorMsg);
    // Run on the UI thread.
    NetworkManager.dispatchUI(cb);
    mHasInflightAuthRequest = false;
  }

  // NetworkRequest native methods.
  private static native void AuthViewfinder(long net_mgr, String endpoint, String identity, String password,
                                            String first, String last, String name, boolean error_if_linked,
                                            Object callback);
  private static native void ChangePassword(long net_mgr, String oldPassword, String newPassword, Object callback);
  private static native void VerifyViewfinder(long net_mgr, String identity, String access_token, boolean manual_entry,
                                              Object callback);
  private static native void HandleError(long request, String e);
  // TODO(marc): use byte[] data once java no longer calls the network manager.
  private static native void HandleDone(long request, String data, int code);
  private static native void HandleRedirect(long request, String redirectHost);
}


text:
package org.apache.hadoop.hbase.io.hfile.bucket;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.io.ByteBuffAllocator;
import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
import org.apache.hadoop.hbase.io.hfile.BlockCacheUtil;
import org.apache.hadoop.hbase.io.hfile.BlockType;
import org.apache.hadoop.hbase.io.hfile.Cacheable;
import org.apache.hadoop.hbase.io.hfile.HFileBlock;
import org.apache.hadoop.hbase.io.hfile.HFileContext;
import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
import org.apache.hadoop.hbase.io.hfile.bucket.BucketCache.WriterThread;
import org.apache.hadoop.hbase.nio.ByteBuff;
import org.apache.hadoop.hbase.nio.RefCnt;
import org.apache.hadoop.hbase.testclassification.IOTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({ IOTests.class, SmallTests.class })
public class TestBucketCacheRefCnt {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestBucketCacheRefCnt.class);

  private static final String IO_ENGINE = "offheap";
  private static final long CAPACITY_SIZE = 32 * 1024 * 1024;
  private static final int BLOCK_SIZE = 1024;
  private static final int[] BLOCK_SIZE_ARRAY =
    new int[] { 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
  private static final String PERSISTENCE_PATH = null;
  private static final HFileContext CONTEXT = new HFileContextBuilder().build();

  private BucketCache cache;

  private static BucketCache create(int writerSize, int queueSize) throws IOException {
    return new BucketCache(IO_ENGINE, CAPACITY_SIZE, BLOCK_SIZE, BLOCK_SIZE_ARRAY, writerSize,
      queueSize, PERSISTENCE_PATH);
  }

  private static MyBucketCache createMyBucketCache(int writerSize, int queueSize)
    throws IOException {
    return new MyBucketCache(IO_ENGINE, CAPACITY_SIZE, BLOCK_SIZE, BLOCK_SIZE_ARRAY, writerSize,
      queueSize, PERSISTENCE_PATH);
  }

  private static MyBucketCache2 createMyBucketCache2(int writerSize, int queueSize)
    throws IOException {
    return new MyBucketCache2(IO_ENGINE, CAPACITY_SIZE, BLOCK_SIZE, BLOCK_SIZE_ARRAY, writerSize,
      queueSize, PERSISTENCE_PATH);
  }

  private static HFileBlock createBlock(int offset, int size) {
    return createBlock(offset, size, ByteBuffAllocator.HEAP);
  }

  private static HFileBlock createBlock(int offset, int size, ByteBuffAllocator alloc) {
    return new HFileBlock(BlockType.DATA, size, size, -1, ByteBuff.wrap(ByteBuffer.allocate(size)),
      HFileBlock.FILL_HEADER, offset, 52, size, CONTEXT, alloc);
  }

  private static BlockCacheKey createKey(String hfileName, long offset) {
    return new BlockCacheKey(hfileName, offset);
  }

  private void disableWriter() {
    if (cache != null) {
      for (WriterThread wt : cache.writerThreads) {
        wt.disableWriter();
        wt.interrupt();
      }
    }
  }

  @org.junit.Ignore
  @Test // Disabled by HBASE-24079. Reenable issue HBASE-24082
  // Flakey TestBucketCacheRefCnt.testBlockInRAMCache:121 expected:<3> but was:<2>
  public void testBlockInRAMCache() throws IOException {
    cache = create(1, 1000);
    // Set this to true;
    cache.wait_when_cache = true;
    disableWriter();
    final String prefix = "testBlockInRamCache";
    try {
      for (int i = 0; i < 10; i++) {
        HFileBlock blk = createBlock(i, 1020);
        BlockCacheKey key = createKey(prefix, i);
        assertEquals(1, blk.refCnt());
        cache.cacheBlock(key, blk);
        assertEquals(i + 1, cache.getBlockCount());
        assertEquals(2, blk.refCnt());

        Cacheable block = cache.getBlock(key, false, false, false);
        try {
          assertEquals(3, blk.refCnt());
          assertEquals(3, block.refCnt());
          assertEquals(blk, block);
        } finally {
          block.release();
        }
        assertEquals(2, blk.refCnt());
        assertEquals(2, block.refCnt());
      }

      for (int i = 0; i < 10; i++) {
        BlockCacheKey key = createKey(prefix, i);
        Cacheable blk = cache.getBlock(key, false, false, false);
        assertEquals(3, blk.refCnt());
        assertFalse(blk.release());
        assertEquals(2, blk.refCnt());

        assertTrue(cache.evictBlock(key));
        assertEquals(1, blk.refCnt());
        assertTrue(blk.release());
        assertEquals(0, blk.refCnt());
      }
    } finally {
      cache.shutdown();
    }
  }

  private static void waitUntilFlushedToCache(BucketCache bucketCache, BlockCacheKey blockCacheKey)
    throws InterruptedException {
    while (
      !bucketCache.backingMap.containsKey(blockCacheKey)
        || bucketCache.ramCache.containsKey(blockCacheKey)
    ) {
      Thread.sleep(100);
    }
    Thread.sleep(1000);
  }

  @Test
  public void testBlockInBackingMap() throws Exception {
    ByteBuffAllocator alloc = ByteBuffAllocator.create(HBaseConfiguration.create(), true);
    cache = create(1, 1000);
    try {
      HFileBlock blk = createBlock(200, 1020, alloc);
      BlockCacheKey key = createKey("testHFile-00", 200);
      cache.cacheBlock(key, blk);
      waitUntilFlushedToCache(cache, key);
      assertEquals(1, blk.refCnt());

      Cacheable block = cache.getBlock(key, false, false, false);
      assertTrue(block instanceof HFileBlock);
      assertTrue(((HFileBlock) block).getByteBuffAllocator() == alloc);
      assertEquals(2, block.refCnt());

      block.retain();
      assertEquals(3, block.refCnt());

      Cacheable newBlock = cache.getBlock(key, false, false, false);
      assertTrue(newBlock instanceof HFileBlock);
      assertTrue(((HFileBlock) newBlock).getByteBuffAllocator() == alloc);
      assertEquals(4, newBlock.refCnt());

      // release the newBlock
      assertFalse(newBlock.release());
      assertEquals(3, newBlock.refCnt());
      assertEquals(3, block.refCnt());

      // Evict the key
      cache.evictBlock(key);
      assertEquals(2, block.refCnt());

      // Evict again, shouldn't change the refCnt.
      cache.evictBlock(key);
      assertEquals(2, block.refCnt());

      assertFalse(block.release());
      assertEquals(1, block.refCnt());

      /**
       * The key was evicted from {@link BucketCache#backingMap} and {@link BucketCache#ramCache},
       * so {@link BucketCache#getBlock} return null.
       */
      Cacheable newestBlock = cache.getBlock(key, false, false, false);
      assertNull(newestBlock);
      assertEquals(1, block.refCnt());
      assertTrue(((HFileBlock) newBlock).getByteBuffAllocator() == alloc);

      // Release the block
      assertTrue(block.release());
      assertEquals(0, block.refCnt());
      assertEquals(0, newBlock.refCnt());
    } finally {
      cache.shutdown();
    }
  }

  @Test
  public void testInBucketCache() throws IOException {
    ByteBuffAllocator alloc = ByteBuffAllocator.create(HBaseConfiguration.create(), true);
    cache = create(1, 1000);
    try {
      HFileBlock blk = createBlock(200, 1020, alloc);
      BlockCacheKey key = createKey("testHFile-00", 200);
      cache.cacheBlock(key, blk);
      assertTrue(blk.refCnt() == 1 || blk.refCnt() == 2);

      Cacheable block1 = cache.getBlock(key, false, false, false);
      assertTrue(block1.refCnt() >= 2);
      assertTrue(((HFileBlock) block1).getByteBuffAllocator() == alloc);

      Cacheable block2 = cache.getBlock(key, false, false, false);
      assertTrue(((HFileBlock) block2).getByteBuffAllocator() == alloc);
      assertTrue(block2.refCnt() >= 3);

      cache.evictBlock(key);
      assertTrue(blk.refCnt() >= 1);
      assertTrue(block1.refCnt() >= 2);
      assertTrue(block2.refCnt() >= 2);

      // Get key again
      Cacheable block3 = cache.getBlock(key, false, false, false);
      if (block3 != null) {
        assertTrue(((HFileBlock) block3).getByteBuffAllocator() == alloc);
        assertTrue(block3.refCnt() >= 3);
        assertFalse(block3.release());
      }

      blk.release();
      boolean ret1 = block1.release();
      boolean ret2 = block2.release();
      assertTrue(ret1 || ret2);
      assertEquals(0, blk.refCnt());
      assertEquals(0, block1.refCnt());
      assertEquals(0, block2.refCnt());
    } finally {
      cache.shutdown();
    }
  }

  @Test
  public void testMarkStaleAsEvicted() throws Exception {
    cache = create(1, 1000);
    try {
      HFileBlock blk = createBlock(200, 1020);
      BlockCacheKey key = createKey("testMarkStaleAsEvicted", 200);
      cache.cacheBlock(key, blk);
      waitUntilFlushedToCache(cache, key);
      assertEquals(1, blk.refCnt());
      assertNotNull(cache.backingMap.get(key));
      assertEquals(1, cache.backingMap.get(key).refCnt());

      // RPC reference this cache.
      Cacheable block1 = cache.getBlock(key, false, false, false);
      assertEquals(2, block1.refCnt());
      BucketEntry be1 = cache.backingMap.get(key);
      assertNotNull(be1);
      assertEquals(2, be1.refCnt());

      // We've some RPC reference, so it won't have any effect.
      assertFalse(cache.evictBucketEntryIfNoRpcReferenced(key, be1));
      assertEquals(2, block1.refCnt());
      assertEquals(2, cache.backingMap.get(key).refCnt());

      // Release the RPC reference.
      block1.release();
      assertEquals(1, block1.refCnt());
      assertEquals(1, cache.backingMap.get(key).refCnt());

      // Mark the stale as evicted again, it'll do the de-allocation.
      assertTrue(cache.evictBucketEntryIfNoRpcReferenced(key, be1));
      assertEquals(0, block1.refCnt());
      assertNull(cache.backingMap.get(key));
      assertEquals(0, cache.size());
    } finally {
      cache.shutdown();
    }
  }

  /**
   *

   * This test is for HBASE-26281,
   * test two threads for replacing Block and getting Block execute concurrently.
   * The threads sequence is:
   * 1. Block1 was cached successfully,the {@link RefCnt} of Block1 is 1.
   * 2. Thread1 caching the same {@link BlockCacheKey} with Block2 satisfied
   *    {@link BlockCacheUtil#shouldReplaceExistingCacheBlock}, so Block2 would
   *    replace Block1, but thread1 stopping before {@link BucketCache#cacheBlockWithWaitInternal}
   * 3. Thread2 invoking {@link BucketCache#getBlock} with the same {@link BlockCacheKey},
   *    which returned Block1, the {@link RefCnt} of Block1 is 2.
   * 4. Thread1 continues caching Block2, in {@link BucketCache.WriterThread#putIntoBackingMap},
   *    the old Block1 is freed directly which {@link RefCnt} is 2, but the Block1 is still used
   *    by Thread2 and the content of Block1 would be overwritten after it is freed, which may
   *    cause a serious error.
   *

   *
   * n
   */
  @Test
  public void testReplacingBlockAndGettingBlockConcurrently() throws Exception {
    ByteBuffAllocator byteBuffAllocator =
      ByteBuffAllocator.create(HBaseConfiguration.create(), true);
    final MyBucketCache myBucketCache = createMyBucketCache(1, 1000);
    try {
      HFileBlock hfileBlock = createBlock(200, 1020, byteBuffAllocator);
      final BlockCacheKey blockCacheKey = createKey("testTwoThreadConcurrent", 200);
      myBucketCache.cacheBlock(blockCacheKey, hfileBlock);
      waitUntilFlushedToCache(myBucketCache, blockCacheKey);
      assertEquals(1, hfileBlock.refCnt());

      assertTrue(!myBucketCache.ramCache.containsKey(blockCacheKey));
      final AtomicReference<Throwable> exceptionRef = new AtomicReference<Throwable>();
      Thread cacheBlockThread = new Thread(() -> {
        try {
          HFileBlock newHFileBlock = createBlock(200, 1020, byteBuffAllocator);
          myBucketCache.cacheBlock(blockCacheKey, newHFileBlock);
          waitUntilFlushedToCache(myBucketCache, blockCacheKey);

        } catch (Throwable exception) {
          exceptionRef.set(exception);
        }
      });
      cacheBlockThread.setName(MyBucketCache.CACHE_BLOCK_THREAD_NAME);
      cacheBlockThread.start();

      String oldThreadName = Thread.currentThread().getName();
      HFileBlock gotHFileBlock = null;
      try {

        Thread.currentThread().setName(MyBucketCache.GET_BLOCK_THREAD_NAME);

        gotHFileBlock = (HFileBlock) (myBucketCache.getBlock(blockCacheKey, false, false, false));
        assertTrue(gotHFileBlock.equals(hfileBlock));
        assertTrue(gotHFileBlock.getByteBuffAllocator() == byteBuffAllocator);
        assertEquals(2, gotHFileBlock.refCnt());
        /**
         * Release the second cyclicBarrier.await in
         * {@link MyBucketCache#cacheBlockWithWaitInternal}
         */
        myBucketCache.cyclicBarrier.await();

      } finally {
        Thread.currentThread().setName(oldThreadName);
      }

      cacheBlockThread.join();
      assertTrue(exceptionRef.get() == null);
      assertEquals(1, gotHFileBlock.refCnt());
      assertTrue(gotHFileBlock.equals(hfileBlock));
      assertTrue(myBucketCache.overwiteByteBuff == null);
      assertTrue(myBucketCache.freeBucketEntryCounter.get() == 0);

      gotHFileBlock.release();
      assertEquals(0, gotHFileBlock.refCnt());
      assertTrue(myBucketCache.overwiteByteBuff != null);
      assertTrue(myBucketCache.freeBucketEntryCounter.get() == 1);
      assertTrue(myBucketCache.replaceCounter.get() == 1);
      assertTrue(myBucketCache.blockEvictCounter.get() == 1);
    } finally {
      myBucketCache.shutdown();
    }

  }

  /**
   *

   * This test also is for HBASE-26281,
   * test three threads for evicting Block,caching Block and getting Block
   * execute concurrently.
   * 1. Thread1 caching Block1, stopping after {@link BucketCache.WriterThread#putIntoBackingMap},
   *    the {@link RefCnt} of Block1 is 1.
   * 2. Thread2 invoking {@link BucketCache#evictBlock} with the same {@link BlockCacheKey},
   *    but stopping after {@link BucketCache#removeFromRamCache}.
   * 3. Thread3 invoking {@link BucketCache#getBlock} with the same {@link BlockCacheKey},
   *    which returned Block1, the {@link RefCnt} of Block1 is 2.
   * 4. Thread1 continues caching block1,but finding that {@link BucketCache.RAMCache#remove}
   *    returning false, so invoking {@link BucketCache#blockEvicted} to free the the Block1
   *    directly which {@link RefCnt} is 2 and the Block1 is still used by Thread3.
   *

   */
  @Test
  public void testEvictingBlockCachingBlockGettingBlockConcurrently() throws Exception {
    ByteBuffAllocator byteBuffAllocator =
      ByteBuffAllocator.create(HBaseConfiguration.create(), true);
    final MyBucketCache2 myBucketCache2 = createMyBucketCache2(1, 1000);
    try {
      final HFileBlock hfileBlock = createBlock(200, 1020, byteBuffAllocator);
      final BlockCacheKey blockCacheKey = createKey("testThreeThreadConcurrent", 200);
      final AtomicReference<Throwable> cacheBlockThreadExceptionRef =
        new AtomicReference<Throwable>();
      Thread cacheBlockThread = new Thread(() -> {
        try {
          myBucketCache2.cacheBlock(blockCacheKey, hfileBlock);
          /**
           * Wait for Caching Block completed.
           */
          myBucketCache2.writeThreadDoneCyclicBarrier.await();
        } catch (Throwable exception) {
          cacheBlockThreadExceptionRef.set(exception);
        }
      });
      cacheBlockThread.setName(MyBucketCache2.CACHE_BLOCK_THREAD_NAME);
      cacheBlockThread.start();

      final AtomicReference<Throwable> evictBlockThreadExceptionRef =
        new AtomicReference<Throwable>();
      Thread evictBlockThread = new Thread(() -> {
        try {
          myBucketCache2.evictBlock(blockCacheKey);
        } catch (Throwable exception) {
          evictBlockThreadExceptionRef.set(exception);
        }
      });
      evictBlockThread.setName(MyBucketCache2.EVICT_BLOCK_THREAD_NAME);
      evictBlockThread.start();

      String oldThreadName = Thread.currentThread().getName();
      HFileBlock gotHFileBlock = null;
      try {
        Thread.currentThread().setName(MyBucketCache2.GET_BLOCK_THREAD_NAME);
        gotHFileBlock = (HFileBlock) (myBucketCache2.getBlock(blockCacheKey, false, false, false));
        assertTrue(gotHFileBlock.equals(hfileBlock));
        assertTrue(gotHFileBlock.getByteBuffAllocator() == byteBuffAllocator);
        assertEquals(2, gotHFileBlock.refCnt());
        try {
          /**
           * Release the second cyclicBarrier.await in {@link MyBucketCache2#putIntoBackingMap} for
           * {@link BucketCache.WriterThread},getBlock completed,{@link BucketCache.WriterThread}
           * could continue.
           */
          myBucketCache2.putCyclicBarrier.await();
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }

      } finally {
        Thread.currentThread().setName(oldThreadName);
      }

      cacheBlockThread.join();
      evictBlockThread.join();
      assertTrue(cacheBlockThreadExceptionRef.get() == null);
      assertTrue(evictBlockThreadExceptionRef.get() == null);

      assertTrue(gotHFileBlock.equals(hfileBlock));
      assertEquals(1, gotHFileBlock.refCnt());
      assertTrue(myBucketCache2.overwiteByteBuff == null);
      assertTrue(myBucketCache2.freeBucketEntryCounter.get() == 0);

      gotHFileBlock.release();
      assertEquals(0, gotHFileBlock.refCnt());
      assertTrue(myBucketCache2.overwiteByteBuff != null);
      assertTrue(myBucketCache2.freeBucketEntryCounter.get() == 1);
      assertTrue(myBucketCache2.blockEvictCounter.get() == 1);
    } finally {
      myBucketCache2.shutdown();
    }

  }

  static class MyBucketCache extends BucketCache {
    private static final String GET_BLOCK_THREAD_NAME = "_getBlockThread";
    private static final String CACHE_BLOCK_THREAD_NAME = "_cacheBlockThread";

    private final CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
    private final AtomicInteger replaceCounter = new AtomicInteger(0);
    private final AtomicInteger blockEvictCounter = new AtomicInteger(0);
    private final AtomicInteger freeBucketEntryCounter = new AtomicInteger(0);
    private ByteBuff overwiteByteBuff = null;

    public MyBucketCache(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
      int writerThreadNum, int writerQLen, String persistencePath) throws IOException {
      super(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
        persistencePath);
    }

    /**
     * Simulate the Block could be replaced.
     */
    @Override
    protected boolean shouldReplaceExistingCacheBlock(BlockCacheKey cacheKey, Cacheable newBlock) {
      replaceCounter.incrementAndGet();
      return true;
    }

    @Override
    public Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat,
      boolean updateCacheMetrics) {
      if (Thread.currentThread().getName().equals(GET_BLOCK_THREAD_NAME)) {
        /**
         * Wait the first cyclicBarrier.await() in {@link MyBucketCache#cacheBlockWithWaitInternal},
         * so the {@link BucketCache#getBlock} is executed after the {@link BucketEntry#isRpcRef}
         * checking.
         */
        try {
          cyclicBarrier.await();
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      Cacheable result = super.getBlock(key, caching, repeat, updateCacheMetrics);
      return result;
    }

    @Override
    protected void cacheBlockWithWaitInternal(BlockCacheKey cacheKey, Cacheable cachedItem,
      boolean inMemory, boolean wait) {
      if (Thread.currentThread().getName().equals(CACHE_BLOCK_THREAD_NAME)) {
        /**
         * Wait the cyclicBarrier.await() in {@link MyBucketCache#getBlock}
         */
        try {
          cyclicBarrier.await();
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      if (Thread.currentThread().getName().equals(CACHE_BLOCK_THREAD_NAME)) {
        /**
         * Wait the cyclicBarrier.await() in
         * {@link TestBucketCacheRefCnt#testReplacingBlockAndGettingBlockConcurrently} for
         * {@link MyBucketCache#getBlock} and Assert completed.
         */
        try {
          cyclicBarrier.await();
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      super.cacheBlockWithWaitInternal(cacheKey, cachedItem, inMemory, wait);
    }

    @Override
    void blockEvicted(BlockCacheKey cacheKey, BucketEntry bucketEntry, boolean decrementBlockNumber,
      boolean evictedByEvictionProcess) {
      blockEvictCounter.incrementAndGet();
      super.blockEvicted(cacheKey, bucketEntry, decrementBlockNumber, evictedByEvictionProcess);
    }

    /**
     * Overwrite 0xff to the {@link BucketEntry} content to simulate it would be overwrite after the
     * {@link BucketEntry} is freed.
     */
    @Override
    void freeBucketEntry(BucketEntry bucketEntry) {
      freeBucketEntryCounter.incrementAndGet();
      super.freeBucketEntry(bucketEntry);
      this.overwiteByteBuff = getOverwriteByteBuff(bucketEntry);
      try {
        this.ioEngine.write(this.overwiteByteBuff, bucketEntry.offset());
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

  static class MyBucketCache2 extends BucketCache {
    private static final String GET_BLOCK_THREAD_NAME = "_getBlockThread";
    private static final String CACHE_BLOCK_THREAD_NAME = "_cacheBlockThread";
    private static final String EVICT_BLOCK_THREAD_NAME = "_evictBlockThread";

    private final CyclicBarrier getCyclicBarrier = new CyclicBarrier(2);
    private final CyclicBarrier evictCyclicBarrier = new CyclicBarrier(2);
    private final CyclicBarrier putCyclicBarrier = new CyclicBarrier(2);
    /**
     * This is used for {@link BucketCache.WriterThread},{@link #CACHE_BLOCK_THREAD_NAME} and
     * {@link #EVICT_BLOCK_THREAD_NAME},waiting for caching block completed.
     */
    private final CyclicBarrier writeThreadDoneCyclicBarrier = new CyclicBarrier(3);
    private final AtomicInteger blockEvictCounter = new AtomicInteger(0);
    private final AtomicInteger removeRamCounter = new AtomicInteger(0);
    private final AtomicInteger freeBucketEntryCounter = new AtomicInteger(0);
    private ByteBuff overwiteByteBuff = null;

    public MyBucketCache2(String ioEngineName, long capacity, int blockSize, int[] bucketSizes,
      int writerThreadNum, int writerQLen, String persistencePath) throws IOException {
      super(ioEngineName, capacity, blockSize, bucketSizes, writerThreadNum, writerQLen,
        persistencePath);
    }

    @Override
    protected void putIntoBackingMap(BlockCacheKey key, BucketEntry bucketEntry) {
      super.putIntoBackingMap(key, bucketEntry);
      /**
       * The {@link BucketCache.WriterThread} wait for evictCyclicBarrier.await before
       * {@link MyBucketCache2#removeFromRamCache} for {@link #EVICT_BLOCK_THREAD_NAME}
       */
      try {
        evictCyclicBarrier.await();
      } catch (Throwable e) {
        throw new RuntimeException(e);
      }

      /**
       * Wait the cyclicBarrier.await() in
       * {@link TestBucketCacheRefCnt#testEvictingBlockCachingBlockGettingBlockConcurrently} for
       * {@link MyBucketCache#getBlock} and Assert completed.
       */
      try {
        putCyclicBarrier.await();
      } catch (Throwable e) {
        throw new RuntimeException(e);
      }
    }

    @Override
    void doDrain(List<RAMQueueEntry> entries, ByteBuffer metaBuff) throws InterruptedException {
      super.doDrain(entries, metaBuff);
      if (entries.size() > 0) {
        /**
         * Caching Block completed,release {@link #GET_BLOCK_THREAD_NAME} and
         * {@link #EVICT_BLOCK_THREAD_NAME}.
         */
        try {
          writeThreadDoneCyclicBarrier.await();
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }

    }

    @Override
    public Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat,
      boolean updateCacheMetrics) {
      if (Thread.currentThread().getName().equals(GET_BLOCK_THREAD_NAME)) {
        /**
         * Wait for second getCyclicBarrier.await in {@link MyBucketCache2#removeFromRamCache} after
         * {@link BucketCache#removeFromRamCache}.
         */
        try {
          getCyclicBarrier.await();
        } catch (Throwable e) {
          throw new RuntimeException(e);
        }
      }
      Cacheable result = super.getBlock(key, caching, repeat, updateCacheMetrics);
      return result;
    }

    @Override
    protected boolean removeFromRamCache(BlockCacheKey cacheKey) {
      boolean firstTime = false;
      if (Thread.currentThread().getName().equals(EVICT_BLOCK_THREAD_NAME)) {
        int count = this.removeRamCounter.incrementAndGet();
        firstTime = (count == 1);
        if (firstTime) {
          /**
           * The {@link #EVICT_BLOCK_THREAD_NAME} wait for evictCyclicBarrier.await after
           * {@link BucketCache#putIntoBackingMap}.
           */
          try {
            evictCyclicBarrier.await();
          } catch (Throwable e) {
            throw new RuntimeException(e);
          }
        }
      }
      boolean result = super.removeFromRamCache(cacheKey);
      if (Thread.currentThread().getName().equals(EVICT_BLOCK_THREAD_NAME)) {
        if (firstTime) {
          /**
           * Wait for getCyclicBarrier.await before {@link BucketCache#getBlock}.
           */
          try {
            getCyclicBarrier.await();
          } catch (Throwable e) {
            throw new RuntimeException(e);
          }
          /**
           * Wait for Caching Block completed, after Caching Block completed, evictBlock could
           * continue.
           */
          try {
            writeThreadDoneCyclicBarrier.await();
          } catch (Throwable e) {
            throw new RuntimeException(e);
          }
        }
      }

      return result;
    }

    @Override
    void blockEvicted(BlockCacheKey cacheKey, BucketEntry bucketEntry, boolean decrementBlockNumber,
      boolean evictedByEvictionProcess) {
      /**
       * This is only invoked by {@link BucketCache.WriterThread}. {@link MyMyBucketCache2} create
       * only one {@link BucketCache.WriterThread}.
       */
      assertTrue(Thread.currentThread() == this.writerThreads[0]);

      blockEvictCounter.incrementAndGet();
      super.blockEvicted(cacheKey, bucketEntry, decrementBlockNumber, evictedByEvictionProcess);
    }

    /**
     * Overwrite 0xff to the {@link BucketEntry} content to simulate it would be overwrite after the
     * {@link BucketEntry} is freed.
     */
    @Override
    void freeBucketEntry(BucketEntry bucketEntry) {
      freeBucketEntryCounter.incrementAndGet();
      super.freeBucketEntry(bucketEntry);
      this.overwiteByteBuff = getOverwriteByteBuff(bucketEntry);
      try {
        this.ioEngine.write(this.overwiteByteBuff, bucketEntry.offset());
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

  private static ByteBuff getOverwriteByteBuff(BucketEntry bucketEntry) {
    int byteSize = bucketEntry.getLength();
    byte[] data = new byte[byteSize];
    Arrays.fill(data, (byte) 0xff);
    return ByteBuff.wrap(ByteBuffer.wrap(data));
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*=====================================================================
**
** Source:  GetFileSizeEx.c (test 1)
**
** Purpose: Tests the PAL implementation of the GetFileSizeEx function.
**
**
**===================================================================*/

#include <palsuite.h>

const char* szTextFile = "text.txt";

void CleanUp(HANDLE hFile)
{
    if (CloseHandle(hFile) != TRUE)
    {
        Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n",
            szTextFile);
    }
    if (!DeleteFileA(szTextFile))
    {
        Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n",
            szTextFile);
    }
}

void CheckFileSize(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder)
{
    DWORD dwRc = 0;
    DWORD dwError = 0;
    LARGE_INTEGER qwFileSize;

    dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN);
    if (dwRc == INVALID_SET_FILE_POINTER)
    {
        Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n",
            GetLastError());
        CleanUp(hFile);
        Fail("");
    }
    else
    {
        if (!SetEndOfFile(hFile))
        {
            dwError = GetLastError();
            CleanUp(hFile);
            if (dwError == 112)
            {
                Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of "
                    "disk space\n");
            }
            else
            {
                Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed "
                    "with error %ld\n", dwError);
            }
        }
        else
        {
            GetFileSizeEx(hFile, &qwFileSize);
            if ((qwFileSize.u.LowPart != dwOffset) ||
                (qwFileSize.u.HighPart != dwHighOrder))
            {
                CleanUp(hFile);
                Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n");
            }
        }
    }
}

int __cdecl main(int argc, char *argv[])
{
    HANDLE hFile = NULL;
    BOOL bRc = FALSE;
    DWORD lpNumberOfBytesWritten;
    LARGE_INTEGER qwFileSize;
    LARGE_INTEGER qwFileSize2;
    char * data = "1234567890";

    qwFileSize.QuadPart = 0;
    qwFileSize2.QuadPart = 0;

    if (0 != PAL_Initialize(argc,argv))
    {
        return FAIL;
    }

    /* test on a null file */
    bRc = GetFileSizeEx(NULL, &qwFileSize);
    if (bRc != FALSE)
    {
        Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for "
            "a null handle.\n");
    }

    /* test on an invalid file */
    bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize);
    if (bRc != FALSE)
    {
        Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for "
            "an invalid handle.\n");
    }

    /* create a test file */
    hFile = CreateFile(szTextFile,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n",
            szTextFile);
    }

    /* give the file a size */
    CheckFileSize(hFile, 256, 0);

    /* make the file large using the high order option */
    CheckFileSize(hFile, 256, 1);

    /* set the file size to zero */
    CheckFileSize(hFile, 0, 0);

    /*  test if file size changes by writing to it. */
    /* get file size */
    GetFileSizeEx(hFile, &qwFileSize);

    /* test writing to the file */
    if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0)
    {
        Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n",
             GetLastError());
        CleanUp(hFile);
        Fail("");
    }

    /* make sure the buffer flushed.*/
    if(FlushFileBuffers(hFile)==0)
    {
        Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n",
             GetLastError());
        CleanUp(hFile);
        Fail("");
    }

    /* get file size after writing some chars */
    GetFileSizeEx(hFile, &qwFileSize2);
    if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data))
    {
        CleanUp(hFile);
        Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n"
             "writing %d chars\n", strlen(data));
    }

    CleanUp(hFile);
    PAL_Terminate();
    return PASS;
}


text:
package sql.generic.ddl.alter;

import hydra.Log;

import java.sql.SQLException;

import sql.generic.ddl.DDLAction;
import sql.generic.ddl.Executor;

public class AlterGatewaySenderOperation extends Operation {

  AlterGatewaySenderOperation(String ddl , Executor executor , DDLAction action){
    super(ddl,executor,action);
  }

  public AlterGatewaySenderOperation parse(){
     return this;
  }

  public void handleAlterDDLException (SQLException  derby , SQLException gemxd){
    Log.getLogWriter().info("Derby Exception is : " + derby);
    Log.getLogWriter().info("GFXD Exception is : " + gemxd);
    compareExceptions(derby,gemxd);
  }

  public void handleAlterDDLException (SQLException gemxd){
    Log.getLogWriter().info("GFXD Exception is : " + gemxd);
  }

}


text:
Package.describe({
  name: 'nicolaslopezj:options',
  summary: 'Set app options reactively',
  version: '1.0.1',
  git: 'https://github.com/nicolaslopezj/options'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');

  api.use('meteor-platform');

  api.addFiles('options.js');
  api.addFiles('options_client.js', 'client');

  api.export('Options');
});

Package.onTest(function(api) {
  api.use('tinytest');
});


text:
using System;

namespace Thinktecture.IdentityServer3.Admin.Persistence.Models.Storage
{
    public class ClientSecret
    {
        public string Description { get; set; }
        public string Value { get; set; }
        public DateTimeOffset? Expiration { get; set; }
    }
}


text:
using namespace llvm;

#define DEBUG_TYPE "arm-subtarget"

#define GET_SUBTARGETINFO_TARGET_DESC
#define GET_SUBTARGETINFO_CTOR
#include "ARMGenSubtargetInfo.inc"

static cl::opt<bool>
UseFusedMulOps("arm-use-mulops",
               cl::init(true), cl::Hidden);

enum ITMode {
  DefaultIT,
  RestrictedIT,
  NoRestrictedIT
};

static cl::opt<ITMode>
IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT),
   cl::ZeroOrMore,
   cl::values(clEnumValN(DefaultIT, "arm-default-it",
                         "Generate IT block based on arch"),
              clEnumValN(RestrictedIT, "arm-restrict-it",
                         "Disallow deprecated IT based on ARMv8"),
              clEnumValN(NoRestrictedIT, "arm-no-restrict-it",
                         "Allow IT blocks based on ARMv7")));

/// ForceFastISel - Use the fast-isel, even for subtargets where it is not
/// currently supported (for testing only).
static cl::opt<bool>
ForceFastISel("arm-force-fast-isel",
               cl::init(false), cl::Hidden);

/// initializeSubtargetDependencies - Initializes using a CPU and feature string
/// so that we can use initializer lists for subtarget initialization.
ARMSubtarget &ARMSubtarget::initializeSubtargetDependencies(StringRef CPU,
                                                            StringRef FS) {
  initializeEnvironment();
  initSubtargetFeatures(CPU, FS);
  return *this;
}

ARMFrameLowering *ARMSubtarget::initializeFrameLowering(StringRef CPU,
                                                        StringRef FS) {
  ARMSubtarget &STI = initializeSubtargetDependencies(CPU, FS);
  if (STI.isThumb1Only())
    return (ARMFrameLowering *)new Thumb1FrameLowering(STI);

  return new ARMFrameLowering(STI);
}

ARMSubtarget::ARMSubtarget(const Triple &TT, const std::string &CPU,
                           const std::string &FS,
                           const ARMBaseTargetMachine &TM, bool IsLittle,
                           bool MinSize)
    : ARMGenSubtargetInfo(TT, CPU, FS), UseMulOps(UseFusedMulOps),
      CPUString(CPU), OptMinSize(MinSize), IsLittle(IsLittle),
      TargetTriple(TT), Options(TM.Options), TM(TM),
      FrameLowering(initializeFrameLowering(CPU, FS)),
      // At this point initializeSubtargetDependencies has been called so
      // we can query directly.
      InstrInfo(isThumb1Only()
                    ? (ARMBaseInstrInfo *)new Thumb1InstrInfo(*this)
                    : !isThumb()
                          ? (ARMBaseInstrInfo *)new ARMInstrInfo(*this)
                          : (ARMBaseInstrInfo *)new Thumb2InstrInfo(*this)),
      TLInfo(TM, *this) {

  CallLoweringInfo.reset(new ARMCallLowering(*getTargetLowering()));
  Legalizer.reset(new ARMLegalizerInfo(*this));

  auto *RBI = new ARMRegisterBankInfo(*getRegisterInfo());

  // FIXME: At this point, we can't rely on Subtarget having RBI.
  // It's awkward to mix passing RBI and the Subtarget; should we pass
  // TII/TRI as well?
  InstSelector.reset(createARMInstructionSelector(
      *static_cast<const ARMBaseTargetMachine *>(&TM), *this, *RBI));

  RegBankInfo.reset(RBI);
}

const CallLowering *ARMSubtarget::getCallLowering() const {
  return CallLoweringInfo.get();
}

InstructionSelector *ARMSubtarget::getInstructionSelector() const {
  return InstSelector.get();
}

const LegalizerInfo *ARMSubtarget::getLegalizerInfo() const {
  return Legalizer.get();
}

const RegisterBankInfo *ARMSubtarget::getRegBankInfo() const {
  return RegBankInfo.get();
}

bool ARMSubtarget::isXRaySupported() const {
  // We don't currently suppport Thumb, but Windows requires Thumb.
  return hasV6Ops() && hasARMOps() && !isTargetWindows();
}

void ARMSubtarget::initializeEnvironment() {
  // MCAsmInfo isn't always present (e.g. in opt) so we can't initialize this
  // directly from it, but we can try to make sure they're consistent when both
  // available.
  UseSjLjEH = (isTargetDarwin() && !isTargetWatchABI() &&
               Options.ExceptionModel == ExceptionHandling::None) ||
              Options.ExceptionModel == ExceptionHandling::SjLj;
  assert((!TM.getMCAsmInfo() ||
          (TM.getMCAsmInfo()->getExceptionHandlingType() ==
           ExceptionHandling::SjLj) == UseSjLjEH) &&
         "inconsistent sjlj choice between CodeGen and MC");
}

void ARMSubtarget::initSubtargetFeatures(StringRef CPU, StringRef FS) {
  if (CPUString.empty()) {
    CPUString = "generic";

    if (isTargetDarwin()) {
      StringRef ArchName = TargetTriple.getArchName();
      ARM::ArchKind AK = ARM::parseArch(ArchName);
      if (AK == ARM::ArchKind::ARMV7S)
        // Default to the Swift CPU when targeting armv7s/thumbv7s.
        CPUString = "swift";
      else if (AK == ARM::ArchKind::ARMV7K)
        // Default to the Cortex-a7 CPU when targeting armv7k/thumbv7k.
        // ARMv7k does not use SjLj exception handling.
        CPUString = "cortex-a7";
    }
  }

  // Insert the architecture feature derived from the target triple into the
  // feature string. This is important for setting features that are implied
  // based on the architecture version.
  std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple, CPUString);
  if (!FS.empty()) {
    if (!ArchFS.empty())
      ArchFS = (Twine(ArchFS) + "," + FS).str();
    else
      ArchFS = FS;
  }
  ParseSubtargetFeatures(CPUString, ArchFS);

  // FIXME: This used enable V6T2 support implicitly for Thumb2 mode.
  // Assert this for now to make the change obvious.
  assert(hasV6T2Ops() || !hasThumb2());

  // Execute only support requires movt support
  if (genExecuteOnly()) {
    NoMovt = false;
    assert(hasV8MBaselineOps() && "Cannot generate execute-only code for this target");
  }

  // Keep a pointer to static instruction cost data for the specified CPU.
  SchedModel = getSchedModelForCPU(CPUString);

  // Initialize scheduling itinerary for the specified CPU.
  InstrItins = getInstrItineraryForCPU(CPUString);

  // FIXME: this is invalid for WindowsCE
  if (isTargetWindows())
    NoARM = true;

  if (isAAPCS_ABI())
    stackAlignment = Align(8);
  if (isTargetNaCl() || isAAPCS16_ABI())
    stackAlignment = Align(16);

  // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
  // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
  // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
  // support in the assembler and linker to be used. This would need to be
  // fixed to fully support tail calls in Thumb1.
  //
  // For ARMv8-M, we /do/ implement tail calls.  Doing this is tricky for v8-M
  // baseline, since the LDM/POP instruction on Thumb doesn't take LR.  This
  // means if we need to reload LR, it takes extra instructions, which outweighs
  // the value of the tail call; but here we don't know yet whether LR is going
  // to be used. We take the optimistic approach of generating the tail call and
  // perhaps taking a hit if we need to restore the LR.

  // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
  // but we need to make sure there are enough registers; the only valid
  // registers are the 4 used for parameters.  We don't currently do this
  // case.

  SupportsTailCall = !isThumb() || hasV8MBaselineOps();

  if (isTargetMachO() && isTargetIOS() && getTargetTriple().isOSVersionLT(5, 0))
    SupportsTailCall = false;

  switch (IT) {
  case DefaultIT:
    RestrictIT = hasV8Ops();
    break;
  case RestrictedIT:
    RestrictIT = true;
    break;
  case NoRestrictedIT:
    RestrictIT = false;
    break;
  }

  // NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.
  const FeatureBitset &Bits = getFeatureBits();
  if ((Bits[ARM::ProcA5] || Bits[ARM::ProcA8]) && // Where this matters
      (Options.UnsafeFPMath || isTargetDarwin()))
    UseNEONForSinglePrecisionFP = true;

  if (isRWPI())
    ReserveR9 = true;

  // If MVEVectorCostFactor is still 0 (has not been set to anything else), default it to 2
  if (MVEVectorCostFactor == 0)
    MVEVectorCostFactor = 2;

  // FIXME: Teach TableGen to deal with these instead of doing it manually here.
  switch (ARMProcFamily) {
  case Others:
  case CortexA5:
    break;
  case CortexA7:
    LdStMultipleTiming = DoubleIssue;
    break;
  case CortexA8:
    LdStMultipleTiming = DoubleIssue;
    break;
  case CortexA9:
    LdStMultipleTiming = DoubleIssueCheckUnalignedAccess;
    PreISelOperandLatencyAdjustment = 1;
    break;
  case CortexA12:
    break;
  case CortexA15:
    MaxInterleaveFactor = 2;
    PreISelOperandLatencyAdjustment = 1;
    PartialUpdateClearance = 12;
    break;
  case CortexA17:
  case CortexA32:
  case CortexA35:
  case CortexA53:
  case CortexA55:
  case CortexA57:
  case CortexA72:
  case CortexA73:
  case CortexA75:
  case CortexA76:
  case CortexR4:
  case CortexR4F:
  case CortexR5:
  case CortexR7:
  case CortexM3:
  case CortexR52:
    break;
  case Exynos:
    LdStMultipleTiming = SingleIssuePlusExtras;
    MaxInterleaveFactor = 4;
    if (!isThumb())
      PrefLoopLogAlignment = 3;
    break;
  case Kryo:
    break;
  case Krait:
    PreISelOperandLatencyAdjustment = 1;
    break;
  case NeoverseN1:
    break;
  case Swift:
    MaxInterleaveFactor = 2;
    LdStMultipleTiming = SingleIssuePlusExtras;
    PreISelOperandLatencyAdjustment = 1;
    PartialUpdateClearance = 12;
    break;
  }
}

bool ARMSubtarget::isTargetHardFloat() const { return TM.isTargetHardFloat(); }

bool ARMSubtarget::isAPCS_ABI() const {
  assert(TM.TargetABI != ARMBaseTargetMachine::ARM_ABI_UNKNOWN);
  return TM.TargetABI == ARMBaseTargetMachine::ARM_ABI_APCS;
}
bool ARMSubtarget::isAAPCS_ABI() const {
  assert(TM.TargetABI != ARMBaseTargetMachine::ARM_ABI_UNKNOWN);
  return TM.TargetABI == ARMBaseTargetMachine::ARM_ABI_AAPCS ||
         TM.TargetABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16;
}
bool ARMSubtarget::isAAPCS16_ABI() const {
  assert(TM.TargetABI != ARMBaseTargetMachine::ARM_ABI_UNKNOWN);
  return TM.TargetABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16;
}

bool ARMSubtarget::isROPI() const {
  return TM.getRelocationModel() == Reloc::ROPI ||
         TM.getRelocationModel() == Reloc::ROPI_RWPI;
}
bool ARMSubtarget::isRWPI() const {
  return TM.getRelocationModel() == Reloc::RWPI ||
         TM.getRelocationModel() == Reloc::ROPI_RWPI;
}

bool ARMSubtarget::isGVIndirectSymbol(const GlobalValue *GV) const {
  if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
    return true;

  // 32 bit macho has no relocation for a-b if a is undefined, even if b is in
  // the section that is being relocated. This means we have to use o load even
  // for GVs that are known to be local to the dso.
  if (isTargetMachO() && TM.isPositionIndependent() &&
      (GV->isDeclarationForLinker() || GV->hasCommonLinkage()))
    return true;

  return false;
}

bool ARMSubtarget::isGVInGOT(const GlobalValue *GV) const {
  return isTargetELF() && TM.isPositionIndependent() &&
         !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
}

unsigned ARMSubtarget::getMispredictionPenalty() const {
  return SchedModel.MispredictPenalty;
}

bool ARMSubtarget::enableMachineScheduler() const {
  // The MachineScheduler can increase register usage, so we use more high
  // registers and end up with more T2 instructions that cannot be converted to
  // T1 instructions. At least until we do better at converting to thumb1
  // instructions, on cortex-m at Oz where we are size-paranoid, don't use the
  // Machine scheduler, relying on the DAG register pressure scheduler instead.
  if (isMClass() && hasMinSize())
    return false;
  // Enable the MachineScheduler before register allocation for subtargets
  // with the use-misched feature.
  return useMachineScheduler();
}

// This overrides the PostRAScheduler bit in the SchedModel for any CPU.
bool ARMSubtarget::enablePostRAScheduler() const {
  if (disablePostRAScheduler())
    return false;
  // Don't reschedule potential IT blocks.
  return !isThumb1Only();
}

bool ARMSubtarget::enableAtomicExpand() const { return hasAnyDataBarrier(); }

bool ARMSubtarget::useStride4VFPs() const {
  // For general targets, the prologue can grow when VFPs are allocated with
  // stride 4 (more vpush instructions). But WatchOS uses a compact unwind
  // format which it's more important to get right.
  return isTargetWatchABI() ||
         (useWideStrideVFP() && !OptMinSize);
}

bool ARMSubtarget::useMovt() const {
  // NOTE Windows on ARM needs to use mov.w/mov.t pairs to materialise 32-bit
  // immediates as it is inherently position independent, and may be out of
  // range otherwise.
  return !NoMovt && hasV8MBaselineOps() &&
         (isTargetWindows() || !OptMinSize || genExecuteOnly());
}

bool ARMSubtarget::useFastISel() const {
  // Enable fast-isel for any target, for testing only.
  if (ForceFastISel)
    return true;

  // Limit fast-isel to the targets that are or have been tested.
  if (!hasV6Ops())
    return false;

  // Thumb2 support on iOS; ARM support on iOS, Linux and NaCl.
  return TM.Options.EnableFastISel &&
         ((isTargetMachO() && !isThumb1Only()) ||
          (isTargetLinux() && !isThumb()) || (isTargetNaCl() && !isThumb()));
}

unsigned ARMSubtarget::getGPRAllocationOrder(const MachineFunction &MF) const {
  // The GPR register class has multiple possible allocation orders, with
  // tradeoffs preferred by different sub-architectures and optimisation goals.
  // The allocation orders are:
  // 0: (the default tablegen order, not used)
  // 1: r14, r0-r13
  // 2: r0-r7
  // 3: r0-r7, r12, lr, r8-r11
  // Note that the register allocator will change this order so that
  // callee-saved registers are used later, as they require extra work in the
  // prologue/epilogue (though we sometimes override that).

  // For thumb1-only targets, only the low registers are allocatable.
  if (isThumb1Only())
    return 2;

  // Allocate low registers first, so we can select more 16-bit instructions.
  // We also (in ignoreCSRForAllocationOrder) override  the default behaviour
  // with regards to callee-saved registers, because pushing extra registers is
  // much cheaper (in terms of code size) than using high registers. After
  // that, we allocate r12 (doesn't need to be saved), lr (saving it means we
  // can return with the pop, don't need an extra "bx lr") and then the rest of
  // the high registers.
  if (isThumb2() && MF.getFunction().hasMinSize())
    return 3;

  // Otherwise, allocate in the default order, using LR first because saving it
  // allows a shorter epilogue sequence.
  return 1;
}

bool ARMSubtarget::ignoreCSRForAllocationOrder(const MachineFunction &MF,
                                               unsigned PhysReg) const {
  // To minimize code size in Thumb2, we prefer the usage of low regs (lower
  // cost per use) so we can  use narrow encoding. By default, caller-saved
  // registers (e.g. lr, r12) are always  allocated first, regardless of
  // their cost per use. When optForMinSize, we prefer the low regs even if
  // they are CSR because usually push/pop can be folded into existing ones.
  return isThumb2() && MF.getFunction().hasMinSize() &&
         ARM::GPRRegClass.contains(PhysReg);
}


text:
require 'test_helper'

class TakenokoTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Takenoko
  end
end


text:
package com.hawk.utility.example.socket.nio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

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

public class TimeClient {

	private static Logger logger = LoggerFactory.getLogger(TimeClient.class);

	public static class TimeClientHandle implements Runnable{

		private String host;
		private int port;
		private Selector selector;
		private SocketChannel socketChannel;
		private volatile boolean stop;

		public TimeClientHandle(String host,int port){
			this.host = host == null? "127.0.0.1":host;
			this.port = port;
			try {
				selector = Selector.open();
				socketChannel = SocketChannel.open();
				socketChannel.configureBlocking(false);
			} catch (IOException e) {
				logger.error("Failed to iniitiate TimeClientHandle",e);
				System.exit(1);
			}
		}

		@Override
		public void run() {
			try {
				doConnect();
			} catch (IOException e) {
				logger.error("Failed to connect to time server",e);
				System.exit(1);
			}

			while(!stop){
				try {
					selector.select(1000);
					Set<SelectionKey> selectedKeys = selector.selectedKeys();
					Iterator<SelectionKey> it = selectedKeys.iterator();
					SelectionKey key = null;
					while(it.hasNext()){
						key = it.next();
						it.remove();

						try {
							handleInput(key);
						} catch (Exception e) {
							if (key!=null){
								key.cancel();
								if (key.channel()!=null)
									key.channel().close();
							}
						}

					}
				} catch (IOException e) {
					logger.error("meet error",e);
					System.exit(1);
				}

			}

			/**
			 * 多路复用器关闭,所有相关资源自动关闭
			 */
			if (selector != null){
				try {
					selector.close();
				} catch (IOException e) {
					logger.error("meet error",e);
				}
			}

		}

		 private void doConnect() throws IOException{
			 if (socketChannel.connect(new InetSocketAddress(host, port))){
				 socketChannel.register(selector, SelectionKey.OP_READ);
				 doWrite(socketChannel);
			 }else{
				 socketChannel.register(selector, SelectionKey.OP_CONNECT);
			 }
		 }

		 private void doWrite(SocketChannel sc) throws IOException {
			 try {
				byte[] req = "QUERY TIME ORDER".getBytes("UTF-8");
				ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
				writeBuffer.put(req);
				writeBuffer.flip();
				sc.write(writeBuffer);
				if (!writeBuffer.hasRemaining()){
					logger.info("Succeed to send order 2 server");
				}
			} catch (UnsupportedEncodingException e) {
				logger.error("meet error",e);
			}
		 }

		 private void handleInput(SelectionKey key) throws IOException{
			 if (!key.isValid())
				 return;
			 SocketChannel sc = (SocketChannel)key.channel();
			 if (key.isConnectable()){
				 if (sc.finishConnect()){
					 sc.register(selector, SelectionKey.OP_READ);
					 doWrite(sc);
				 }else{
					 logger.error("connect failed");
					 System.exit(1);
				 }
			 }

			 if (key.isReadable()){
				 ByteBuffer readBuffer = ByteBuffer.allocate(1024);
				 int readBytes = sc.read(readBuffer);
				 if (readBytes > 0){
					 readBuffer.flip();
					 byte[] bytes = new byte[readBuffer.remaining()];
					 readBuffer.get(bytes);
					 String body = new String(bytes,"utf-8");
					 logger.info("Receive message : {}",body);
					 this.stop=true;
				 }else if (readBytes<0){
					 /**
					  * 对端链路关闭
					  */
					 key.cancel();
					 sc.close();
				 }else{
					 ;
				 }
			 }
		 }

	}

	public static void main(String[] args) {

		int port = 8080;
		if (args != null && args.length > 0) {
			try {
				port = Integer.valueOf(args[0]);
			} catch (NumberFormatException e) {
				// 采用默认值
			}
		}

		new Thread(new TimeClientHandle("127.0.0.1", port), "TimeClient-001")
		.start();
	}
}


text:
<?php namespace EvdB\OpenExchangeRates\Exception;

class MissingAppId extends \Exception
{
}


text:
@import XCTest;
@import Hankai;

@interface HKTestObj : NSObject <HKJsonPropertyMappings>

@property (nonatomic, strong) NSString * prop1;

@property (nonatomic, assign) NSUInteger prop2;

@property (nonatomic, assign) BOOL prop3;

@property (nonatomic, strong) NSDate * prop4;

@property (nonatomic, strong) NSString * prop5;

@end

@implementation HKTestObj

#pragma mark - HKJsonPropertyMappings

- (NSDictionary *)jsonPropertyMappings {
    return @{
             @"p1": @"prop1",
             @"p2": @"prop2",
             @"p3": @"prop3",
             @"p4": @"prop4",
             @"p5": @"prop5"
             };
}

- (NSString *)dateFormat {
    return @"yyyy-MM-dd HH:mm:ss";
}

@end

@interface HKJsonUtilsTests : XCTestCase

@end

@implementation HKJsonUtilsTests

- (void)testUpdatePropertiesWithData {
    NSString * json = @"{\"p1\" : \"prop111\",\"p2\" : 222,\"p3\" : true,\"p4\" : \"2015-11-06 11:55:55\",\"p5\":null}";
    NSError * error = nil;
    NSDictionary * data = [json jsonObject:&error];
    XCTAssertNil(error);
    HKTestObj * obj = [HKTestObj new];
    [HKJsonUtils updatePropertiesWithData:data forObject:obj];
    XCTAssertTrue([obj.prop1 isKindOfClass:[NSString class]] && [obj.prop1 isEqualToString:@"prop111"]);
    XCTAssertTrue(obj.prop2 == 222);
    XCTAssertTrue(obj.prop3);
    NSComparisonResult cr = [obj.prop4 compare:[NSDate dateFromNSString:@"2015-11-06 11:55:55" withFormat:[obj dateFormat]] mode:NSDatePart | NSTimePart];
    XCTAssertTrue([obj.prop4 isKindOfClass:[NSDate class]] && cr == NSOrderedSame);
    XCTAssertTrue(obj.prop5 == nil);
}

@end


text:
package no.obje.jdbcmiddleware.service;

import no.obje.jdbcmiddleware.HsqlUtil;
import no.obje.jdbcmiddleware.exception.MalformedSqlException;
import org.hsqldb.jdbc.JDBCDataSource;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@SuppressWarnings({"SqlNoDataSourceIn-spection", "SqlResolve", "SqlNoDataSourceInspection"})
public class JdbcServiceQueryForListTest {

    private JdbcService jdbcService;
    private MapCustomer mapCustomer = new MapCustomer();

    @Before
    public void setUp() throws Exception {
        final JDBCDataSource dataSource = HsqlUtil.setupDataSource();
        HsqlUtil.createCustomerTableAndInsertJonSnow(dataSource);
        jdbcService = new JdbcService(dataSource);
    }

    @Test
    public void query_for_list_should_return_empty_list_when_no_row_was_found() {
        final List<String> result = jdbcService.queryForList("SELECT * from customer where id = ?", mapCustomer, 999);
        assertTrue(result.isEmpty());
    }

    @Test
    public void query_for_list_should_return_list_with_expected_result_when_rows_was_found() {
        final List<String> result = jdbcService.queryForList("SELECT * from customer", mapCustomer);
        assertEquals(1, result.size());
        assertEquals("Jon Snow", result.get(0));
    }

    @Test(expected = MalformedSqlException.class)
    public void query_for_list_with_malformed_query_should_throw_expected_exception() {
        jdbcService.queryForList("asd", mapCustomer);
    }

    @Test(expected = MalformedSqlException.class)
    public void query_for_list_for_table_which_does_not_exist_should_throw_expected_exception() {
        jdbcService.queryForList("SELECT * from doesnotexist", mapCustomer);
    }

    @Test(expected = MalformedSqlException.class)
    public void query_for_list_for_column_which_does_not_exist_should_throw_expected_exception() {
        jdbcService.queryForList("SELECT id, name, age FROM customer WHERE id = ?", mapCustomer, 1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void query_for_list_with_null_sql_should_throw_expected_exception() {
        jdbcService.queryForList(null, mapCustomer);
    }

    @Test(expected = IllegalArgumentException.class)
    public void query_for_list_with_null_row_mapper_should_throw_expected_exception() {
        jdbcService.queryForList("SELECT * FROM customer", null);
    }

}