text:
using UnityEditor;
using UnityEngine;

///
/// Editor undo manager.
/// To use it:
/// <list type="number">
/// <item>
/// <description>Store an instance in the related Editor Class (instantiate it inside the OnEnable method).</description>
/// </item>
/// <item>
/// <description>Call undoManagerInstance.CheckUndo() BEFORE the first UnityGUI call in OnInspectorGUI.</description>
/// </item>
/// <item>
/// <description>Call undoManagerInstance.CheckDirty() AFTER the last UnityGUI call in OnInspectorGUI.</description>
/// </item>
/// </list>
///
///
public class FXMakerUndoManager
{
    private     Object              defTarget;
    private     string              defName;
    private     bool                autoSetDirty;
    private     bool                listeningForGuiChanges;
    private     bool                isMouseDown;
    private     Object              waitingToRecordPrefab;	// If different than NULL indicates the prefab instance that will need to record its state as soon as the mouse is released.

    public FXMakerUndoManager( Object p_target, string p_name ) : this( p_target, p_name, true ) {}
    public FXMakerUndoManager( Object p_target, string p_name, bool p_autoSetDirty )
    {
        defTarget = p_target;
        defName = p_name;
        autoSetDirty = p_autoSetDirty;
    }

    // ===================================================================================
    public void CheckUndo() { CheckUndo( defTarget, defName ); }
    public void CheckUndo( Object p_target ) { CheckUndo( p_target, defName ); }
    public void CheckUndo( Object p_target, string p_name )
    {
        Event e = Event.current;

        if ( waitingToRecordPrefab != null ) {
            // Record eventual prefab instance modification.
            // TODO Avoid recording if nothing changed (no harm in doing so, but it would be nicer).
            switch ( e.type ) {
            case EventType.MouseDown :
            case EventType.MouseUp :
            case EventType.KeyDown :
            case EventType.KeyUp :
                PrefabUtility.RecordPrefabInstancePropertyModifications( waitingToRecordPrefab );
                break;
            }
        }

        if ( ( e.type == EventType.MouseDown && e.button == 0 ) || ( e.type == EventType.KeyUp && e.keyCode == KeyCode.Tab ) ) {
            // When the LMB is pressed or the TAB key is released,
            // store a snapshot, but don't register it as an undo
            // (so that if nothing changes we avoid storing a useless undo).
            Undo.SetSnapshotTarget( p_target, p_name );
            Undo.CreateSnapshot();
            Undo.ClearSnapshotTarget(); // Not sure if this is necessary.
            listeningForGuiChanges = true;
        }
    }

    public bool CheckDirty() { return CheckDirty( defTarget, defName ); }
    public bool CheckDirty( Object p_target ) { return CheckDirty( p_target, defName ); }
    public bool CheckDirty( Object p_target, string p_name )
    {
        if ( listeningForGuiChanges && GUI.changed ) {
            // Some GUI value changed after pressing the mouse
            // or releasing the TAB key.
            // Register the previous snapshot as a valid undo.
            SetDirty( p_target, p_name );
            return true;
        }
        return false;
    }

    public void ForceDirty() { ForceDirty( defTarget, defName ); }
    public void ForceDirty( Object p_target ) { ForceDirty( p_target, defName ); }
    public void ForceDirty( Object p_target, string p_name )
    {
        if ( !listeningForGuiChanges ) {
            // Create a new snapshot.
            Undo.SetSnapshotTarget( p_target, p_name );
            Undo.CreateSnapshot();
            Undo.ClearSnapshotTarget();
        }
        SetDirty( p_target, p_name );
    }

    // ===================================================================================
    // PRIVATE METHODS -------------------------------------------------------------------

    private void SetDirty( Object p_target, string p_name )
    {
        Undo.SetSnapshotTarget( p_target, p_name );
        Undo.RegisterSnapshot();
        Undo.ClearSnapshotTarget(); // Not sure if this is necessary.
        if ( autoSetDirty )     EditorUtility.SetDirty( p_target );
        listeningForGuiChanges = false;

        if ( CheckTargetIsPrefabInstance( p_target ) ) {
            // Prefab instance: record immediately and also wait for value to be changed and than re-record it
            // (otherwise prefab instances are not updated correctly when using Custom Inspectors).
            PrefabUtility.RecordPrefabInstancePropertyModifications( p_target );
            waitingToRecordPrefab = p_target;
        } else {
            waitingToRecordPrefab = null;
        }
    }

    private bool CheckTargetIsPrefabInstance( Object p_target )
    {
        return ( PrefabUtility.GetPrefabType( p_target ) == PrefabType.PrefabInstance );
    }
}


text:
package mil.tatrc.physiology.utilities;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

import com.sun.mail.smtp.SMTPTransport;

public class EmailUtil
{
  /** Email Recipients */
	protected List<String> recipients = new ArrayList<String>();
	/** Who the email is from */
	protected String from="EmailUtil";
	/** Where this mail is coming from */
	protected String smtp="localhost";
	protected int    smtpPort=25;
	/** Email subject */
	protected String subject;

	/** Add a recipient to the email */
	public void addRecipient(String recipient)
	{
		this.recipients.add(recipient);
	}

	/** Who is the email from */
	public void setSender(String sender)
	{
	  this.from=sender;
	}

	/** Email subject*/
	public void setSubject(String subject)
	{
		this.subject = subject;
	}

	/** Set the STMP host server */
	public void setSMTP(String smtp)
	{
	  this.smtp=smtp;
	  this.smtpPort=25;
	}

	/** Set the STMP host server */
  public void setSMTP(String smtp, int port)
  {
    this.smtp=smtp;
    this.smtpPort=port;
  }

	/**
	 * Sends html to provided recipients
	 * and other configuration data
	 * @param content
	 */
   public void sendHTML(String content)
   {
     try
     {
       // Get system properties
       Properties properties = System.getProperties();
       // Setup mail server
       properties.setProperty("mail.smtp.host", this.smtp);
       properties.setProperty("mail.smtp.port", String.valueOf(this.smtpPort));
       // Get the default Session object.
       Session session = Session.getDefaultInstance(properties);
       //session.setDebug(true);
       Transport trans = session.getTransport("smtp");
       // Override the host for HELO or EHLO
       if (smtp != null && trans instanceof SMTPTransport)
       {
         ((SMTPTransport) trans).setLocalHost("SED-ABRAY.ara.wan");
       }
       // Create a default MimeMessage object.
       MimeMessage message = new MimeMessage(session);
       // Set From: header field of the header.
       message.setFrom(new InternetAddress(this.from));
       for(String recipient : this.recipients)
       {
         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(recipient));
       }
       // Set Subject: header field
       message.setSubject(this.subject);
       // Send the actual HTML message, as big as you like
       message.setContent(content,"text/html");
       // Send message
       Transport.send(message);
     }
     catch (MessagingException mex)
     {
       Log.error(mex);
     }
   }

   public static void main(String[] args)
   {
  	 EmailUtil emailer = new EmailUtil();
  	 emailer.setSender("abray@ara.com");
  	 emailer.addRecipient("abray@ara.com");
  	 emailer.addRecipient("boday@ara.com");
  	 emailer.setSMTP("smtp.ara.wan");
  	 emailer.setSubject("Test Email");
  	 emailer.sendHTML("<title>Test</title>Test Email");
   }
}

redpajama_set_name: RedPajamaGithub


text:
#include "webrtc/modules/audio_device/android/audio_record_jni.h"

#include <android/log.h>

#include "webrtc/base/arraysize.h"
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_device/android/audio_common.h"

#define TAG "AudioRecordJni"
#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define ALOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define ALOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)

