text:
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Maintenance
 */

require_once __DIR__ . '/Maintenance.php';

/**
 * Maintenance script that deletes all pages in the MediaWiki namespace
 * of which the content is equal to the system default.
 *
 * @ingroup Maintenance
 */
class DeleteEqualMessages extends Maintenance {
	public function __construct() {
		parent::__construct();
		$this->mDescription = 'Deletes all pages in the MediaWiki namespace that are equal to '
			. 'the default message';
		$this->addOption( 'delete', 'Actually delete the pages (default: dry run)' );
		$this->addOption( 'delete-talk', 'Don\'t leave orphaned talk pages behind during deletion' );
		$this->addOption( 'lang-code', 'Check for subpages of this language code (default: root '
			. 'page against content language). Use value "*" to run for all mwfile language code '
			. 'subpages (including the base pages that override content language).', false, true );
	}

	/**
	 * @param string|bool $langCode See --lang-code option.
	 * @param array &$messageInfo
	 */
	protected function fetchMessageInfo( $langCode, array &$messageInfo ) {
		global $wgContLang;

		if ( $langCode ) {
			$this->output( "\n... fetching message info for language: $langCode" );
			$nonContLang = true;
		} else {
			$this->output( "\n... fetching message info for content language" );
			$langCode = $wgContLang->getCode();
			$nonContLang = false;
		}

		/* Based on SpecialAllmessages::reallyDoQuery #filter=modified */

		$l10nCache = Language::getLocalisationCache();
		$messageNames = $l10nCache->getSubitemList( 'en', 'messages' );
		// Normalise message names for NS_MEDIAWIKI page_title
		$messageNames = array_map( array( $wgContLang, 'ucfirst' ), $messageNames );

		$statuses = AllMessagesTablePager::getCustomisedStatuses(
			$messageNames, $langCode, $nonContLang );
		// getCustomisedStatuses is stripping the sub page from the page titles, add it back
		$titleSuffix = $nonContLang ? "/$langCode" : '';

		foreach ( $messageNames as $key ) {
			$customised = isset( $statuses['pages'][$key] );
			if ( $customised ) {
				$actual = wfMessage( $key )->inLanguage( $langCode )->plain();
				$default = wfMessage( $key )->inLanguage( $langCode )->useDatabase( false )->plain();

				$messageInfo['relevantPages']++;

				if (
					// Exclude messages that are empty by default, such as sitenotice, specialpage
					// summaries and accesskeys.
					$default !== '' && $default !== '-' &&
						$actual === $default
				) {
					$hasTalk = isset( $statuses['talks'][$key] );
					$messageInfo['results'][] = array(
						'title' => $key . $titleSuffix,
						'hasTalk' => $hasTalk,
					);
					$messageInfo['equalPages']++;
					if ( $hasTalk ) {
						$messageInfo['equalPagesTalks']++;
					}
				}
			}
		}
	}

	public function execute() {
		$doDelete = $this->hasOption( 'delete' );
		$doDeleteTalk = $this->hasOption( 'delete-talk' );
		$langCode = $this->getOption( 'lang-code' );

		$messageInfo = array(
			'relevantPages' => 0,
			'equalPages' => 0,
			'equalPagesTalks' => 0,
			'results' => array(),
		);

		$this->output( 'Checking for pages with default message...' );

		// Load message information
		if ( $langCode ) {
			$langCodes = Language::fetchLanguageNames( null, 'mwfile' );
			if ( $langCode === '*' ) {
				// All valid lang-code subpages in NS_MEDIAWIKI that
				// override the messsages in that language
				foreach ( $langCodes as $key => $value ) {
					$this->fetchMessageInfo( $key, $messageInfo );
				}
				// Lastly, the base pages in NS_MEDIAWIKI that override
				// messages in content language
				$this->fetchMessageInfo( false, $messageInfo );
			} else {
				if ( !isset( $langCodes[$langCode] ) ) {
					$this->error( 'Invalid language code: ' . $langCode, 1 );
				}
				$this->fetchMessageInfo( $langCode, $messageInfo );
			}
		} else {
			$this->fetchMessageInfo( false, $messageInfo );
		}

		if ( $messageInfo['equalPages'] === 0 ) {
			// No more equal messages left
			$this->output( "\ndone.\n" );

			return;
		}

		$this->output( "\n{$messageInfo['relevantPages']} pages in the MediaWiki namespace "
			. "override messages." );
		$this->output( "\n{$messageInfo['equalPages']} pages are equal to the default message "
			. "(+ {$messageInfo['equalPagesTalks']} talk pages).\n" );

		if ( !$doDelete ) {
			$list = '';
			foreach ( $messageInfo['results'] as $result ) {
				$title = Title::makeTitle( NS_MEDIAWIKI, $result['title'] );
				$list .= "* [[$title]]\n";
				if ( $result['hasTalk'] ) {
					$title = Title::makeTitle( NS_MEDIAWIKI_TALK, $result['title'] );
					$list .= "* [[$title]]\n";
				}
			}
			$this->output( "\nList:\n$list\nRun the script again with --delete to delete these pages" );
			if ( $messageInfo['equalPagesTalks'] !== 0 ) {
				$this->output( " (include --delete-talk to also delete the talk pages)" );
			}
			$this->output( "\n" );

			return;
		}

		$user = User::newFromName( 'MediaWiki default' );
		if ( !$user ) {
			$this->error( "Invalid username", true );
		}
		global $wgUser;
		$wgUser = $user;

		// Hide deletions from RecentChanges
		$user->addGroup( 'bot' );

		// Handle deletion
		$this->output( "\n...deleting equal messages (this may take a long time!)..." );
		$dbw = wfGetDB( DB_MASTER );
		foreach ( $messageInfo['results'] as $result ) {
			wfWaitForSlaves();
			$dbw->ping();
			$title = Title::makeTitle( NS_MEDIAWIKI, $result['title'] );
			$this->output( "\n* [[$title]]" );
			$page = WikiPage::factory( $title );
			$error = ''; // Passed by ref
			$success = $page->doDeleteArticle( 'No longer required', false, 0, true, $error, $user );
			if ( !$success ) {
				$this->output( " (Failed!)" );
			}
			if ( $result['hasTalk'] && $doDeleteTalk ) {
				$title = Title::makeTitle( NS_MEDIAWIKI_TALK, $result['title'] );
				$this->output( "\n* [[$title]]" );
				$page = WikiPage::factory( $title );
				$error = ''; // Passed by ref
				$success = $page->doDeleteArticle( 'Orphaned talk page of no longer required message',
					false, 0, true, $error, $user );
				if ( !$success ) {
					$this->output( " (Failed!)" );
				}
			}
		}
		$this->output( "\n\ndone!\n" );
	}
}

$maintClass = "DeleteEqualMessages";
require_once RUN_MAINTENANCE_IF_MAIN;


text:
package com.renomad.capsaicin;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import java.io.IOException;
import java.util.List;
import java.util.Date;
import java.io.File;
import java.text.SimpleDateFormat;
import com.renomad.capsaicin.CameraPreview;

public class RecordVideoActivity extends Activity {

    public static final int MEDIA_TYPE_VIDEO = 2;
    private CameraPreview mPreview;
    private Camera mCamera;
    private MediaRecorder mMediaRecorder;
    private int numberOfCameras;
    private int cameraCurrentlyLocked;

    private String mMediaFilename;
    private boolean isRecording = false;

    private static final String TAG = "RecordVideoActivity";
    private Button captureButton;
    private Button sendButton;

    // The first rear facing camera
    int defaultCameraId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Hide the window title.
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mPreview = new CameraPreview(this);
        setContentView(R.layout.activity_record_video);
        ((FrameLayout)findViewById(R.id.previewplaceholder)).addView(mPreview);

        // wire up the buttons
        captureButton = (Button) findViewById(R.id.button_capture);
        sendButton = (Button) findViewById(R.id.button_send);

        // Find the total number of cameras available
        numberOfCameras = Camera.getNumberOfCameras();

