text:
TabRendererData::TabRendererData()
    : network_state(NETWORK_STATE_NONE),
      loading(false),
      crashed_status(base::TERMINATION_STATUS_STILL_RUNNING),
      incognito(false),
      show_icon(true),
      pinned(false),
      blocked(false),
      app(false),
      media_state(TAB_MEDIA_STATE_NONE) {
}

TabRendererData::~TabRendererData() {}

bool TabRendererData::IsCrashed() const {
  return (crashed_status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ||
#if defined(OS_CHROMEOS)
          crashed_status ==
              base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM ||
#endif
          crashed_status == base::TERMINATION_STATUS_PROCESS_CRASHED ||
          crashed_status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
          crashed_status == base::TERMINATION_STATUS_LAUNCH_FAILED);
}

bool TabRendererData::Equals(const TabRendererData& data) {
  return
      favicon.BackedBySameObjectAs(data.favicon) &&
      network_state == data.network_state &&
      title == data.title &&
      url == data.url &&
      loading == data.loading &&
      crashed_status == data.crashed_status &&
      incognito == data.incognito &&
      show_icon == data.show_icon &&
      pinned == data.pinned &&
      blocked == data.blocked &&
      app == data.app &&
      media_state == data.media_state;
}


text:
'use strict';

var setTimeout = require('timers').setTimeout;

var allocCluster = require('../lib/test-cluster.js');

allocCluster.test('forwarding small timeout', {
    size: 5
}, function t(cluster, assert) {
    var steve = cluster.remotes.steve;
    var bob = cluster.remotes.bob;

    cluster.checkExitPeers(assert, {
        serviceName: 'steve',
        hostPort: steve.hostPort
    });

    steve.serverChannel.register('method', function m(req, res) {
        // long delay
        setTimeout(function sendStuff() {
            res.headers.as = 'raw';
            res.sendOk(null, 'oh hi');
        }, 500);
    });

    bob.clientChannel.request({
        serviceName: steve.serviceName,
        timeout: 300
    }).send('method', null, null, onFirst);

    function onFirst(err) {
        assert.ok(err, 'first request should time out');

        bob.clientChannel.request({
            serviceName: steve.serviceName,
            timeout: 600
        }).send('method', null, null, onSecond);
    }

    function onSecond(err, res, arg2, arg3) {
        assert.ifError(err, 'second request should succeed');

        assert.ok(res && res.ok);

        assert.equal(String(arg3), 'oh hi');

        assert.end();
    }
});

redpajama_set_name: RedPajamaGithub


text:
class HandShape
  def initialize(user)
    @user = user
    @sex_human = user.sex_human
  end

  def result_waste
    result = nil
    if @user.palm.hand_shape_waste then
      I18n.t('models.hand_shape.waste', uname: @user.uname)
    end
  end

  def result_report
    result = nil
    if @user.palm.hand_shape_report then
      I18n.t('models.hand_shape.report', uname: @user.uname)
    end
  end
end


text:
package com.pushinginertia.commons.core.math;

import com.pushinginertia.commons.core.validation.ValidateAs;

import java.util.TreeSet;

/**
 * Encapsulates a combination of N choose K and includes a payload that can be attached to the combination.
 *
 * @param <P> Type of the payload contained within each {@link Combination} instance.
 */
public class Combination<P extends Combination.Payload<P>> {
	private final Key key;
	private final P payload;

	public interface Payload<P> {
		/**
		 * Adds the payloads from two combinations together to produce a combination for a larger value of K. This is
		 * taken from an N choose X and an N choose Y combination where X+Y equals the value of K that this payload is
		 * for. This should be an immutable operation and not mutate either {@link Payload} instance.
		 * @param rhs Payload to add to this one.
		 * @return A new instance in which whatever additions or compositions have been applied.
		 */
		public P add(P rhs);

		/**
		 * Merges a given payload into this instance. This is a mutating operation that mutates this instance but does
		 * not mutate the given instance.
		 * @param rhs Payload to merge into this one.
		 */
		public void merge(P rhs);
	}

	/**
	 * Combines two combinations into one by merging the the two combinations' {@link Combination.Key}s and adding the
	 * payloads together.
	 * @param left Left combination.
	 * @param right Right combination.
	 */
	public Combination(final Combination<P> left, final Combination<P> right) {
		ValidateAs.notNull(left, "left");
		ValidateAs.notNull(right, "right");
		this.key = new Key(left.getKey(), right.getKey());
		this.payload = left.payload.add(right.payload);
		if (this.payload == null) {
			throw new IllegalStateException(left.payload.getClass().getName() + ".add(rhs) cannot return null.");
		}
	}

	public Combination(final int index, final P payload) {
		this.key = new Key(index);
		this.payload = ValidateAs.notNull(payload, "payload");
	}

	public Key getKey() {
		return key;
	}

	public int size() {
		return key.size();
	}

	public P getPayload() {
		return payload;
	}

	@Override
	public boolean equals(final Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		return key.equals(((Combination)o).key);
	}

	@Override
	public int hashCode() {
		return key.hashCode();
	}

	@Override
	public String toString() {
		return key.toString();
	}

	/**
	 * Represents the indexes for this combination of N choose K. The count of indexes equals K. Note that internally
	 * the indexes are zero-based, so an index of {0,1} indicates the first two items of N for this combination.
	 */
	public static class Key {
		private final TreeSet<Integer> indexes;  // must be ordered

		private Key(final Key left, final Key right) {
			this.indexes = new TreeSet<Integer>(left.indexes);
			this.indexes.addAll(right.indexes);
		}

		private Key(final int index) {
			this.indexes = new TreeSet<Integer>();
			this.indexes.add(index);
		}

		public int size() {
			return indexes.size();
		}

		public int getRightIndex() {
			return indexes.last();
		}

		public int getOnlyIndex() {
			if (indexes.size() != 1) {
				throw new IllegalStateException("Index count is not 1");
			}
			return indexes.last();
		}

		@Override
		public boolean equals(final Object o) {
			if (this == o) {
				return true;
			}
			if (o == null || getClass() != o.getClass()) {
				return false;
			}
			return indexes.equals(((Key)o).indexes);
		}

		@Override
		public int hashCode() {
			return indexes.hashCode();
		}

		@Override
		public String toString() {
			final StringBuilder sb = new StringBuilder();
			for (final int i: indexes) {
				if (sb.length() > 0) {
					sb.append(',');
				}
				sb.append(i);
			}
			return '{' + sb.toString() + '}';
		}
	}
}


text:
<?php
/**
 * The template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages and that other
 * 'pages' on your WordPress site will use a different template.
 *
 * @package WordPress
 * @subpackage East_Blue
 * @since East Blue 1.0
 */

get_header(); ?>

		<?php /* The loop */ ?>
		<?php while ( have_posts() ) : the_post(); ?>
		<article id="post-<?php the_ID(); ?>" class="article">
		<?php if ( has_post_thumbnail() && ! post_password_required() ) : ?>

				<?php the_post_thumbnail(); ?>

		<?php endif; ?>

<?php the_title(); ?>

				<?php the_content(); ?>
				<?php wp_link_pages( array( 'before' => '
' . __( 'Pages:', 'eastBlue' ) . '', 'after' => '
', 'link_before' => '', 'link_after' => '' ) ); ?>

				<?php edit_post_link( __( 'Edit', 'eastBlue' ), '', '' ); ?>

<?php comments_template(); ?>
		<?php endwhile; ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
extern NSString * const AMTagViewNotification;

@interface AMTagView : UIView

@property (nonatomic, assign) float		radius UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) float		tagLength UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) float		innerTagPadding UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) float		holeRadius UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) float		textPadding UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIFont	*textFont UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor	*textColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor	*tagColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIColor	*innerTagColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, strong) UIImage	*accessoryImage UI_APPEARANCE_SELECTOR;
@property (nonatomic, assign) float     imagePadding UI_APPEARANCE_SELECTOR;

- (void)setupWithText:(NSString*)text;
- (NSString*)tagText;

@end


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
function invariant(condition, format, a, b, c, d, e, f) {
  if (!condition) {
    var error = void 0;
    if (format === undefined) {
      error = new Error("Minified exception occurred; use the non-minified dev environment " + "for the full error message and additional helpful warnings.");
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(format.replace(/%s/g, function () {
        return args[argIndex++];
      }));
      error.name = "Invariant Violation";
    }

    error.framesToPop = 1;
    throw error;
  }
}

exports.default = invariant;