namespace webrtc {

// Number of bytes per audio frame.
// Example: 16-bit PCM in mono => 1*(16/8)=2 [bytes/frame]
static const int kBytesPerFrame = kNumChannels * (kBitsPerSample / 8);

// We are unable to obtain exact measurements of the hardware delay on Android.
// Instead, a lower bound (based on measurements) is used.
// TODO(henrika): is it possible to improve this?
static const int kHardwareDelayInMilliseconds = 100;

static JavaVM* g_jvm = NULL;
static jobject g_context = NULL;
static jclass g_audio_record_class = NULL;

void AudioRecordJni::SetAndroidAudioDeviceObjects(void* jvm, void* env,
                                                  void* context) {
  ALOGD("SetAndroidAudioDeviceObjects%s", GetThreadInfo().c_str());

  CHECK(jvm);
  CHECK(env);
  CHECK(context);

  g_jvm = reinterpret_cast<JavaVM*>(jvm);
  JNIEnv* jni = GetEnv(g_jvm);
  CHECK(jni) << "AttachCurrentThread must be called on this tread";

  // Protect context from being deleted during garbage collection.
  g_context = NewGlobalRef(jni, reinterpret_cast<jobject>(context));

  // Load the locally-defined WebRtcAudioRecord class and create a new global
  // reference to it.
  jclass local_class = FindClass(
      jni, "org/webrtc/voiceengine/WebRtcAudioRecord");
  g_audio_record_class = reinterpret_cast<jclass>(
      NewGlobalRef(jni, local_class));

  // Register native methods with the WebRtcAudioRecord class. These methods
  // are declared private native in WebRtcAudioRecord.java.
  JNINativeMethod native_methods[] = {
      {"nativeCacheDirectBufferAddress", "(Ljava/nio/ByteBuffer;J)V",
          reinterpret_cast<void*>(
       &webrtc::AudioRecordJni::CacheDirectBufferAddress)},
      {"nativeDataIsRecorded", "(IJ)V",
          reinterpret_cast<void*>(&webrtc::AudioRecordJni::DataIsRecorded)}};
  jni->RegisterNatives(g_audio_record_class,
                       native_methods, arraysize(native_methods));
  CHECK_EXCEPTION(jni) << "Error during RegisterNatives";
}

void AudioRecordJni::ClearAndroidAudioDeviceObjects() {
  ALOGD("ClearAndroidAudioDeviceObjects%s", GetThreadInfo().c_str());
  JNIEnv* jni = GetEnv(g_jvm);
  CHECK(jni) << "AttachCurrentThread must be called on this tread";
  jni->UnregisterNatives(g_audio_record_class);
  CHECK_EXCEPTION(jni) << "Error during UnregisterNatives";
  DeleteGlobalRef(jni, g_audio_record_class);
  g_audio_record_class = NULL;
  DeleteGlobalRef(jni, g_context);
  g_context = NULL;
  g_jvm = NULL;
}

AudioRecordJni::AudioRecordJni()
    : j_audio_record_(NULL),
      direct_buffer_address_(NULL),
      direct_buffer_capacity_in_bytes_(0),
      frames_per_buffer_(0),
      initialized_(false),
      recording_(false),
      audio_device_buffer_(NULL),
      sample_rate_hz_(0) {
  ALOGD("ctor%s", GetThreadInfo().c_str());
  CHECK(HasDeviceObjects());
  CreateJavaInstance();
  // Detach from this thread since we want to use the checker to verify calls
  // from the Java based audio thread.
  thread_checker_java_.DetachFromThread();
}

AudioRecordJni::~AudioRecordJni() {
  ALOGD("~dtor%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  Terminate();
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jni->DeleteGlobalRef(j_audio_record_);
  j_audio_record_ = NULL;
}

int32_t AudioRecordJni::Init() {
  ALOGD("Init%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  return 0;
}

int32_t AudioRecordJni::Terminate() {
  ALOGD("Terminate%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  StopRecording();
  return 0;
}

int32_t AudioRecordJni::InitRecording() {
  ALOGD("InitRecording%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(!initialized_);
  DCHECK(!recording_);
  if (initialized_ || recording_) {
    return -1;
  }
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID initRecordingID = GetMethodID(
      jni, g_audio_record_class, "InitRecording", "(I)I");
  jint frames_per_buffer = jni->CallIntMethod(
      j_audio_record_, initRecordingID, sample_rate_hz_);
  CHECK_EXCEPTION(jni);
  if (frames_per_buffer < 0) {
    ALOGE("InitRecording failed!");
    return -1;
  }
  frames_per_buffer_ = frames_per_buffer;
  ALOGD("frames_per_buffer: %d", frames_per_buffer_);
  CHECK_EQ(direct_buffer_capacity_in_bytes_,
           frames_per_buffer_ * kBytesPerFrame);
  initialized_ = true;
  return 0;
}

int32_t AudioRecordJni::StartRecording() {
  ALOGD("StartRecording%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(initialized_);
  DCHECK(!recording_);
  if (!initialized_ || recording_) {
    return -1;
  }
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID startRecordingID = GetMethodID(
      jni, g_audio_record_class, "StartRecording", "()Z");
  jboolean res = jni->CallBooleanMethod(j_audio_record_, startRecordingID);
  CHECK_EXCEPTION(jni);
  if (!res) {
    ALOGE("StartRecording failed!");
    return -1;
  }
  recording_ = true;
  return 0;
}

int32_t AudioRecordJni::StopRecording() {
  ALOGD("StopRecording%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!initialized_) {
    return 0;
  }
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID stopRecordingID = GetMethodID(
      jni, g_audio_record_class, "StopRecording", "()Z");
  jboolean res = jni->CallBooleanMethod(j_audio_record_, stopRecordingID);
  CHECK_EXCEPTION(jni);
  if (!res) {
    ALOGE("StopRecording failed!");
    return -1;
  }
  // If we don't detach here, we will hit a DCHECK in OnDataIsRecorded() next
  // time StartRecording() is called since it will create a new Java thread.
  thread_checker_java_.DetachFromThread();
  initialized_ = false;
  recording_ = false;
  return 0;

}

int32_t AudioRecordJni::RecordingDelay(uint16_t& delayMS) const {  // NOLINT
  // TODO(henrika): is it possible to improve this estimate?
  delayMS = kHardwareDelayInMilliseconds;
  return 0;
}

void AudioRecordJni::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
  ALOGD("AttachAudioBuffer");
  DCHECK(thread_checker_.CalledOnValidThread());
  audio_device_buffer_ = audioBuffer;
  sample_rate_hz_ = GetNativeSampleRate();
  ALOGD("SetRecordingSampleRate(%d)", sample_rate_hz_);
  audio_device_buffer_->SetRecordingSampleRate(sample_rate_hz_);
  audio_device_buffer_->SetRecordingChannels(kNumChannels);
}

bool AudioRecordJni::BuiltInAECIsAvailable() const {
  ALOGD("BuiltInAECIsAvailable%s", GetThreadInfo().c_str());
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID builtInAECIsAvailable = jni->GetStaticMethodID(
      g_audio_record_class, "BuiltInAECIsAvailable", "()Z");
  CHECK_EXCEPTION(jni);
  CHECK(builtInAECIsAvailable);
  jboolean hw_aec = jni->CallStaticBooleanMethod(g_audio_record_class,
                                                 builtInAECIsAvailable);
  CHECK_EXCEPTION(jni);
  return hw_aec;
}

int32_t AudioRecordJni::EnableBuiltInAEC(bool enable) {
  ALOGD("EnableBuiltInAEC%s", GetThreadInfo().c_str());
  DCHECK(thread_checker_.CalledOnValidThread());
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID enableBuiltInAEC = GetMethodID(
      jni, g_audio_record_class, "EnableBuiltInAEC", "(Z)Z");
  jboolean res = jni->CallBooleanMethod(
      j_audio_record_, enableBuiltInAEC, enable);
  CHECK_EXCEPTION(jni);
  if (!res) {
    ALOGE("EnableBuiltInAEC failed!");
    return -1;
  }
  return 0;
}

void JNICALL AudioRecordJni::CacheDirectBufferAddress(
    JNIEnv* env, jobject obj, jobject byte_buffer, jlong nativeAudioRecord) {
  webrtc::AudioRecordJni* this_object =
      reinterpret_cast<webrtc::AudioRecordJni*> (nativeAudioRecord);
  this_object->OnCacheDirectBufferAddress(env, byte_buffer);
}

void AudioRecordJni::OnCacheDirectBufferAddress(
    JNIEnv* env, jobject byte_buffer) {
  ALOGD("OnCacheDirectBufferAddress");
  DCHECK(thread_checker_.CalledOnValidThread());
  direct_buffer_address_ =
      env->GetDirectBufferAddress(byte_buffer);
  jlong capacity = env->GetDirectBufferCapacity(byte_buffer);
  ALOGD("direct buffer capacity: %lld", capacity);
  direct_buffer_capacity_in_bytes_ = static_cast<int> (capacity);
}

void JNICALL AudioRecordJni::DataIsRecorded(
  JNIEnv* env, jobject obj, jint length, jlong nativeAudioRecord) {
  webrtc::AudioRecordJni* this_object =
      reinterpret_cast<webrtc::AudioRecordJni*> (nativeAudioRecord  );
  this_object->OnDataIsRecorded(length);
}

// This method is called on a high-priority thread from Java. The name of
// the thread is 'AudioRecordThread'.
void AudioRecordJni::OnDataIsRecorded(int length) {
  DCHECK(thread_checker_java_.CalledOnValidThread());
  audio_device_buffer_->SetRecordedBuffer(direct_buffer_address_,
                                          frames_per_buffer_);
  // TODO(henrika): improve playout delay estimate.
  audio_device_buffer_->SetVQEData(0, kHardwareDelayInMilliseconds, 0);
  audio_device_buffer_->DeliverRecordedData();
}

bool AudioRecordJni::HasDeviceObjects() {
  return (g_jvm && g_context && g_audio_record_class);
}

void AudioRecordJni::CreateJavaInstance() {
  ALOGD("CreateJavaInstance");
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID constructorID = GetMethodID(
      jni, g_audio_record_class, "<init>", "(Landroid/content/Context;J)V");
  j_audio_record_ = jni->NewObject(g_audio_record_class,
                                   constructorID,
                                   g_context,
                                   reinterpret_cast<intptr_t>(this));
  CHECK_EXCEPTION(jni) << "Error during NewObject";
  CHECK(j_audio_record_);
  j_audio_record_ = jni->NewGlobalRef(j_audio_record_);
  CHECK_EXCEPTION(jni) << "Error during NewGlobalRef";
  CHECK(j_audio_record_);
}

int AudioRecordJni::GetNativeSampleRate() {
  AttachThreadScoped ats(g_jvm);
  JNIEnv* jni = ats.env();
  jmethodID getNativeSampleRate = GetMethodID(
      jni, g_audio_record_class, "GetNativeSampleRate", "()I");
  jint sample_rate_hz = jni->CallIntMethod(
      j_audio_record_, getNativeSampleRate);
  CHECK_EXCEPTION(jni);
  return sample_rate_hz;
}

}  // namespace webrtc


text:
const { serialize } = require('.');

const formDataAppend = global.FormData.prototype.append;

beforeEach(() => {
  global.FormData.prototype.append = jest.fn(formDataAppend);
});

test('undefined', () => {
  const formData = serialize({
    foo: undefined,
  });

  expect(formData.append).not.toHaveBeenCalled();
  expect(formData.get('foo')).toBe(null);
});

test('null', () => {
  const formData = serialize({
    foo: null,
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', '');
  expect(formData.get('foo')).toBe('');
});

test('null with nullsAsUndefineds option', () => {
  const formData = serialize(
    {
      foo: null,
    },
    {
      nullsAsUndefineds: true,
    },
  );

  expect(formData.append).not.toHaveBeenCalled();
  expect(formData.get('foo')).toBe(null);
});

test('boolean', () => {
  const formData = serialize({
    foo: true,
    bar: false,
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo', true);
  expect(formData.append).toHaveBeenNthCalledWith(2, 'bar', false);
  expect(formData.get('foo')).toBe('true');
  expect(formData.get('bar')).toBe('false');
});

test('boolean with booleansAsIntegers option', () => {
  const formData = serialize(
    {
      foo: true,
      bar: false,
    },
    {
      booleansAsIntegers: true,
    },
  );

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo', 1);
  expect(formData.append).toHaveBeenNthCalledWith(2, 'bar', 0);
  expect(formData.get('foo')).toBe('1');
  expect(formData.get('bar')).toBe('0');
});

test('integer', () => {
  const formData = serialize({
    foo: 1,
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', 1);
  expect(formData.get('foo')).toBe('1');
});

test('float', () => {
  const formData = serialize({
    foo: 1.01,
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', 1.01);
  expect(formData.get('foo')).toBe('1.01');
});

test('string', () => {
  const formData = serialize({
    foo: 'bar',
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', 'bar');
  expect(formData.get('foo')).toBe('bar');
});

test('empty string', () => {
  const formData = serialize({
    foo: '',
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', '');
  expect(formData.get('foo')).toBe('');
});

test('Object', () => {
  const formData = serialize({
    foo: {
      bar: 'baz',
      qux: 'quux',
    },
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[bar]', 'baz');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[qux]', 'quux');
  expect(formData.get('foo[bar]')).toBe('baz');
  expect(formData.get('foo[qux]')).toBe('quux');
});

test('empty Object', () => {
  const formData = serialize({
    foo: {},
  });

  expect(formData.append).not.toHaveBeenCalled();
  expect(formData.get('foo')).toBe(null);
});

test('Object in Array', () => {
  const formData = serialize({
    foo: [
      {
        bar: 'baz',
      },
      {
        qux: 'quux',
      },
    ],
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[][bar]', 'baz');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[][qux]', 'quux');
  expect(formData.get('foo[][bar]')).toBe('baz');
  expect(formData.get('foo[][qux]')).toBe('quux');
});

test('Object in Object', () => {
  const formData = serialize({
    foo: {
      bar: {
        baz: {
          qux: 'quux',
        },
      },
    },
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo[bar][baz][qux]', 'quux');
  expect(formData.get('foo[bar][baz][qux]')).toBe('quux');
});

test('Object with dotsForObjectNotation option', () => {
  const formData = serialize(
    {
      foo: {
        bar: 'baz',
        qux: [
          {
            quux: 'corge',
          },
        ],
      },
    },
    {
      dotsForObjectNotation: true,
    },
  );

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo.bar', 'baz');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo.qux[].quux', 'corge');
  expect(formData.get('foo.bar')).toBe('baz');
  expect(formData.get('foo.qux[].quux')).toBe('corge');
});

test('Array', () => {
  const formData = serialize({
    foo: ['bar', 'baz'],
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[]', 'bar');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[]', 'baz');
  expect(formData.getAll('foo[]')).toEqual(['bar', 'baz']);
});

test('empty Array', () => {
  const formData = serialize({
    foo: [],
  });

  expect(formData.append).not.toHaveBeenCalled();
  expect(formData.get('foo')).toBe(null);
});

test('Array in Array', () => {
  const formData = serialize({
    foo: [[['bar', 'baz']]],
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[][][]', 'bar');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[][][]', 'baz');
  expect(formData.getAll('foo[][][]')).toEqual(['bar', 'baz']);
});

test('Array in Object', () => {
  const formData = serialize({
    foo: {
      bar: ['baz', 'qux'],
    },
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[bar][]', 'baz');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[bar][]', 'qux');
  expect(formData.getAll('foo[bar][]')).toEqual(['baz', 'qux']);
});

test('Array where key ends with "[]"', () => {
  const formData = serialize({
    'foo[]': ['bar', 'baz'],
  });

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[]', 'bar');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[]', 'baz');
  expect(formData.getAll('foo[]')).toEqual(['bar', 'baz']);
});

test('Array with indices option', () => {
  const formData = serialize(
    {
      foo: ['bar', 'baz'],
    },
    {
      indices: true,
    },
  );

  expect(formData.append).toHaveBeenCalledTimes(2);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[0]', 'bar');
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo[1]', 'baz');
  expect(formData.get('foo[0]')).toBe('bar');
  expect(formData.get('foo[1]')).toBe('baz');
});

test('Array with allowEmptyArrays option', () => {
  const formData = serialize(
    {
      foo: [],
    },
    {
      allowEmptyArrays: true,
    },
  );

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo[]', '');
  expect(formData.get('foo[]')).toBe('');
});

test('Date', () => {
  const foo = new Date(2000, 0, 1, 1, 1, 1);
  const formData = serialize({
    foo,
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', foo.toISOString());
  expect(formData.get('foo')).toBe(foo.toISOString());
});

test('File', () => {
  const foo = new File([], '');
  const formData = serialize({
    foo,
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', foo);
  expect(formData.get('foo')).toBe(foo);
});

test('File with noFilesWithArrayNotation option', () => {
  const bar = new File([], '');
  const baz = new File([], '');
  const foo = [bar, baz, 'qux'];
  const formData = serialize(
    {
      foo,
    },
    {
      noFilesWithArrayNotation: true,
    },
  );

  expect(formData.append).toHaveBeenCalledTimes(3);
  expect(formData.append).toHaveBeenNthCalledWith(1, 'foo', bar);
  expect(formData.append).toHaveBeenNthCalledWith(2, 'foo', baz);
  expect(formData.append).toHaveBeenNthCalledWith(3, 'foo[]', 'qux');
  expect(formData.getAll('foo')).toEqual([bar, baz]);
  expect(formData.getAll('foo[]')).toEqual(['qux']);
});

test('Blob', () => {
  const foo = new Blob([]);
  const formData = serialize({
    foo,
  });

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', foo);
  expect(formData.get('foo')).toEqual(new File([], ''));
});

test('React Native Blob', () => {
  global.FormData.prototype.getParts = () => {};

  const foo = {
    uri: 'content://...',
  };
  const formData = serialize({
    foo,
  });

  delete global.FormData.prototype.getParts;

  expect(formData.append).toHaveBeenCalledTimes(1);
  expect(formData.append).toHaveBeenCalledWith('foo', foo);
  expect(formData.get('foo')).toBe('[object Object]');
});


text: package kieker.monitoring.probe.aspectj.flow;


text:
package com.beetle.WebDemo.presentation;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.beetle.framework.web.controller.AbnormalViewControlerImp;
import com.beetle.framework.web.controller.ControllerException;
import com.beetle.framework.web.controller.WebInput;

public class DownloadController extends AbnormalViewControlerImp {
	public DownloadController() {
		//this.enableSessionCheck();
		this.setMaxParallelAmount(5);
	}

	public void performX(WebInput wi, OutputStream out)
			throws ControllerException {
		InputStream is = null;
		try {
			is = this.getServletContext()
					.getResourceAsStream("images/logo.zip");
			this.setContentType("application/octet-stream");
			this.addHeader("Content-Disposition",
					"attachment; filename=logo.zip");
			byte[] buff = new byte[2048];
			while (is.read(buff) != -1) {
				out.write(buff);
			}
		} catch (Exception e) {
			throw new ControllerException(e);
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				out.flush();
				out.close();
			} catch (IOException e) {
			}
		}
	}
}


text:
package org.apache.pig.impl.plan;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.Collections;

import org.apache.pig.data.DataType;
import org.apache.pig.impl.logicalLayer.schema.Schema;
import org.apache.pig.impl.util.MultiMap;
import org.apache.pig.impl.plan.optimizer.RuleOperator;
import org.apache.pig.impl.plan.optimizer.RulePlan;
import org.apache.pig.impl.plan.optimizer.RulePlanVisitor;

/**
 * A visitor mechanism printing out the logical plan.
 */
public class PlanPrinter<O extends Operator, P extends OperatorPlan<O>> extends PlanVisitor<O, P> {

    private PrintStream mStream = null;
    private String TAB1 = "    ";
    private String TABMore = "|   ";
    private String LSep = "|\n|---";
    private int levelCntr = -1;

    /**
     * @param ps PrintStream to output plan information to
     * @param plan Logical plan to print
     */
    public PlanPrinter(PrintStream ps, P plan) {
        //super(plan, new DependencyOrderWalker(plan));
        super(plan, new DepthFirstWalker<O, P>(plan));
        mStream = ps;
    }

    @Override
    public void visit() throws VisitorException {
        try {
            mStream.write(depthFirst().getBytes());
        } catch (IOException e) {
            throw new VisitorException(e);
        }
    }

    public void print(OutputStream printer) throws VisitorException, IOException {
        printer.write(depthFirst().getBytes());
    }

    @SuppressWarnings("unchecked")
    protected String depthFirst() throws VisitorException, IOException {
        StringBuilder sb = new StringBuilder();
        List<O> leaves = mPlan.getLeaves();
        Collections.sort(leaves);
        for (O leaf : leaves) {
            sb.append(depthFirst(leaf));
            sb.append("\n");
        }
        //sb.delete(sb.length() - "\n".length(), sb.length());
        //sb.delete(sb.length() - "\n".length(), sb.length());
        return sb.toString();
    }

    @SuppressWarnings("unchecked")
    private String depthFirst(O node) throws VisitorException, IOException {
        StringBuilder sb = new StringBuilder(node.name());
        sb.append("\n");

        List<O> originalPredecessors =  mPlan.getPredecessors(node);
        if (originalPredecessors == null)
            return sb.toString();

        List<O> predecessors =  new ArrayList<O>(originalPredecessors);

        Collections.sort(predecessors);
        int i = 0;
        for (O pred : predecessors) {
            i++;
            String DFStr = depthFirst(pred);
            if (DFStr != null) {
                sb.append(LSep);
                if (i < predecessors.size())
                    sb.append(shiftStringByTabs(DFStr, 2));
                else
                    sb.append(shiftStringByTabs(DFStr, 1));
            }
        }
        return sb.toString();
    }

    private String shiftStringByTabs(String DFStr, int TabType) {
        StringBuilder sb = new StringBuilder();
        String[] spl = DFStr.split("\n");

        String tab = (TabType == 1) ? TAB1 : TABMore;

        sb.append(spl[0] + "\n");
        for (int i = 1; i < spl.length; i++) {
            sb.append(tab);
            sb.append(spl[i]);
            sb.append("\n");
        }
        return sb.toString();
    }

    private void dispTabs() {
        for (int i = 0; i < levelCntr; i++)
            System.out.print(TAB1);
    }
}


text:
title: How to use express validator?
summary: How to use express validator through full examples. I found express validator very powerful, but having a poor documentation.
categories: webservice
tags: express nodejs validator
date: 2022-03-17 09:09:09 +0000
cover: https://cdn.pixabay.com/photo/2022/03/01/02/51/galaxy-7040416_1280.png
layout: post
---

How to use express validator through full examples. I found express validator very powerful, but having a poor documentation. I decided to offer some examples that are very common and probably mainly searched.

The official documentation can be checked on [Express Validator Documentation](https://express-validator.github.io/docs/) .

## Validate nested object using express validator

Sometimes you need to validate an object. If the object is required that's simple:

```js
req.body = {
    user: {
        email: "email@test.com",
        password: "pass"
    }
}
```

the validator looks like:

```js
app.post(
  '/user',
  // user is a required object
    body('user').exists().isObject(),
  // email must be an email
    body('user.email').exists().isEmail(),
  // password must be at least 5 chars long
    body('user.password').exists().isLength({ min: 3 }),

  (req, res, next) => {
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    next()
  },
);
```

What happens if the user object is optional, but if present email and password are required?

```js
app.post(
  '/user',
  // user is a required object
    body('user').exists().isObject(),
  // email must be an email
    body('user.email')
        .if(body('user').exists()) // check if user property exists
        .exists() // then check user.email to exists
        .isEmail(),
  // password must be at least 5 chars long
    body('user.password')
        .if(body('user').exists())
        .exists().isLength({ min: 3 }),

  (req, res, next) => {
    // Finds the validation errors in this request and wraps them in an object with handy functions
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    next()
  },
);
```


text:
@(inputType: String, field: Field, args: (Symbol,Any)*)(inputGroup: Html => Html)(implicit fc: b3.B3FieldConstructor, messages: Messages)
@inputFormGroup(field, withFeedback = true, withLabelFor = true, bs.Args.withAddingStringValue(args, 'class, "form-control")) { fieldInfo =>
	@inputGroup {
	    <input type="@inputType" id="@fieldInfo.id" name="@fieldInfo.name" value="@fieldInfo.value" @toHtmlArgs(fieldInfo.innerArgsMap)>
		@if(fieldInfo.hasFeedback) {

			(@fieldInfo.status)
		}
	}
}(fc, messages)


text:
from ..java import JavaSimProcedure

# pylint: disable=arguments-differ,unused-argument

class Exit(JavaSimProcedure):

    NO_RET = True

    __provides__ = (
        ("java.lang.System", "exit(int)"),
    )

    def run(self, exit_code):
        self.exit(exit_code)


text:
SELECT DISTINCT maker
FROM product
WHERE type = 'printer';


text:
package org.pentaho.di.trans.steps.metainject.lifecycle;

import org.pentaho.di.core.annotations.LifecyclePlugin;
import org.pentaho.di.core.lifecycle.LifeEventHandler;
import org.pentaho.di.core.lifecycle.LifecycleException;
import org.pentaho.di.core.lifecycle.LifecycleListener;
import org.pentaho.di.trans.steps.metainject.analyzer.MetaInjectAnalyzer;
import org.pentaho.platform.engine.core.system.PentahoSystem;

/**
 * Created by spravasahu on 08/02/22.
 */
@LifecyclePlugin( id = "KettleMetaInjectPlugin", name = "KettleMetaInjectPlugin" )
public class KettleMetaInjectPluginLifecycleListener implements LifecycleListener {

  @Override
  public void onStart( LifeEventHandler handler ) throws LifecycleException {
    MetaInjectAnalyzer getMetaInjectAnalyzer = new MetaInjectAnalyzer();

    PentahoSystem.registerObject( getMetaInjectAnalyzer );
  }

  @Override public void onExit( LifeEventHandler handler ) throws LifecycleException {
    // no-op
  }
}


text:
import os
import astropy.units as u
from astropy.io import fits
import numpy as np

from astropy.cosmology import FlatLambdaCDM
cosmo = FlatLambdaCDM(H0=70, Om0=0.3)

from .operator import Operator
from .. import standards
from ..filters import surveysetup
from ..external_links import file_humvi_compose
from .. import visualtools

class Imager(Operator):

	def __init__(self, **kwargs):
		"""
		Imager, parent class for all obj operator for images

		Params
		------
		Operator params:
			/either
				obj (object of class obsobj): with attributes ra, dec, dir_obj
			/or
				ra (float)
				dec (float)
				/either
					dir_obj (string)
				/or
					dir_parent (string): attr dir_obj is set to dir_parent+'SDSSJXXXX+XXXX/'

		survey (str):
			survey of the photometric system
			if not provided, use self.obj.survey. Raise exception if self.obj.survey does not exist.

		z=-1 (float):
			redshift, if not provided, use self.obj.z or self.obj.sdss.z. It does not automatically query sdss to get z. If nothing is pecified then set to -1.

		center_mode='n/2' (str):
			how is image center defined in case of even n, 'n/2' or 'n/2-1'. Should be set to n/2-1 if the image is downloaded from HSC quarry.

		Attributes
		----------
		Operator Attributes:
			obj (instance of objObj)
			ra (float)
			dec (float)
			dir_obj (string)

		survey (str): e.g., 'hsc'
			survey of the photometric system
		z (float):
			redshift
		pixsize (astropy angle quantity):
			in unit of arcsec
		pixelscale (astropy pixscale quantity):
			for pixel and arcsec conversion

		"""

		super(Imager, self).__init__(**kwargs)

		# set survey
		if hasattr(self.obj, 'survey'):
			default_survey = self.obj.survey
			self.survey = kwargs.pop('survey', default_survey)
		else:
			self.survey = kwargs.pop('survey')

		# set up obj.survey
		if self.survey == 'hsc':
			self.obj.add_hsc()
		elif self.survey == 'sdss':
			self.obj.add_sdss()

		# set z
		if hasattr(self.obj, 'z'):
			self.z = kwargs.pop('z', self.obj.z)
		elif hasattr(self.obj, 'sdss'):
			self.z = kwargs.pop('z', self.obj.sdss.z)
		elif 'z' in kwargs:
			self.z = kwargs.pop('z')
		else:
			print("[imager] not redshift used, assuming -1")
			self.z = -1

		# set center_mode
		self.center_mode = kwargs.pop('center_mode', 'n/2')

		# set pixsize
		self.pixsize = surveysetup.pixsize[self.survey]
		self.pixelscale = u.pixel_scale(self.pixsize/u.pixel)

	def get_fp_stamp(self, band):
		return self.dir_obj + self.get_fn_stamp(band)

	def get_fn_stamp(self, band):
		return 'stamp-{0}.fits'.format(band)

	def get_fp_psf(self, band):
		return self.dir_obj + self.get_fn_psf(band)

	def get_fn_psf(self, band):
		return 'psf-{0}.fits'.format(band)

	def get_fp_stamp_line(self, line):
		""" e.g., stamp-OIII5008.fits, for stamp in observed frame in flux """
		return self.dir_obj+'stamp-{0}.fits'.format(line)

	def get_fp_stamp_line_I(self, line):
		""" e.g., stamp-OIII5008_I.fits for stamp in rest frame in intensity"""
		return self.dir_obj+'stamp-{0}_I.fits'.format(line)

	def get_fp_stamp_img(self, imgtag):
		""" e.g., stamp-{imgtag}.fits"""
		return self.dir_obj+'stamp-{imgtag}.fits'.format(imgtag=imgtag)

	def get_stamp_img(self, imgtag, wunit=False):
		""" return the image as numpy array """
		fn_img = self.get_fp_stamp_img(imgtag=imgtag)
		hdus = fits.open(fn_img)
		if wunit:
			img = hdus[0].data * u.Unit(hdus[0].header['BUNIT'])
		else:
			img = hdus[0].data

		return img

	def _theta_to_pix(self, theta):
		""" convert an angular quantity (*u.arcsec) theta to pixel scale (float) """
		return (theta.to(u.pix, self.pixelscale)/u.pix).to(u.dimensionless_unscaled)

	def _pix_to_theta(self, pix, wunit=True):
		""" convert pix (float) to angular quantity (*u.arcsec) """
		result = (pix*u.pix).to(u.arcsec, self.pixelscale)
		if wunit:
			return result
		else:
			return (result/u.arcsec).to(u.dimensionless_unscaled)

	def _theta_to_kpc(self, theta, wunit=True):
		result = (theta*self._get_kpc_proper_per_arcsec()).to(u.kpc)

		if wunit:
			return result
		else:
			return (result/u.kpc).to(u.dimensionless_unscaled)

	def _get_kpc_proper_per_arcsec(self):
		return 1./cosmo.arcsec_per_kpc_proper(self.z)

	def _get_xc_yc(self, img):
		""" return (xc, yc) the coordinate of image center given image, according to self.center_mode """

		xc, yc = standards.get_img_xycenter(img, center_mode=self.center_mode)
		return xc, yc

	def make_colorimg(self, bands ='riz', img_type='stamp', s=[1.0, 1.1, 1.0], p=[1.6, 1.6], overwrite=False):
		"""
		make color composit image using external package HumVI. Example file name: 'color_stamp-riz.png'.

		See Humvi documentation -- https://github.com/drphilmarshall/HumVI

		Params
		------
		bands ='riz'
		img_type='stamp'
		s=[1.0, 1.1, 1.0]
			humvi params for color balance. Default is set to bring out the middle band.
		p=[1.6, 1.6]
			humvi params Q, alpha
		overwrite=False

		Return
		------
		status (bool)
		"""
		fn = self.dir_obj+'color_{img_type}-{bands}.png'.format(bands=bands, img_type=img_type)

		fns_in = [self.dir_obj+img_type+'-'+band+'.fits' for band in bands[::-1]]

		# set params, for example, commandparams = ' -s 1.0,1.1,1.0  -p 1.6,1.6  -o '
		commandparams = ' -s {}  -p {}  -o '.format(','.join(np.array(s).astype('str')), ','.join(np.array(p).astype('str')))

		if (not os.path.isfile(fn)) or overwrite:
			commandfiles = '{0} {1} {2} {3}'.format(fn, fns_in[0], fns_in[1], fns_in[2])
			commandHumVI = file_humvi_compose+commandparams+commandfiles

			os.system(commandHumVI)

		status = os.path.isfile(fn)

		return status

	def plot_stamp_linemap_I(self, line='OIII5008', overwrite=False, vmin=None, vmax=10.):
		"""
		plot line map I as png.

		Params
		------
		self
		line='OIII5008' (str)
		overwrite=False (bool)

		Return
		------
		status (bool)
		"""
		fn = self.get_fp_stamp_line_I(line=line)
		fn_out = os.path.splitext(fn)[0]+'.png'

		if not os.path.isfile(fn_out) or overwrite:
			print("[decomposer] plotting linemap")
			visualtools.fits_to_png(fn_in=fn, fn_out=fn_out, vmin=vmin, vmax=vmax, scaling='arcsinh')
		else:
			print("[decomposer] skip plotting linemap as files exist")

		return os.path.isfile(fn_out)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.allyants.boardview.BoardView
        xmlns:boardview="http://schemas.android.com/apk/res-auto/com.allyants.boardview"
        boardview:boardItemBackground="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/boardView" />
</RelativeLayout>


text:
<?php
namespace Oro\Bundle\MeasureBundle\Tests\DependencyInjection;

use Oro\Bundle\MeasureBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Test related class
 *
 *
 */
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Test related method
     */
    public function testGetConfigTreeBuilder()
    {
        $configuration = new Configuration();
        $this->assertTrue($configuration->getConfigTreeBuilder() instanceof TreeBuilder);
    }
}


text:
package org.apache.beam.examples.complete.datatokenization.transforms;

import static org.apache.beam.sdk.util.RowJsonUtils.rowToJson;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.services.bigquery.model.TableRow;
import com.google.auto.value.AutoValue;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.beam.examples.complete.datatokenization.utils.FailsafeElement;
import org.apache.beam.examples.complete.datatokenization.utils.FailsafeElementCoder;
import org.apache.beam.sdk.coders.RowCoder;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.Field;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.GroupIntoBatches;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.util.RowJson;
import org.apache.beam.sdk.util.RowJsonUtils;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionTuple;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TupleTagList;
import org.apache.beam.vendor.grpc.v1p36p0.com.google.gson.Gson;
import org.apache.beam.vendor.grpc.v1p36p0.com.google.gson.JsonArray;
import org.apache.beam.vendor.grpc.v1p36p0.com.google.gson.JsonObject;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Throwables;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.joda.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The {@link DataProtectors} Using passing parameters transform will buffer input rows in batch and
 * will send it when the count of buffered rows will equal specified batch size. When it takes the
 * last one batch, it will send it when the last row will come to doFn even count of buffered rows
 * will less than the batch size.
 */
public class DataProtectors {

  /** Logger for class. */
  private static final Logger LOG = LoggerFactory.getLogger(DataProtectors.class);

  public static final String ID_FIELD_NAME = "ID";
  private static final Long MAX_BUFFERING_DURATION_MS =
      Long.valueOf(System.getenv().getOrDefault("MAX_BUFFERING_DURATION_MS", "100"));

  /**
   * The {@link RowToTokenizedRow} transform converts {@link Row} to {@link TableRow} objects. The
   * transform accepts a {@link FailsafeElement} object so the original payload of the incoming
   * record can be maintained across multiple series of transforms.
   */
  @AutoValue
  public abstract static class RowToTokenizedRow<T>
      extends PTransform<PCollection<KV<Integer, Row>>, PCollectionTuple> {

    public static <T> Builder<T> newBuilder() {
      return new AutoValue_DataProtectors_RowToTokenizedRow.Builder<>();
    }

    public abstract TupleTag<Row> successTag();

    public abstract TupleTag<FailsafeElement<Row, Row>> failureTag();

    public abstract Schema schema();

    public abstract int batchSize();

    public abstract String rpcURI();

    @Override
    public PCollectionTuple expand(PCollection<KV<Integer, Row>> inputRows) {
      FailsafeElementCoder<Row, Row> coder =
          FailsafeElementCoder.of(RowCoder.of(schema()), RowCoder.of(schema()));

      Duration maxBuffering = Duration.millis(MAX_BUFFERING_DURATION_MS);
      PCollectionTuple pCollectionTuple =
          inputRows
              .apply(
                  "GroupRowsIntoBatches",
                  GroupIntoBatches.<Integer, Row>ofSize(batchSize())
                      .withMaxBufferingDuration(maxBuffering))
              .apply(
                  "Tokenize",
                  ParDo.of(new TokenizationFn(schema(), rpcURI(), failureTag()))
                      .withOutputTags(successTag(), TupleTagList.of(failureTag())));

      return PCollectionTuple.of(
              successTag(), pCollectionTuple.get(successTag()).setRowSchema(schema()))
          .and(failureTag(), pCollectionTuple.get(failureTag()).setCoder(coder));
    }

    /** Builder for {@link RowToTokenizedRow}. */
    @AutoValue.Builder
    public abstract static class Builder<T> {

      public abstract Builder<T> setSuccessTag(TupleTag<Row> successTag);

      public abstract Builder<T> setFailureTag(TupleTag<FailsafeElement<Row, Row>> failureTag);

      public abstract Builder<T> setSchema(Schema schema);

      public abstract Builder<T> setBatchSize(int batchSize);

      public abstract Builder<T> setRpcURI(String rpcURI);

      public abstract RowToTokenizedRow<T> build();
    }
  }

  /** Class implements stateful doFn for data tokenization using remote RPC. */
  @SuppressWarnings("initialization.static.fields.uninitialized")
  public static class TokenizationFn extends DoFn<KV<Integer, Iterable<Row>>, Row> {

    private static Schema schemaToRpc;
    private static CloseableHttpClient httpclient;
    private static ObjectMapper objectMapperSerializerForSchema;
    private static ObjectMapper objectMapperDeserializerForSchema;

    private final Schema schema;
    private final String rpcURI;
    private final TupleTag<FailsafeElement<Row, Row>> failureTag;

    private Map<String, Row> inputRowsWithIds;

    public TokenizationFn(
        Schema schema, String rpcURI, TupleTag<FailsafeElement<Row, Row>> failureTag) {
      this.schema = schema;
      this.rpcURI = rpcURI;
      this.failureTag = failureTag;
      this.inputRowsWithIds = new HashMap<>();
    }

    @Setup
    public void setup() {

      List<Field> fields = schema.getFields();
      fields.add(Field.of(ID_FIELD_NAME, FieldType.STRING));
      schemaToRpc = new Schema(fields);

      objectMapperSerializerForSchema =
          RowJsonUtils.newObjectMapperWith(RowJson.RowJsonSerializer.forSchema(schemaToRpc));

      objectMapperDeserializerForSchema =
          RowJsonUtils.newObjectMapperWith(RowJson.RowJsonDeserializer.forSchema(schemaToRpc));

      httpclient = HttpClients.createDefault();
    }

    @Teardown
    public void close() {
      try {
        httpclient.close();
      } catch (IOException exception) {
        String exceptionMessage = exception.getMessage();
        if (exceptionMessage != null) {
          LOG.warn("Can't close connection: {}", exceptionMessage);
        }
      }
    }

    @ProcessElement
    @SuppressWarnings("argument.type.incompatible")
    public void process(@Element KV<Integer, Iterable<Row>> element, ProcessContext context) {
      Iterable<Row> rows = element.getValue();

      try {
        for (Row outputRow : getTokenizedRow(rows)) {
          context.output(outputRow);
        }
      } catch (Exception e) {
        for (Row outputRow : rows) {
          context.output(
              failureTag,
              FailsafeElement.of(outputRow, outputRow)
                  .setErrorMessage(e.getMessage())
                  .setStacktrace(Throwables.getStackTraceAsString(e)));
        }
      }
    }

    private ArrayList<String> rowsToJsons(Iterable<Row> inputRows) {
      ArrayList<String> jsons = new ArrayList<>();
      Map<String, Row> inputRowsWithIds = new HashMap<>();
      for (Row inputRow : inputRows) {

        Row.Builder builder = Row.withSchema(schemaToRpc);
        for (Schema.Field field : schemaToRpc.getFields()) {
          if (inputRow.getSchema().hasField(field.getName())) {
            builder = builder.addValue(inputRow.getValue(field.getName()));
          }
        }
        String id = UUID.randomUUID().toString();
        builder = builder.addValue(id);
        inputRowsWithIds.put(id, inputRow);

        Row row = builder.build();

        jsons.add(rowToJson(objectMapperSerializerForSchema, row));
      }
      this.inputRowsWithIds = inputRowsWithIds;
      return jsons;
    }

    private String formatJsonsToRpcBatch(Iterable<String> jsons) {
      StringBuilder stringBuilder = new StringBuilder(String.join(",", jsons));
      stringBuilder.append("]").insert(0, "{\"data\": [").append("}");
      return stringBuilder.toString();
    }

    @SuppressWarnings("argument.type.incompatible")
    private ArrayList<Row> getTokenizedRow(Iterable<Row> inputRows) throws IOException {
      ArrayList<Row> outputRows = new ArrayList<>();

      CloseableHttpResponse response =
          sendRpc(formatJsonsToRpcBatch(rowsToJsons(inputRows)).getBytes(Charset.defaultCharset()));

      if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        LOG.error("Send to RPC '{}' failed with '{}'", this.rpcURI, response.getStatusLine());
      }

      String tokenizedData =
          IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);

      Gson gson = new Gson();
      JsonArray jsonTokenizedRows =
          gson.fromJson(tokenizedData, JsonObject.class).getAsJsonArray("data");

      for (int i = 0; i < jsonTokenizedRows.size(); i++) {
        Row tokenizedRow =
            RowJsonUtils.jsonToRow(
                objectMapperDeserializerForSchema, jsonTokenizedRows.get(i).toString());
        Row.FieldValueBuilder rowBuilder =
            Row.fromRow(this.inputRowsWithIds.get(tokenizedRow.getString(ID_FIELD_NAME)));
        for (Schema.Field field : schemaToRpc.getFields()) {
          if (field.getName().equals(ID_FIELD_NAME)) {
            continue;
          }
          rowBuilder =
              rowBuilder.withFieldValue(field.getName(), tokenizedRow.getValue(field.getName()));
        }
        outputRows.add(rowBuilder.build());
      }

      return outputRows;
    }

    private CloseableHttpResponse sendRpc(byte[] data) throws IOException {
      HttpPost httpPost = new HttpPost(rpcURI);
      HttpEntity stringEntity = new ByteArrayEntity(data, ContentType.APPLICATION_JSON);
      httpPost.setEntity(stringEntity);
      return httpclient.execute(httpPost);
    }
  }
}


text:
using content::WebContents;

namespace {

// The height in pixels of the titlebar.
const int kTitlebarHeight = 24;

// The thickness in pixels of the border.
#if defined(USE_AURA)
// No border inside the window frame; see comment in PaintFrameBorder().
const int kResizableBorderThickness = 0;
const int kNonResizableBorderThickness = 0;
#else
const int kResizableBorderThickness = 4;
const int kNonResizableBorderThickness = 1;
#endif

// Client edge is only present on thick border when the panel is resizable.
const int kResizableClientEdgeThickness = 1;
const int kNonResizableClientEdgeThickness = 0;

// In the window corners, the resize areas don't actually expand bigger, but the
// 16 px at the end of each edge triggers diagonal resizing.
const int kResizeAreaCornerSize = 16;

// Colors used to draw client edges. These are experimental values.
const SkColor kClientEdgeColor = SkColorSetRGB(210, 225, 246);
const SkColor kContentsBorderShadow = SkColorSetARGB(51, 0, 0, 0);

// The spacing in pixels between the icon and the left border.
const int kIconAndBorderSpacing = 4;

// The height and width in pixels of the icon.
const int kIconSize = 16;

// The spacing in pixels between the title and the icon on the left, or the
// button on the right.
const int kTitleSpacing = 8;

// The spacing in pixels between the close button and the right border.
const int kCloseButtonAndBorderSpacing = 8;

// The spacing in pixels between the close button and the minimize/restore
// button.
const int kMinimizeButtonAndCloseButtonSpacing = 8;

// Colors used to draw active titlebar under default theme.
const SkColor kActiveTitleTextDefaultColor = SK_ColorBLACK;
const SkColor kActiveBackgroundDefaultColorStart = 0xfff0f8fa;
const SkColor kActiveBackgroundDefaultColorEnd = 0xffc1d2dd;

// Colors used to draw inactive titlebar under default theme.
const SkColor kInactiveTitleTextDefaultColor = 0x80888888;
const SkColor kInactiveBackgroundDefaultColorStart = 0xffffffff;
const SkColor kInactiveBackgroundDefaultColorEnd = 0xffe7edf1;

// Alpha value used in drawing inactive titlebar under default theme.
const U8CPU kInactiveAlphaBlending = 0x80;

// Colors used to draw titlebar for drawing attention under default theme.
// It is also used in non-default theme since attention color is not defined
// in the theme.
const SkColor kAttentionTitleTextDefaultColor = SK_ColorWHITE;
const SkColor kAttentionBackgroundDefaultColorStart = 0xffffab57;
const SkColor kAttentionBackgroundDefaultColorEnd = 0xfff59338;

// Color used to draw the border.
const SkColor kBorderColor = 0xc0000000;

// Color used to draw the divider line between the titlebar and the client area.
const SkColor kDividerColor = 0xffb5b5b5;

struct ButtonResources {
  SkBitmap* normal_image;
  SkBitmap* hover_image;
  string16 tooltip_text;

  ButtonResources(int normal_image_id, int hover_image_id, int tooltip_id)
      : normal_image(NULL),
        hover_image(NULL) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    normal_image = rb.GetBitmapNamed(normal_image_id);
    hover_image = rb.GetBitmapNamed(hover_image_id);
    tooltip_text = l10n_util::GetStringUTF16(tooltip_id);
  }
};

struct EdgeResources {
  SkBitmap* top_left;
  SkBitmap* top;
  SkBitmap* top_right;
  SkBitmap* right;
  SkBitmap* bottom_right;
  SkBitmap* bottom;
  SkBitmap* bottom_left;
  SkBitmap* left;

  EdgeResources(int top_left_id, int top_id, int top_right_id, int right_id,
                int bottom_right_id, int bottom_id, int bottom_left_id,
                int left_id)
      : top_left(NULL),
        top(NULL),
        top_right(NULL),
        right(NULL),
        bottom_right(NULL),
        bottom(NULL),
        bottom_left(NULL),
        left(NULL) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    top_left = rb.GetBitmapNamed(top_left_id);
    top = rb.GetBitmapNamed(top_id);
    top_right = rb.GetBitmapNamed(top_right_id);
    right = rb.GetBitmapNamed(right_id);
    bottom_right = rb.GetBitmapNamed(bottom_right_id);
    bottom = rb.GetBitmapNamed(bottom_id);
    bottom_left = rb.GetBitmapNamed(bottom_left_id);
    left = rb.GetBitmapNamed(left_id);
  }
};

SkBitmap* CreateGradientBitmap(SkColor start_color, SkColor end_color) {
  int gradient_size = kResizableBorderThickness +
      kResizableClientEdgeThickness + kTitlebarHeight;
  SkShader* shader = gfx::CreateGradientShader(
      0, gradient_size, start_color, end_color);
  SkPaint paint;
  paint.setStyle(SkPaint::kFill_Style);
  paint.setAntiAlias(true);
  paint.setShader(shader);
  shader->unref();
  gfx::Canvas canvas(gfx::Size(1, gradient_size), true);
  canvas.DrawRect(gfx::Rect(0, 0, 1, gradient_size), paint);
  return new SkBitmap(canvas.ExtractBitmap());
}

const ButtonResources& GetCloseButtonResources() {
  static ButtonResources* buttons = NULL;
  if (!buttons) {
    buttons = new ButtonResources(IDR_PANEL_CLOSE,
                                  IDR_PANEL_CLOSE_H,
                                  IDS_PANEL_CLOSE_TOOLTIP);
  }
  return *buttons;
}

const ButtonResources& GetMinimizeButtonResources() {
  static ButtonResources* buttons = NULL;
  if (!buttons) {
    buttons = new ButtonResources(IDR_PANEL_MINIMIZE,
                                  IDR_PANEL_MINIMIZE_H,
                                  IDS_PANEL_MINIMIZE_TOOLTIP);
  }
  return *buttons;
}

const ButtonResources& GetRestoreButtonResources() {
  static ButtonResources* buttons = NULL;
  if (!buttons) {
    buttons = new ButtonResources(IDR_PANEL_RESTORE,
                                  IDR_PANEL_RESTORE_H,
                                  IDS_PANEL_RESTORE_TOOLTIP);
  }
  return *buttons;
}

const EdgeResources& GetFrameEdges() {
  static EdgeResources* edges = NULL;
  if (!edges) {
    edges = new EdgeResources(
        IDR_WINDOW_TOP_LEFT_CORNER, IDR_WINDOW_TOP_CENTER,
        IDR_WINDOW_TOP_RIGHT_CORNER, IDR_WINDOW_RIGHT_SIDE,
        IDR_PANEL_BOTTOM_RIGHT_CORNER, IDR_WINDOW_BOTTOM_CENTER,
        IDR_PANEL_BOTTOM_LEFT_CORNER, IDR_WINDOW_LEFT_SIDE);
  }
  return *edges;
}

const EdgeResources& GetClientEdges() {
  static EdgeResources* edges = NULL;
  if (!edges) {
    edges = new EdgeResources(
        IDR_APP_TOP_LEFT, IDR_APP_TOP_CENTER,
        IDR_APP_TOP_RIGHT, IDR_CONTENT_RIGHT_SIDE,
        IDR_CONTENT_BOTTOM_RIGHT_CORNER, IDR_CONTENT_BOTTOM_CENTER,
        IDR_CONTENT_BOTTOM_LEFT_CORNER, IDR_CONTENT_LEFT_SIDE);
  }
  return *edges;
}

const gfx::Font& GetTitleFont() {
  static gfx::Font* font = NULL;
  if (!font) {
    ResourceBundle& rb = ResourceBundle::GetSharedInstance();
    font = new gfx::Font(rb.GetFont(ResourceBundle::BoldFont));
  }
  return *font;
}

SkBitmap* GetActiveBackgroundDefaultBitmap() {
  static SkBitmap* bitmap = NULL;
  if (!bitmap) {
    bitmap = CreateGradientBitmap(kActiveBackgroundDefaultColorStart,
                                  kActiveBackgroundDefaultColorEnd);
  }
  return bitmap;
}

SkBitmap* GetInactiveBackgroundDefaultBitmap() {
  static SkBitmap* bitmap = NULL;
  if (!bitmap) {
    bitmap = CreateGradientBitmap(kInactiveBackgroundDefaultColorStart,
                                  kInactiveBackgroundDefaultColorEnd);
  }
  return bitmap;
}

SkBitmap* GetAttentionBackgroundDefaultBitmap() {
  static SkBitmap* bitmap = NULL;
  if (!bitmap) {
    bitmap = CreateGradientBitmap(kAttentionBackgroundDefaultColorStart,
                                  kAttentionBackgroundDefaultColorEnd);
  }
  return bitmap;
}

bool IsHitTestValueForResizing(int hc) {
  return hc == HTLEFT || hc == HTRIGHT || hc == HTTOP || hc == HTBOTTOM ||
         hc == HTTOPLEFT || hc == HTTOPRIGHT || hc == HTBOTTOMLEFT ||
         hc == HTBOTTOMRIGHT;
}

}  // namespace

PanelBrowserFrameView::PanelBrowserFrameView(BrowserFrame* frame,
                                             PanelBrowserView* browser_view)
    : BrowserNonClientFrameView(frame, browser_view),
      panel_browser_view_(browser_view),
      paint_state_(NOT_PAINTED),
      close_button_(NULL),
      minimize_button_(NULL),
      restore_button_(NULL),
      title_icon_(NULL),
      title_label_(NULL) {
  frame->set_frame_type(views::Widget::FRAME_TYPE_FORCE_CUSTOM);

  const ButtonResources& close_button_resources = GetCloseButtonResources();
  close_button_ = new views::ImageButton(this);
  close_button_->SetImage(views::CustomButton::BS_NORMAL,
                          close_button_resources.normal_image);
  close_button_->SetImage(views::CustomButton::BS_HOT,
                          close_button_resources.hover_image);
  close_button_->SetTooltipText(close_button_resources.tooltip_text);
  close_button_->SetAccessibleName(close_button_resources.tooltip_text);
  AddChildView(close_button_);

  const ButtonResources& minimize_button_resources =
      GetMinimizeButtonResources();
  minimize_button_ = new views::ImageButton(this);
  minimize_button_->SetImage(views::CustomButton::BS_NORMAL,
                             minimize_button_resources.normal_image);
  minimize_button_->SetImage(views::CustomButton::BS_HOT,
                             minimize_button_resources.hover_image);
  minimize_button_->SetTooltipText(minimize_button_resources.tooltip_text);
  minimize_button_->SetAccessibleName(minimize_button_resources.tooltip_text);
  AddChildView(minimize_button_);

  const ButtonResources& restore_button_resources =
      GetRestoreButtonResources();
  restore_button_ = new views::ImageButton(this);
  restore_button_->SetImage(views::CustomButton::BS_NORMAL,
                            restore_button_resources.normal_image);
  restore_button_->SetImage(views::CustomButton::BS_HOT,
                            restore_button_resources.hover_image);
  restore_button_->SetTooltipText(restore_button_resources.tooltip_text);
  restore_button_->SetAccessibleName(restore_button_resources.tooltip_text);
  restore_button_->SetVisible(false);  // only visible when panel is minimized
  AddChildView(restore_button_);

  title_icon_ = new TabIconView(this);
  title_icon_->set_is_light(true);
  AddChildView(title_icon_);
  title_icon_->Update();

  title_label_ = new views::Label(GetTitleText());
  title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  title_label_->SetAutoColorReadabilityEnabled(false);
  AddChildView(title_label_);
}

PanelBrowserFrameView::~PanelBrowserFrameView() {
}

gfx::Rect PanelBrowserFrameView::GetBoundsForTabStrip(
    views::View* tabstrip) const {
  // Panels never show a tab strip.
  NOTREACHED();
  return gfx::Rect();
}

int PanelBrowserFrameView::GetHorizontalTabStripVerticalOffset(
    bool restored) const {
  // This is not needed since we do not show tab strip for the panel.
  return 0;
}

void PanelBrowserFrameView::UpdateThrobber(bool running) {
  // Tells the title icon to update the throbber when we need to show the
  // animation to indicate we're still loading.
  title_icon_->Update();
}

gfx::Rect PanelBrowserFrameView::GetBoundsForClientView() const {
  return client_view_bounds_;
}

gfx::Rect PanelBrowserFrameView::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) const {
  int top_height = NonClientTopBorderHeight();
  int border_thickness = NonClientBorderThickness();
  return gfx::Rect(std::max(0, client_bounds.x() - border_thickness),
                   std::max(0, client_bounds.y() - top_height),
                   client_bounds.width() + (2 * border_thickness),
                   client_bounds.height() + top_height + border_thickness);
}

int PanelBrowserFrameView::NonClientHitTest(const gfx::Point& point) {
  PanelStrip* panel_strip = panel_browser_view_->panel()->panel_strip();
  if (!panel_strip)
    return HTNOWHERE;

  if (!bounds().Contains(point))
    return HTNOWHERE;

  int frame_component =
      frame()->client_view()->NonClientHitTest(point);
  if (frame_component != HTNOWHERE)
    return frame_component;

  if (close_button_->visible() &&
      close_button_->GetMirroredBounds().Contains(point))
    return HTCLOSE;

  if (minimize_button_->visible() &&
      minimize_button_->GetMirroredBounds().Contains(point))
    return HTMINBUTTON;

  if (restore_button_->visible() &&
      restore_button_->GetMirroredBounds().Contains(point))
    return HTMAXBUTTON;

  int window_component = GetHTComponentForFrame(point,
      NonClientBorderThickness(), NonClientBorderThickness(),
      kResizeAreaCornerSize, kResizeAreaCornerSize,
      CanResize());

  // The bottom edge and corners cannot be used to resize in some scenarios,
  // i.e docked panels.
  panel::Resizability resizability = panel_strip->GetPanelResizability(
      panel_browser_view_->panel());
  if (resizability == panel::RESIZABLE_ALL_SIDES_EXCEPT_BOTTOM &&
      (window_component == HTBOTTOM ||
       window_component == HTBOTTOMLEFT ||
       window_component == HTBOTTOMRIGHT))
    return HTNOWHERE;

  // Fall back to the caption if no other component matches.
  return (window_component == HTNOWHERE) ? HTCAPTION : window_component;
}

void PanelBrowserFrameView::GetWindowMask(const gfx::Size& size,
                                          gfx::Path* window_mask) {
  window_mask->moveTo(0, 3);
  window_mask->lineTo(1, 2);
  window_mask->lineTo(1, 1);
  window_mask->lineTo(2, 1);
  window_mask->lineTo(3, 0);
  window_mask->lineTo(SkIntToScalar(size.width() - 3), 0);
  window_mask->lineTo(SkIntToScalar(size.width() - 2), 1);
  window_mask->lineTo(SkIntToScalar(size.width() - 1), 1);
  window_mask->lineTo(SkIntToScalar(size.width() - 1), 2);
  window_mask->lineTo(SkIntToScalar(size.width() - 1), 3);
  window_mask->lineTo(SkIntToScalar(size.width()),
                      SkIntToScalar(size.height()));
  window_mask->lineTo(0, SkIntToScalar(size.height()));
  window_mask->close();
}

void PanelBrowserFrameView::ResetWindowControls() {
  // The close button isn't affected by this constraint.
}

void PanelBrowserFrameView::UpdateWindowIcon() {
  title_icon_->SchedulePaint();
}

void PanelBrowserFrameView::OnPaint(gfx::Canvas* canvas) {
  // The font and color need to be updated depending on the panel's state.
  PaintState paint_state;
  if (panel_browser_view_->panel()->IsDrawingAttention())
    paint_state = PAINT_FOR_ATTENTION;
  else if (panel_browser_view_->focused())
    paint_state = PAINT_AS_ACTIVE;
  else
    paint_state = PAINT_AS_INACTIVE;

  UpdateControlStyles(paint_state);
  PaintFrameBackground(canvas);
  PaintFrameEdge(canvas);
  PaintClientEdge(canvas);
}

void PanelBrowserFrameView::OnThemeChanged() {
}

gfx::Size PanelBrowserFrameView::GetMinimumSize() {
  // This makes the panel be able to shrink to very small, like minimized panel.
  return gfx::Size();
}

gfx::Size PanelBrowserFrameView::GetMaximumSize() {
  // When the user resizes the panel, there is no max size limit.
  return gfx::Size();
}

void PanelBrowserFrameView::Layout() {
  Panel* panel = panel_browser_view_->panel();
  PanelStrip* panel_strip = panel->panel_strip();
  if (!panel_strip)
    return;

  // Layout the close button.
  int right = width();
  gfx::Size close_button_size = close_button_->GetPreferredSize();
  close_button_->SetBounds(
      width() - NonClientBorderThickness() - kCloseButtonAndBorderSpacing -
      close_button_size.width(),
      (NonClientTopBorderHeight() - close_button_size.height()) / 2,
      close_button_size.width(),
      close_button_size.height());
  right = close_button_->x();

  // Layout the minimize and restore button. Both occupy the same space,
  // but at most one is visible at any time.
  gfx::Size button_size = minimize_button_->GetPreferredSize();
  minimize_button_->SetBounds(
      right - kMinimizeButtonAndCloseButtonSpacing - button_size.width(),
      (NonClientTopBorderHeight() - button_size.height()) / 2,
      button_size.width(),
      button_size.height());
  restore_button_->SetBoundsRect(minimize_button_->bounds());
  right = minimize_button_->x();

  // Layout the icon.
  int icon_y = (NonClientTopBorderHeight() - kIconSize) / 2;
  title_icon_->SetBounds(
      NonClientBorderThickness() + kIconAndBorderSpacing,
      icon_y,
      kIconSize,
      kIconSize);

  // Layout the title.
  int title_x = title_icon_->bounds().right() + kTitleSpacing;
  int title_height = BrowserFrame::GetTitleFont().GetHeight();
  title_label_->SetBounds(
      title_x,
      icon_y + ((kIconSize - title_height - 1) / 2),
      std::max(0, right - kTitleSpacing - title_x),
      title_height);

  // Calculate the client area bounds.
  int top_height = NonClientTopBorderHeight();
  int border_thickness = NonClientBorderThickness();
  client_view_bounds_.SetRect(
      border_thickness,
      top_height,
      std::max(0, width() - (2 * border_thickness)),
      std::max(0, height() - top_height - border_thickness));
}

void PanelBrowserFrameView::GetAccessibleState(ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_TITLEBAR;
}

bool PanelBrowserFrameView::OnMousePressed(const views::MouseEvent& event) {
  gfx::Point mouse_location = event.location();

  if (CanResize() &&
      IsHitTestValueForResizing(NonClientHitTest(mouse_location)))
    return BrowserNonClientFrameView::OnMousePressed(event);

  // |event.location| is in the view's coordinate system. Convert it to the
  // screen coordinate system.
  views::View::ConvertPointToScreen(this, &mouse_location);

  if (event.IsOnlyLeftMouseButton() &&
      panel_browser_view_->OnTitlebarMousePressed(mouse_location)) {
    return true;
  }
  return BrowserNonClientFrameView::OnMousePressed(event);
}

bool PanelBrowserFrameView::OnMouseDragged(const views::MouseEvent& event) {
  // |event.location| is in the view's coordinate system. Convert it to the
  // screen coordinate system.
  gfx::Point mouse_location = event.location();
  views::View::ConvertPointToScreen(this, &mouse_location);

  if (panel_browser_view_->OnTitlebarMouseDragged(mouse_location))
    return true;
  return BrowserNonClientFrameView::OnMouseDragged(event);
}

void PanelBrowserFrameView::OnMouseReleased(const views::MouseEvent& event) {
  if (panel_browser_view_->OnTitlebarMouseReleased(
          event.IsControlDown() ? panel::APPLY_TO_ALL : panel::NO_MODIFIER))
    return;
  BrowserNonClientFrameView::OnMouseReleased(event);
}

void PanelBrowserFrameView::OnMouseCaptureLost() {
  if (panel_browser_view_->OnTitlebarMouseCaptureLost())
    return;
  BrowserNonClientFrameView::OnMouseCaptureLost();
}

void PanelBrowserFrameView::ButtonPressed(views::Button* sender,
                                          const views::Event& event) {
  if (sender == close_button_) {
    frame()->Close();
  } else {
    panel::ClickModifier modifier =
        event.IsControlDown() ? panel::APPLY_TO_ALL : panel::NO_MODIFIER;
    if (sender == minimize_button_)
      panel_browser_view_->panel()->OnMinimizeButtonClicked(modifier);
    else if (sender == restore_button_)
      panel_browser_view_->panel()->OnRestoreButtonClicked(modifier);
  }
}

bool PanelBrowserFrameView::ShouldTabIconViewAnimate() const {
  // This function is queried during the creation of the window as the
  // TabIconView we host is initialized, so we need to NULL check the selected
  // WebContents because in this condition there is not yet a selected tab.
  WebContents* current_tab = browser_view()->GetSelectedWebContents();
  return current_tab ? current_tab->IsLoading() : false;
}

SkBitmap PanelBrowserFrameView::GetFaviconForTabIconView() {
  return frame()->widget_delegate()->GetWindowIcon();
}

int PanelBrowserFrameView::NonClientBorderThickness() const {
  if (CanResize())
    return kResizableBorderThickness + kResizableClientEdgeThickness;
  else
    return kNonResizableBorderThickness + kNonResizableClientEdgeThickness;
}

int PanelBrowserFrameView::NonClientTopBorderHeight() const {
  return NonClientBorderThickness() + kTitlebarHeight;
}

gfx::Size PanelBrowserFrameView::NonClientAreaSize() const {
  return gfx::Size(NonClientBorderThickness() * 2,
                   NonClientTopBorderHeight() + NonClientBorderThickness());
}

int PanelBrowserFrameView::IconOnlyWidth() const {
  return NonClientBorderThickness() * 2 + kIconAndBorderSpacing * 2 + kIconSize;
}

bool PanelBrowserFrameView::UsingDefaultTheme(PaintState paint_state) const {
  // No theme is provided for attention painting.
  if (paint_state == PAINT_FOR_ATTENTION)
    return true;

  ThemeService* theme_service = ThemeServiceFactory::GetForProfile(
      panel_browser_view_->panel()->browser()->profile());
  return theme_service->UsingDefaultTheme();
}

SkColor PanelBrowserFrameView::GetTitleColor(PaintState paint_state) const {
  bool use_default = UsingDefaultTheme(paint_state);
  switch (paint_state) {
    case PAINT_AS_INACTIVE:
      return use_default ? kActiveTitleTextDefaultColor: SkColorSetA(
          GetThemeProvider()->GetColor(ThemeService::COLOR_BACKGROUND_TAB_TEXT),
          kInactiveAlphaBlending);
    case PAINT_AS_ACTIVE:
      return use_default ? kActiveTitleTextDefaultColor :
          GetThemeProvider()->GetColor(ThemeService::COLOR_TAB_TEXT);
    case PAINT_FOR_ATTENTION:
      return kAttentionTitleTextDefaultColor;
    default:
      NOTREACHED();
      return SkColor();
  }
}

SkBitmap* PanelBrowserFrameView::GetFrameTheme(PaintState paint_state) const {
  bool use_default = UsingDefaultTheme(paint_state);
  switch (paint_state) {
    case PAINT_AS_INACTIVE:
      return use_default ? GetInactiveBackgroundDefaultBitmap() :
          GetThemeProvider()->GetBitmapNamed(IDR_THEME_TAB_BACKGROUND);
    case PAINT_AS_ACTIVE:
      return use_default ? GetActiveBackgroundDefaultBitmap() :
          GetThemeProvider()->GetBitmapNamed(IDR_THEME_TOOLBAR);
    case PAINT_FOR_ATTENTION:
      return GetAttentionBackgroundDefaultBitmap();
    default:
      return GetInactiveBackgroundDefaultBitmap();
  }
}

void PanelBrowserFrameView::UpdateControlStyles(PaintState paint_state) {
  DCHECK(paint_state != NOT_PAINTED);

  if (paint_state == paint_state_)
    return;
  paint_state_ = paint_state;

  SkColor title_color = GetTitleColor(paint_state_);
  title_label_->SetEnabledColor(title_color);
  title_label_->SetFont(GetTitleFont());

  close_button_->SetBackground(title_color,
                               GetCloseButtonResources().normal_image,
                               NULL);

  minimize_button_->SetBackground(title_color,
                                  GetMinimizeButtonResources().normal_image,
                                  NULL);

  restore_button_->SetBackground(title_color,
                                 GetRestoreButtonResources().normal_image,
                                 NULL);
}

void PanelBrowserFrameView::PaintFrameBackground(gfx::Canvas* canvas) {
  int top_area_height = NonClientTopBorderHeight();
  int thickness = NonClientBorderThickness();
  SkBitmap* bitmap = GetFrameTheme(paint_state_);

  // Top area, including title-bar.
  canvas->TileImageInt(*bitmap, 0, 0, width(), top_area_height);

  // For all the non-client area below titlebar, we paint it by using the last
  // line from the theme bitmap, instead of using the frame color provided
  // in the theme because the frame color in some themes is very different from
  // the tab colors we use to render the titlebar and it can produce abrupt
  // transition which looks bad.

  // Left border, below title-bar.
  canvas->DrawBitmapInt(*bitmap, 0, top_area_height - 1, thickness, 1,
      0, top_area_height, thickness, height() - top_area_height, false);

  // Right border, below title-bar.
  canvas->DrawBitmapInt(*bitmap, (width() % bitmap->width()) - thickness,
      top_area_height - 1, thickness, 1,
      width() - thickness, top_area_height,
      thickness, height() - top_area_height, false);

  // Bottom border.
  canvas->DrawBitmapInt(*bitmap, 0, top_area_height - 1, bitmap->width(), 1,
      0, height() - thickness, width(), thickness, false);
}

void PanelBrowserFrameView::PaintFrameEdge(gfx::Canvas* canvas) {
#if defined(USE_AURA)
  // Aura recognizes aura::client::WINDOW_TYPE_PANEL and will draw the
  // appropriate frame and shadow. See ash/wm/shadow_controller.h.

  // Draw the divider between the titlebar and the client area.
  if (!IsShowingTitlebarOnly()) {
    canvas->DrawRect(gfx::Rect(0, kTitlebarHeight, width() - 1, 1),
                     kDividerColor);
  }
#else
  // Draw the top border.
  const EdgeResources& frame_edges = GetFrameEdges();
  canvas->DrawBitmapInt(*(frame_edges.top_left), 0, 0);
  canvas->TileImageInt(
      *(frame_edges.top), frame_edges.top_left->width(), 0,
      width() - frame_edges.top_right->width(), frame_edges.top->height());
  canvas->DrawBitmapInt(
      *(frame_edges.top_right),
      width() - frame_edges.top_right->width(), 0);

  // Draw the right border.
  canvas->TileImageInt(
      *(frame_edges.right), width() - frame_edges.right->width(),
      frame_edges.top_right->height(), frame_edges.right->width(),
      height() - frame_edges.top_right->height() -
          frame_edges.bottom_right->height());

  // Draw the bottom border.
  canvas->DrawBitmapInt(
      *(frame_edges.bottom_right),
      width() - frame_edges.bottom_right->width(),
      height() - frame_edges.bottom_right->height());
  canvas->TileImageInt(
      *(frame_edges.bottom), frame_edges.bottom_left->width(),
      height() - frame_edges.bottom->height(),
      width() - frame_edges.bottom_left->width() -
          frame_edges.bottom_right->width(),
      frame_edges.bottom->height());
  canvas->DrawBitmapInt(
      *(frame_edges.bottom_left), 0,
      height() - frame_edges.bottom_left->height());

  // Draw the left border.
  canvas->TileImageInt(
      *(frame_edges.left), 0, frame_edges.top_left->height(),
      frame_edges.left->width(),
      height() - frame_edges.top_left->height() -
          frame_edges.bottom_left->height());

  // Draw the divider between the titlebar and the client area.
  if (!IsShowingTitlebarOnly() && !CanResize()) {
    canvas->DrawRect(gfx::Rect(NonClientBorderThickness(), kTitlebarHeight,
                               width() - 1 - 2 * NonClientBorderThickness(),
                               NonClientBorderThickness()), kDividerColor);
  }
#endif  // !defined(USE_AURA)
}

void PanelBrowserFrameView::PaintClientEdge(gfx::Canvas* canvas) {
#if !defined(USE_AURA)
  // No need to draw client edges when a non-resizable panel that has thin
  // border.
  if (!CanResize())
    return;

  gfx::Rect client_edge_bounds(client_view_bounds_);
  client_edge_bounds.Inset(-kResizableClientEdgeThickness,
                           -kResizableClientEdgeThickness);
  gfx::Rect frame_shadow_bounds(client_edge_bounds);
  frame_shadow_bounds.Inset(-kFrameShadowThickness, -kFrameShadowThickness);

  canvas->FillRect(frame_shadow_bounds, kContentsBorderShadow);
  canvas->FillRect(client_edge_bounds, kClientEdgeColor);
#endif  // !defined(USE_AURA)
}

string16 PanelBrowserFrameView::GetTitleText() const {
  return frame()->widget_delegate()->GetWindowTitle();
}

void PanelBrowserFrameView::UpdateTitleBar() {
  title_label_->SetText(GetTitleText());
}

void PanelBrowserFrameView::UpdateTitleBarMinimizeRestoreButtonVisibility() {
  Panel* panel = panel_browser_view_->panel();
  minimize_button_->SetVisible(panel->CanMinimize());
  restore_button_->SetVisible(panel->CanRestore());
}

bool PanelBrowserFrameView::CanResize() const {
  return panel_browser_view_->panel()->CanResizeByMouse() !=
      panel::NOT_RESIZABLE;
}

bool PanelBrowserFrameView::IsShowingTitlebarOnly() const {
  return height() <= kTitlebarHeight;
}


text:
<?php

namespace Zettacast\Support;

interface ExposableInterface
{
	/**
	 * Gives access to object's raw contents. That is, it exposes the internal
	 * content that is wrapped by the object.
	 * @return mixed The raw object contents.
	 */
	public function raw();
}


text:
package muksihs.ipfs.photogallery.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.ValueBoxBase.TextAlignment;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.binder.EventBinder;
import com.google.web.bindery.event.shared.binder.EventHandler;

import elemental2.dom.DomGlobal;
import gwt.material.design.client.ui.MaterialButton;
import gwt.material.design.client.ui.MaterialIntegerBox;
import gwt.material.design.client.ui.MaterialPanel;
import gwt.material.design.client.ui.MaterialTextBox;
import gwt.material.design.client.ui.MaterialTitle;
import muksihs.ipfs.photogallery.client.Event;

public class PostGallery extends EventBusComposite {

	interface MyEventBinder extends EventBinder<PostGallery>{}
	interface PostGalleryUiBinder extends UiBinder<Widget, PostGallery> {
	}
	private static PostGalleryUiBinder uiBinder = GWT.create(PostGalleryUiBinder.class);

	@UiField
	protected MaterialButton cancel;

	@UiField
	protected MaterialIntegerBox tipAmount;
	@UiField
	protected MaterialTextBox username;
	@UiField
	protected MaterialTextBox postingKey;

	@UiField
	protected MaterialButton post;

	@UiField
	protected MaterialTitle previewTitle;

	@UiField
	protected MaterialPanel previewPanel;
	public PostGallery() {
		initWidget(uiBinder.createAndBindUi(this));
		cancel.addClickHandler((e)->Location.reload());
		tipAmount.setMin("0");
		tipAmount.setMax("100");
		tipAmount.setAlignment(TextAlignment.RIGHT);
		tipAmount.addBlurHandler((e)->{
			if (tipAmount.getValue()<0) {
				tipAmount.setValue(0);
			}
			if (tipAmount.getValue()>100) {
				tipAmount.setValue(100);
			}
			tipAmount.setValue(tipAmount.getValue());
		});
		post.addClickHandler((e)->{
			DomGlobal.console.log("Posting...");
			Event.PostGallery event = new Event.PostGallery(username.getValue(), postingKey.getValue(), tipAmount.getValue());
			GWT.log("Event data: "+event.toString());
			fireEvent(event);
		});
	}

	@Override
	protected <T extends EventBinder<EventBusComposite>> T getEventBinder() {
		return GWT.create(MyEventBinder.class);
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		GWT.log("firing: Event.ViewLoaded");
		fireEvent(new Event.WantsHtmlDisplayed());
	}

	@EventHandler
	protected void setPreviewHtml(Event.SetPreviewHtml event) {
		previewPanel.getElement().removeAllChildren();
		previewPanel.getElement().appendChild(event.getPreviewHtml());
	}
	@EventHandler
	protected void setPreviewTitle(Event.SetPreviewTitle event) {
		previewTitle.setTitle(event.getTitle());
	}

}


text:
module Neoid
  class SearchSession
    def initialize(response, *models)
      @response = response || []
      @models = models
    end

    def hits
      @response.map { |x| Neography::Node.new(x) }
    end

    def ids
      @response.collect { |x| x['data']['ar_id'] }
    end

    def results
      models_by_name = @models.inject({}) { |all, curr| all[curr.name] = curr; all }

      ids_by_klass = @response.inject({}) do |all, curr|
        klass_name = curr['data']['ar_type']
        (all[models_by_name[klass_name]] ||= []) << curr['data']['ar_id']
        all
      end

      ids_by_klass.map { |klass, ids| klass.where(id: ids) }.flatten
    end
  end
end


text:
This example demonstrates how to build a client from the generated client
to work against a streaming server.

Thanks to @nelz9999, who raised this in issue #883.

This example calls `https://jigsaw.w3c.org/` so as to contentrate on the client
side. For an example mixing the generated server and a client, see [here](../streaming-server/README.md).

The URL called by the API returns a blob of ASCII digits (1000 lines).

## Try it

### Blocking client

The client sends a request and blocks until the server has finished sending the response.

```
SWAGGER_DEBUG=1 go run jigsaw.go

2021/01/17 17:09:59 asking jigsaw server with blockingMode: true, chunkingMode: true
GET /HTTP/ChunkedScript HTTP/1.1
Host: jigsaw.w3.org
User-Agent: Go-http-client/1.1
Accept: application/json
Accept-Encoding: gzip

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Cache-Control: max-age=0
Content-Type: text/plain
...
Server: Jigsaw/2.3.0-beta2
Strict-Transport-Security: max-age=15552015; includeSubDomains; preload
X-Frame-Options: deny
X-Xss-Protection: 1; mode=block

2021/01/17 17:10:00 result: This output will be chunked encoded by the server, if your client is HTTP/1.1
Below this line, is 1000 repeated lines of 0-9.
-------------------------------------------------------------------------
01234567890123456789012345678901234567890123456789012345678901234567890
...
01234567890123456789012345678901234567890123456789012345678901234567890
```

```
# http2 client is detected by jigsaw: response is not chunked
SWAGGER_DEBUG=1 go run jigsaw.go nochunking

2021/01/17 17:10:12 asking jigsaw server with blockingMode: true, chunkingMode: false
GET /HTTP/ChunkedScript HTTP/1.1
Host: jigsaw.w3.org
User-Agent: Go-http-client/1.1
Accept: application/json
Accept-Encoding: gzip

HTTP/2.0 200 OK
Connection: close
Cache-Control: max-age=0
Content-Type: text/plain
...
Server: Jigsaw/2.3.0-beta3
Strict-Transport-Security: max-age=15552015; includeSubDomains; preload
X-Frame-Options: deny
X-Xss-Protection: 1; mode=block
...

2021/01/17 17:10:12 result: This output will be chunked encoded by the server, if your client is HTTP/1.1
Below this line, is 1000 repeated lines of 0-9.
-------------------------------------------------------------------------
01234567890123456789012345678901234567890123456789012345678901234567890
...
01234567890123456789012345678901234567890123456789012345678901234567890
```

### Non-blocking client

The client sends a request and consumes the chunks as they are produced.

```
SWAGGER_DEBUG=1 go run jigsaw.go nonblocking

2021/01/17 17:09:23 asking jigsaw server with blockingMode: false, chunkingMode: true
GET /HTTP/ChunkedScript HTTP/1.1
Host: jigsaw.w3.org
User-Agent: Go-http-client/1.1
Accept: application/json
Accept-Encoding: gzip

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Cache-Control: max-age=0
Content-Type: text/plain
...
Server: Jigsaw/2.3.0-beta4
Strict-Transport-Security: max-age=15552015; includeSubDomains; preload
X-Frame-Options: deny
X-Xss-Protection: 1; mode=block

2021/01/17 17:09:23 line[1]: This output will be chunked encoded by the server, if your client is HTTP/1.1
2021/01/17 17:09:23 line[2]: Below this line, is 1000 repeated lines of 0-9.
2021/01/17 17:09:23 line[3]: -------------------------------------------------------------------------
2021/01/17 17:09:23 line[4]: 01234567890123456789012345678901234567890123456789012345678901234567890
2021/01/17 17:09:23 line[5]: 01234567890123456789012345678901234567890123456789012345678901234567890
...
2021/01/17 17:09:23 line[1003]: 01234567890123456789012345678901234567890123456789012345678901234567890
2021/01/17 17:09:23 EOF
```

```
SWAGGER_DEBUG=1 go run jigsaw.go nonblocking nochunking

2021/01/17 17:09:39 asking jigsaw server with blockingMode: false, chunkingMode: false
GET /HTTP/ChunkedScript HTTP/1.1
Host: jigsaw.w3.org
User-Agent: Go-http-client/1.1
Accept: application/json
Accept-Encoding: gzip

HTTP/2.0 200 OK
Connection: close
Cache-Control: max-age=0
Content-Type: text/plain
...
Server: Jigsaw/2.3.0-beta3
Strict-Transport-Security: max-age=15552015; includeSubDomains; preload
X-Frame-Options: deny
X-Xss-Protection: 1; mode=block

2021/01/17 17:09:39 line[1]: This output will be chunked encoded by the server, if your client is HTTP/1.1
2021/01/17 17:09:39 line[2]: Below this line, is 1000 repeated lines of 0-9.
2021/01/17 17:09:39 line[3]: -------------------------------------------------------------------------
2021/01/17 17:09:39 line[4]: 01234567890123456789012345678901234567890123456789012345678901234567890
2021/01/17 17:09:39 line[5]: 01234567890123456789012345678901234567890123456789012345678901234567890
...
2021/01/17 17:09:39 line[1002]: 01234567890123456789012345678901234567890123456789012345678901234567890
2021/01/17 17:09:39 line[1003]: 01234567890123456789012345678901234567890123456789012345678901234567890
2021/01/17 17:09:39 EOF
```

## How does it work?

### Blocking: customizing the `io.Writer`

We have specified a `binary` format for the response (instead of, say, `[]string`).

We need to provide the runtime consumer with some means to unmarshal `text/plain` in this buffer.

The simplest way is to equip the destination buffer with a `UnmarshalText()` method. Like so:
```go
type Buffer struct {
	*bytes.Buffer
}

// UnmarshalText handles text/plain
func (b *Buffer) UnmarshalText(text []byte) error {
	_, err := b.Write(text)
	return err
}

buf := NewBuffer()
_, err := c.Chunked(operations.NewChunkedParams(), buf)
```

### Non-blocking: customizing the consumer

We need to instruct the runtime client to use a `ByteStreamConsumer` when the response is `text/plain`.
Like so:

```go
	transport.Consumers[runtime.TextMime] = runtime.ByteStreamConsumer()
```

#### Non-blocking: unmarshalling the stream

The response is just a stream of byte, so the client has to unmarshal the messages received unitarily.
In this example, the stream is separated by line feed, so we can use a `bufio.Scanner` to do the job.

Notice the use of the `cancel()` method to interrupt the ongoing request if the go routine fails.


text:
<?xml version="1.0" encoding="UTF-8"?>
<cheatsheetState buttonstate="0" id="com.xilinx.sdk.docs.cheatsheets.createNewBsp" item="3">
<completed item="0"/>
<completed item="1"/>
<completed item="2"/>
<expanded item="3"/>
</cheatsheetState>


text:
package com.thedeanda.ajaxproxy.ui.serverconfig.tamper;

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

import javax.swing.AbstractListModel;

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

import com.thedeanda.ajaxproxy.model.tamper.TamperItem;

public class TamperListModel extends AbstractListModel<TamperItem> {
	private static final Logger log = LoggerFactory
			.getLogger(TamperListModel.class);
	private static final long serialVersionUID = -7159966628455887784L;

	private List<TamperItem> items = new ArrayList<>();

	@Override
	public int getSize() {
		return items.size();
	}

	@Override
	public TamperItem getElementAt(int index) {
		return items.get(index);
	}

	public void add(TamperItem element) {
		int size = items.size();
		items.add(element);
		fireIntervalAdded(this, size, size);
	}

	public List<TamperItem> items() {
		return new ArrayList<>(items);
	}

	public void clear() {
		int oldSize = items.size();
		items.clear();
		fireIntervalRemoved(this, 0, oldSize);
	}

}


text:
<?php
namespace Annoncea\Model;

class Categorie
{

    public $id_cat;
    public $lib_cat;

    public function exchangeArray($data)
    {
        $this->id_cat  = (!empty($data['id_cat'])) ? $data['id_cat'] : null; /*si la clé id correspond à une valeur on prend cette valeurr là)*/
        $this->lib_cat = (!empty($data['lib_cat'])) ? $data['lib_cat'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars($this);
    }

}


text:
#include <pthread.h>

#include "metal-test.h"
#include "metal/log.h"
#include "metal/sys.h"
#include "metal/spinlock.h"

static const int spinlock_test_count = 1000;
static unsigned int total = 0;

static void *spinlock_thread(void *arg)
{
	struct metal_spinlock *l = arg;
	int i;

	for (i = 0; i < spinlock_test_count; i++) {
		metal_spinlock_acquire(l);
		total++;
		metal_spinlock_release(l);
	}

	return NULL;
}

static int spinlock(void)
{
	struct metal_spinlock lock = METAL_SPINLOCK_INIT;
	const int threads = 10;
	int value, error;

	error = metal_run(threads, spinlock_thread, &lock);
	if (!error) {
		value = total;
		value -= spinlock_test_count * threads;
		if (value) {
			metal_log(LOG_DEBUG, "counter mismatch, delta = %d\n",
				  value);
			error = -EINVAL;
		}
	}

	return error;
}
METAL_ADD_TEST(spinlock);


text:
'use babel';
// custom search utility
import { Point, Range } from 'atom';

export default function searchForFrom(item, point, opt, extra, editor) {
  let start;

  if (extra && extra.newline)
    item = `(\n)?${item}(\n)?`;
  if (extra && extra.tab)
    item = `(\t)?${item}`;
  const cb = opt && opt.cb;
  const range = rangePointToLimit(point, opt);
  const args = [
    new RegExp(escapeRegExp(item)),
    range,
    cb
  ];

  if (opt && opt.back)
    editor.backwardsScanInBufferRange.apply(editor, args);
  else
    editor.scanInBufferRange.apply(editor, args);

  return start;
}
// utility of searchForFrom()
function rangePointToLimit(p, opt) {
  const limit = (opt && opt.back) ? Point.ZERO : Point.INFINITY;
  return new Range(limit, [p.row, p.column]);
}
// utility of searchForFrom()
function escapeRegExp(str) {
  const specialChar = ['*'];
  let res = '';
  specialChar.forEach(x => {
    res = str.replace(x, m => `\\${m}`);
  });
  return res;
}


text:
package ru.job4j.cartrade.controller.exit;
import ru.job4j.cartrade.storage.Storage;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Class CloseStorage описывает завершение работы с хранилищем при разрушении ServletContext.
 * @author Timur Kapkaev (timur.kap@yandex.ru)
 * @version $ID$
 * @since 25.01.20118
 * */
@WebListener
public class CloseStorage implements ServletContextListener {
    /**
     * Вызывается при наступлении события - инициализация объекта ServletContext.
     * @param varl - объект, содержащий ServletContext
     * */
    @Override
    public void contextInitialized(ServletContextEvent varl) {
    }

    /**
     * Закрывает SessionFactory в случае разрушения объекта ServletContext.
     * @param varl - объект, содержащий ServletContext
     * */
    @Override
    public void contextDestroyed(ServletContextEvent varl) {
        Storage.getInstance().close();
    }
}