        // Find the ID of the default camera
        CameraInfo cameraInfo = new CameraInfo();
            for (int i = 0; i < numberOfCameras; i++) {
                Camera.getCameraInfo(i, cameraInfo);
                if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                    defaultCameraId = i;
                }
            }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Open the default i.e. the first rear facing camera.
        mCamera = Camera.open();
        cameraCurrentlyLocked = defaultCameraId;
        CameraPreview.setCameraDisplayOrientation(this, defaultCameraId, mCamera);
        mPreview.setCamera(mCamera);
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();
        // Because the Camera object is a shared resource, it's very
        // important to release it when the activity is paused.
        releaseCamera();
    }

    private void releaseCamera(){
        if (mCamera != null){
            // release the camera for other applications
            mPreview.setCamera(null);
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate our menu which can gather user input for switching camera
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.camera_menu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.switch_cam:
            // check for availability of multiple cameras
            if (numberOfCameras == 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(this.getString(R.string.camera_alert))
                       .setNeutralButton("Close", null);
                AlertDialog alert = builder.create();
                alert.show();
                return true;
            }

            // OK, we have multiple cameras.
            // Release this camera -> cameraCurrentlyLocked
            if (mCamera != null) {
                mCamera.stopPreview();
                mPreview.setCamera(null);
                mCamera.release();
                mCamera = null;
            }

            // Acquire the next camera and request Preview to reconfigure
            // parameters.
            mCamera = Camera
                    .open((cameraCurrentlyLocked + 1) % numberOfCameras);
            cameraCurrentlyLocked = (cameraCurrentlyLocked + 1)
                    % numberOfCameras;
            mPreview.switchCamera(mCamera);

            // Start the preview
            mCamera.startPreview();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    //The following section is from the old file
    //OLD SECTION BEGINS
    //OLD SECTION BEGINS
    //OLD SECTION BEGINS

    public void onSendClick(View view) {
        Log.i(TAG, "setting result to OK");
        Intent intent = new Intent();
        intent.putExtra("com.renomad.capsaicin.fileuri", mMediaFilename);
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * The capture button controls all user interaction. When recording, the button click
     * stops recording, releases {@link android.media.MediaRecorder}
     * and {@link android.hardware.Camera}. When not recording,
     * it prepares the {@link android.media.MediaRecorder} and starts recording.
     *
     * @param view the view generating the event.
     */
    public void onCaptureClick(View view) {
        if (isRecording) {
            // stop recording and release camera
            mMediaRecorder.stop();  // stop the recording
            releaseMediaRecorder(); // release the MediaRecorder object
            mCamera.lock();         // take camera access back from MediaRecorder
            // inform the user that recording has stopped
            setCaptureButtonText("Capture");
            isRecording = false;
            releaseCamera();
        } else {
            new MediaPrepareTask().execute(null, null, null);
        }
    }

    private void setCaptureButtonText(String title) {
        captureButton.setText(title);
    }

    private void releaseMediaRecorder(){
        if (mMediaRecorder != null) {
            // clear recorder configuration
            mMediaRecorder.reset();
            // release the recorder object
            mMediaRecorder.release();
            mMediaRecorder = null;
            // Lock camera for later use i.e taking it back from MediaRecorder.
            // MediaRecorder doesn't need it anymore and we will release it if the activity pauses.
            mCamera.lock();
        }
    }

    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                                                        Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4");

        return mediaFile;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private boolean prepareVideoRecorder(){

        // BEGIN_INCLUDE (configure_media_recorder)
        mMediaRecorder = new MediaRecorder();

        // Step 1: Unlock and set camera to MediaRecorder
        Log.i(TAG, "unlocking and setting camera to MediaRecorder");
        mCamera.stopPreview();
        mCamera.unlock();
        Log.i(TAG, String.format("assigning mCamera %s to mMediaRecorder %s",
                                 mCamera.toString(), mMediaRecorder.toString()));
        mMediaRecorder.setCamera(mCamera);

        // Step 2: Set sources
        Log.i(TAG, "setting sources...");
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER );
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        // Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
        Log.i(TAG, "setting a CamcorderProfile");
        mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_CIF));

        // Step 4: Set output file
        Log.i(TAG, "setting an output file...");
        //mMediaFilename = CameraHelper.getOutputMediaFile(getExternalFilesDir("videos")).toString();
        mMediaFilename = getOutputMediaFile(MEDIA_TYPE_VIDEO).toString();
        mMediaRecorder.setOutputFile(mMediaFilename);

        Log.i(TAG, String.format("output file is %s", mMediaFilename));

        // Step 4.5: set preview display for camcorder:
        Log.i(TAG, "setting preview display for camcorder");
        mMediaRecorder.setPreviewDisplay(mPreview.getSurface());

        // Step 5: Prepare configured MediaRecorder
        try {
            mMediaRecorder.prepare();
        } catch (IllegalStateException e) {
            Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
            releaseMediaRecorder();
            return false;
        }
        return true;
    }

    /**
     * Asynchronous task for preparing the {@link android.media.MediaRecorder}
     * since it's a long blocking
     * operation.
     */
    class MediaPrepareTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... voids) {
            // initialize video camera
            if (prepareVideoRecorder()) {
                Log.i("MediaPrepareTask",
                      "camera is available and unlocked, MediaRecorder is prepared");
                // Camera is available and unlocked, MediaRecorder is prepared,
                // now you can start recording
                mMediaRecorder.start();

                isRecording = true;
            } else {
                Log.i("MediaPrepareTask", "prepare didn't work, release the camera");
                // prepare didn't work, release the camera
                releaseMediaRecorder();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                RecordVideoActivity.this.finish();
            }
            // inform the user that recording has started
            setCaptureButtonText("Stop");

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.emm.agent.services;

import org.wso2.emm.agent.AndroidAgentException;
import org.wso2.emm.agent.api.DeviceInfo;
import org.wso2.emm.agent.api.GPSTracker;
import org.wso2.emm.agent.beans.Device;
import org.wso2.emm.agent.factory.DeviceStateFactory;
import org.wso2.emm.agent.interfaces.DeviceState;
import org.wso2.emm.agent.utils.Constants;
import org.wso2.emm.agent.utils.Preference;

import android.content.Context;
import android.util.Log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

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

/**
 * This class handles building of the device information payload to be sent to the server.
 */
public class BuildDeviceInfoPayload {
	private DeviceInfo deviceInfo;
	private Device device;
	private Context context;
	private static final String TAG = BuildDeviceInfoPayload.class.getName();
	ObjectMapper mapper;

	public BuildDeviceInfoPayload(Context context) {
		deviceInfo = new DeviceInfo(context.getApplicationContext());
		this.context = context;
		mapper = new ObjectMapper();
	}

	/**
	 * Builds device information payload.
	 *
	 * @param type - Device ownership type.
	 * @param owner - Current user name.
	 */
	public void build(String type, String owner) {
		device = new Device();
		Device.EnrolmentInfo info = new Device.EnrolmentInfo();
		//setting up basic details of the device
		info.setOwner(owner);
		device.setDeviceIdentifier(deviceInfo.getMACAddress());
		device.setDescription(deviceInfo.getDeviceName());
		device.setName(deviceInfo.getDeviceName());
		info.setOwnership(type.equals(Constants.OWNERSHIP_BYOD)?Device.EnrolmentInfo.OwnerShip.BYOD
				: Device.EnrolmentInfo.OwnerShip.COPE);
		device.setEnrolmentInfo(info);
		//adding extra properties
		List<Device.Property> properties = new ArrayList<>();
		Device.Property property = new Device.Property();
		property.setName(Constants.Device.IMEI);
		property.setValue(deviceInfo.getDeviceId());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.IMSI);
		property.setValue(deviceInfo.getIMSINumber());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.MODEL);
		property.setValue(deviceInfo.getDeviceModel());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.VENDOR);
		property.setValue(deviceInfo.getDeviceManufacturer());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.OS);
		property.setValue(deviceInfo.getOsVersion());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.NAME);
		property.setValue(deviceInfo.getDeviceName());
		properties.add(property);

		device.setProperties(properties);
	}

	/**
	 * This method builds the payload including device current state.
	 *
	 * @throws AndroidAgentException
	 */
	public void build() throws AndroidAgentException {
		DeviceState phoneState = DeviceStateFactory.getDeviceState(context.getApplicationContext(),
				deviceInfo.getSdkVersion());
		GPSTracker gps = new GPSTracker(context.getApplicationContext());
        String registrationId = Preference.getString(context.getApplicationContext(), Constants.REG_ID);

		device = new Device();

		device.setDeviceIdentifier(deviceInfo.getMACAddress());
		device.setDescription(deviceInfo.getDeviceName());
		device.setName(deviceInfo.getDeviceName());

		List<Device.Property> properties = new ArrayList<>();
		Device.Property property = new Device.Property();
		property.setName(Constants.Device.IMEI);
		property.setValue(deviceInfo.getDeviceId());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.IMSI);
		property.setValue(deviceInfo.getIMSINumber());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.MODEL);
		property.setValue(deviceInfo.getDeviceModel());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.VENDOR);
		property.setValue(deviceInfo.getDeviceManufacturer());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.OS);
		property.setValue(deviceInfo.getOsVersion());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.NAME);
		property.setValue(deviceInfo.getDeviceName());
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.BATTERY_LEVEL);
		int batteryLevel = Math.round(phoneState.getBatteryLevel());
		property.setValue(String.valueOf(batteryLevel));
		properties.add(property);

		double latitude = gps.getLatitude();
		double longitude = gps.getLongitude();

		if (latitude != 0 && longitude !=0) {
			property = new Device.Property();
			property.setName(Constants.Device.MOBILE_DEVICE_LATITUDE);
			property.setValue(String.valueOf(latitude));
			properties.add(property);

			property = new Device.Property();
			property.setName(Constants.Device.MOBILE_DEVICE_LONGITUDE);
			property.setValue(String.valueOf(longitude));
			properties.add(property);
		}

		property = new Device.Property();
		property.setName(Constants.Device.MEMORY_INFO_INTERNAL_TOTAL);
		property.setValue(String.valueOf(phoneState.getTotalInternalMemorySize()));
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.MEMORY_INFO_INTERNAL_AVAILABLE);
		property.setValue(String.valueOf(phoneState.getAvailableInternalMemorySize()));
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.MEMORY_INFO_EXTERNAL_TOTAL);
		property.setValue(String.valueOf(phoneState.getTotalExternalMemorySize()));
		properties.add(property);

		property = new Device.Property();
		property.setName(Constants.Device.MEMORY_INFO_EXTERNAL_AVAILABLE);
		property.setValue(String.valueOf(phoneState.getAvailableExternalMemorySize()));
		properties.add(property);

		if (registrationId != null) {
			property = new Device.Property();
			property.setName(Constants.Device.GCM_TOKEN);
			property.setValue(registrationId);
			properties.add(property);
		}

		property = new Device.Property();
		property.setName(Constants.Device.NETWORK_OPERATOR);
		property.setValue(String.valueOf(deviceInfo.getNetworkOperatorName()));
		properties.add(property);

		// building device info json payload
		String deviceInfoPayload;
		try {
			deviceInfoPayload = mapper.writeValueAsString(properties);
		} catch (JsonProcessingException e) {
			String errorMsg = "Error occurred while parsing property object to json.";
			Log.e(TAG, errorMsg);
			throw new AndroidAgentException(errorMsg, e);
		}
		property = new Device.Property();
		property.setName(Constants.Device.INFO);
		property.setValue(deviceInfoPayload);
		properties.add(property);

		device.setProperties(properties);

	}

	/**
	 * Returns the final payload.
	 *
	 * @return - Device info payload as a string.
	 */
	public String getDeviceInfoPayload() {
		try {
			return device.toJSON();
		} catch (AndroidAgentException e) {
			Log.e(TAG, "Error occurred while building device info payload. " + e.getMessage());
		}
		return null;
	}
}