text:
package com.wowwee.snappetssampleproject.fragments;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wowwee.bluetoothrobotcontrollib.snappets.SnapPets;
import com.wowwee.snappetssampleproject.R;
import com.wowwee.snappetssampleproject.SnappetsApplication;
import com.wowwee.snappetssampleproject.enums.CAMERA_FLASH;
import com.wowwee.snappetssampleproject.enums.CAMERA_MODE;
import com.wowwee.snappetssampleproject.enums.CAMERA_STATUS;
import com.wowwee.snappetssampleproject.enums.CAMERA_TIMER;
import com.wowwee.snappetssampleproject.enums.PICTURE_EVERY_TIMER;
import com.wowwee.snappetssampleproject.fragments.popups.CheckPinPopup;
import com.wowwee.snappetssampleproject.fragments.popups.SearchPopup;
import com.wowwee.snappetssampleproject.fragments.popups.SetupNamePopup;
import com.wowwee.snappetssampleproject.interfaces.IDownloadImageStatisticListener;
import com.wowwee.snappetssampleproject.services.DownloadService;
import com.wowwee.snappetssampleproject.snappethelper.AuthenticateCallback;
import com.wowwee.snappetssampleproject.snappethelper.ConnectSnappetCallback;
import com.wowwee.snappetssampleproject.snappethelper.SnappetsHelper;
import com.wowwee.snappetssampleproject.ui.CameraPreview;
import com.wowwee.snappetssampleproject.util.CameraInstance;
import com.wowwee.snappetssampleproject.util.ConnectionManager;
import com.wowwee.snappetssampleproject.util.DialogUtil;
import com.wowwee.snappetssampleproject.util.DialogUtil.Callback;
import com.wowwee.snappetssampleproject.util.DrawableUtil;
import com.wowwee.snappetssampleproject.util.FragmentHelper;
import com.wowwee.snappetssampleproject.util.ShareUtil;
import com.wowwee.snappetssampleproject.util.SharedSettingsHelper;
import com.wowwee.snappetssampleproject.util.SnappetsScreenReference;
import com.wowwee.snappetssampleproject.util.ViewHelper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CameraFragment extends BaseFragment implements View.OnClickListener {

    public static CAMERA_MODE cameraMode = CAMERA_MODE.PHONE;
    public static boolean isSearchingSnappets = false;
    private static boolean firstStartOfFragment = true;
    private final int EXPECTED_PHOTO_WIDTH = 640;
    private final int EXPECTED_PHTOT_HEIGHT = 480;

    public CameraInstance.Callback cameraCallback;
    public Handler handler;
    private CameraInstance cameraInstance;
    private CameraPreview mPreview;

    private CAMERA_FLASH cameraFlash = CAMERA_FLASH.DISABLE;

    private CAMERA_TIMER cameraTimer = CAMERA_TIMER.OFF;

    private CountDownTimer countDownTimer;
    private Button snappetButton;
    private CAMERA_STATUS cameraStatus = CAMERA_STATUS.READY;

    private View settingButton;
    private TextView countdownText;
    private View cameraToolLayout;
    private Button switchFlashButton;
    private ImageView previewImage;
    private Button switchCameraButton;
    private View imageToolLayout;
    private Button switchTimerButton;
    private View shareButton;
    private View editButton;
    private View deleteButton;
    private View loadingLayout;
    private ProgressBar loadingProgress;
    private View cameraControlLayout;
    private ViewGroup switchTimerLayout;
    private PICTURE_EVERY_TIMER pictureEveryTimer;
    private Button everyTimerButton;
    private ViewGroup everyTimerLayout;
    private View snapPhoneLayout;
    private TextView countdownSnapText;
    private View saveButton;
    private DownloadService downloadService;
    private Button captureButton;

    public CameraFragment() {
        initializeFragment(R.layout.fragment_camera, new SnappetsScreenReference());
    }

    @Override
    public void _onCreateView(final View view) {

        createCameraInstance();
        changeHeaderHeight(view);
        setupSettingsButton(view);
        setupSimpleViews(view);
        setupImageActionButtons(view);
        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                createCameraPreview(view);
            }
        }, 500);

        setupSwitchFlashButton(view);
        setupSwitchCameraButton(view);
        setupSwithTimerLayout(view);
        setupPictureEveryTimeLayout(view);

        setupCameraCallback();

        setupHandler();

        setupCaptureButton(view);
        setupCameraCancelButton(view);
        setupGalleryButton(view);
        setupSnappetButton(view);

        cameraCallback.init();
    }

    private void changeHeaderHeight(View view) {
        RelativeLayout header = (RelativeLayout) view.findViewById(R.id.camera_fragment_header);
        LinearLayout.LayoutParams headerLayoutParams = (LinearLayout.LayoutParams) header.getLayoutParams();
        headerLayoutParams.height = ((getResources().getDisplayMetrics().heightPixels - ViewHelper.navBarHeight(getActivity())) - getResources().getDisplayMetrics().widthPixels) / 2;
        header.setLayoutParams(headerLayoutParams);
    }

    @Override
    public void onStart() {
        super.onStart();

        Activity activity = getActivity();
        if (activity != null) {
            downloadService = SnappetsApplication.getApplicationClass(activity).getDownloadService();
            if (downloadService != null) {
                downloadService.setPhotoTakingCallback(createTakePhotoCallback());
                downloadService.setIdleCallback(getChecksnappetPressButtonCallback());
                downloadService.setPhotoDownloadingCallback(getChecksnappetPressButtonCallback());
                downloadService.setIdleCameraCallback(cameraCallback);
                downloadService.setTakingPhotoCameraCallback(cameraCallback);
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (downloadService != null) {
            downloadService.setPhotoTakingCallback(null);
            downloadService.setIdleCallback(null);
            downloadService.setStatisticListener(null);
            downloadService.setPhotoDownloadingCallback(null);
            downloadService.setIdleCameraCallback(null);
            downloadService.setTakingPhotoCameraCallback(null);
        }
    }

    private void setupPictureEveryTimeLayout(View view) {
        everyTimerButton = (Button) view.findViewById(R.id.btn_pic_every_time);
        everyTimerButton.setVisibility(View.GONE);
        pictureEveryTimer = PICTURE_EVERY_TIMER.OFF;

        ViewHelper.setButtonTouchListener(everyTimerButton);
        everyTimerButton.setEnabled(false);
        everyTimerButton.setOnClickListener(this);

        view.findViewById(R.id.sec30).setOnClickListener(this);
        view.findViewById(R.id.min2).setOnClickListener(this);
        view.findViewById(R.id.min5).setOnClickListener(this);
        view.findViewById(R.id.close_every_time_bar).setOnClickListener(this);
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.sec30));
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.min2));
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.min5));
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.close_every_time_bar));
        everyTimerLayout = (ViewGroup) view.findViewById(R.id.layout_every_time_tool);
    }

    private void setupImageActionButtons(View view) {
        shareButton = view.findViewById(R.id.btn_share);
        editButton = view.findViewById(R.id.btn_edit);
        deleteButton = view.findViewById(R.id.btn_delete);
        saveButton = view.findViewById(R.id.btn_save);
    }

    private void setupGalleryButton(View view) {
        //handle the gallery button
        View galleryButton = view.findViewById(R.id.btn_photoalbum);
        galleryButton.setOnClickListener(this);
        int padding = getSideButtonPadding();
        galleryButton.setPadding(padding, padding, padding, padding);
    }

    private void setupSimpleViews(View view) {
        countdownText = (TextView) view.findViewById(R.id.txt_countdown);
        countdownSnapText = (TextView) view.findViewById(R.id.txt_countdown_snap);
        cameraToolLayout = view.findViewById(R.id.layout_camera_tool);
        previewImage = (ImageView) view.findViewById(R.id.img_camera_preview);
        imageToolLayout = view.findViewById(R.id.layout_image_tool);
        loadingLayout = view.findViewById(R.id.layout_loading);
        loadingProgress = (ProgressBar) view.findViewById(R.id.progress_loading);
        cameraControlLayout = view.findViewById(R.id.layout_camera_control);
        snapPhoneLayout = view.findViewById(R.id.snapPhoneLayout);
    }

    private ConnectSnappetCallback createTakePhotoCallback() {
        return new ConnectSnappetCallback() {
            @Override
            public void receivedImagePieceSize(int size) {
                //handler.updateLoadingProgress(imageBufferSize * 100 / imageTotalSize);
            }

            @Override
            public void receivedImageBuffer(byte[] buffer) {
                //takePictureFromSnappet(buffer);
            }

            @Override
            public void receiveImageTotalSize(int size) {
            }

            @Override
            public void disconnected(SnapPets snapPet) {
            }

            @Override
            public void connected(SnapPets snapPet) {
            }

            @Override
            public void didPressedButton() {
            }

            @Override
            public void receivedPhotoCount(int count) {
            }

            @Override
            public void didDeletePhoto(int id) {
            }
        };
    }

    @Override
    public void onResume() {
        Log.d(CameraFragment.class.toString(), "onResume");
        super.onResume();
        startUpdateCameraPreviewThread();
        cameraCallback.init();
        if (firstStartOfFragment) {
            firstStartOfFragment = false;
//            snappetButtonClicked();
        }
    }

    @Override
    public void onPause() {
        Log.d(CameraFragment.class.toString(), "onPause");
        SnappetsHelper.getInstance().stopSearch();
        super.onPause();
        releaseCamera();
    }

    @Override
    public boolean allowBackPress() {
        if (cameraStatus == CAMERA_STATUS.CONFIRM) {
            cameraCallback.init();
            return false;
        } else if (cameraStatus == CAMERA_STATUS.WORKING) {
            return false;
        }

        return true;
    }

    @Override
    public void onClick(View v) {
        if(isSearchingSnappets) {
            Log.i("","onClick is blocked because SearchPopup is shown");
            return;
        }
        if (v.getId() == R.id.btn_settings) {
            settingsButtonClicked();
        } else if (v == mPreview) {
            previewClicked();
        } else if (v.getId() == R.id.btn_flash) {
            switchFlashButtonClicked();
        } else if (v.getId() == R.id.btn_camswitch) {
            switchCameraButtonClicked();
        } else if (v.getId() == R.id.btn_back) {
            backButtonClicked();
        } else if (v.getId() == R.id.btn_snap) {
            snapButtonClicked();
        } else if (v.getId() == R.id.btn_cam_cancel) {
            cameraCancelButtonClicked();
        } else if (v.getId() == R.id.btn_photoalbum) {
            galleryButtonClicked();
        } else if (v.getId() == R.id.btn_cammode) {
            snappetButtonClicked();
        } else if (v.getId() == R.id.btn_timer) {
            switchTimerButtonClicked();
        } else if (v.getId() == R.id.sec3) {
            updateCameraTimer(CAMERA_TIMER.THREE_SECONDS);
        } else if (v.getId() == R.id.sec7) {
            updateCameraTimer(CAMERA_TIMER.SEVEN_SECONDS);
        } else if (v.getId() == R.id.sec10) {
            updateCameraTimer(CAMERA_TIMER.TEN_SECONDS);
        } else if (v.getId() == R.id.close_timer_bar) {
            updateCameraTimer(CAMERA_TIMER.OFF);
        } else if (v.getId() == R.id.btn_pic_every_time) {
            everyTimerButtonClicked();
        } else if (v.getId() == R.id.sec30) {
            updateEveryTimer(PICTURE_EVERY_TIMER.THIRTY_SECONDS);
        } else if (v.getId() == R.id.min2) {
            updateEveryTimer(PICTURE_EVERY_TIMER.TWO_MINUTES);
        } else if (v.getId() == R.id.min5) {
            updateEveryTimer(PICTURE_EVERY_TIMER.FIVE_MINUTES);
        } else if (v.getId() == R.id.close_every_time_bar) {
            updateEveryTimer(PICTURE_EVERY_TIMER.OFF);
        }
    }

    private void everyTimerButtonClicked() {
        ViewHelper.showViewWithAnimation(getActivity(), everyTimerLayout);
        ViewHelper.hideViewWithAnimation(getActivity(), cameraToolLayout);
        ViewHelper.hideViewWithAnimation(getActivity(), cameraControlLayout);
    }

    private void updateEveryTimer(PICTURE_EVERY_TIMER newTimer) {
        pictureEveryTimer = newTimer;
        updateEveryTimerLayout();
    }

    private void updateEveryTimerLayout() {
        ViewHelper.hideViewWithAnimation(getActivity(), everyTimerLayout);
        ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);
        ViewHelper.showViewWithAnimation(getActivity(), cameraControlLayout);
    }

    private void updateCameraTimer(CAMERA_TIMER newTimer) {
        cameraTimer = newTimer;
        updateTimeSwitchLayout();
    }

    private void updateTimeSwitchLayout() {
        ViewHelper.hideViewWithAnimation(getActivity(), switchTimerLayout);
        ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);
        ViewHelper.showViewWithAnimation(getActivity(), cameraControlLayout);
        if(cameraTimer.getIndex() == CAMERA_TIMER.THREE_SECONDS.index) {
            switchTimerButton.setText(getResources().getString(R.string.timer) + ": " + getResources().getString(R.string.sec3));
        } else if(cameraTimer.getIndex() == CAMERA_TIMER.SEVEN_SECONDS.index) {
            switchTimerButton.setText(getResources().getString(R.string.timer) + ": " + getResources().getString(R.string.sec7));
        } else if(cameraTimer.getIndex() == CAMERA_TIMER.TEN_SECONDS.index) {
            switchTimerButton.setText(getResources().getString(R.string.timer) + ": " + getResources().getString(R.string.sec10));
        } else {
            switchTimerButton.setText(getResources().getString(R.string.timer));
        }
    }

    private void releaseCamera() {
        if (mPreview != null)
            mPreview.disbleCallback();
        if (cameraInstance != null)
            cameraInstance.releaseCamera();              // release the camera immediately on pause event
    }

    private void startUpdateCameraPreviewThread() {
        Thread newThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        cameraInstance.createCamera();
                        mPreview.updateCamera(cameraInstance.camera);
                        cameraCallback.init();
                    }
                });
            }
        });
        newThread.start();
    }

    private void setupSnappetButton(View view) {
        //show the search popup / switch to snappet mode
        snappetButton = (Button) view.findViewById(R.id.btn_cammode);
        snappetButton.setOnClickListener(this);
        int padding = getSideButtonPadding();
        snappetButton.setPadding(padding, padding, padding, padding);
    }

    private void snappetButtonClicked() {
        if (SnappetsHelper.getInstance().getConnectedSnappet() != null) {
            cameraMode = cameraMode.swap();
            cameraCallback.init();
        } else {
            //show the search popup
            SearchPopup fragment = new SearchPopup();
            fragment.setCameraCallback(cameraCallback);
            FragmentHelper.showWithoutSlideAnimation(getFragmentManager(), fragment, R.id.layout_popup, true);
        }
    }

    private void setupCaptureButton(View view) {
        // Add a listener to the Capture button
        captureButton = (Button) view.findViewById(R.id.btn_snap);
        captureButton.setOnClickListener(this);

        int padding = getCenterButtonPadding();
        captureButton.setPadding(padding, padding, padding, padding);
    }

    private int getCenterButtonPadding() {
        int padding = 0;
        padding = (getResources().getDisplayMetrics().heightPixels - getResources().getDisplayMetrics().widthPixels
                + (int) (getResources().getDisplayMetrics().ydpi - getResources().getDisplayMetrics().xdpi)) / 18;
        return padding;
    }

    private int getSideButtonPadding() {
        int padding = 0;
        padding = (getResources().getDisplayMetrics().heightPixels - getResources().getDisplayMetrics().widthPixels
                + (int) (getResources().getDisplayMetrics().ydpi - getResources().getDisplayMetrics().xdpi)) / 14;
        return padding;
    }

    private void setupCameraCancelButton(View view) {
        // Add a listener to the Capture button
        Button cameraCancelButton = (Button) view.findViewById(R.id.btn_cam_cancel);
        cameraCancelButton.setOnClickListener(this);

        int padding = getCenterButtonPadding();
        cameraCancelButton.setPadding(padding, padding, padding, padding);
    }

    private void setupHandler() {
        handler = new Handler() {
            @Override
            public boolean pressTakePicture() {
                if (cameraStatus == CAMERA_STATUS.CONFIRM) {
                    cameraCallback.init();
                    if (cameraMode == CAMERA_MODE.PHONE)
                        return false;
//                    return false;
                } else if (cameraStatus == CAMERA_STATUS.WORKING) {
                    return false;
                }

                //handler the timer if it is enabled
                if (cameraTimer != CAMERA_TIMER.OFF) {
                    if (countDownTimer != null) {
                        countDownTimer.cancel();
                        countDownTimer = null;
                    }

                    //hidden the camera tool
                    ViewHelper.showViewWithAnimation(getActivity(), cameraControlLayout.findViewById(R.id.btn_cam_cancel));
                    ViewHelper.invisibleViewWithAnimation(getActivity(), cameraToolLayout);

                    if (cameraMode == CAMERA_MODE.PHONE) {
                        //hidden any preview
                        ViewHelper.hideViewWithAnimation(getActivity(), previewImage);
                        previewImage.setImageResource(0);
                    } else if (cameraMode == CAMERA_MODE.SNAPPET) {
                        //show pure theme color
                        previewImage.setImageResource(0);
                    }

                    //show the count down
                    if (cameraMode == CAMERA_MODE.PHONE) {
                        ViewHelper.showViewWithAnimation(getActivity(), countdownText);
                        ViewHelper.invisibleViewWithAnimation(getActivity(), countdownSnapText);
                    } else {
                        ViewHelper.showViewWithAnimation(getActivity(), countdownSnapText);
                        ViewHelper.invisibleViewWithAnimation(getActivity(), countdownText);
                    }

                    countDownTimer = new CountDownTimer(cameraTimer.waitTime, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            countdownText.setText("" + millisUntilFinished / 1000);
                            countdownSnapText.setText("" + millisUntilFinished / 1000);
                        }

                        @Override
                        public void onFinish() {
                            //cancel the countdown
                            countDownTimer.cancel();
                            countDownTimer = null;

                            //show the camera tool
                            ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);

                            //hidden the cancel button
                            ViewHelper.hideViewWithAnimation(getActivity(), cameraControlLayout.findViewById(R.id.btn_cam_cancel));

                            //hidden the count down
                            ViewHelper.invisibleViewWithAnimation(getActivity(), countdownText);
                            ViewHelper.invisibleViewWithAnimation(getActivity(), countdownSnapText);

                            countdownText.post(new Runnable() {

                                @Override
                                public void run() {
                                    doTakePicture();
                                }
                            });
                        }
                    };
                    countDownTimer.start();
                } else {
                    doTakePicture();
                }

                return true;
            }

            @Override
            public void updateLoadingProgress(int percentage) {
                loadingProgress.setProgress(percentage);
            }

            @Override
            public void setTitle(String name) {
            }
        };

    }

    private void setupCameraCallback() {
        cameraCallback = new CameraInstance.Callback() {
            @Override
            public void init() {
                final SnapPets snapPet = SnappetsHelper.getInstance().getConnectedSnappet();
                if (snapPet != null) {
                    setupLayoutWhenSnapPetDetected(snapPet);
                } else {
                    cameraMode = CAMERA_MODE.PHONE;
                }

                cameraStatus = CAMERA_STATUS.READY;
                if (cameraMode == CAMERA_MODE.PHONE) {
                    updateLayoutForPhoneCamera();
                } else if (cameraMode == CAMERA_MODE.SNAPPET) {
                    updateLayoutForSnappetCamera();
                }

                if (snapPet != null) {
                    ViewHelper.showViewWithAnimation(getActivity(), settingButton);
                    settingButton.setVisibility(View.VISIBLE);
                } else {
                    settingButton.setVisibility(View.GONE);
                }

                ViewHelper.invisibleViewWithAnimation(getActivity(), imageToolLayout);
                ViewHelper.hideViewWithAnimation(getActivity(), loadingLayout);
            }

            @Override
            public void beforeTakePicture() {
                cameraStatus = CAMERA_STATUS.WORKING;

                //camera tool
                ViewHelper.hideViewWithAnimation(getActivity(), cameraToolLayout);

                ViewHelper.invisibleViewWithAnimation(getActivity(), imageToolLayout);

                //loading layout
                if (cameraMode == CAMERA_MODE.PHONE) {
                    ViewHelper.hideViewWithAnimation(getActivity(), loadingLayout);
                } else if (cameraMode == CAMERA_MODE.SNAPPET) {
                    ViewHelper.showViewWithAnimation(getActivity(), loadingLayout);
                    captureButton.setEnabled(false);

                    //assign 0 into loading progress
                    handler.updateLoadingProgress(0);
                }
            }

            @Override
            public void afterTakePicture(final File file) {
                cameraStatus = CAMERA_STATUS.CONFIRM;

                ViewHelper.hideViewWithAnimation(getActivity(), cameraToolLayout);
                ViewHelper.hideViewWithAnimation(getActivity(), loadingLayout);
                captureButton.setEnabled(true);

                ViewHelper.showViewWithAnimation(getActivity(), previewImage);
                previewImage.setImageDrawable(DrawableUtil.getDrawableFromFile(context, file));

                ViewHelper.showViewWithAnimation(getActivity(), imageToolLayout);
                ViewHelper.hideViewWithAnimation(getActivity(), snapPhoneLayout);

                shareButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        ShareUtil.shareTextWithImage(context, getString(R.string.share_msg), file);
                        ShareUtil.shareTextWithImage(context, "", file);
                    }
                });
                ViewHelper.setButtonTouchListener(shareButton);

                editButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        saveCurrentPhoto(file);
//                        StickerFragment fragment = new StickerFragment();
//                        fragment.setImageFile(file);
//                        FragmentHelper.switchFragment(getFragmentManager(), fragment, R.id.layout_core, true);
                    }
                });
                ViewHelper.setButtonTouchListener(editButton);

                deleteButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //TODO: read the text from Resource
                        DialogUtil.showYesNoDialog(
                                context,
                                getString(R.string.photos_will_be_deleted_on_snappet_and_app),
                                getString(R.string.yes),
                                getString(R.string.no),
                                new Callback() {
                                    @Override
                                    public void callback(DialogInterface dialog) {
                                        //delete the current image
                                        file.delete();

                                        cameraCallback.init();
                                    }
                                },
                                null);
                    }
                });
                ViewHelper.setButtonTouchListener(deleteButton);

                saveButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        cameraCallback.init();
                    }
                });
                ViewHelper.setButtonTouchListener(saveButton);
            }
        };
    }

    private void setupLayoutWhenSnapPetDetected(final SnapPets snapPet) {
        if (SnappetsHelper.IS_ENABLE_PIN_CHECKING) {
            if (!SnappetsHelper.getInstance().isPinCodeChecked) {
                if (SnappetsHelper.getInstance().needTutorial(snapPet)) {
                    //TRY TO SAVE device name. need for checking if need tutorial
                    //TODO now this method sometimes not work
                    android.os.Handler handler = new android.os.Handler();

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            snapPet.writeModuleInfoUserDeviceName(BluetoothAdapter.getDefaultAdapter().getName());
                        }
                    }, 1000);

                    if (getView() != null)
                        getView().post(new Runnable() {
                            @Override
                            public void run() {
                                startSetPetNameFragment(snapPet);
                            }
                        });

                } else {
                    if (getView() != null)
                        getView().post(new Runnable() {
                            @Override
                            public void run() {
                                //If this is no first snap pet start - start if we need only pin dialog
                                //TODO implement checking need pin dialog start
                                if (!SnappetsHelper.getInstance().isPinCodeChecked) {
                                    startCheckPinDialog(snapPet);
                                }
                            }

                        });
                }
            }
        } else {
            SnappetsHelper.getInstance().isPinCodeChecked = true;
            SnappetsApplication.getApplicationClass(getActivity()).getDownloadService().startCheckNewPhotosThread();
            try {
                Thread.sleep(500);
            } catch (Exception ex) {

            }
        }
    }

    private void startSetPetNameFragment(SnapPets snapPet) {
        SetupNamePopup fragment = new SetupNamePopup();
        fragment.setSnappet(snapPet);
        fragment.setCameraFragment(cameraCallback);
        FragmentHelper.showWithoutSlideAnimation(getFragmentManager(), fragment, R.id.layout_popup, true);
    }

    private void startCheckPinDialog(final SnapPets snapPet) {
        String lastDeviceName = SharedSettingsHelper.getLastName(getActivity());
        String lastDevicePin = SharedSettingsHelper.getLastPin(getActivity());
        if (lastDeviceName != null && lastDeviceName.equals(ConnectionManager.mName) && lastDevicePin != null) {
            if (SnappetsHelper.IS_ENABLE_PIN_CHECKING) {
// AUTHENTICATION VIA PIN - UNCOMENT THIS SECTION OF CODE
                SnappetsHelper.getInstance().authenticateCallback = new AuthenticateCallback() {
                    @Override
                    public void didAuthenticate(boolean isAuthenticate) {
                        SnappetsHelper.getInstance().authenticateCallback = null;
                        if (!isAuthenticate) {
                            showCheckPinDialog(snapPet);
                        } else {
                            SnappetsHelper.getInstance().isPinCodeChecked = true;
                            SnappetsApplication.getApplicationClass(getActivity()).getDownloadService().startCheckNewPhotosThread();

                        }
                    }
                };
                snapPet.authenticatePinCode(lastDevicePin);
            } else {
// NOT AUTHENTICATION VIA PIN
                SnappetsHelper.getInstance().isPinCodeChecked = true;
                SnappetsApplication.getApplicationClass(getActivity()).getDownloadService().startCheckNewPhotosThread();
            }
        } else {
            showCheckPinDialog(snapPet);
        }
    }

    private void showCheckPinDialog(SnapPets snapPet) {
        CheckPinPopup checkPinFragment = new CheckPinPopup();
        checkPinFragment.setSnapPet(snapPet);
        checkPinFragment.setCameraCallback(cameraCallback);
        FragmentHelper.showWithoutSlideAnimation(getFragmentManager(), checkPinFragment, R.id.layout_popup, false);
    }

    private void updateLayoutForSnappetCamera() {
        ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);
        cameraToolLayout.setBackgroundColor(getResources().getColor(R.color.dark_grey_color));
        switchTimerLayout.setBackgroundColor(getResources().getColor(R.color.dark_grey_color));
        everyTimerLayout.setBackgroundColor(getResources().getColor(R.color.dark_grey_color));
        ViewHelper.invisibleViewWithAnimation(getActivity(), switchFlashButton);
        ViewHelper.invisibleViewWithAnimation(getActivity(), switchCameraButton);
        ViewHelper.showViewWithAnimation(getActivity(), previewImage);
        ViewHelper.showViewWithAnimation(getActivity(), snapPhoneLayout);
    }

    private void updateLayoutForPhoneCamera() {
//        ViewHelper.invisibleViewWithAnimation(getActivity(), settingButton);

        ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);

        cameraToolLayout.setBackgroundColor(context.getResources().getColor(R.color.camera_tool_bg));
        switchTimerLayout.setBackgroundColor(context.getResources().getColor(R.color.camera_tool_bg));
        everyTimerLayout.setBackgroundColor(context.getResources().getColor(R.color.camera_tool_bg));

        if (cameraInstance.hasCameraFlash()) {
            ViewHelper.showViewWithAnimation(getActivity(), switchFlashButton);
        } else {
            ViewHelper.hideViewWithAnimation(getActivity(), switchFlashButton);
        }

        if (cameraInstance.hasCameraSwitch()) {
            ViewHelper.showViewWithAnimation(getActivity(), switchCameraButton);
        } else {
            ViewHelper.hideViewWithAnimation(getActivity(), switchCameraButton);
        }

        ViewHelper.hideViewWithAnimation(getActivity(), previewImage);
        previewImage.setImageResource(0);
        ViewHelper.hideViewWithAnimation(getActivity(), snapPhoneLayout);
    }

    private ConnectSnappetCallback getChecksnappetPressButtonCallback() {
        return new ConnectSnappetCallback() {
            @Override
            public void connected(SnapPets snapPet) {

            }

            @Override
            public void disconnected(SnapPets snapPet) {

            }

            @Override
            public void receiveImageTotalSize(int size) {

            }

            @Override
            public void receivedImagePieceSize(int size) {

            }

            @Override
            public void receivedImageBuffer(byte[] buffer) {

            }

            @Override
            public void didPressedButton() {
                handler.pressTakePicture();
            }

            @Override
            public void receivedPhotoCount(int count) {

            }

            @Override
            public void didDeletePhoto(int id) {

            }
        };
    }

    private void setupSwithTimerLayout(View view) {
        // Add switch timer mode
        switchTimerButton = (Button) view.findViewById(R.id.btn_timer);
        switchFlashButton.setText(getResources().getString(R.string.flash_mode_off));
        cameraTimer = CAMERA_TIMER.OFF;

        switchTimerButton.setOnClickListener(this);
        ViewHelper.setButtonTouchListener(switchTimerButton);

        view.findViewById(R.id.sec3).setOnClickListener(this);
        view.findViewById(R.id.sec7).setOnClickListener(this);
        view.findViewById(R.id.sec10).setOnClickListener(this);
        view.findViewById(R.id.close_timer_bar).setOnClickListener(this);
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.sec3));
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.sec7));
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.sec10));
        ViewHelper.setButtonTouchListener(view.findViewById(R.id.close_timer_bar));
        switchTimerLayout = (ViewGroup) view.findViewById(R.id.layout_timer_tool);
    }

    private void setupSwitchCameraButton(View view) {
        // Add switch camera
        switchCameraButton = (Button) view.findViewById(R.id.btn_camswitch);
        switchCameraButton.setText(getResources().getString(R.string.front_camera));
        if (cameraInstance.hasCameraSwitch()) {
            ViewHelper.setButtonTouchListener(switchCameraButton);
            switchCameraButton.setOnClickListener(this);
        }

    }

    private void setupSwitchFlashButton(View view) {
        // Add switch flash mode
        switchFlashButton = (Button) view.findViewById(R.id.btn_flash);
        if (cameraInstance.hasCameraFlash()) {
            cameraFlash = CAMERA_FLASH.OFF;

            ViewHelper.setButtonTouchListener(switchFlashButton);
            switchFlashButton.setOnClickListener(this);
        }
    }

    private void createCameraPreview(View rootView) {
        // Create our Preview view and set it as the content of our activity.
        mPreview = new CameraPreview(context, cameraInstance.camera);
        mPreview.setOnClickListener(this);
        RelativeLayout preview = (RelativeLayout) rootView.findViewById(R.id.layout_camera_xxx);
        preview.addView(mPreview);
    }

    private void setupSettingsButton(View rootView) {
        settingButton = rootView.findViewById(R.id.btn_settings);
        ViewHelper.setButtonTouchListener(settingButton);
        settingButton.setOnClickListener(this);
        ViewHelper.setButtonTouchListener(settingButton);
    }

    private void galleryButtonClicked() {
        FragmentHelper.switchFragment(getFragmentManager(), new GalleryFragment(), R.id.layout_core, true);
    }

    private void snapButtonClicked() {
        if (!handler.pressTakePicture()) {
        }
    }

    private void cameraCancelButtonClicked() {
        countDownTimer.cancel();
        countDownTimer = null;

        ViewHelper.invisibleViewWithAnimation(getActivity(), countdownText);
        ViewHelper.invisibleViewWithAnimation(getActivity(), countdownSnapText);

        ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);
        ViewHelper.hideViewWithAnimation(getActivity(), cameraControlLayout.findViewById(R.id.btn_cam_cancel));
    }

    private void backButtonClicked() {
        cameraCallback.init();
    }

    private void switchTimerButtonClicked() {
        ViewHelper.showViewWithAnimation(getActivity(), switchTimerLayout);
        ViewHelper.hideViewWithAnimation(getActivity(), cameraToolLayout);
        ViewHelper.hideViewWithAnimation(getActivity(), cameraControlLayout);
    }

    private void switchCameraButtonClicked() {
        if (cameraInstance.switchCamera()) {
            mPreview.updateCamera(cameraInstance.camera);
            if (cameraInstance.hasCameraFlash()) {
                if (cameraInstance.getCameraId() == 0) {
                    switchFlashButton.setEnabled(true);
                    cameraInstance.setCameraFlash(cameraFlash.mode);
                    switchCameraButton.setText(getResources().getString(R.string.front_camera));
                } else {
                    switchFlashButton.setEnabled(false);
                    switchCameraButton.setText(getResources().getString(R.string.back_camera));
                }
            }
        }
    }

    private void switchFlashButtonClicked() {
        cameraFlash = cameraFlash.next();
        cameraInstance.setCameraFlash(cameraFlash.mode);
        if(cameraFlash.mode == CAMERA_FLASH.OFF.mode) {
            switchFlashButton.setText(getResources().getString(R.string.flash_mode_off));
        } else if(cameraFlash.mode == CAMERA_FLASH.ON.mode) {
            switchFlashButton.setText(getResources().getString(R.string.flash_mode_on));
        } else if(cameraFlash.mode == CAMERA_FLASH.AUTO.mode) {
            switchFlashButton.setText(getResources().getString(R.string.flash_mode_auto));
        } else {
            switchFlashButton.setText(getResources().getString(R.string.flash_mode_disable));
        }
    }

    private void previewClicked() {
        if (cameraTimer != CAMERA_TIMER.OFF
                && countDownTimer != null) {
            //cancel the countdown
            countDownTimer.cancel();
            countDownTimer = null;

            //show the camera tool
            ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);

            //hidden the count down
            ViewHelper.invisibleViewWithAnimation(getActivity(), countdownText);
            ViewHelper.invisibleViewWithAnimation(getActivity(), countdownSnapText);

            if (cameraMode == CAMERA_MODE.SNAPPET) {
                //camera tool
                ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);
                ViewHelper.hideViewWithAnimation(getActivity(), cameraControlLayout.findViewById(R.id.btn_cam_cancel));
//                cameraToolLayout.setBackgroundResource(0);

                //show the snappet's hint
//                ViewHelper.showViewWithAnimation(getActivity(), previewImage);
//                previewImage.setBackgroundColor(context.getResources().getColor(R.color.theme_color));
//                if (animationPlayback != null) {
//                    animationPlayback.stop();
//                }
//                animationPlayback = new ImageViewAnimationPlayback(
//                        previewImage, new int[]{
//                        R.drawable.anime_popup_pet_as_cam_1,
//                        R.drawable.anime_popup_pet_as_cam_2},
//                        500 else {
                ViewHelper.showViewWithAnimation(getActivity(), cameraToolLayout);
                ViewHelper.hideViewWithAnimation(getActivity(), cameraControlLayout.findViewById(R.id.btn_cam_cancel));
            }
            //TODO: show the Toast for cancel
        }
    }

    private void settingsButtonClicked() {
        //use current Snappet instead of null for SettingsFragmment
        SettingsFragment fragment = new SettingsFragment();
        fragment.setSnappet(SnappetsHelper.getInstance().getConnectedSnappet());
        fragment.setCameraCallback(cameraCallback);
        FragmentHelper.switchFragment(getFragmentManager(), fragment, R.id.layout_core, true);
    }

    private void createCameraInstance() {
        cameraInstance = CameraInstance.createInstance(context, getResources().getString(R.string.store_image_folder), EXPECTED_PHOTO_WIDTH, EXPECTED_PHTOT_HEIGHT);
        cameraInstance.createCamera();
    }

    public void remoteTakePictureFromSnanpet() {
        handler.pressTakePicture();
    }

    //don't call this function directly, since this function will be triggered by TIMER too
    private void doTakePicture() {
        if (cameraMode == CAMERA_MODE.PHONE) {
            // get an image from the camera
            cameraInstance.takePicture(cameraCallback);
        } else if (cameraMode == CAMERA_MODE.SNAPPET) {
            /**
             * workflow for show the picture:
             *
             * 1. [UI] trigger the transfer UI by cameraCallback.beforeTakePicture()
             * 2. [BLE] send cmd and receive callback from BLE?
             * 3. [BLE] receive the data from snappet
             * 4. [UI] update the loading progress by handler.updateLoadingProgress(progress)
             * 5. [UI] when transfer is done, do post-process and trigger the picture UI by takePictureFromSnappet(data)
             */

            //send the command to snappet to take picture
            //TODO new logic of loading picture
            if (downloadService == null)
                downloadService = SnappetsApplication.getApplicationClass(this.getActivity()).getDownloadService();
            if (downloadService != null) {
                downloadService.setStatisticListener(getDownloadStatisticListener());
                downloadService.startTakePicture();
                cameraCallback.beforeTakePicture();
            }
        }
    }

    private void saveCurrentPhoto(File imageFile) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(imageFile), null, options);
            Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
            savePhotoOnDisk(mutableBitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void savePhotoOnDisk(Bitmap mutableBitmap) {
        String file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
        File dir = new File(file_path);

        if (!dir.exists())
            dir.mkdirs();

        DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
        Date date = new Date();

        String name = getResources().getString(R.string.new_photo_default_name).concat(dateFormat.format(date)).concat(".png");
        File file = new File(dir, name);
        try {
            file.createNewFile();
            FileOutputStream fOut = null;

            fOut = new FileOutputStream(file);
            mutableBitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);

            fOut.flush();
            fOut.close();

            notifyGallery(file.getPath());

            Toast.makeText(getActivity(), getResources().getString(R.string.saved_photo_text).concat(file_path),
                    Toast.LENGTH_SHORT).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void notifyGallery(String path) {
        MediaScannerConnection.scanFile(context,
                new String[]{path}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String path, Uri uri) {
                    }
                });
    }

    private IDownloadImageStatisticListener getDownloadStatisticListener() {
        return new IDownloadImageStatisticListener() {

            @Override
            public void finishDownload() {

            }

            @Override
            public void downloadedPictureProgress(int pictruesCount, int picturesTotalCount, int imageBufferSize, int imageTotalSize) {
                handler.updateLoadingProgress(imageBufferSize * 100 / imageTotalSize);
            }
        };
    }

    public interface Handler {
        boolean pressTakePicture();

        void updateLoadingProgress(int percentage);    //100 is the base value

        void setTitle(String name);
    }
}