text:
require 'httparty'
require 'active_support/core_ext/object/blank'

require File.expand_path('../errors', __FILE__)
require File.expand_path('../operations', __FILE__)

module JokerAPI
  class Client
    include HTTParty

    DEFAULT_RESULT_POLL_INTERVAL = 0.5
    @@result_poll_interval = nil

    # @param [Float,nil] interval
    def self.set_result_poll_interval(interval)
      @@result_poll_interval = interval
    end

    @@user_agent = nil
    def self.user_agent
      @@user_agent ||= begin
        engine  = defined?(RUBY_ENGINE)  ? RUBY_ENGINE.capitalize : "Ruby"
        "JokerAPI::Client/#{JokerAPI::VERSION} (#{engine} #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}/#{RUBY_PLATFORM})"
      end
    end

    attr_reader :balance, :tlds

    def initialize(username, password, host = 'dmapi.joker.com', options = {})
      @username, @password = username, password
      @default_options = options.merge(:base_uri => HTTParty.normalize_base_uri("https://#{host}"))

      @default_options[:headers] ||= {}
      @default_options[:headers]['User-Agent'] = self.class.user_agent

      @auth_sid = nil
      @balance = 0.00
      @tlds = []
    end

    def inspect
      "#<#{self.class.name} #{@default_options[:base_uri]} (#{@username})#{@auth_sid && " logged in"}>"
    end

    # @param [Float,nil] interval
    def set_result_poll_interval(interval)
      @result_poll_interval = interval
    end

    def with_result_poll_interval(interval)
      rpi = @result_poll_interval
      begin
        @result_poll_interval = interval
        return yield self
      ensure
        @result_poll_interval = rpi
      end
    end

    def login
      response = perform_request('login', {:username => @username, :password => @password})

      @auth_sid = response.auth_sid
      @balance = response.account_balance
      @tlds = response.body.split("\n").sort

      self
    end

    # Returns the last HTTP request sent
    # @return [String]
    def last_http_request
      req = last_response.request
      out = "#{req.http_method::METHOD} #{req.uri.request_uri}\n"
      out += "Host: #{req.uri.host}\nConnection: close\n"
      req.options[:headers].each do |header, value|
        out += header.capitalize.gsub(/\-([a-z])/) { |m| "-#{m[1].chr.upcase}" }
        out += ": #{value}\n"
      end

      out # we only do GET requests so no need to append body, add if needed
    end
    # Returns the last HTTP response sent
    # @return [String]
    def last_http_response
      resp = last_response.response
      out = "HTTP/#{resp.http_version} #{resp.code} #{resp.message}\n"
      resp.each_header do |header, value|
        out += header.capitalize.gsub(/\-([a-z])/) { |m| "-#{m[1].chr.upcase}" }
        out += ": #{value}\n"
      end

      out += "\n#{resp.body}"
    end

    # Returns the last response received.
    # @return [Response]
    def last_response
      @response
    end

    # Returns the last error received from a response
    # @return [Response::Error]
    def last_error
      @last_error
    end

    # Returns the number of seconds the last request/response took
    # @return [Float]
    def response_time
      @response_time
    end

    include Operations::QueryContactList
    include Operations::ContactCreate
    include Operations::ContactDelete
    include Operations::ContactModify

    include Operations::QueryDomainList
    include Operations::DomainDelete
    include Operations::DomainModify
    include Operations::DomainOwnerChange
    include Operations::DomainRegister
    include Operations::DomainRenew
    include Operations::DomainTransferIn
    include Operations::DomainTransferGetAuthId

    include Operations::DomainLock
    include Operations::DomainUnlock

    include Operations::DomainGetProperty
    include Operations::DomainSetProperty

    include Operations::QueryNsList
    include Operations::NsCreate
    include Operations::NsDelete
    include Operations::NsModify

    include Operations::QueryWhois

    include Operations::ResultRetrieve

    include Operations::WhoisAccreditation

    # @param [String] domain Domain name
    # @param [Boolean] value Enable/disable autorenew
    # @see Operations::DomainSetProperty#domain_set_property
    def domain_autorenew(domain, value = nil)
      return domain_get_property(domain, 'autorenew') == "1" if value.nil?
      domain_set_property(domain, 'autorenew', value ? "1" : "0")
    end

    # @param [String] domain Domain name
    # @param [Boolean] value Enable/disable WHOIS opt out
    # @see Operations::DomainSetProperty#domain_set_property
    def domain_whois_optout(domain, value = nil)
      return domain_get_property(domain, 'whois-opt-out') == "1" if value.nil?
      domain_set_property(domain, 'whois-opt-out', value ? "1" : "0")
    end

    protected
      def default_options
        @default_options
      end
      def perform_request(path, query = {})
        path = "/request/#{path}"
        options = default_options.dup

        query = query.reject { |_,v| v.blank? }

        begin
          query = query.merge('auth-sid' => @auth_sid) if @auth_sid
          options = options.merge(:query => query) unless query.empty?

          response_data = stopwatch do
            self.class.get(path, options)
          end

          @response = Response.new(response_data)
          store_response_information(@response)

          @response
        rescue AuthorisationError
          login
          retry
        end
      end
      def store_response_information(response)
        @last_error = response.error if response.error?
        @balance = response.account_balance || @balance
      end

      def stopwatch
        start = Time.now.utc.to_f
        result = yield
        @response_time = Time.now.utc.to_f - start
        return result
      end

      def result_poll_interval
        (@result_poll_interval || @@result_poll_interval || DEFAULT_RESULT_POLL_INTERVAL).to_f
      end

      # @param [Response] response
      # @yield [result] Gives the 'result-retrieve' headers to the block
      # @yieldparam result [Hash] The 'result-retrieve' headers as a hash
      # @return [Object,Boolean] False on errors, whatever the block results on success
      def wait_for_result(response)
        tries = 0
        begin
          sleep result_poll_interval
          result = result_retrieve(response)
          tries += 1

          case result["Completion-Status"]
          when "ack"  # Request Processed
            return yield result
          when "?"    # Request still pending
            raise IncompleteRequest.new(response)
          else        # dunno really
            return false
          end
        rescue IncompleteRequest
          retry unless tries > 4
          raise
        end
      end
  end
end


text:
<?php

namespace Lunr\Vortex\APNS\ApnsPHP;

use \ApnsPHP_Message;
use \ApnsPHP_Message_Exception;
use \ApnsPHP_Exception;
use Lunr\Vortex\APNS\APNSPayload;
use Lunr\Vortex\PushNotificationMultiDispatcherInterface;

/**
 * Apple Push Notification Service Push Notification Dispatcher.
 */
class APNSDispatcher implements PushNotificationMultiDispatcherInterface
{

    /**
     * Shared instance of ApnsPHP\Push.
     * @var \ApnsPHP\Push
     */
    protected $apns_push;

    /**
     * Apns Message instance
     * @var \ApnsPHP\Message
     */
    protected $apns_message;

    /**
     * Shared instance of a Logger class.
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * Constructor.
     *
     * @param LoggerInterface $logger    Shared instance of a Logger.
     * @param ApnsPHP\Push    $apns_push Apns Push instance.
     */
    public function __construct($logger, $apns_push)
    {
        $this->logger    = $logger;
        $this->apns_push = $apns_push;

        $this->reset();
    }

    /**
     * Destructor.
     */
    public function __destruct()
    {
        unset($this->apns_push);
        unset($this->apns_message);
        unset($this->logger);
    }

    /**
     * Reset the variable members of the class.
     *
     * @return void
     */
    protected function reset()
    {
        unset($this->apns_message);
    }

    /**
     * Return a new APNS message.
     *
     * @codeCoverageIgnore
     *
     * @return ApnsPHP_Message
     */
    protected function get_new_apns_message()
    {
        return new ApnsPHP_Message();
    }