text:
<?php

namespace Home\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RoleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('role', 'choice', array(
            'label' => 'Papeis',
            'choices' => array('ROLE_ADMIN' => 'ADMIN', 'ROLE_USER' => 'USER')
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Home\UserBundle\Entity\Role'
        ));
    }

    public function getName()
    {
        return "roles";
    }
}


text:
package producerstest;

import dagger.Component;

@Component(modules = DependedModule.class)
interface DependedComponent {
  String getGreeting();
}


text:
echo Entering "$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")" in "$(pwd)"

# Fail the whole script if any command fails
set -e

# Print commands as they are executed
set -x

export SHELLOPTS

if [ "$(uname)" = "Darwin" ] ; then
  export JAVA_HOME=${JAVA_HOME:-$(/usr/libexec/java_home)}
else
  export JAVA_HOME=${JAVA_HOME:-$(dirname "$(dirname "$(readlink -f "$(which javac)")")")}
fi
echo "JAVA_HOME=$JAVA_HOME"
export AFU="${AFU:-$(cd annotation-file-utilities && pwd -P)}"

export PATH=$AFU/scripts:$JAVA_HOME/bin:$PATH

## Download Gradle and its dependencies (retry in case of network lossage).
(cd "${AFU}" && \
  TERM=dumb timeout 300 ./gradlew --write-verification-metadata sha256 help --dry-run </dev/null >/dev/null 2>&1 || \
  TERM=dumb ./gradlew --write-verification-metadata sha256 help --dry-run </dev/null >/dev/null 2>&1 || \
  (sleep 1m && ./gradlew --write-verification-metadata sha256 help --dry-run))

## Compile
(cd "${AFU}" && ./gradlew assemble)

echo Exiting "$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")" in "$(pwd)"


text:
Submission for teaching block 1 CNOS coursework

## Synopsis

An implementation of the SNTP client and server specified here in [RFC4330](https://tools.ietf.org/html/rfc4330)

## Code Example

### Server

Run the server with `./sntp-server` accepted arguments are:

`-help`, lists all options.

`-port`, sets the port number.

`-multicast`, puts the server in multicast mode, will listen on multicast group `224.0.1.1`

Multiple arguments can be passed.

### Client

Run the client with `./sntp-client`, accepted arguments are:

`-help`, lists all options.

`-port`, sets the port number.

`-host`, sets the hostname of the server to contact.

`-multicast`, puts the client in multicast mode, will request on multicast group `224.0.1.1`

Multiple arguments can be passed.

## Installation

Use `CMAKE` to generate the executables and test suite.

## Tests

The test suite uses the googletest framework to acheive test coverage, load the project into an IDE to run the test suite or run `checks.cpp` from the command line. `CMAKE` will handle the set up.

## Contributors

Nathaniel Steers (SN 10018627)


text:
/* ************************************************
 * GEANT4 CAD INTERFACE
 *
 * File:      CADMesh.cc
 *
 * Author:    Christopher M Poole,
 * Email:     mail@christopherpoole.net
 *
 * Date:      7th March, 2011
 **************************************************/

// CADMesh //
#include "CADMeshTemplate.hh"
#include "Exceptions.hh"

namespace CADMesh
{

template <typename T>
CADMeshTemplate<T>::CADMeshTemplate() : CADMeshTemplate<T>("")
{
}

template <typename T>
CADMeshTemplate<T>::CADMeshTemplate(G4String file_name)
        : CADMeshTemplate<T>(file_name, File::Unknown)
{
}

template <typename T>
CADMeshTemplate<T>::CADMeshTemplate( G4String file_name, File::Type file_type)
        : CADMeshTemplate<T>(file_name, file_type, CADMESH_DEFAULT_READER)
{
}

template <typename T>
CADMeshTemplate<T>::CADMeshTemplate( std::shared_ptr<File::Reader> reader)
        : CADMeshTemplate<T>("", reader)
{
}

template <typename T>
CADMeshTemplate<T>::CADMeshTemplate( G4String file_name
                                   , std::shared_ptr<File::Reader> reader)
        : CADMeshTemplate<T>(file_name, File::Unknown, reader)
{
}

template <typename T>
CADMeshTemplate<T>::CADMeshTemplate( G4String file_name
                                   , File::Type file_type
                                   , std::shared_ptr<File::Reader> reader)
{
    if (!reader->CanRead(file_type))
    {
        Exceptions::ReaderCantReadError( reader->GetName()
                                       , file_type
                                       , file_name);
    }

    file_name_ = file_name;
    file_type_ = file_type;

    scale_ = mm;

    offset_ = G4ThreeVector();

    verbose_ = 0;

    reader_ = reader;

    reader_->Read(file_name_);
}

template <typename T>
std::shared_ptr<T> CADMeshTemplate<T>::FromPLY(G4String file_name)
{
    return std::make_shared<T>(file_name, File::PLY);
}

template <typename T>
std::shared_ptr<T> CADMeshTemplate<T>::FromPLY( G4String file_name
                                              , std::shared_ptr<File::Reader> reader)
{
    return std::make_shared<T>(file_name, File::PLY, reader);
}

template <typename T>
std::shared_ptr<T> CADMeshTemplate<T>::FromSTL(G4String file_name)
{
    return std::make_shared<T>(file_name, File::STL);
}

template <typename T>
std::shared_ptr<T> CADMeshTemplate<T>::FromSTL( G4String file_name
                                              , std::shared_ptr<File::Reader> reader)
{
    return std::make_shared<T>(file_name, File::STL, reader);
}

template <typename T>
CADMeshTemplate<T>::~CADMeshTemplate()
{
}

template <typename T>
bool CADMeshTemplate<T>::IsValidForNavigation()
{
    return reader_->GetMesh()->IsValidForNavigation();
}

template <typename T>
G4String CADMeshTemplate<T>::GetFileName()
{
    return file_name_;
}

template <typename T>
File::Type CADMeshTemplate<T>::GetFileType()
{
    return file_type_;
}

template <typename T>
void CADMeshTemplate<T>::SetVerbose(G4int verbose)
{
    verbose_ = verbose;
}

template <typename T>
G4int CADMeshTemplate<T>::GetVerbose()
{
    return verbose_;
}

template <typename T>
void CADMeshTemplate<T>::SetScale(G4double scale)
{
    scale_ = scale;
}

template <typename T>
G4double CADMeshTemplate<T>::GetScale()
{
    return scale_;
}

template <typename T>
void CADMeshTemplate<T>::SetOffset(G4ThreeVector offset)
{
    offset_ = offset;
}

template <typename T>
G4ThreeVector CADMeshTemplate<T>::GetOffset()
{
    return offset_;
}

} // CADMesh namespace


text:
using BLEGuitar.Commons;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static BLEGuitar.Server.DXHelper;

namespace BLEGuitar.Server
{
    public class GuitarController
    {
        private readonly DXHelper simulator = new DXHelper();
        private readonly ConcurrentQueue<GuitarButtonsState> queue = new ConcurrentQueue<GuitarButtonsState>();
        private Dictionary<string, DIKKeyCode> KeyMap;

        public void LoadMaps()
        {
            KeyMap = new Dictionary<string, DIKKeyCode>();

            foreach (var property in typeof(GuitarButtonsState).GetProperties())
            {
                string keyValue = ConfigurationManager.AppSettings[property.Name];
                if (Enum.TryParse(keyValue, true, out DIKKeyCode keyMap))
                {
                    KeyMap.Add(property.Name, keyMap);
                }
            }
        }

        private Tuple<KeyFlag, short> ProcessButtonState(ButtonState state, DIKKeyCode keycode)
        {
            return Tuple.Create(state == ButtonState.Pressed ? KeyFlag.KeyDown : KeyFlag.KeyUp, (short)keycode);
        }

        public void Guitar_DataReceived(object sender, DataReceivedArgs e)
        {
            var inputs = GetInputs(e.Snapshot);
            simulator.SendInput(inputs);
            simulator.SendMouseInput(e.Snapshot.WhammyBar, e.Snapshot.WhammyBar);
        }

        private List<Tuple<KeyFlag, short>> GetInputs(GuitarButtonsState e)
        {
            List<Tuple<KeyFlag, short>> inputs = new List<Tuple<KeyFlag, short>>()
            {
                ProcessButtonState(e.Fret1, KeyMap[nameof(GuitarButtonsState.Fret1)]),
                ProcessButtonState(e.Fret2, KeyMap[nameof(GuitarButtonsState.Fret2)]),
                ProcessButtonState(e.Fret3, KeyMap[nameof(GuitarButtonsState.Fret3)]),
                ProcessButtonState(e.Fret4, KeyMap[nameof(GuitarButtonsState.Fret4)]),
                ProcessButtonState(e.Fret5, KeyMap[nameof(GuitarButtonsState.Fret5)]),
                ProcessButtonState(e.Fret6, KeyMap[nameof(GuitarButtonsState.Fret6)]),
                ProcessButtonState(e.Pause, KeyMap[nameof(GuitarButtonsState.Pause)]),
                ProcessButtonState(e.LiveTV, KeyMap[nameof(GuitarButtonsState.LiveTV)]),
                ProcessButtonState(e.HeroPower, KeyMap[nameof(GuitarButtonsState.HeroPower)]),
                ProcessButtonState(e.Power, KeyMap[nameof(GuitarButtonsState.Power)])
            };

            switch (e.StrumBar)
            {
                case StrumBarState.StrumBarNeutral:
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_8));
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_9));
                    break;
                case StrumBarState.StrumBarUp:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_8));
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_9));
                    break;
                case StrumBarState.StrumBarDown:
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_8));
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_9));
                    break;
                default:
                    break;
            }

            switch (e.Navigator)
            {
                case 0:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_W));
                    break;
                case 1:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_W));
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_A));
                    break;
                case 2:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_A));
                    break;
                case 3:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_A));
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_S));
                    break;
                case 4:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_S));
                    break;
                case 5:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_S));
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_D));
                    break;
                case 6:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_D));
                    break;
                case 7:
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_D));
                    inputs.Add(ProcessButtonState(ButtonState.Pressed, DIKKeyCode.DIK_W));
                    break;
                case 15:
                default:
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_W));
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_A));
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_S));
                    inputs.Add(ProcessButtonState(ButtonState.NotPressed, DIKKeyCode.DIK_D));
                    break;
            }

            return inputs;
        }
    }
}