    /**
     * Push the notification.
     *
     * @param APNSPayload $payload   Payload object
     * @param array       $endpoints Endpoints to send to in this batch
     *
     * @return APNSResponse $return Response object
     */
    public function push($payload, &$endpoints)
    {
        // Create message
        $tmp_payload = json_decode($payload->get_payload(), TRUE);

        $this->apns_message = $this->get_new_apns_message();

        try
        {
            if (!empty($tmp_payload['alert']))
            {
                $this->apns_message->setText($tmp_payload['alert']);
            }

            if (!empty($tmp_payload['sound']))
            {
                $this->apns_message->setSound($tmp_payload['sound']);
            }

            if (!empty($tmp_payload['badge']))
            {
                $this->apns_message->setBadge($tmp_payload['badge']);
            }

            if (!empty($tmp_payload['custom_data']))
            {
                foreach ($tmp_payload['custom_data'] as $key => $value)
                {
                    $this->apns_message->setCustomProperty($key, $value);
                }
            }
        }
        catch (ApnsPHP_Message_Exception $e)
        {
            $this->logger->warning($e->getMessage());
        }

        // Add endpoints
        $invalid_endpoints = [];

        foreach ($endpoints as $endpoint)
        {
            try
            {
                $this->apns_message->addRecipient($endpoint);
            }
            catch (ApnsPHP_Message_Exception $e)
            {
                $invalid_endpoints[] = $endpoint;

                $this->logger->warning($e->getMessage());
            }
        }

        // Send message
        try
        {
            $this->apns_push->add($this->apns_message);
            $this->apns_push->connect();
            $this->apns_push->send();
            $this->apns_push->disconnect();

            $errors = $this->apns_push->getErrors();
        }
        catch (ApnsPHP_Exception $e)
        {
            $errors = NULL;

            $context = [ 'error' => $e->getMessage() ];
            $this->logger->warning('Dispatching push notification failed: {error}', $context);
        }

        // Return response
        $response = new APNSResponse($this->logger, $endpoints, $invalid_endpoints, $errors);

        $this->reset();

        return $response;
    }

}

?>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="users" extends="struts-default" namespace="/users">
		<!-- global redirect -->
		<global-results>
			<result name="error" type="redirect">/error.jsp</result>
		</global-results>
		<!-- 注册 -->
		<action name="register" class="userAction" method="registerUserAction">
			<result name="success">/users/info.jsp</result>
			<result name="illegalEmail">/register.jsp</result>
		</action>
		<!-- 认证邮箱 -->
		<action name="emailAuthentication" class="userAction" method="emailAuthentication">
			<result name="reEmailAuth">/users/info.jsp</result>
			<result name="success">/users/info.jsp</result>
			<result name="userNotFound">/users/info.jsp</result>
		</action>
		<!-- 找回密码 -->
		<action name="findPassword" class="userAction" method="findPassword">
			<result name="success">/users/info.jsp</result>
		</action>

		<!-- 用户列表 -->
		<action name="userList" class="userAction" method="userList">
			<result name="success">/user_manager/list_user.jsp</result>
		</action>

		<!-- 跳转添加用户 -->
		<action name="addUser" class="userAction" method="addUser">
			<result name="success">/user_manager/add_user.jsp</result>
		</action>

		<!-- 添加用户 -->
		<action name="addUserAction" class="userAction" method="addUserAction">
			<result name="success" type="redirectAction">
				<param name="actionName">userList</param>
				<param name="namespace">/users</param>
			</result>
		</action>

		<!-- 更新用户 -->
		<action name="updateUser" class="userAction" method="updateUser">
			<result name="success">/user_manager/update_user.jsp</result>
		</action>

		<!-- 删除用户 -->
		<action name="deleteUser" class="userAction" method="deleteUser">
			<result name="success">/user_manager/list_user.jsp</result>
		</action>

		<!-- 管理员信息 -->
		<action name="adminInfo" class="userAction" method="adminInfo">
			<result name="success">/person_center/user_infor.jsp</result>
		</action>

		<!-- 修改管理员密码 -->
		<action name="changeAdminPasswd" class="userAction" method="changeAdminPasswd">
			<result name="success">/person_center/change_passwd.jsp</result>
		</action>
	</package>
</struts>


text:
<form class="search-form" (submit)="crawlSEData(tag.value)">
  <md-form-field class="search-full-width">
    <input mdInput placeholder="Search Tag" #tag>
  </md-form-field>
  <md-select placeholder="Select a Stack Exchange Site" #site>
    <md-option *ngFor="let site of stackSites" [value]="site.value">
      {{ site.viewValue }}
    </md-option>
  </md-select>

  <button md-raised-button (click)="crawlSEData(tag.value,site.value)">Submit</button>

</form>

<md-card *ngFor="let data of (stackData ? stackData : []); let i = index">
  <md-card-header>

    <md-card-title>{{ data.user.display_name }}</md-card-title>
    <md-card-subtitle>
      {{ data.user.link }}
    </md-card-subtitle>
  </md-card-header>
  <md-card-content>
    <md-chip-list>
      <md-chip color="primary" selected="true">Reputation : {{ data.user.reputation }}</md-chip>
      <md-chip>Accept Rate : {{ data.user.accept_rate }}% </md-chip>
      <md-chip color="accent" selected="true">User Type : {{ data.user.user_type }}</md-chip>
      <md-chip>User Id : {{ data.user.user_id }}</md-chip>
    </md-chip-list>
  </md-card-content>
  <md-card-actions>
  </md-card-actions>
</md-card>


text:
function solve(input) {
    let matrix = input.map(r => r.split(' ').map(Number))
    let [mainDiagonalSum, secondaryDiagonalSum] = getBothDiagonalsSum(matrix)
    if(mainDiagonalSum === secondaryDiagonalSum) {
        for(let row = 0; row < matrix.length; row++) {
            for(let col = 0; col < matrix[row].length; col++) {
                let temp = matrix[row][col]
                if (row !== col && col !== matrix[row].length - 1 - row) {
                    matrix[row][col] = mainDiagonalSum
                }

            }
        }
    }

    for(let row = 0; row < matrix.length; row++) {
        console.log(matrix[row].join(' '))
    }

    function getBothDiagonalsSum(matrix) {
        let mainDiagonalSum = 0
        let secondaryDiagonalSum = 0
        for(let row = 0; row < matrix.length; row++) {
            mainDiagonalSum += matrix[row][row]
            secondaryDiagonalSum += matrix[row][matrix[row].length - 1 - row]
        }

        return [mainDiagonalSum, secondaryDiagonalSum]
    }
}


text:
import { graphql } from "relay-runtime"
import { setupTestWrapper } from "v2/DevTools/setupTestWrapper"
import { HomeFeaturedShowsFragmentContainer } from "../Components/HomeFeaturedShows"
import { HomeFeaturedShows_Test_Query } from "v2/__generated__/HomeFeaturedShows_Test_Query.graphql"

jest.unmock("react-relay")

const { getWrapper } = setupTestWrapper<HomeFeaturedShows_Test_Query>({
  Component: HomeFeaturedShowsFragmentContainer,
  query: graphql`
    query HomeFeaturedShows_Test_Query {
      orderedSet(id: "example") {
        ...HomeFeaturedShows_orderedSet
      }
    }
  `,
})

describe("HomeFeaturedShows", () => {
  it("renders correctly", () => {
    const wrapper = getWrapper({
      Show: () => ({
        name: "Example Show",
        startAt: "Jun 9",
        endAt: "25",
        href: "/show/partner-show",
      }),
      Partner: () => ({
        name: "Example Partner",
      }),
    })

    expect(wrapper.text()).toContain("Featured shows")
    expect(wrapper.text()).toContain("Explore all shows")
    expect(wrapper.text()).toContain("Example Show")
    expect(wrapper.text()).toContain("Example Partner")
    expect(wrapper.text()).toContain("Jun 9–25")
    expect(wrapper.html()).toContain("/show/partner-show")
  })
})


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.DataBoxEdge.Models
{
    /// <summary> Current status of the container. </summary>
    public readonly partial struct DataBoxEdgeStorageContainerStatus : IEquatable<DataBoxEdgeStorageContainerStatus>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="DataBoxEdgeStorageContainerStatus"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public DataBoxEdgeStorageContainerStatus(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string OKValue = "OK";
        private const string OfflineValue = "Offline";
        private const string UnknownValue = "Unknown";
        private const string UpdatingValue = "Updating";
        private const string NeedsAttentionValue = "NeedsAttention";

        /// <summary> OK. </summary>
        public static DataBoxEdgeStorageContainerStatus OK { get; } = new DataBoxEdgeStorageContainerStatus(OKValue);
        /// <summary> Offline. </summary>
        public static DataBoxEdgeStorageContainerStatus Offline { get; } = new DataBoxEdgeStorageContainerStatus(OfflineValue);
        /// <summary> Unknown. </summary>
        public static DataBoxEdgeStorageContainerStatus Unknown { get; } = new DataBoxEdgeStorageContainerStatus(UnknownValue);
        /// <summary> Updating. </summary>
        public static DataBoxEdgeStorageContainerStatus Updating { get; } = new DataBoxEdgeStorageContainerStatus(UpdatingValue);
        /// <summary> NeedsAttention. </summary>
        public static DataBoxEdgeStorageContainerStatus NeedsAttention { get; } = new DataBoxEdgeStorageContainerStatus(NeedsAttentionValue);
        /// <summary> Determines if two <see cref="DataBoxEdgeStorageContainerStatus"/> values are the same. </summary>
        public static bool operator ==(DataBoxEdgeStorageContainerStatus left, DataBoxEdgeStorageContainerStatus right) => left.Equals(right);
        /// <summary> Determines if two <see cref="DataBoxEdgeStorageContainerStatus"/> values are not the same. </summary>
        public static bool operator !=(DataBoxEdgeStorageContainerStatus left, DataBoxEdgeStorageContainerStatus right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="DataBoxEdgeStorageContainerStatus"/>. </summary>
        public static implicit operator DataBoxEdgeStorageContainerStatus(string value) => new DataBoxEdgeStorageContainerStatus(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is DataBoxEdgeStorageContainerStatus other && Equals(other);
        /// <inheritdoc />
        public bool Equals(DataBoxEdgeStorageContainerStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
<?php
/* ACL selector json backend */

require_once("include/acl_selectors.php");

function acl_init(&$a){
	acl_lookup($a);
}


text:
/** @jsx hJSX */

import cuid from 'cuid';
import assign from 'fast.js/object/assign';
import model from './../shared/model';
import view from './view';
import moleculeInputError from './../molecule-input-error/index';
import moleculeInputContainer from './../molecule-input-container/index';
import renderLabel from './../shared/renderLabel.js';
import {hJSX} from '@cycle/dom'; // eslint-disable-line

const DIALOGUE_NAME = `molecule-Input`;

/**
 * `moculeInput` is a single-line text field with Material Design styling.
 *
 *     moleculeInput({DOM, props$: Rx.Observable.just({label: `Input label`})});
 *
 * It may include an optional error message.
 *
 *     moleculeInput({DOM, props$: Rx.Observable.just({
 *       errorMessage: `Invalid input!`, label: `Input label`
 *     })});
 *
 * ### Styling
 *
 * See `moleculeInputContainer` for a list of variables and classes used to
 * style this component.
 *
 * @param {Function} DOM the DOM driver function.
 * @param {Observable} props$ An Observable of object of properties.
 * @returns {Object} The moleculeInput object. The object has the following
 * structure:
 *
 *     {
 *       DOM: Observable,
 *       id: String,
 *       state$: Observable
 *     }
 */
function moleculeInput({DOM, props$}) {
  const id = cuid();
  const state$ = model({props$, dialogueName: DIALOGUE_NAME});
  const input$ = view({state$, id});

  const inputContainer = moleculeInputContainer({
    DOM, props$: state$.combineLatest(
      input$,
      (state, inputVTree) => assign(
        {}, state, {
          label: renderLabel(state),
          input: inputVTree,
          addOns: [moleculeInputError],
        }
      )
    ),
  });

  return {
    DOM: inputContainer.DOM,
    id: inputContainer.id,
    state$: inputContainer.state$,
  };
}

export {DIALOGUE_NAME};

export default moleculeInput;


text:
<?php

class Mirasvit_SearchIndex_Model_Index_Azebiz_Support_Kbarticle_Indexer
    extends Mirasvit_SearchIndex_Model_Indexer_Abstract
{
    protected function _getSearchableEntities($storeId, $entityIds, $lastEntityId, $limit = 100)
    {
        $collection = Mage::getModel('support/kbarticle')->getCollection();
        $collection->addFieldToFilter('status', 1);

        if ($entityIds) {
            $collection->addFieldToFilter('kb_article_id', array('in' => $entityIds));
        }

        $collection->getSelect()->where('main_table.kb_article_id > ?', $lastEntityId)
            ->limit($limit)
            ->order('main_table.kb_article_id');

        return $collection;
    }
}


text:
var _ = require("underscore"),
    assert = require("assert"),
    vows = require("vows");

var validActivity = function(act) {
    assert.isObject(act);
    assert.isFalse(_.has(act, "_uuid"));
    assert.include(act, "id");
    assert.isString(act.id);
    assert.include(act, "actor");
    assert.isObject(act.actor);
    assert.include(act.actor, "id");
    assert.isString(act.actor.id);
    assert.include(act.actor, "objectType");
    assert.isString(act.actor.objectType);
    assert.include(act.actor, "displayName");
    assert.isString(act.actor.displayName);
    assert.isFalse(_.has(act.actor, "_uuid"));
    assert.include(act, "verb");
    assert.isString(act.verb);
    assert.include(act, "object");
    assert.isObject(act.object);
    assert.include(act.object, "id");
    assert.isString(act.object.id);
    assert.include(act.object, "objectType");
    assert.isString(act.object.objectType);
    assert.isFalse(_.has(act.object, "_uuid"));
    assert.include(act, "published");
    assert.isString(act.published);
    assert.include(act, "updated");
    assert.isString(act.updated);
};

exports.validActivity = validActivity;


text:
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
    internal partial class CrefCompletionProvider
    {
        private class CrefCompletionItem : CSharpCompletionItem
        {
            public readonly string InsertionText;

            public CrefCompletionItem(
                Workspace workspace,
                ICompletionProvider completionProvider,
                string displayText,
                string insertionText,
                TextSpan textSpan,
                Func<CancellationToken,
                Task<ImmutableArray<SymbolDisplayPart>>> descriptionFactory,
                Glyph? glyph,
                string sortText)
                : base(workspace, completionProvider, displayText, textSpan, descriptionFactory, glyph, sortText)
            {
                this.InsertionText = insertionText;
            }
        }
    }
}


text:
class RemovePasswordFromAdmins < ActiveRecord::Migration
  def change
    remove_column :admins, :password, :string
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/XCUIApplicationProcess.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/XCUIApplicationProcess</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setAXClient_iOS:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCAXClient_iOS *AXClient_iOS</Declaration>

			<Anchor>//api/name/AXClient_iOS</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/AXClient_iOS</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCAXClient_iOS *AXClient_iOS</Declaration>

			<Anchor>//api/name/AXClient_iOS</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/AXClient_iOS</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCAXClient_iOS *AXClient_iOS</Declaration>

			<Anchor>//api/name/AXClient_iOS</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setIDEProxy:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property id<XCTestManager_IDEInterface> IDEProxy</Declaration>

			<Anchor>//api/name/IDEProxy</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/IDEProxy</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property id<XCTestManager_IDEInterface> IDEProxy</Declaration>

			<Anchor>//api/name/IDEProxy</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/IDEProxy</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property id<XCTestManager_IDEInterface> IDEProxy</Declaration>

			<Anchor>//api/name/IDEProxy</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setAccessibilityActive:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) _Bool accessibilityActive</Declaration>

			<Anchor>//api/name/accessibilityActive</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/accessibilityActive</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) _Bool accessibilityActive</Declaration>

			<Anchor>//api/name/accessibilityActive</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/accessibilityActive</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) _Bool accessibilityActive</Declaration>

			<Anchor>//api/name/accessibilityActive</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setAccessibilityElement:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (readonly, copy) XCAccessibilityElement *accessibilityElement</Declaration>

			<Anchor>//api/name/accessibilityElement</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/accessibilityElement</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (readonly, copy) XCAccessibilityElement *accessibilityElement</Declaration>

			<Anchor>//api/name/accessibilityElement</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/accessibilityElement</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (readonly, copy) XCAccessibilityElement *accessibilityElement</Declaration>

			<Anchor>//api/name/accessibilityElement</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setAnimationsHaveFinished:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool animationsHaveFinished</Declaration>

			<Anchor>//api/name/animationsHaveFinished</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/animationsHaveFinished</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool animationsHaveFinished</Declaration>

			<Anchor>//api/name/animationsHaveFinished</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/animationsHaveFinished</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool animationsHaveFinished</Declaration>

			<Anchor>//api/name/animationsHaveFinished</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setApplicationImplementation:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCUIApplicationImpl *applicationImplementation</Declaration>

			<Anchor>//api/name/applicationImplementation</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/applicationImplementation</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCUIApplicationImpl *applicationImplementation</Declaration>

			<Anchor>//api/name/applicationImplementation</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/applicationImplementation</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCUIApplicationImpl *applicationImplementation</Declaration>

			<Anchor>//api/name/applicationImplementation</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setApplicationMonitor:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCApplicationMonitor *applicationMonitor</Declaration>

			<Anchor>//api/name/applicationMonitor</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/applicationMonitor</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCApplicationMonitor *applicationMonitor</Declaration>

			<Anchor>//api/name/applicationMonitor</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/applicationMonitor</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property XCApplicationMonitor *applicationMonitor</Declaration>

			<Anchor>//api/name/applicationMonitor</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setApplicationState:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) unsigned long long applicationState</Declaration>

			<Anchor>//api/name/applicationState</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/applicationState</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) unsigned long long applicationState</Declaration>

			<Anchor>//api/name/applicationState</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/applicationState</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) unsigned long long applicationState</Declaration>

			<Anchor>//api/name/applicationState</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/dealloc</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (void)dealloc</Declaration>

			<Anchor>//api/name/dealloc</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/description</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (id)description</Declaration>

			<Anchor>//api/name/description</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setEventLoopHasIdled:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool eventLoopHasIdled</Declaration>

			<Anchor>//api/name/eventLoopHasIdled</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/eventLoopHasIdled</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool eventLoopHasIdled</Declaration>

			<Anchor>//api/name/eventLoopHasIdled</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/eventLoopHasIdled</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool eventLoopHasIdled</Declaration>

			<Anchor>//api/name/eventLoopHasIdled</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setHasReceivedAnimationsHaveFinished:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool hasReceivedAnimationsHaveFinished</Declaration>

			<Anchor>//api/name/hasReceivedAnimationsHaveFinished</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/hasReceivedAnimationsHaveFinished</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool hasReceivedAnimationsHaveFinished</Declaration>

			<Anchor>//api/name/hasReceivedAnimationsHaveFinished</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/hasReceivedAnimationsHaveFinished</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool hasReceivedAnimationsHaveFinished</Declaration>

			<Anchor>//api/name/hasReceivedAnimationsHaveFinished</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setHasReceivedEventLoopHasIdled:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool hasReceivedEventLoopHasIdled</Declaration>

			<Anchor>//api/name/hasReceivedEventLoopHasIdled</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/hasReceivedEventLoopHasIdled</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool hasReceivedEventLoopHasIdled</Declaration>

			<Anchor>//api/name/hasReceivedEventLoopHasIdled</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/hasReceivedEventLoopHasIdled</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property _Bool hasReceivedEventLoopHasIdled</Declaration>

			<Anchor>//api/name/hasReceivedEventLoopHasIdled</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/init</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (id)init</Declaration>

			<Anchor>//api/name/init</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/initWithApplicationMonitor:AXInterface:IDEProxy:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (id)initWithApplicationMonitor:(id)arg1 AXInterface:(id)arg2 IDEProxy:(id)arg3</Declaration>

			<Anchor>//api/name/initWithApplicationMonitor:AXInterface:IDEProxy:</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setProcessID:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) int processID</Declaration>

			<Anchor>//api/name/processID</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/processID</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) int processID</Declaration>

			<Anchor>//api/name/processID</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/processID</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (nonatomic) int processID</Declaration>

			<Anchor>//api/name/processID</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/setToken:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (retain) id token</Declaration>

			<Anchor>//api/name/token</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/token</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (retain) id token</Declaration>

			<Anchor>//api/name/token</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/XCUIApplicationProcess/token</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>@property (retain) id token</Declaration>

			<Anchor>//api/name/token</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/terminate</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (void)terminate</Declaration>

			<Anchor>//api/name/terminate</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/waitForQuiescence</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (void)waitForQuiescence</Declaration>

			<Anchor>//api/name/waitForQuiescence</Anchor>
            <NodeRef refid="43"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/XCUIApplicationProcess/waitForViewControllerViewDidDisappearWithTimeout:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>XCUIApplicationProcess.h</DeclaredIn>

			<Declaration>- (void)waitForViewControllerViewDidDisappearWithTimeout:(double)arg1</Declaration>

			<Anchor>//api/name/waitForViewControllerViewDidDisappearWithTimeout:</Anchor>
            <NodeRef refid="43"/>
		</Token>

	</File>
</Tokens>


text:
import json
import requests
import base64
import datetime
from binascii import hexlify, unhexlify
from math import ceil,log

class BadResult():
	def __init__(self):
		self.ok = False

class FileApi:
	def getBlockAt(self, height):
		data = None
		with open('../blocks/b' + str(height) + '.json') as data_file:
			data = json.load(data_file)
		return data

	def getHeight(self):
		return {'height':215190}

class HttpApi():
	def __init__(self, baseurl):
		self.baseUrl = baseurl
		self.nemEpoch = datetime.datetime(2015, 3, 29, 0, 6, 25, 0, None)

	def getTimeStamp(self):
		now = datetime.datetime.utcnow()
		return int((now - self.nemEpoch).total_seconds())

	def nodeInfo(self):
		r = self.sendGet('node/info', None)
		if r.ok:
			j = r.json()
			if j['metaData']['application'] == 'NIS':
				return j
		return None

	def getBlockAt(self, height):
		r = self.sendPost('local/block/at', {'height':height})
		if r.ok:
			j = r.json()
			return j
		return None

	def getAccount(self, id):
		r = self.sendGet('account/get?address=%s' % id, None)
		if r.ok:
			j = r.json()
			return j
		return None

	def getHeight(self):
		r = self.sendGet('chain/height', None)
		if r.ok:
			j = r.json()
			return j
		return None

	def sendGet(self, callName, data):
		headers = {'Content-type': 'application/json' }
		uri = self.baseUrl + callName
		try:
			ret = requests.get(uri, data=json.dumps(data), headers=headers, timeout=10)
		except (requests.exceptions.ConnectionError,requests.exceptions.ReadTimeout) as e:
			return BadResult()
		return ret

	def sendPost(self, callName, data):
		headers = {'Content-type': 'application/json' }
		uri = self.baseUrl + callName
		try:
			ret = requests.post(uri, data=json.dumps(data), headers=headers, timeout=10)
		except (requests.exceptions.ConnectionError,requests.exceptions.ReadTimeout) as e:
			print e
			return BadResult()
		return ret


text:
/**
 * @ngdoc directive
 * @name adf.directive:adfDashboard
 * @element div
 * @restrict EA
 * @scope
 * @description
 *
 * `adfDashboard` is a directive which renders the dashboard with all its
 * components. The directive requires a name attribute. The name of the
 * dashboard can be used to store the model.
 */

'use strict';

angular.module('adf')
  .directive('adfDashboard', function($rootScope, $log, $modal, dashboard, adfTemplatePath){

    function copyWidgets(source, target){
      if ( source.widgets && source.widgets.length > 0 ){
        var w = source.widgets.shift();
        while (w){
          target.widgets.push(w);
          w = source.widgets.shift();
        }
      }
    }

    function fillStructure(model, columns, counter){
      angular.forEach(model.rows, function(row){
        angular.forEach(row.columns, function(column){
          if (!column.widgets){
            column.widgets = [];
          }
          if ( columns[counter] ){
            copyWidgets(columns[counter], column);
            counter++;
          }
        });
      });
      return counter;
    }

    function readColumns(model){
      var columns = [];
      angular.forEach(model.rows, function(row){
        angular.forEach(row.columns, function(col){
          columns.push(col);
        });
      });
      return columns;
    }

    function changeStructure(model, structure){
      var columns = readColumns(model);
      model.rows = angular.copy(structure.rows);
      var counter = 0;
      while ( counter < columns.length ){
        counter = fillStructure(model, columns, counter);
      }
    }

    function createConfiguration(type){
      var cfg = {};
      var config = dashboard.widgets[type].config;
      if (config){
        cfg = angular.copy(config);
      }
      return cfg;
    }

    return {
      replace: true,
      restrict: 'EA',
      transclude : false,
      scope: {
        structure: '@',
        name: '@',
        collapsible: '@',
        adfModel: '=',
        adfWidgetFilter: '='
      },
      controller: function($scope){
        // sortable options for drag and drop
        $scope.sortableOptions = {
          connectWith: ".column",
          handle: ".fa-arrows",
          cursor: 'move',
          tolerance: 'pointer',
          placeholder: 'placeholder',
          forcePlaceholderSize: true,
          opacity: 0.4
        };

        var model = {};
        var structure = {};
        var widgetFilter = {};
        var structureName = {};
        var name = $scope.name;

        // Watching for changes on adfModel
        $scope.$watch('adfModel', function(oldVal, newVal) {
          if(newVal =! null) {
            model = $scope.adfModel;
            widgetFilter = $scope.adfWidgetFilter;
            if ( ! model || ! model.rows ){
              structureName = $scope.structure;
              structure = dashboard.structures[structureName];
              if (structure){
                if (model){
                  model.rows = angular.copy(structure).rows;
                } else {
                  model = angular.copy(structure);
                }
                model.structure = structureName;
              } else {
                $log.error( 'could not find structure ' + structureName);
              }
            }

            if (model) {
              if (!model.title){
                model.title = 'Dashboard';
              }
              $scope.model = model;
            } else {
              $log.error('could not find or create model');
            }
          }
        }, true);

        // edit mode
        $scope.editMode = false;
        $scope.editClass = "";

        $scope.toggleEditMode = function(){
          $scope.editMode = ! $scope.editMode;
    		  if ($scope.editMode){
            $scope.modelCopy = angular.copy($scope.adfModel, {});
    		  }

          if (!$scope.editMode){
            $rootScope.$broadcast('adfDashboardChanged', name, model);
          }
        };

        $scope.cancelEditMode = function(){
          $scope.editMode = false;
		      $scope.modelCopy = angular.copy($scope.modelCopy, $scope.adfModel);
        };

        // edit dashboard settings
        $scope.editDashboardDialog = function(){
          var editDashboardScope = $scope.$new();
          editDashboardScope.structures = dashboard.structures;
          var instance = $modal.open({
            scope: editDashboardScope,
            templateUrl: adfTemplatePath + 'dashboard-edit.html'
          });
          $scope.changeStructure = function(name, structure){
            $log.info('change structure to ' + name);
            changeStructure(model, structure);
          };
          editDashboardScope.closeDialog = function(){
            instance.close();
            editDashboardScope.$destroy();
          };
        };

        // add widget dialog
        $scope.addWidgetDialog = function(){
          var addScope = $scope.$new();
          var widgets;
          if (angular.isFunction(widgetFilter)){
            widgets = {};
            angular.forEach(dashboard.widgets, function(widget, type){
              if (widgetFilter(widget, type)){
                widgets[type] = widget;
              }
            });
          } else {
            widgets = dashboard.widgets;
          }
          addScope.widgets = widgets;
          var opts = {
            scope: addScope,
            templateUrl: adfTemplatePath + 'widget-add.html'
          };
          var instance = $modal.open(opts);
          addScope.addWidget = function(widget){
            var w = {
              type: widget,
              config: createConfiguration(widget)
            };
            addScope.model.rows[0].columns[0].widgets.unshift(w);
            instance.close();

            addScope.$destroy();
          };
          addScope.closeDialog = function(){
            instance.close();
            addScope.$destroy();
          };
        };
      },
      link: function ($scope, $element, $attr) {
        // pass attributes to scope
        $scope.name = $attr.name;
        $scope.structure = $attr.structure;
      },
      templateUrl: adfTemplatePath + 'dashboard.html'
    };
  });


text:
from mistralclient.api import base as mistral_base
from mistralclient.api import client as mistral_client

from heat.common import exception
from heat.engine.clients import client_plugin
from heat.engine import constraints

CLIENT_NAME = 'mistral'

class MistralClientPlugin(client_plugin.ClientPlugin):

    service_types = [WORKFLOW_V2] = ['workflowv2']

    def _create(self):
        endpoint_type = self._get_client_option(CLIENT_NAME, 'endpoint_type')
        endpoint = self.url_for(service_type=self.WORKFLOW_V2,
                                endpoint_type=endpoint_type)

        args = {
            'mistral_url': endpoint,
            'auth_token': self.auth_token
        }

        client = mistral_client.client(**args)
        return client

    def is_not_found(self, ex):
        return (isinstance(ex, mistral_base.APIException) and
                ex.error_code == 404)

    def is_over_limit(self, ex):
        return (isinstance(ex, mistral_base.APIException) and
                ex.error_code == 413)

    def is_conflict(self, ex):
        return (isinstance(ex, mistral_base.APIException) and
                ex.error_code == 409)

    def get_workflow_by_identifier(self, workflow_identifier):
        try:
            return self.client().workflows.get(
                workflow_identifier)
        except Exception as ex:
            if self.is_not_found(ex):
                raise exception.EntityNotFound(
                    entity="Workflow",
                    name=workflow_identifier)
            raise ex

class WorkflowConstraint(constraints.BaseCustomConstraint):
    resource_client_name = CLIENT_NAME
    resource_getter_name = 'get_workflow_by_identifier'
    expected_exceptions = (exception.EntityNotFound,)


text:
package com.splunk.hunk.input.entry;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.BoundedInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.MapFile;
import org.apache.hadoop.io.MapFile.Reader;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

public class MapEntryReader implements EntryReader {

	@Override
	public InputStream getHdfsFileStream(String fsUri, String path, String key)
			throws IOException {
		FileSystem fs = FileSystem.get(URI.create(fsUri), new Configuration());
		String mapDir = new File(path).getParent();
		Reader reader = new MapFile.Reader(fs, mapDir, fs.getConf());
		return getEntryStream(path, key, reader);
	}

	private InputStream getEntryStream(String path, String key, Reader reader)
			throws IOException {
		try {
			BytesWritable value = new BytesWritable();
			Writable writable = reader.get(new Text(key), value);
			return toInputStream(path, key, value, writable);
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}

	private InputStream toInputStream(String path, String key,
			BytesWritable value, Writable writable) {
		if (writable == null)
			throw new RuntimeException("Could not find key: " + key
					+ ", at path: " + path);
		else
			return new BoundedInputStream(new ByteArrayInputStream(
					value.getBytes()), value.getLength());
	}

}


text:
Made for Git Concepts Understanding

We read, we test, we know.


text:
sc.define(["notEquals", "!="], {
  Number: function(arg) {
    return this !== arg;
  },
  Array: function(arg) {
    return !this.equals(arg);
  },
  String: function(arg) {
    return this !== arg;
  },
  Function: function(arg) {
    return this !== arg;
  }
});


text:
@implementation UIButton (HWWebImage)

@end


text:
external help file: Microsoft.Azure.Commands.Network.dll-Help.xml
Module Name: AzureRM.Network
online version:
schema: 2.0.0
---

# Get-AzureRmApplicationGatewayAvailableWafRuleSets

## SYNOPSIS
Gets all available web application firewall rule sets.

## SYNTAX

```
Get-AzureRmApplicationGatewayAvailableWafRuleSets [<CommonParameters>]
```

## DESCRIPTION
The **Get-AzureRmApplicationGatewayAvailableWafRuleSets** cmdlet gets all available web application firewall rule sets.

## EXAMPLES

### Example 1
```
PS C:\>$availableRuleSets = Get-AzureRmApplicationGatewayAvailableWafRuleSets
```

This commands returns all the available web application firewall rule sets.

## PARAMETERS

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### Microsoft.Azure.Commands.Network.Models.PSApplicationGatewayAvailableWafRuleSetsResult

## NOTES
**List-AzureRmApplicationGatewayAvailableWafRuleSets** is an alias for the **Get-AzureRmApplicationGatewayAvailableWafRuleSets** cmdlet.

## RELATED LINKS


text:
package com.echo.holographlibrary;

import android.graphics.Color;
import android.graphics.Path;
import android.graphics.Region;

public class Bar {

    private final Path mPath = new Path();
    private final Region mRegion = new Region();
    private int mColor = 0xFF33B5E5;
    private int mLabelColor = -1;
    private int mSelectedColor = -1;
    private int mValueColor = Color.WHITE;
    private int mColorAlpha = 255;//no transparency by default. Used in animations to transition to a final alpha.
    private String mName = null;
    private float mValue;
    private float mOldValue;
    private float mGoalValue;
    private String mValueString = null;
    private String mValuePrefix = null;
    private String mValueSuffix = null;

    public int mAnimateSpecial = HoloGraphAnimate.ANIMATE_NORMAL;//add getter setter

    public int getColor() {
        return mColor;
    }

    public int getColorAlpha(){return mColorAlpha;}

    public void setColor(int color) {
        mColor = color;
        mColorAlpha = Color.alpha(color);
    }

    public int getLabelColor() {
        return mLabelColor == -1 ? mColor : mLabelColor;
    }

    public void setLabelColor(int labelColor) {
        mLabelColor = labelColor;
    }

    public int getSelectedColor() {
        if (-1 == mSelectedColor) mSelectedColor = Utils.darkenColor(mColor);
        return mSelectedColor;
    }

    public void setSelectedColor(int selectedColor) {
        mSelectedColor = selectedColor;
    }

    public int getValueColor() {
        return mValueColor;
    }

    public void setValueColor(int valueColor) {
        mValueColor = valueColor;
    }

    public String getName() {
        return (null == mName) ? "" : mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public float getValue() {
        return mValue;
    }

    public void setValue(float value) {
        mValue = value;
    }

    public float getOldValue() {
        return mOldValue;
    }

    public void setOldValue(float oldValue) { mOldValue = oldValue; }

    public float getGoalValue() {
        return mGoalValue;
    }

    public void setGoalValue(float goalValue) { mGoalValue = goalValue; }

    public String getValueString() {
        if (mValueString != null) {
            return mValueString;
        } else {
            return String.valueOf(mValue);
        }
    }

    public void setValueString(final String valueString) {
        mValueString = valueString;
    }
    public String getValuePrefix() {return mValuePrefix;}

    public void setValuePrefix(String valuePrefix) { mValuePrefix = valuePrefix; }

    public String getValueSuffix() {return mValueSuffix;}

    public void setValueSuffix(String valueSuffix) { mValueSuffix = valueSuffix; }

    public void makeValueString(int decimalPrecision){
        String base = String.format("%." + String.valueOf(decimalPrecision)+"f",mValue);
        if (getValuePrefix() != null) base = getValuePrefix() + base;
        if (getValueSuffix() != null) base = base + getValueSuffix();
        setValueString(base);
    }

    public Path getPath() {
        return mPath;
    }

    public Region getRegion() {
        return mRegion;
    }
}


text:
/* global describe, it */

var requirejs = require("requirejs");
var assert = require("assert");
var should = require("should");

requirejs.config({
  baseUrl: '',
  paths: {
    jquery: 'scripts/libs/jquery.min',
    text: 'scripts/libs/text',
    json: 'scripts/libs/json',
    'jquery.pwstabs': 'scripts/libs/jquery.pwstabs.min',
    'jquery.mixitup': 'scripts/libs/jquery.mixitup.min',
    ckeditor: 'ckeditor/ckeditor',
    lodash: 'scripts/libs/loadsh.min',
    ko: 'scripts/libs/knockout',
    ractive: 'scripts/libs/ractive.min',
    rv: 'scripts/libs/rv',
    amplify: 'scripts/libs/amplify.min',
    'amplify.request': 'scripts/libs/amplify.request.min',
    'spectrum': 'scripts/spectrum/spectrum',
    'jquery.nicescroll': 'scripts/libs/jquery.nicescroll.min'
  },
  'shim': {
    ko: {
      exports: "ko"
    },
    lodash: {
      exports: "_"
    },
    'amplify.request': {
      deps: ['amplify']
    },
    'amplify': {
      deps: ['jquery'],
      exports: 'amplify'
    },
    'spectrum': {
      deps: ['jquery']
    },
    'jquery.mixitup': {
      deps: ['jquery']
    },
    'jquery.nicescroll': {
      deps: ['jquery']
    },
    'jquery.pwstabs': {
      deps: ['jquery']
    }
  },
  nodeRequire: require
});

describe('Basic Test', function () {
  var hrView, parasView, config = {
    'defaultColor': '#4caf50',
    'defaultFontSize': '20px'
  };

  before(function (done) {
    requirejs(['scripts/views/hrView', 'scripts/views/parasView' ], function (HRView, ParasView) {
      hrView = HRView.init(config);
      parasView = ParasView.init(config);
      done();
    });
  });

  describe('Basic HR View Test', function () {
    it('should return correctly color', function () {
      var section = hrView.findComponent('Grid').get('styles.1');
      section.color.should.equal(config.defaultColor);
      section.p_style.should.equal('background-color: #fff;border-top: 3px double');
    });

    it('should return correctly color when change color', function () {
      hrView.fire('changeColor', {color: '#fff'});
      var section = hrView.findComponent('Grid').get('styles.2');
      section.color.should.equal('#fff');
    });
  });

  describe('Basic Paras View Test', function () {
    it('should return correctly color', function () {
      parasView.findComponent('Grid').set('Style.*.p_style', "font-size:15px;");
      var section = parasView.findComponent('Grid').get('styles.1');
      section.color.should.equal(config.defaultColor);
      section.p_style.should.equal('font-size:15px;');
      parasView.findComponent('Grid').set('Style.*.color', "#fff");
      section.color.should.equal("#fff");
    });
  });
});


text:
//
using System;

namespace Alachisoft.NosDB.Core.Toplogies.Impl.StateTransfer
{
    public interface IAllocator
    {
        Boolean IsTaskAvailable { get; }
        void AllocateResource();
    }
}


text:
'use strict';

angular.module('realizeChangeApp')
  .service('UserInfo', function (User, Auth) {
    // AngularJS will instantiate a singleton by calling "new" on this function
    var currentUser = Auth.getCurrentUser();

    var UserInfo = function(){
	    this.name = currentUser.name; //user db
      this.email = currentUser.email; //user db //string
      this.share = currentUser.share; //user db
      this.world = currentUser.world; //dreams db //string
      this.future = currentUser.future; //dreams db //string
      this.flagged = currentUser.flagged; //dreams db
      this.dream_id = currentUser.dream_id; //user db
    };
    return new UserInfo();
  });


text:
package org.apache.naming.resources;

import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.directory.DirContext;

/**
 * Stream handler to a JNDI directory context.
 *
 * @author Remy Maucherat
 * @version $Revision: 1.6 $
 */
public class DirContextURLStreamHandler
    extends URLStreamHandler {

    // ----------------------------------------------------------- Constructors

    public DirContextURLStreamHandler() {
    }

    public DirContextURLStreamHandler(DirContext context) {
        this.context = context;
    }

    // -------------------------------------------------------------- Variables

    /**
     * Bindings class loader - directory context. Keyed by CL id.
     */
    private static Hashtable clBindings = new Hashtable();

    /**
     * Bindings thread - directory context. Keyed by thread id.
     */
    private static Hashtable threadBindings = new Hashtable();

    // ----------------------------------------------------- Instance Variables

    /**
     * Directory context.
     */
    protected DirContext context = null;

    // ------------------------------------------------------------- Properties

    // ----------------------------------------------- URLStreamHandler Methods

    /**
     * Opens a connection to the object referenced by the URL
     * argument.
     */
    protected URLConnection openConnection(URL u)
        throws IOException {
        DirContext currentContext = this.context;
        if (currentContext == null)
            currentContext = get();
        return new DirContextURLConnection(currentContext, u);
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Set the java.protocol.handler.pkgs system property.
     */
    public static void setProtocolHandler() {
        String value = System.getProperty(Constants.PROTOCOL_HANDLER_VARIABLE);
        if (value == null) {
            value = Constants.Package;
            System.setProperty(Constants.PROTOCOL_HANDLER_VARIABLE, value);
        } else if (value.indexOf(Constants.Package) == -1) {
            value += "|" + Constants.Package;
            System.setProperty(Constants.PROTOCOL_HANDLER_VARIABLE, value);
        }
    }

    /**
     * Returns true if the thread or the context class loader of the current
     * thread is bound.
     */
    public static boolean isBound() {
        return (clBindings.containsKey
                (Thread.currentThread().getContextClassLoader()))
            || (threadBindings.containsKey(Thread.currentThread()));
    }

    /**
     * Binds a directory context to a class loader.
     */
    public static void bind(DirContext dirContext) {
        ClassLoader currentCL =
            Thread.currentThread().getContextClassLoader();
        if (currentCL != null)
            clBindings.put(currentCL, dirContext);
    }

    /**
     * Unbinds a directory context to a class loader.
     */
    public static void unbind() {
        ClassLoader currentCL =
            Thread.currentThread().getContextClassLoader();
        if (currentCL != null)
            clBindings.remove(currentCL);
    }

    /**
     * Binds a directory context to a thread.
     */
    public static void bindThread(DirContext dirContext) {
        threadBindings.put(Thread.currentThread(), dirContext);
    }

    /**
     * Unbinds a directory context to a thread.
     */
    public static void unbindThread() {
        threadBindings.remove(Thread.currentThread());
    }

    /**
     * Get the bound context.
     */
    public static DirContext get() {

        DirContext result = null;

        Thread currentThread = Thread.currentThread();
        ClassLoader currentCL = currentThread.getContextClassLoader();

        // Checking CL binding
        result = (DirContext) clBindings.get(currentCL);
        if (result != null)
            return result;

        // Checking thread biding
        result = (DirContext) threadBindings.get(currentThread);

        // Checking parent CL binding
        currentCL = currentCL.getParent();
        while (currentCL != null) {
            result = (DirContext) clBindings.get(currentCL);
            if (result != null)
                return result;
            currentCL = currentCL.getParent();
        }

        if (result == null)
            throw new IllegalStateException("Illegal class loader binding");

        return result;

    }

    /**
     * Binds a directory context to a class loader.
     */
    public static void bind(ClassLoader cl, DirContext dirContext) {
        clBindings.put(cl, dirContext);
    }

    /**
     * Unbinds a directory context to a class loader.
     */
    public static void unbind(ClassLoader cl) {
        clBindings.remove(cl);
    }

    /**
     * Get the bound context.
     */
    public static DirContext get(ClassLoader cl) {
        return (DirContext) clBindings.get(cl);
    }

    /**
     * Get the bound context.
     */
    public static DirContext get(Thread thread) {
        return (DirContext) threadBindings.get(thread);
    }

}


text:
@interface JLMovieTableViewController : UITableViewController <UIAlertViewDelegate>

@property (copy, nonatomic) NSString *imagesBaseUrlString;
@property (strong, nonatomic) NSArray *moviesArray;

@end


text:
stage.loadFile('data://1crn.pdb').then(function (o) {
  o.addRepresentation('ball+stick')
  o.autoView()
})


text:
tags: technology
layout: post
title: "If my house burned down..."
---

...I seriously doubt that among my first thousand reactions would be to ask slashdot about smoke damage. Wow.


text:
package com.divinitor.discord.vahrhedralbot.secrets.impl;

import com.divinitor.discord.vahrhedralbot.secrets.SecretHandle;
import com.divinitor.discord.vahrhedralbot.secrets.SecretsStore;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.NoSuchElementException;
import java.util.function.Consumer;

public class RedisSecretStore implements SecretsStore {

    public static final String SECRETS_KEY_BASE = "com.divinitor.discord.vahrhedralbot.secrets.";
    private JedisPool pool;

    private Table<String, String, Consumer<String>> listeners;

    public RedisSecretStore(JedisPool pool) {
        this.pool = pool;
        listeners = HashBasedTable.create();
    }

    @Override
    public void putSecret(String key, String value) {
        try (Jedis jedis = pool.getResource()) {
            jedis.set(SECRETS_KEY_BASE + key, value);
            listeners.column(key).values().forEach(c -> c.accept(value));
        }
    }

    @Override
    public String getSecret(String key) throws NoSuchElementException {
        return getSecret(key, true);
    }

    public String getSecret(String key, boolean throwExcept) throws NoSuchElementException {
        try (Jedis jedis = pool.getResource()) {
            String ret = jedis.get(SECRETS_KEY_BASE + key);
            if (ret == null && throwExcept) {
                throw new NoSuchElementException(key);
            }
            return ret;
        }
    }

    @Override
    public String registerChangeListener(String key, Consumer<String> listener) {
        String listenerId = listener.toString();    //  really lazy here
        String publicListenerId = key + ":" + listenerId;
        listeners.put(key, listenerId, listener);
        return publicListenerId;
    }

    @Override
    public void unregisterChangeListener(String listenerId) {
        String[] split = listenerId.split(":");
        String key = split[0];
        String internalListenerId = split[1];
        listeners.remove(key, internalListenerId);
    }

    @Override
    public SecretHandle getSecretHandler(String key) {
        return () -> getSecret(key, false);
    }
}


text:
/*
CARRE NICOLAS
OPTRAJ
*/

(function () {
	if (sessionStorage.lvladminreq == 2){
		document.getElementById('add').parentNode.removeChild(document.getElementById('add'));
		}
	}) ()


text:
package format

import (
	"code.cloudfoundry.org/bbs/encryption"
	"code.cloudfoundry.org/lager"
)

type serializer struct {
	encoder Encoder
}

type Serializer interface {
	Marshal(logger lager.Logger, model Model) ([]byte, error)
	Unmarshal(logger lager.Logger, encodedPayload []byte, model Model) error
}

func NewSerializer(cryptor encryption.Cryptor) Serializer {
	return &serializer{
		encoder: NewEncoder(cryptor),
	}
}

func (s *serializer) Marshal(logger lager.Logger, model Model) ([]byte, error) {
	envelopedPayload, err := MarshalEnvelope(model)
	if err != nil {
		return nil, err
	}

	return s.encoder.Encode(envelopedPayload)
}

func (s *serializer) Unmarshal(logger lager.Logger, encodedPayload []byte, model Model) error {
	unencodedPayload, err := s.encoder.Decode(encodedPayload)
	if err != nil {
		return err
	}
	return UnmarshalEnvelope(logger, unencodedPayload, model)
}


text:
@interface IDEFindNavigatorSymbolicReferenceQuery : IDEBatchFindSymbolicReferenceQuery
{
}

- (id)allocWithZone:(struct _NSZone *)arg1;

@end