text:
/*
 * @test
 * @bug 5045306 6356004 6993490
 * @library ../../httptest/
 * @build HttpCallback HttpServer HttpTransaction
 * @run main/othervm B5045306
 * @summary Http keep-alive implementation is not efficient
 */

import java.net.*;
import java.io.*;
import java.lang.management.*;

/* Part 1:
 * The http client makes a connection to a URL whos content contains a lot of
 * data, more than can fit in the socket buffer. The client only reads
 * 1 byte of the data from the InputStream leaving behind more data than can
 * fit in the socket buffer. The client then makes a second call to the http
 * server. If the connection port used by the client is the same as for the
 * first call then that means that the connection is being reused.
 *
 * Part 2:
 * Test buggy webserver that sends less data than it specifies in its
 * Content-length header.
 */

public class B5045306
{
    static SimpleHttpTransaction httpTrans;
    static HttpServer server;

    public static void main(String[] args) throws Exception {
        startHttpServer();
        clientHttpCalls();
    }

    public static void startHttpServer() {
        try {
            httpTrans = new SimpleHttpTransaction();
            server = new HttpServer(httpTrans, 1, 10, 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void clientHttpCalls() {
        try {
            System.out.println("http server listen on: " + server.getLocalPort());
            String baseURLStr = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" +
                                  server.getLocalPort() + "/";

            URL bigDataURL = new URL (baseURLStr + "firstCall");
            URL smallDataURL = new URL (baseURLStr + "secondCall");

            HttpURLConnection uc = (HttpURLConnection)bigDataURL.openConnection();

            //Only read 1 byte of response data and close the stream
            InputStream is = uc.getInputStream();
            byte[] ba = new byte[1];
            is.read(ba);
            is.close();

            // Allow the KeepAliveStreamCleaner thread to read the data left behind and cache the connection.
            try { Thread.sleep(2000); } catch (Exception e) {}

            uc = (HttpURLConnection)smallDataURL.openConnection();
            uc.getResponseCode();

            if (SimpleHttpTransaction.failed)
                throw new RuntimeException("Failed: Initial Keep Alive Connection is not being reused");

            // Part 2
            URL part2Url = new URL (baseURLStr + "part2");
            uc = (HttpURLConnection)part2Url.openConnection();
            is = uc.getInputStream();
            is.close();

            // Allow the KeepAliveStreamCleaner thread to try and read the data left behind and cache the connection.
            try { Thread.sleep(2000); } catch (Exception e) {}

            ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            if (threadMXBean.isThreadCpuTimeSupported()) {
                long[] threads = threadMXBean.getAllThreadIds();
                ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threads);
                for (int i=0; i<threadInfo.length; i++) {
                    if (threadInfo[i].getThreadName().equals("Keep-Alive-SocketCleaner"))  {
                        System.out.println("Found Keep-Alive-SocketCleaner thread");
                        long threadID = threadInfo[i].getThreadId();
                        long before = threadMXBean.getThreadCpuTime(threadID);
                        try { Thread.sleep(2000); } catch (Exception e) {}
                        long after = threadMXBean.getThreadCpuTime(threadID);

                        if (before ==-1 || after == -1)
                            break;  // thread has died, OK

                        // if Keep-Alive-SocketCleaner consumes more than 50% of cpu then we
                        // can assume a recursive loop.
                        long total = after - before;
                        if (total >= 1000000000)  // 1 second, or 1 billion nanoseconds
                            throw new RuntimeException("Failed: possible recursive loop in Keep-Alive-SocketCleaner");
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            server.terminate();
        }
    }
}

class SimpleHttpTransaction implements HttpCallback
{
    static boolean failed = false;

    // Need to have enough data here that is too large for the socket buffer to hold.
    // Also http.KeepAlive.remainingData must be greater than this value, default is 256K.
    static final int RESPONSE_DATA_LENGTH = 128 * 1024;

    int port1;

    public void request(HttpTransaction trans) {
        try {
            String path = trans.getRequestURI().getPath();
            if (path.equals("/firstCall")) {
                port1 = trans.channel().socket().getPort();
                System.out.println("First connection on client port = " + port1);

                byte[] responseBody = new byte[RESPONSE_DATA_LENGTH];
                for (int i=0; i<responseBody.length; i++)
                    responseBody[i] = 0x41;
                trans.setResponseEntityBody (responseBody, responseBody.length);
                trans.sendResponse(200, "OK");
            } else if (path.equals("/secondCall")) {
                int port2 = trans.channel().socket().getPort();
                System.out.println("Second connection on client port = " + port2);

                if (port1 != port2)
                    failed = true;

                trans.setResponseHeader ("Content-length", Integer.toString(0));

                 /* Force the server to not respond for more that the timeout
                  * set by the keepalive cleaner (5000 millis). This ensures the
                  * timeout is correctly resets the default read timeout,
                  * infinity. See 6993490. */
                System.out.println("server sleeping...");
                try {Thread.sleep(6000); } catch (InterruptedException e) {}

                trans.sendResponse(200, "OK");
            } else if(path.equals("/part2")) {
                System.out.println("Call to /part2");
                byte[] responseBody = new byte[RESPONSE_DATA_LENGTH];
                for (int i=0; i<responseBody.length; i++)
                    responseBody[i] = 0x41;
                trans.setResponseEntityBody (responseBody, responseBody.length);

                // override the Content-length header to be greater than the actual response body
                trans.setResponseHeader("Content-length", Integer.toString(responseBody.length+1));
                trans.sendResponse(200, "OK");

                // now close the socket
                trans.channel().socket().close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
<tool id="stacks_pstacks" name="Stacks: pstacks" version="@WRAPPER_VERSION@.0">
    <description>find stacks from short reads mapped to a reference genome</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro="requirements"/>
    <expand macro="stdio"/>
    <command><![CDATA[

        @CLEAN_EXT@

        mkdir stacks_inputs stacks_outputs

        &&

        #if $sample.is_of_type('sam')
            #set $data_path = "stacks_inputs/" + $clean_ext($sample.element_identifier) + ".sam"
            #set inputype = "sam"
        #else
            #set $data_path = "stacks_inputs/" + $clean_ext($sample.element_identifier) + ".bam"
            #set inputype = "bam"
        #end if

        ln -s '${sample}' '${data_path}'

        &&

        pstacks

            -p \${GALAXY_SLOTS:-1}

            -f $data_path

            -t $inputype

            ## Batch description
            -i $sample_id

            -m $m

            --max_clipped $max_clipped
            --min_mapq $min_mapq
            $keep_sec_alns

            ## snp_model
            #if str( $snp_options.select_model.model_type) == "bounded"
                --model_type bounded
                --bound_low $snp_options.select_model.bound_low
                --bound_high $snp_options.select_model.bound_high
                --alpha $snp_options.select_model.alpha
            #else if str( $snp_options.select_model.model_type) == "snp"
                --model_type snp
                --alpha $snp_options.select_model.alpha
            #else
                --model_type fixed
                --bc_err_freq $bc_err_freq
            #end if

            -o stacks_outputs

             2>&1 | tee pstacks.log

            ## If input is in bam format, stacks will output gzipped files (no option to control this)
            && if ls stacks_outputs/*.gz > /dev/null 2>&1; then gunzip stacks_outputs/*.gz; fi

            &&

            stacks_summary.py --stacks-prog pstacks --res-dir stacks_outputs --logfile pstacks.log --summary stacks_outputs/summary.html
    ]]></command>

    <inputs>
        <param name="sample" argument="-f" format="sam,bam" type="data" label="Input short reads from an individual" />

        <param name="sample_id" argument="-i" type="integer" value="" label="Give a unique numeric ID to this sample"/>

        <param name="m" argument="-m" type="integer" value="1" label="Minimum depth of coverage required to create a stack"/>

        <param name="max_clipped" argument="--max_clipped" type="float" value="0.15" min="0.0" max="1.0" label="Alignments with more than this fraction of soft-clipped bases are discarded"/>

        <param name="min_mapq" argument="--min_mapq" type="integer" value="10" label="Minimum required mapping quality"/>

        <param name="keep_sec_alns" argument="--keep_sec_alns" type="boolean" checked="false" truevalue="--keep_sec_alns" falsevalue="" label="Keep secondary alignments" />

        <!-- SNP Model options -->
        <section name="snp_options" title="SNP Model Options (pstacks options)" expanded="False">
            <expand macro="snp_options_full"/>
        </section>
    </inputs>

    <outputs>
        <data format="txt" name="output_log" label="pstacks.log with ${tool.name} on ${on_string}" from_work_dir="pstacks.log" />

        <data format="html" name="output_summary" label="Summary from ${tool.name} on ${on_string}" from_work_dir="stacks_outputs/summary.html" />

        <collection name="tabs" type="list" label="Stacks from ${on_string}">
            <discover_datasets pattern="(?P<name>.+\.tags)\.tsv$" ext="tabular" directory="stacks_outputs" />
            <discover_datasets pattern="(?P<name>.+\.snps)\.tsv$" ext="tabular" directory="stacks_outputs" />
            <discover_datasets pattern="(?P<name>.+\.alleles)\.tsv$" ext="tabular" directory="stacks_outputs" />
            <discover_datasets pattern="(?P<name>.+\.models)\.tsv$" ext="tabular" directory="stacks_outputs" />
        </collection>
    </outputs>

    <tests>
        <test>
            <param name="sample" value="refmap/PopA_01.bam" ftype="bam" />
            <param name="sample_id" value="4" />

            <output name="output_log">
                <assert_contents>
                    <has_text text="done." />
                </assert_contents>
            </output>
            <output name="output_summary">
                <assert_contents>
                    <has_text text="Stacks Statistics" />
                </assert_contents>
            </output>

            <output_collection name="tabs">
                <element name="PopA_01.tags">
                    <assert_contents>
                        <has_text text="generated on " />
                    </assert_contents>
                </element>
                <element name="PopA_01.snps">
                    <assert_contents>
                        <has_text text="generated on " />
                    </assert_contents>
                </element>
                <element name="PopA_01.alleles">
                    <assert_contents>
                        <has_text text="generated on " />
                    </assert_contents>
                </element>
                <element name="PopA_01.models">
                    <assert_contents>
                        <has_text text="generated on " />
                    </assert_contents>
                </element>
            </output_collection>
        </test>
    </tests>

    <help>
<![CDATA[
.. class:: infomark

**What it does**

Similar to ustacks, except this program will extract stacks that have been aligned to a reference genome by a program such as Bowtie and identify SNPs. These stacks can then be processed with cstacks or sstacks.

--------

**Input files**

- SAM, BAM (e.g. from bowtie or bwa)

**Output files**

- XXX.tags.tsv file:

See `Stacks output description <http://catchenlab.life.illinois.edu/stacks/manual/#files>`_

Notes: For the tags file, each stack will start in the file with a consensus sequence for the entire stack followed by the flags for that stack. Then, each individual read that was merged into that stack will follow. The next stack will start with another consensus sequence.

- XXX.snps.tsv file:

See `Stacks output description <http://catchenlab.life.illinois.edu/stacks/manual/#files>`_

Notes: If a stack has two SNPs called within it, then there will be two lines in this file listing each one.

- XXX.alleles.tsv file:

See `Stacks output description <http://catchenlab.life.illinois.edu/stacks/manual/#files>`_

@STACKS_INFOS@
]]>
    </help>
    <expand macro="citation" />
</tool>


text:
ActsAsElementInCategory is a categorizing plugin literally.

You can implement simple categorizing to your Rails applications.
For instance, posts of a blog, pages of a wiki and more.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'acts_as_element_in_category'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install acts_as_element_in_category

## Usage

Setup

```ruby
class YourCategory < ActiveRecord::Base
end

class Element < ActiveRecord::Base
  acts_as_element_in_your_category
end
```

Categorizing:

```ruby
category = YourCategory.find(params[:category_id])
element = Element.find(params[:element_id])
element.cateddgory = category
element.save
```

Category filter:

```ruby
category = YourCategory.find(params[:category_id])
elements = Element.in category
```

Query chain:

```ruby
category = YourCategory.find(params[:category_id])
elements = Element.where(your conditions).in(category).order(:id)
```

## Contributing

1. Fork it ( https://github.com/zakuro9715/acts_as_element_in_category/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
package org.innovateuk.ifs.assessment.transactional;

import com.google.common.collect.Streams;
import org.innovateuk.ifs.assessment.domain.Assessment;
import org.innovateuk.ifs.assessment.domain.AssessmentParticipant;
import org.innovateuk.ifs.assessment.mapper.AssessmentInviteMapper;
import org.innovateuk.ifs.assessment.mapper.AssessmentParticipantMapper;
import org.innovateuk.ifs.assessment.period.domain.AssessmentPeriod;
import org.innovateuk.ifs.assessment.period.mapper.AssessmentPeriodMapper;
import org.innovateuk.ifs.assessment.repository.AssessmentParticipantRepository;
import org.innovateuk.ifs.assessment.repository.AssessmentRepository;
import org.innovateuk.ifs.assessment.resource.AssessmentState;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competition.domain.CompetitionParticipant;
import org.innovateuk.ifs.competition.mapper.CompetitionParticipantRoleMapper;
import org.innovateuk.ifs.competition.resource.AssessmentPeriodResource;
import org.innovateuk.ifs.invite.mapper.ParticipantStatusMapper;
import org.innovateuk.ifs.invite.mapper.RejectionReasonMapper;
import org.innovateuk.ifs.invite.resource.CompetitionParticipantResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;
import static org.innovateuk.ifs.assessment.resource.AssessmentState.*;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.util.CollectionFunctions.sort;

/**
 * Service for managing {@link CompetitionParticipant}s.
 */
@Service
@Transactional(readOnly = true)
public class CompetitionParticipantServiceImpl implements CompetitionParticipantService {

    @Autowired
    private AssessmentParticipantRepository assessmentParticipantRepository;

    @Autowired
    private AssessmentParticipantMapper compParticipantMapper;

    @Autowired
    private AssessmentRepository assessmentRepository;

    @Autowired
    private AssessmentInviteMapper assessmentInviteMapper;

    @Autowired
    private RejectionReasonMapper rejectionReasonMapper;

    @Autowired
    private CompetitionParticipantRoleMapper competitionParticipantRoleMapper;

    @Autowired
    private ParticipantStatusMapper participantStatusMapper;

    @Autowired
    private AssessmentPeriodMapper assessmentPeriodMapper;

    @Override
    public ServiceResult<List<CompetitionParticipantResource>> getCompetitionAssessors(long userId) {

        List<CompetitionParticipantResource> competitionParticipantResources = assessmentParticipantRepository.getByAssessorId(userId).stream()
                .map(compParticipantMapper::mapToResource)
                .filter(participant -> !participant.isRejected() && participant.isUpcomingOrInAssessment())
                .collect(toList());

        competitionParticipantResources.forEach(competitionParticipant -> determineStatusOfCompetitionAssessments(competitionParticipant, false));

        return serviceSuccess(competitionParticipantResources);
    }

    @Override
    public ServiceResult<List<CompetitionParticipantResource>> getCompetitionAssessorsWithAssessmentPeriod(long userId) {

        List<CompetitionParticipantResource> competitionParticipantResources = assessmentParticipantRepository.getByAssessorId(userId).stream()
                .flatMap(assessmentParticipant -> buildAssessmentParticipant(assessmentParticipant))
                .filter(competitionParticipant -> !competitionParticipant.isRejected() && isUpcomingOrInAssessment(competitionParticipant))
                .collect(toList());

        competitionParticipantResources.forEach(competitionParticipant -> determineStatusOfCompetitionAssessments(competitionParticipant, true));

        return serviceSuccess(competitionParticipantResources);
    }

    private Stream<CompetitionParticipantResource> buildAssessmentParticipant(AssessmentParticipant assessmentParticipant) {
        return Streams
                .mapWithIndex(sort(assessmentParticipant.getProcess().getAssessmentPeriods(), Comparator.comparingLong(o -> o.getId())).stream(),
                        (assessmentPeriod, index) -> buildCompetitionParticipantResource(assessmentParticipant, assessmentPeriod, index+1));
    }

    private CompetitionParticipantResource buildCompetitionParticipantResource(AssessmentParticipant assessmentParticipant,
                                                                               AssessmentPeriod assessmentPeriod,
                                                                               long assessmentPeriodNumber) {
        return new CompetitionParticipantResource(assessmentParticipant.getId(), assessmentParticipant.getProcess().getId(),
                assessmentParticipant.getUser().getId(), assessmentInviteMapper.mapToResource(assessmentParticipant.getInvite()),
                rejectionReasonMapper.mapToResource(assessmentParticipant.getRejectionReason()), assessmentParticipant.getRejectionReasonComment(),
                competitionParticipantRoleMapper.mapToResource(assessmentParticipant.getRole()), participantStatusMapper.mapToResource(assessmentParticipant.getStatus()),
                assessmentParticipant.getProcess().getName(), assessmentParticipant.getProcess().getAssessorAcceptsDate(assessmentPeriod),
                assessmentParticipant.getProcess().getAssessorDeadlineDate(assessmentPeriod), assessmentParticipant.getProcess().getCompetitionStatus(),
                assessmentParticipant.getProcess().getAlwaysOpen(), assessmentPeriodMapper.mapToResource(assessmentPeriod), assessmentPeriodNumber);
    }

    private boolean isUpcomingOrInAssessment(CompetitionParticipantResource competitionParticipant) {
        if (competitionParticipant.isCompetitionAlwaysOpen()) {
            return competitionParticipant.getAssessmentPeriod().isInAssessment()
                    || !competitionParticipant.getAssessmentPeriod().isAssessmentClosed();
        } else {
            return competitionParticipant.isUpcomingOrInAssessment();
        }
    }

    private void determineStatusOfCompetitionAssessments(CompetitionParticipantResource competitionParticipant, boolean filterByAssessmentPeriod) {
        if (!competitionParticipant.isAccepted() || !isInAssessment(competitionParticipant)) {
            return;
        }

        List<Assessment> assessments = assessmentRepository.findByParticipantUserIdAndTargetCompetitionId(
                competitionParticipant.getUserId(),
                competitionParticipant.getCompetitionId()
        );

        competitionParticipant.setSubmittedAssessments(getAssessmentsSubmittedForCompetitionCount(assessments, competitionParticipant, filterByAssessmentPeriod));
        competitionParticipant.setTotalAssessments(getTotalAssessmentsAcceptedForCompetitionCount(assessments, competitionParticipant, filterByAssessmentPeriod));
        competitionParticipant.setPendingAssessments(getAssessmentsPendingForCompetitionCount(assessments, competitionParticipant, filterByAssessmentPeriod));
    }

    private boolean isInAssessment(CompetitionParticipantResource competitionParticipant) {
        if (competitionParticipant.isCompetitionAlwaysOpen()) {
            return competitionParticipant.getAssessmentPeriod() != null
                && competitionParticipant.getAssessmentPeriod().isInAssessment();
        } else {
            return competitionParticipant.isInAssessment();
        }
    }

    private Long getAssessmentsSubmittedForCompetitionCount(List<Assessment> assessments,
                                                            CompetitionParticipantResource competitionParticipant,
                                                            boolean filterByAssessmentPeriod) {
        Stream<Assessment> assessmentStream =  assessments.stream()
                .filter(assessment -> assessment.getProcessState().equals(SUBMITTED));

        if (filterByAssessmentPeriod) {
            assessmentStream = filterByAssessmentPeriod(assessmentStream, competitionParticipant.getAssessmentPeriod());
        }

        return assessmentStream.count();
    }

    private Stream<Assessment> filterByAssessmentPeriod(Stream<Assessment> assessmentStream, AssessmentPeriodResource assessmentPeriod) {
        return assessmentStream
                .filter(assessment -> Objects.equals(assessment.getTarget().getAssessmentPeriod().getId(), assessmentPeriod.getId()));
    }

    private Long getTotalAssessmentsAcceptedForCompetitionCount(List<Assessment> assessments,
                                                                CompetitionParticipantResource competitionParticipant,
                                                                boolean filterByAssessmentPeriod) {
        Set<AssessmentState> allowedAssessmentStates = EnumSet.of(ACCEPTED, OPEN, READY_TO_SUBMIT, SUBMITTED);
        Stream<Assessment> assessmentStream = assessments.stream()
                .filter(assessment -> allowedAssessmentStates.contains(assessment.getProcessState()));

        if (filterByAssessmentPeriod) {
            assessmentStream = filterByAssessmentPeriod(assessmentStream, competitionParticipant.getAssessmentPeriod());
        }

        return assessmentStream.count();
    }

    private Long getAssessmentsPendingForCompetitionCount(List<Assessment> assessments,
                                                          CompetitionParticipantResource competitionParticipant,
                                                          boolean filterByAssessmentPeriod) {
        Stream<Assessment> assessmentStream = assessments.stream()
                .filter(assessment -> assessment.getProcessState().equals(PENDING));

        if (filterByAssessmentPeriod) {
            assessmentStream = filterByAssessmentPeriod(assessmentStream, competitionParticipant.getAssessmentPeriod());
        }

        return assessmentStream.count();
    }
}


text:
<?php

namespace comyii\user\events\account;

use comyii\user\events\AccountEvent;

/**
 * Class AuthEvent is used for triggering all user authorization events
 *
 * @package comyii\user\events\account
 */
class AuthEvent extends AccountEvent
{
    const RESULT_LOGGED_IN = 1;
    const RESULT_DUPLICATE_EMAIL = 2;
    const RESULT_SIGNUP_ERROR = 3;
    const RESULT_SIGNUP_SUCCESS = 4;
    const RESULT_AUTH_ERROR = 5;

    /**
     * @var \yii\authclient\BaseClient the client
     */
    public $client;

    /**
     * @var string the user class
     */
    public $userClass;

    /**
     * @var string the social class
     */
    public $socialClass;

    /**
     * @var bool the result of the authorization attempt. Should be one of the `AuthEvent::RESULT` constants.
     */
    public $result;
}


text:
module Hello
  class DeactivateEntity < AbstractEntity

    def info_message
      t("info")
    end

  end
end