text:
package org.nextime.ion.backoffice.exception;

import javax.servlet.ServletException;

public class StandardException extends ServletException {

    /**
     * Constructor for StandardException.
     */
    public StandardException() {
        super();
    }

    /**
     * Constructor for StandardException.
     *
     * @param arg0
     */
    public StandardException(String arg0) {
        super(arg0);
    }

    /**
     * Constructor for StandardException.
     *
     * @param arg0
     * @param arg1
     */
    public StandardException(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }

    /**
     * Constructor for StandardException.
     *
     * @param arg0
     */
    public StandardException(Throwable arg0) {
        super(arg0);
    }

}


text:
package ru.job4j.principle_007;

import java.io.*;

public class ParseFile {
    private File file;

    public synchronized void setFile(File f) {
        file = f;
    }

    public synchronized File getFile() {
        return file;
    }

    public String getContent() throws IOException {
        InputStream i = new FileInputStream(file);
        String output = "";
        int data;
        while ((data = i.read()) > 0) {
            output += (char) data;
        }
        return output;
    }

    public String getContentWithoutUnicode() throws IOException {
        InputStream i = new FileInputStream(file);
        String output = "";
        int data;
        while ((data = i.read()) > 0) {
            if (data < 0x80) {
                output += (char) data;
            }
        }
        return output;
    }

    public void saveContent(String content) throws IOException {
        OutputStream o = new FileOutputStream(file);
        for (int i = 0; i < content.length(); i += 1) {
            o.write(content.charAt(i));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE InstanceSigs #-}
module TraversableTest where
  import Data.Foldable
  import Data.Monoid
  data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving Show

  instance Functor Tree where
    fmap g (Leaf x) = Leaf (g x)
    fmap g (Node l x r) = Node (fmap g l) (g x) (fmap g r)

  instance Foldable Tree where
    fold :: Monoid m => Tree m -> m
    fold (Leaf x) = x
    fold (Node l x r) = (fold l) `mappend` x `mappend` (fold r)

    foldMap :: Monoid m => (a -> m) -> Tree a -> m
    foldMap g x = fold (fmap g x)

  instance Traversable Tree where
    sequenceA :: (Applicative f) => Tree (f a) -> f (Tree a)
    sequenceA (Leaf x) = fmap Leaf x
    sequenceA (Node l x r) = Node <$> (sequenceA l) <*> x <*> (sequenceA r)

  test :: IO ()
  test = do
    print $ tree3
    print $ fmap (+1) tree3
    print $ getSum $ foldMap Sum tree3
    print $ getProduct $ foldMap Product tree3
    print $ length tree3
    print $ length $ traverse (\x -> [x, x+1, x+2])tree3
    where
      tree1 = Node (Leaf 1) 2 (Leaf 3)
      tree2 = Node (Leaf 5) 6 (Leaf 7)
      tree3 = Node tree1 4 tree2


text:
'use babel'

import path from 'path';
export default function moduleFromPath(thePath){
  let p = thePath.split(path.sep);
  let ind = p.indexOf('modules');
  if(ind === -1) {
    return "";
  }
  else {
    return p[ind + 1];
  }
};


text:
var GuiDisplayOneItem = {
		ItemData : null,
		ItemIndexData : null,

		selectedItem : 0,
		topLeftItem : 0,
		MAXCOLUMNCOUNT : 4,
		MAXROWCOUNT : 3,

		indexSeekPos : -1,
		isResume : false,
		genreType : "",

		startParams : [],
		isLatest : false,
		backdropTimeout : null
}

GuiDisplayOneItem.onFocus = function() {
	GuiHelper.setControlButtons(null,null,null,GuiMusicPlayer.Status == "PLAYING" || GuiMusicPlayer.Status == "PAUSED" ? "Music" : null,"Return");
}

GuiDisplayOneItem.getMaxDisplay = function() {
	return this.MAXCOLUMNCOUNT * this.MAXROWCOUNT;
}

GuiDisplayOneItem.start = function(title,url,selectedItem,topLeftItem) {
	alert("Page Enter : GuiDisplayOneItem");

	//Save Start Params
	this.startParams = [title,url];

	alert (url);

	//Set background
/*	this.backdropTimeout = setTimeout(function(){
		Support.fadeImage("images/lensflare2-960x540.jpg");
	}, 1000);*/

	//Reset Values
	this.indexSeekPos = -1;
	this.selectedItem = selectedItem;
	this.topLeftItem = topLeftItem;
	this.genreType = null;

	//Load Data
	this.ItemData = Server.getContent(url);
	if (this.ItemData == null) { return; }

	//Setup display width height based on title
	switch (title) {
	case "Media Folders":
	case "Collections":
		this.MAXCOLUMNCOUNT = 3;
		this.MAXROWCOUNT = 2;
		break;
	case "Music":
	case "Albums":
	case "Artists":
		this.MAXCOLUMNCOUNT = 6;
		this.MAXROWCOUNT = 3;
		break;
	default:
		this.MAXCOLUMNCOUNT = 4;
		this.MAXROWCOUNT = 3;
		break;
	}

	//Set Page Content
	document.getElementById("pageContent").innerHTML = "
"+title+"
" +
			"

";

	//Set Top
	GuiDisplayOneItem.setPadding(title);

	if (this.ItemData.Items.length > 0) {
		//Set isResume based on title - used in UpdateDisplayedItems
		this.isResume = (title == "Resume") ? true : false;

		//Alter to only allow indexing on certain pages??
		this.ItemIndexData = Support.processIndexing(this.ItemData.Items);

		//Display first XX series
		this.updateDisplayedItems();

		//Update Selected Collection CSS
		this.updateSelectedItems();

		//Set Focus for Key Events
		document.getElementById("GuiDisplayOneItem").focus();
	} else {
		//Set message to user
		document.getElementById("Counter").innerHTML = "";
		document.getElementById("Content").style.fontSize="20px";
		document.getElementById("Content").innerHTML = "Huh.. Looks like I have no content to show you in this view I'm afraid
Press return to get back to the previous screen";

		document.getElementById("NoItems").focus();
	}
}

GuiDisplayOneItem.updateDisplayedItems = function() {
	Support.updateDisplayedItems(this.ItemData.Items,this.selectedItem,this.topLeftItem,
			Math.min(this.topLeftItem + this.getMaxDisplay(),this.ItemData.Items.length),"Content","",this.isResume,this.genreType,true);
}

//Function sets CSS Properties so show which user is selected
GuiDisplayOneItem.updateSelectedItems = function () {
	if (this.MAXCOLUMNCOUNT == 3) {
		//Add Collections Class to add more margin
		Support.updateSelectedNEW(this.ItemData.Items,this.selectedItem,this.topLeftItem,
				Math.min(this.topLeftItem + this.getMaxDisplay(),this.ItemData.Items.length),"Series Collection Selected","Series Collection","");
	} else {
		Support.updateSelectedNEW(this.ItemData.Items,this.selectedItem,this.topLeftItem,
				Math.min(this.topLeftItem + this.getMaxDisplay(),this.ItemData.Items.length),"Series Selected","Series","");
	}
}

GuiDisplayOneItem.keyDown = function() {
	var keyCode = event.keyCode;
	alert("Key pressed: " + keyCode);

	if (document.getElementById("Notifications").style.visibility == "") {
		document.getElementById("Notifications").style.visibility = "hidden";
		document.getElementById("NotificationText").innerHTML = "";
		widgetAPI.blockNavigation(event);
		//Change keycode so it does nothing!
		keyCode = "VOID";
	}

	//Update Screensaver Timer
	Support.screensaver();

	//If screensaver is running
	if (Main.getIsScreensaverRunning()) {
		//Update Main.js isScreensaverRunning - Sets to True
		Main.setIsScreensaverRunning();

		//End Screensaver
		GuiImagePlayer_Screensaver.stopScreensaver();

		//Change keycode so it does nothing!
		keyCode = "VOID";
	}

	switch(keyCode) {
		//Need Logout Key
		case tvKey.KEY_LEFT:
			alert("LEFT");
			this.processLeftKey();
			break;
		case tvKey.KEY_RIGHT:
			alert("RIGHT");
			this.processRightKey();
			break;
		case tvKey.KEY_UP:
			alert("UP");
			this.processUpKey();
			break;
		case tvKey.KEY_DOWN:
			alert("DOWN");
			this.processDownKey();
			break;
		case tvKey.KEY_PANEL_CH_UP:
		case tvKey.KEY_CH_UP:
			this.processChannelUpKey();
			break;
		case tvKey.KEY_PANEL_CH_DOWN:
		case tvKey.KEY_CH_DOWN:
			this.processChannelDownKey();
			break;
		case tvKey.KEY_RETURN:
			alert("RETURN");
			widgetAPI.blockNavigation(event);
			Support.processReturnURLHistory();
			break;
		case tvKey.KEY_ENTER:
		case tvKey.KEY_PANEL_ENTER:
			alert("ENTER");
			this.processSelectedItem();
			break;
		case tvKey.KEY_PLAY:
			this.playSelectedItem();
			break;
		case tvKey.KEY_GREEN:
			//Watched - May not be needed on this page
			break;
		case tvKey.KEY_YELLOW:
			//Favourites - May not be needed on this page
			break;
		case tvKey.KEY_BLUE:
			GuiMusicPlayer.showMusicPlayer("GuiDisplayOneItem");
			break;
		case tvKey.KEY_TOOLS:
			widgetAPI.blockNavigation(event);
			this.openMenu();
			break;
		case tvKey.KEY_EXIT:
			alert ("EXIT KEY");
			widgetAPI.sendExitEvent();
			break;
	}
}

GuiDisplayOneItem.processSelectedItem = function() {
	clearTimeout(this.backdropTimeout);
	Support.processSelectedItem("GuiDisplayOneItem",this.ItemData,this.startParams,this.selectedItem,this.topLeftItem,null,this.genreType,this.isLatest);
}

GuiDisplayOneItem.playSelectedItem = function () {
	clearTimeout(this.backdropTimeout);
	Support.playSelectedItem("GuiDisplayOneItem",this.ItemData,this.startParams,this.selectedItem,this.topLeftItem,null);
}

GuiDisplayOneItem.openMenu = function() {
	Support.updateURLHistory("GuiDisplayOneItem",this.startParams[0],this.startParams[1],null,null,this.selectedItem,this.topLeftItem,null);
	GuiMainMenu.requested("GuiDisplayOneItem",this.ItemData.Items[this.selectedItem].Id);
}

GuiDisplayOneItem.processLeftKey = function() {
	if (Support.isPower(this.selectedItem, this.MAXCOLUMNCOUNT)){
		this.openMenu(); //Going left from anywhere in the first column.
	} else {
		this.selectedItem--;
		if (this.selectedItem == -1) {
			this.selectedItem = 0;
			this.openMenu();
		} else {
			if (this.selectedItem < this.topLeftItem) {
				this.topLeftItem = this.selectedItem - (this.getMaxDisplay() - 1);
				if (this.topLeftItem < 0) {
					this.topLeftItem = 0;
				}
				this.updateDisplayedItems();
			}
		}
		this.updateSelectedItems();
	}
}

GuiDisplayOneItem.processRightKey = function() {
	this.selectedItem++;
	if (this.selectedItem >= this.ItemData.Items.length) {
		this.selectedItem--;
	} else {
		if (this.selectedItem >= this.topLeftItem+this.getMaxDisplay() ) {
			this.topLeftItem = this.selectedItem;
			this.updateDisplayedItems();
		}
	}
	this.updateSelectedItems();
}

GuiDisplayOneItem.processUpKey = function() {
	this.selectedItem = this.selectedItem - this.MAXCOLUMNCOUNT;
	if (this.selectedItem < 0) {
		//Check User Setting
		this.selectedItem = this.selectedItem + this.MAXCOLUMNCOUNT;
	} else {
		if (this.selectedItem < this.topLeftItem) {
			if (this.topLeftItem - this.MAXCOLUMNCOUNT < 0) {
				this.topLeftItem = 0;
			} else {
				this.topLeftItem = this.topLeftItem - this.MAXCOLUMNCOUNT;
			}
			this.updateDisplayedItems();
		}
	}
	this.updateSelectedItems();
}

GuiDisplayOneItem.processDownKey = function() {
	this.selectedItem = this.selectedItem + this.MAXCOLUMNCOUNT;
	if (this.selectedItem >= this.ItemData.Items.length) {
		this.selectedItem = (this.ItemData.Items.length-1);
		if (this.selectedItem >= (this.topLeftItem  + this.getMaxDisplay())) {
			this.topLeftItem = this.topLeftItem + this.getMaxDisplay();
			this.updateDisplayedItems();
		}
	} else {
		if (this.selectedItem >= (this.topLeftItem + this.getMaxDisplay())) {
			this.topLeftItem = this.topLeftItem + this.MAXCOLUMNCOUNT;
			this.updateDisplayedItems();
		}
	}
	this.updateSelectedItems();
}

GuiDisplayOneItem.processChannelUpKey = function() {
	this.selectedItem = this.selectedItem - this.getMaxDisplay();
	if (this.selectedItem < 0) {
		this.selectedItem = 0;
		this.topLeftItem = 0;
		this.updateDisplayedItems();
	} else {
		if (this.topLeftItem - this.getMaxDisplay() < 0) {
			this.topLeftItem = 0;
		} else {
			this.topLeftItem = this.topLeftItem - this.getMaxDisplay();
		}
		this.updateDisplayedItems();
	}
	this.updateSelectedItems();
}

GuiDisplayOneItem.processChannelDownKey = function() {
	this.selectedItem = this.selectedItem + this.getMaxDisplay();
	if (this.selectedItem >= this.ItemData.Items.length) {
		this.selectedItem = (this.ItemData.Items.length-1);
		if (this.selectedItem >= this.topLeftItem + this.getMaxDisplay()) {
			this.topLeftItem = this.topLeftItem + this.getMaxDisplay();
		}
		this.updateDisplayedItems();
	} else {
		this.topLeftItem = this.topLeftItem + this.getMaxDisplay();
		this.updateDisplayedItems();
	}
	this.updateSelectedItems();
}

GuiDisplayOneItem.processIndexing = function() {
	var indexLetter = this.ItemIndexData[0];
	var indexPos = this.ItemIndexData[1];

	this.indexSeekPos++;
	if (this.indexSeekPos >= indexPos.length) {
		this.indexSeekPos = 0;
		this.topLeftItem = 0;
	}

	this.selectedItem = indexPos[this.indexSeekPos];
	this.topLeftItem = this.selectedItem;

	this.updateDisplayedItems();
	this.updateSelectedItems();
}

GuiDisplayOneItem.setPadding = function(title) {
	switch (title) {
	case "Media Folders":
	case "Collections":
		if (this.ItemData.Items.length <= this.MAXCOLUMNCOUNT) {
			document.getElementById("Center").style.top = "110px";
		} else {
			document.getElementById("Center").style.top = "90px";
		}
		break;
	case "Music":
	case "Albums":
	case "Artists":
		break;
	default:
		if (this.ItemData.Items.length > this.MAXCOLUMNCOUNT * 2) {
			//3 Rows
			document.getElementById("Center").style.top = "60px";
		} else if (this.ItemData.Items.length > this.MAXCOLUMNCOUNT) {
			//2 Rows
			document.getElementById("Center").style.top = "110px";
		} else {
			//1 Row
			document.getElementById("Center").style.top = "90px";
		}
		break;
	}
}

GuiDisplayOneItem.returnFromMusicPlayer = function() {
	this.selectedItem = 0;
	this.updateDisplayedItems();
	this.updateSelectedItems();
}


text:
import { SIGNATURE as BALLS_DATA } from './balls/balls.signature';

/**
 * List of DataSignatures
 * @type {DataSignature[]}
 */
const DATA = [
    BALLS_DATA,
];

export {
    DATA,
};


text:
unless NewRelic::Control.instance['disable_memcache_instrumentation']

  def self.instrument_method(the_class, method_name)
    return unless the_class.method_defined? method_name.to_sym
    the_class.class_eval <<-EOD
        def #{method_name}_with_newrelic_trace(*args)
          metrics = ["MemCache/#{method_name}",
                     (NewRelic::Agent::Instrumentation::MetricFrame.recording_web_transaction? ? 'MemCache/allWeb' : 'MemCache/allOther')]
          self.class.trace_execution_scoped(metrics) do
            t0 = Time.now
            begin
              #{method_name}_without_newrelic_trace(*args)
            ensure
              #{memcache_key_snippet(method_name)}
            end
          end
        end
        alias #{method_name}_without_newrelic_trace #{method_name}
        alias #{method_name} #{method_name}_with_newrelic_trace
    EOD
      end

      def self.memcache_key_snippet(method_name)
        return "" unless NewRelic::Control.instance['capture_memcache_keys']
        "NewRelic::Agent.instance.transaction_sampler.notice_nosql(args.first.inspect, (Time.now - t0).to_f) rescue nil"
      end

  %w[get get_multi set add incr decr delete replace append prepend cas].each do | method_name |
    instrument_method(::MemCache, method_name) if defined? ::MemCache
    instrument_method(::Memcached, method_name) if defined? ::Memcached
    instrument_method(::Dalli::Client, method_name) if defined? ::Dalli::Client
  end

end


text:
package com.hanyee.androidlib.utils;

import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

/**
 * Created by Hanyee on 15/12/3.
 */
public class CheatSheetUtils {

    /**
     * The estimated height of a toast, in dips (density-independent pixels). This is used to
     * determine whether or not the toast should appear above or below the UI element.
     */
    private static final int ESTIMATED_TOAST_HEIGHT_DIPS = 48;

    /**
     * Sets up a cheat sheet (tooltip) for the given view by setting its {@link
     * View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with
     * the view's {@link View#getContentDescription() content description} will be
     * shown either above (default) or below the view (if there isn't room above it).
     *
     * @param view The view to add a cheat sheet for.
     */
    public static void setup(View view) {
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return show(view, view.getContentDescription());
            }
        });
    }

    /**
     * Sets up a cheat sheet (tooltip) for the given view by setting its {@link
     * View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with
     * the given text will be shown either above (default) or below the view (if there isn't room
     * above it).
     *
     * @param view      The view to add a cheat sheet for.
     * @param textResId The string resource containing the text to show on long-press.
     */
    public static void setup(View view, final int textResId) {
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return show(view, view.getContext().getString(textResId));
            }
        });
    }

    /**
     * Sets up a cheat sheet (tooltip) for the given view by setting its {@link
     * View.OnLongClickListener}. When the view is long-pressed, a {@link Toast} with
     * the given text will be shown either above (default) or below the view (if there isn't room
     * above it).
     *
     * @param view The view to add a cheat sheet for.
     * @param text The text to show on long-press.
     */
    public static void setup(View view, final CharSequence text) {
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return show(view, text);
            }
        });
    }

    /**
     * Removes the cheat sheet for the given view by removing the view's {@link
     * View.OnLongClickListener}.
     *
     * @param view The view whose cheat sheet should be removed.
     */
    public static void remove(final View view) {
        view.setOnLongClickListener(null);
    }

    /**
     * Internal helper method to show the cheat sheet toast.
     */
    private static boolean show(View view, CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            return false;
        }

        final int[] screenPos = new int[2]; // origin is device display
        final Rect displayFrame = new Rect(); // includes decorations (e.g. status bar)
        view.getLocationOnScreen(screenPos);
        view.getWindowVisibleDisplayFrame(displayFrame);

        final Context context = view.getContext();
        final int viewWidth = view.getWidth();
        final int viewHeight = view.getHeight();
        final int viewCenterX = screenPos[0] + viewWidth / 2;
        final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
        final int estimatedToastHeight = (int) (ESTIMATED_TOAST_HEIGHT_DIPS
                * context.getResources().getDisplayMetrics().density);

        Toast cheatSheet = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        boolean showBelow = screenPos[1] < estimatedToastHeight;
        if (showBelow) {
            // Show below
            // Offsets are after decorations (e.g. status bar) are factored in
            cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
                    viewCenterX - screenWidth / 2,
                    screenPos[1] - displayFrame.top + viewHeight);
        } else {
            // Show above
            // Offsets are after decorations (e.g. status bar) are factored in
            // NOTE: We can't use Gravity.BOTTOM because when the keyboard is up
            // its height isn't factored in.
            cheatSheet.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL,
                    viewCenterX - screenWidth / 2,
                    screenPos[1] - displayFrame.top - estimatedToastHeight);
        }

        cheatSheet.show();
        return true;
    }

    private CheatSheetUtils() {
    }
}


text:
The k-Maxoids Functionality
###########################

.. |br| raw:: html

   <br />

Descriptions of the basic functions are given below.

**Function descriptions:**

.. automodule:: k_maxoids
   :members:
   :member-order: bysource


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>OpenCV on Android: practices and tips | Dang-Khoa's blog</title>
    <link rel="stylesheet" href="/css/style.css" />
    <link rel="stylesheet" href="/css/fonts.css" />

Trang chủ

Docs

About Me

dangkhoasdc

Home

About

Categories

Tags

Subscribe

OpenCV on Android: practices and tips

2018/03/08

Transfer MAT objects from Android to NDK

The main idea is to use the address of an MAT object in order to manipulate
the data.

Basically, we have a function playing as a bridge between Java APIs and NDK:

public native void function_name(long matAddress);

To call the function, we use Mat’s address by calling getNativeObjAddr().
All computations in NDK will affect the content of MAT in both Java and
NDK layers.

In the NDK code, to use cv::Mat object regarding java Mat, we can use
static_cast:

Mat& im = *(static_cast<Mat*>(addrImg));

Notes

There is a huge different in image channels between Java OpenCV and NDK OpenCV.
When we decode the path or file to a bitmap in Java, we have to convert
the bitmap to ARGB_8888 color channel, otherwise it does not work. Actually,
it also can work on RGB_565 but for some reasons I can not remember, I always
use ARGB_8888 in the project.

Bitmap bm32_image = bm.copy(Bitmap.Config.ARGB_8888, true);

To manipulate the image correctly in NDK, we should covert it to the normal
RGB channel, otherwise sometimes we get some bugs making us frustrating.

// convert ARGB_8888 to RGB
Mat im = new Mat();
Mat rgb_im = new Mat();
Utils.bitmapToMat(bm32_image, im);
Imgproc.cvtcolor(im, rgb_im, Imgproc.COLOR_RGBA2RGB, 3);

function_name(rgb_im.getNativeObjAddr());

Other practice is to put some assertions in NDK code to make sure that we the
use the correct format for the input.

OpenCV’s Camera

OpenCV supports 3 types of camera:

CameraBridgeViewBase.

JavaCameraView.

CameraSurfaceGLView.

JavaCameraView

Create the layout of the camera. For example, we can put the following lines
to the Activity xml file:

<org.opencv.android.JavaCameraView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/opencvcamera_view"
></org.opencv.android.JavaCameraView>

Next, in the activity which controls the camera, we have to implement
required methods from the CvCameraViewLisener2. There 3 methods are:

onCameraViewStarted.

onCameraViewStopped.

onCameraFrame.

Prior to processing the camera, we need to initialize the variable holding
callbacks of three aforementioned methods:

private CameraBridgeViewBase mOpenCVCamera;

On the onCreate method:

    mOpenCVCamera = (CameraBridgeViewBase) findViewById(R.id.opencvcamera_view);
    mOpenCVCamera.setVisibility(CameraBridgeViewBase.VISIBLE);
    mOpenCVCamera.setCvCameraViewListener(this);

Next, we implement 3 required methods:

    @Override
    public void onCameraViewStarted(int width, int height) {
        // initialize images, variables, settings
    }

    @Override
    public void onCameraViewStopped() {
        // release the resources
    }

    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        // retrieve the frame from `inputFrame`
        // - the grayscale frame by imputFrame.gray()
        // - the RGBA frame by inputFrame.rgba()
        Mat im = inputFrame.rgba();

        // do things
        // postprocess: convert back to the RGBA image
        return im; // `im` will show in the UI
    }

Noting that OpenCV’s Camera is not able to set the portrait mode. One workaround
is to turn the Activity to landscape by putting the following line inside tag Activity
in AndroidManifest.xml

android:screenOrientation="landscape"

Data Manipulation

unsigned char Mat

It is troublesome when we want to assign a value of 255 to an unsigned char Mat
because this language does not support unsigned char as a primitive type.
One workaround is to allocate a 16S Mat, manipulate on that matrix, and
finally convert to 8U.

Point2f and Point

To convert MatOfPoint to MatOfPoint2f, we use the constructor:

MatOfPoint matofpoint = new MatOfPoint(matofpoint2f.toArray());

Accessing the pixel values

In order to retrieve and assign pixel value, we use the getter/setter from Mat.

short[] pixel = new short[nchannels];

m.get(i, j, pixel); // retrieve pixel values at (i, j)
// in this example, the pixel has 3 channels
pixel[0] = 255;
pixel[1] = 0;
pixel[2] = 125;
m.set(i, j, pixel);

  © [Dang-Khoa]() 2017 – 2019 | [Github]() | [Twitter]()


text:
import { ButtonProps } from "react-bootstrap/esm/Button";

export interface ISimpleButton {
  className?: string;
  disabled?: boolean;
  label: string;
  url?: string;
  isExternalUrl?: boolean;
  tooltip?: string;
  onClick?: () => void;
}

export interface IComponentButtonProps extends ButtonProps {
  props?: {
    item?: any;
  };
  label?: string;
  className?: string;
  iconClassName?: string;
}
export interface IComponentButton extends ButtonProps {
  Component: React.ComponentType<IComponentButtonProps>;
  values?: any;
}

export type ButtonItem = ISimpleButton | IComponentButton;

export const isComponentButton = (it: any): it is IComponentButton =>
  it != null && (it as IComponentButton).Component != null;


text:
#include "config.h"
#include "BooleanPrototype.h"

#include "Error.h"
#include "ExceptionHelpers.h"
#include "JSFunction.h"
#include "JSString.h"
#include "ObjectPrototype.h"

namespace JSC {

ASSERT_CLASS_FITS_IN_CELL(BooleanPrototype);

// Functions
static EncodedJSValue JSC_HOST_CALL booleanProtoFuncToString(ExecState*);
static EncodedJSValue JSC_HOST_CALL booleanProtoFuncValueOf(ExecState*);

// ECMA 15.6.4

BooleanPrototype::BooleanPrototype(ExecState* exec, JSGlobalObject* globalObject, Structure* structure, Structure* functionStructure)
    : BooleanObject(exec->globalData(), structure)
{
    setInternalValue(exec->globalData(), jsBoolean(false));

    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, globalObject, functionStructure, 0, exec->propertyNames().toString, booleanProtoFuncToString), DontEnum);
    putDirectFunctionWithoutTransition(exec, new (exec) JSFunction(exec, globalObject, functionStructure, 0, exec->propertyNames().valueOf, booleanProtoFuncValueOf), DontEnum);
}

// ------------------------------ Functions --------------------------

// ECMA 15.6.4.2 + 15.6.4.3

EncodedJSValue JSC_HOST_CALL booleanProtoFuncToString(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (thisValue == jsBoolean(false))
        return JSValue::encode(jsNontrivialString(exec, "false"));

    if (thisValue == jsBoolean(true))
        return JSValue::encode(jsNontrivialString(exec, "true"));

    if (!thisValue.inherits(&BooleanObject::s_info))
        return throwVMTypeError(exec);

    if (asBooleanObject(thisValue)->internalValue() == jsBoolean(false))
        return JSValue::encode(jsNontrivialString(exec, "false"));

    ASSERT(asBooleanObject(thisValue)->internalValue() == jsBoolean(true));
    return JSValue::encode(jsNontrivialString(exec, "true"));
}

EncodedJSValue JSC_HOST_CALL booleanProtoFuncValueOf(ExecState* exec)
{
    JSValue thisValue = exec->hostThisValue();
    if (thisValue.isBoolean())
        return JSValue::encode(thisValue);

    if (!thisValue.inherits(&BooleanObject::s_info))
        return throwVMTypeError(exec);

    return JSValue::encode(asBooleanObject(thisValue)->internalValue());
}

} // namespace JSC


text:
class BambooService < CiService
  include ReactiveService

  prop_accessor :bamboo_url, :build_key, :username, :password

  validates :bamboo_url, presence: true, public_url: true, if: :activated?
  validates :build_key, presence: true, if: :activated?
  validates :username,
    presence: true,
    if: ->(service) { service.activated? && service.password }
  validates :password,
    presence: true,
    if: ->(service) { service.activated? && service.username }

  attr_accessor :response

  after_save :compose_service_hook, if: :activated?
  before_update :reset_password

  def compose_service_hook
    hook = service_hook || build_service_hook
    hook.save
  end

  def reset_password
    if bamboo_url_changed? && !password_touched?
      self.password = nil
    end
  end

  def title
    s_('BambooService|Atlassian Bamboo CI')
  end

  def description
    s_('BambooService|A continuous integration and build server')
  end

  def help
    s_('BambooService|You must set up automatic revision labeling and a repository trigger in Bamboo.')
  end

  def self.to_param
    'bamboo'
  end

  def fields
    [
        { type: 'text', name: 'bamboo_url',
          placeholder: s_('BambooService|Bamboo root URL like https://bamboo.example.com'), required: true },
        { type: 'text', name: 'build_key',
          placeholder: s_('BambooService|Bamboo build plan key like KEY'), required: true },
        { type: 'text', name: 'username',
          placeholder: s_('BambooService|A user with API access, if applicable') },
        { type: 'password', name: 'password' }
    ]
  end

  def build_page(sha, ref)
    with_reactive_cache(sha, ref) {|cached| cached[:build_page] }
  end

  def commit_status(sha, ref)
    with_reactive_cache(sha, ref) {|cached| cached[:commit_status] }
  end

  def execute(data)
    return unless supported_events.include?(data[:object_kind])

    get_path("updateAndBuild.action", { buildKey: build_key })
  end

  def calculate_reactive_cache(sha, ref)
    response = get_path("rest/api/latest/result/byChangeset/#{sha}")

    { build_page: read_build_page(response), commit_status: read_commit_status(response) }
  end

  private

  def get_build_result(response)
    return if response.code != 200

    # May be nil if no result, a single result hash, or an array if multiple results for a given changeset.
    result = response.dig('results', 'results', 'result')

    # In case of multiple results, arbitrarily assume the last one is the most relevant.
    return result.last if result.is_a?(Array)

    result
  end

  def read_build_page(response)
    result = get_build_result(response)
    key =
      if result.blank?
        # If actual build link can't be determined, send user to build summary page.
        build_key
      else
        # If actual build link is available, go to build result page.
        result.dig('planResultKey', 'key')
      end

    build_url("browse/#{key}")
  end

  def read_commit_status(response)
    return :error unless response.code == 200 || response.code == 404

    result = get_build_result(response)
    status =
      if result.blank?
        'Pending'
      else
        result.dig('buildState')
      end

    return :error unless status.present?

    if status.include?('Success')
      'success'
    elsif status.include?('Failed')
      'failed'
    elsif status.include?('Pending')
      'pending'
    else
      :error
    end
  end

  def build_url(path)
    Gitlab::Utils.append_path(bamboo_url, path)
  end

  def get_path(path, query_params = {})
    url = build_url(path)

    if username.blank? && password.blank?
      Gitlab::HTTP.get(url, verify: false, query: query_params)
    else
      query_params[:os_authType] = 'basic'
      Gitlab::HTTP.get(url,
                       verify: false,
                       query: query_params,
                       basic_auth: {
                         username: username,
                         password: password
                       })
    end
  end
end


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ons;

import java.io.File;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Centralizes the simulation execution. Defines what the command line
 * arguments do, and extracts the simulation information from the XML file.
 *
 * @author andred
 */
public class Simulator {

    private static String simName;
    private static final Float simVersion = new Float(0.3);
    public static boolean verbose = false;
    public static boolean trace = false;

    /**
     * Executes simulation based on the given XML file and the used command line arguments.
     *
     * @param simConfigFile name of the XML file that contains all information about the simulation
     * @param trace activates the Tracer class functionalities
     * @param verbose activates the printing of information about the simulation, on runtime, for debugging purposes
     * @param load range of loads for which several simulations are automated; if not specified, load is taken from the XML file
     * @param seed a number in the interval [1,25] that defines up to 25 different random simulations
     */
    public void Execute(String simConfigFile, boolean trace, boolean verbose, double load, int seed) {

        Simulator.verbose = verbose;
        Simulator.trace = trace;

        if (Simulator.verbose) {
            System.out.println("########################################################");
            System.out.println("# Optical Networks Simulator - version " + simVersion.toString() + "  #");
            System.out.println("#######################################################\n");
        }

        try {

            long begin = System.currentTimeMillis();

            if (Simulator.verbose) {
                System.out.println("(0) Accessing simulation file " + simConfigFile + "...");
            }
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(simConfigFile));

            // normalize text representation
            doc.getDocumentElement().normalize();

            // check the root TAG name and version
            int simType = -1;
            simName = doc.getDocumentElement().getTagName();
            System.out.println("Valor do simName antes do switch: "+simName);//TEST
            switch (simName) {
                case "wdmsim":
                    if(Simulator.verbose)
                        System.out.println("Simulation type: " + simName + " (Fixed)");
                    simType = 0;
                    System.out.println("**** simType = 0 ------> wdmsim");//TEST
                    break;
                case "eonsim":
                    System.out.println("Valor do simulador: "+Simulator.verbose);
                    if(Simulator.verbose)
                        System.out.println("Simulation type: " + simName + " (Elastic)");
                    simType = 1;
                    System.out.println("**** simType = 1 ------> eonsim");//TEST
                    break;
                default:
                    System.out.println("Root element of the simulation file is " + doc.getDocumentElement().getNodeName() + ", eonsim or wdmsim is expected!");
                    System.exit(0);
            }

            if (!doc.getDocumentElement().hasAttribute("version")) {
                System.out.println("Cannot find version attribute!");
                System.exit(0);
            }
            if (Float.compare(new Float(doc.getDocumentElement().getAttribute("version")), simVersion) > 0) {
                System.out.println("Simulation config file requires a newer version of the simulator!");
                System.exit(0);
            }
            if (Simulator.verbose) {
                System.out.println("(0) Done. (" + Float.toString((float) ((float) (System.currentTimeMillis() - begin) / (float) 1000)) + " sec)\n");
            }

            /*
             * Extract physical topology part
             */
            begin = System.currentTimeMillis();
            if (Simulator.verbose) {
                System.out.println("(1) Loading physical topology information...");
            }

            PhysicalTopology pt;
            if (simType == 0){
            	pt = new WDMPhysicalTopology((Element) doc.getElementsByTagName("physical-topology").item(0));
                System.out.println("pt simType=0 para wdm");
            } else{
            	pt = new EONPhysicalTopology((Element) doc.getElementsByTagName("physical-topology").item(0));
                System.out.println("***++++ pt simType=1 para eon ..nova pt instanciada para eon");
            }

            if (Simulator.verbose) {
                System.out.println(pt);
            }

            if (Simulator.verbose) {
                System.out.println("(1) Done. (" + Float.toString((float) ((float) (System.currentTimeMillis() - begin) / (float) 1000)) + " sec)\n");
            }

            /*
             * Extract virtual topology part
             */
            begin = System.currentTimeMillis();
            if (Simulator.verbose) {
                System.out.println("(2) Loading virtual topology information...");
            }

            VirtualTopology vt = new VirtualTopology((Element) doc.getElementsByTagName("virtual-topology").item(0), pt);

            if (Simulator.verbose) {
                System.out.println(vt);
            }

            if (Simulator.verbose) {
                System.out.println("(2) Done. (" + Float.toString((float) ((float) (System.currentTimeMillis() - begin) / (float) 1000)) + " sec)\n");
            }

            /*
             * Extract simulation traffic part
             */
            begin = System.currentTimeMillis();
            if (Simulator.verbose) {
                System.out.println("(3) Loading traffic information...");
            }

            EventScheduler events = new EventScheduler();
            TrafficGenerator traffic = new TrafficGenerator((Element) doc.getElementsByTagName("traffic").item(0), load);
            traffic.generateTraffic(pt, events, seed);

            if (Simulator.verbose) {
                System.out.println("(3) Done. (" + Float.toString((float) ((float) (System.currentTimeMillis() - begin) / (float) 1000)) + " sec)\n");
            }

            /*
             * Extract simulation setup part
             */
            begin = System.currentTimeMillis();
            if (Simulator.verbose) {
                System.out.println("(4) Loading simulation setup information...");
            }

            MyStatistics st = MyStatistics.getMyStatisticsObject();
            st.statisticsSetup(pt.getNumNodes(), 3, 0);

            Tracer tr = Tracer.getTracerObject();
            if (Simulator.trace == true)
            {
            	if (load == 0) {
                	tr.setTraceFile(simConfigFile.substring(0, simConfigFile.length() - 4) + ".trace");
            	} else {
                	tr.setTraceFile(simConfigFile.substring(0, simConfigFile.length() - 4) + "_Load_" + Double.toString(load) + ".trace");
            	}
            }
            tr.toogleTraceWriting(Simulator.trace);

            String raModule;
            raModule = "ons.ra." + ((Element) doc.getElementsByTagName("ra").item(0)).getAttribute("module");
            //raModule =(Element) doc.getElementsByTagName("ra").item(0).getAttributes(");
            System.out.println("Impressão do raModule: "+raModule);
            if (Simulator.verbose) {
                System.out.println("RA module: " + raModule);
            }
            ControlPlane cp = new ControlPlane(raModule, pt, vt);

            if (Simulator.verbose) {
                System.out.println("(4) Done. (" + Float.toString((float) ((System.currentTimeMillis() - begin) / (float) 1000)) + " sec)\n");
            }

            /*
             * Run the simulation
             */
            begin = System.currentTimeMillis();
            if (Simulator.verbose) {
                System.out.println("(5) Running the simulation...");
            }

            SimulationRunner sim = new SimulationRunner(cp, events);

            if (Simulator.verbose) {
                System.out.println("(5) Done. (" + Float.toString((float) ((float) (System.currentTimeMillis() - begin) / (float) 1000)) + " sec)\n");
            }

            if (Simulator.verbose) {
                if (load == 0) {
                    System.out.println("Statistics (" + simConfigFile + "):\n");
                } else {
                    System.out.println("Statistics for " + Double.toString(load) + " erlangs (" + simConfigFile + "):\n");
                }
                System.out.println(st.fancyStatistics());
            } else {
                System.out.println("*****");
                if (load != 0) {
                    System.out.println("Load:" + Double.toString(load));
                }
                st.printStatistics();
            }

            // Terminate MyStatistics singleton
            st.finish();

            // Flush and close the trace file and terminate the singleton
            if (Simulator.trace == true){
                tr.finish();
            }

        } catch (SAXParseException err) {
            System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
            System.out.println(" " + err.getMessage());

        } catch (SAXException e) {
            Exception x = e.getException();
            ((x == null) ? e : x).printStackTrace();

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}


text:
from __future__ import absolute_import, print_function

import os
import shlex
import subprocess
import textwrap
import re

from . import util, factory, node, runtime
from .runtime import LOG, CONF

# proxy-create command

def create_ssh_keypair(keyname, comment):
    """Create a new ssh keypair."""
    sshdir = os.path.join(util.get_homedir(), '.ssh')
    util.create_directory(sshdir, 0o700)
    keyfile = os.path.join(sshdir, keyname)
    if util.try_stat(keyfile):
        raise RuntimeError('~/.ssh/{} already exists'.format(keyname))
    subprocess.check_call(['ssh-keygen', '-f', keyfile, '-N', "", '-q', '-C', comment])
    os.chmod(keyfile, 0o600)
    os.chmod(keyfile + '.pub', 0o644)
    return keyfile

def create_proxy(proxyname):
    """Create a proxy wrapper."""
    # Running in a software collection?
    enable_scls = []
    scls = os.environ.get('X_SCLS', '')
    for scl in scls.split():
        with open('/etc/scl/conf/{}'.format(scl)) as fin:
            prefix = fin.readline().rstrip()
        enable_scls.append('. {}/{}/enable'.format(prefix, scl))
    if scls:
        enable_scls.append('X_SCLS={}'.format(shlex.quote(scls)))
        enable_scls.append('export X_SCLS')
    else:
        enable_scls.append('# No software collections enabled.')
    enable_scls = '\n'.join(enable_scls)
    # Running in a virtualenv?
    venv = os.environ.get('VIRTUAL_ENV')
    enable_venv = '. {}/bin/activate'.format(venv) if venv else '# No virtualenv enabled.'
    # Create the ~/bin directory if needed
    bindir = os.path.join(util.get_homedir(), 'bin')
    proxyfile = os.path.join(bindir, proxyname)
    util.create_directory(bindir, 0o755)
    contents = textwrap.dedent("""\
            #!/bin/sh
            {}
            {}
            exec python -mravstack.proxy
            """).format(enable_scls, enable_venv)
    with open(proxyfile, 'w') as fout:
        fout.write(contents)
    os.chmod(proxyfile, 0o700)
    return proxyfile

def install_proxy(pubkey, command):
    """Add a public key to the authorized_keys file."""
    with open(pubkey) as fin:
        keydata = fin.read()
    sshdir = os.path.join(util.get_homedir(), '.ssh')
    authentry = 'no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding'
    authentry += ',command="{}",from="127.0.0.1,::1" '.format(command)
    authentry += keydata
    authfile = os.path.join(sshdir, 'authorized_keys')
    with open(authfile, 'a') as fout:
        fout.write(authentry)
    os.chmod(authfile, 0o600)

def test_proxy(keyfile):
    """Test the proxy."""
    # This also has the benefit that the host key is added to the known hosts file.
    subprocess.check_call(['ssh', '-q', '-o', 'StrictHostKeyChecking=no', '-i', keyfile,
                           'localhost', 'true'])

def do_create(env):
    """The `ravstack proxy-create` command."""
    keyname = env.config['proxy']['key_name']
    proxyname = env.config['proxy']['proxy_name']
    keyfile = create_ssh_keypair(keyname, proxyname)
    proxyfile = create_proxy(proxyname)
    install_proxy(keyfile + '.pub', proxyfile)
    test_proxy(keyfile)
    print('Private key created as: `~/.ssh/{}`.'.format(keyname))
    print('Proxy created at: `~/bin/{}`.'.format(proxyname))

# proxy-run command

# These are the virsh commands used by the ssh power driver in Ironic.
# They need to match and be kept up to date with the following file:
# https://github.com/openstack/ironic/blob/master/ironic/drivers/modules/ssh.py#L151

_virsh_commands = [
    ('true', re.compile('^true$')),
    ('start', re.compile(' start ([^ ]+)')),
    ('stop', re.compile(' destroy ([^ ]+)')),
    ('reboot', re.compile(' reset ([^ ]+)')),
    ('get_node_macs', re.compile(' dumpxml ([^ ]+) .*mac')),
    ('list_running', re.compile(' list --all.*running')),
    ('list_all', re.compile(' list --all')),
    ('get_boot_device', re.compile(' dumpxml ([^ ]+) .*boot')),
    ('set_boot_device', re.compile(r'boot dev=\\"([^\\]+)\\".* edit ([^ ]+)')),
]

def parse_virsh_command_line(command):
    """Parse the virsh command line.

    The proxy script is run as a forced command specified in an ssh private
    key. The original command is available in the $SSH_ORIGINAL_COMMAND
    environment variable.
    """
    for cmd, regex in _virsh_commands:
        match = regex.search(command)
        if match:
            return (cmd,) + match.groups()
    raise RuntimeError('unrecognized command: {}'.format(command))

def main():
    """Proxy main function."""
    args = {'--cached': True}
    CONF.update_from_args(args)

    # Make sure we are running under SSH.
    conn = os.environ.get('SSH_CONNECTION', '?:?')
    if conn is None:
        raise RuntimeError('This command needs to be run through ssh.')

    # Add connection info the the logs.
    cp = conn.split()
    context = '{}:{}'.format('' if cp[0] in ('127.0.0.1', '::1') else cp[0], cp[1])
    runtime.setup_logging(context)

    # Parse the original command to understand what we need to do.
    command = os.environ.get('SSH_ORIGINAL_COMMAND')
    LOG.debug('New request, command = {}'.format(command))
    cmdline = parse_virsh_command_line(command)
    LOG.info('Parsed command: {}'.format(' '.join(cmdline)))

    env = factory.get_environ(args)

    if cmdline[0] == 'true':
        pass
    elif cmdline[0] == 'start':
        node.do_start(env, cmdline[1])
    elif cmdline[0] == 'stop':
        node.do_stop(env, cmdline[1])
    elif cmdline[0] == 'reboot':
        node.do_reboot(env, cmdline[1])
    elif cmdline[0] == 'list_running':
        node.do_list_running(env, True)
    elif cmdline[0] == 'list_all':
        node.do_list_all(env)
    elif cmdline[0] == 'get_boot_device':
        node.do_get_boot_device(env, cmdline[1])
    elif cmdline[0] == 'set_boot_device':
        node.do_set_boot_device(env, cmdline[2], cmdline[1])
    elif cmdline[0] == 'get_node_macs':
        node.do_get_macs(env, cmdline[1], True)

if __name__ == '__main__':
    runtime.run_main(main)


text:
import benchexec.tools.cpachecker as cpachecker

class Tool(cpachecker.Tool):
    """Tool info for CoVeriTest."""

    REQUIRED_PATHS = list(cpachecker.Tool.REQUIRED_PATHS) + ["resources"]

    def name(self):
        return "CoVeriTest"


text:
var vue = new Vue({
      el: '#app',
      delimiters:['{[', ']}'],
      data:{
          keyword:"",
          page:1,
          pages:{},
          plugins:[]
      },
      filters: {
            formatDate: function (time) {
              if(time){
                return formatDate(time, "yyyy-MM-dd hh:mm:ss");
              }
              return "";
            }
      }
    })

    // 加载完页面执行
    $(document).ready(function(){
        var page = $("#page").attr("content");
        vue.page = page?page:vue.page;
        var keyword = $("#keyword").attr("content");
        vue.keyword = keyword?keyword:vue.keyword;
        get_plugins(vue.page,vue.keyword);
    })

    function get_plugins(page, keyword){
        vue.keyword = keyword;
        vue.page = page;
        d = {
            page:page,
            keyword:keyword
        }

        var result = osrHttp("GET","/api/admin/plugin", d, args={not_prompt:true});
        result.then(function (r) {
            vue.plugins = r.data.plugins;
            vue.pages = paging(page_total=vue.plugins.page_total,
                            current_page=vue.plugins.current_page);

        });

        var url = window.location.pathname+"?page="+page;
        if(vue.keyword){
            url = url + "&keyword="+vue.keyword;
        }
        history_state(title=null,url=url);
    }

    function operation_plugin(operation, name){

        if(operation=="delete"){
            d = {
                name:name
            }
            var result = osrHttp("DELETE","/api/admin/plugin", d);

        }else if(operation){
            d = {
                action:operation,
                name:name
            }
            var result = osrHttp("PUT","/api/admin/plugin", d);

        }

        result.then(function (r) {
            if(r.data.msg_type=='s'){
                get_plugins(vue.page, vue.keyword);
            }
        }).catch(function (r) {
           get_plugins(vue.page, vue.keyword);
        });

    }

    function upload_plugin(){
        var formData = new FormData();
        var name = $("#upfile").attr("name");
        formData.append("upfile", $("#upfile")[0].files[0]);

        var result = osrHttpUpload("POST","/api/admin/plugin", formData);
        result.then(function (r) {
            if(r.data.msg_type=="s"){
                get_plugins(vue.page, vue.keyword);
            }
        });
    }

    $(function() {
        $('#upfile').on('change', function() {
          var fileNames = '';
          $.each(this.files, function() {
            fileNames += '' + this.name + ' ';
          });
          $('#file-list').html(fileNames);
        });
    });


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Response
{
    /// <summary>
    /// AlipayOfflineMaterialImageQueryResponse.
    /// </summary>
    public class AlipayOfflineMaterialImageQueryResponse : AopResponse
    {
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Herb. Fr. 9: tab. 386 (1787)

#### Original name
Tremella cerebrina-alba Bull.

### Remarks
null


text:
' Copyright (c) Xun Zhang
' http://www.zhangxun.com
' mailto:zhangxun_service@hotmail.com
' Creation Date: 2015/3/17

Namespace zxweb.xtag

'*******************************************************************************
'

Public Class XTag
	Inherits AbstractTag

'*****************
'	Life cycle
'
'*****************

'XX obsolete
Public Sub New( _
	inkey As String, _
	Optional isHaveParams As Boolean = True _
)
	Keyword = inkey
	Name = inkey

	If isHaveParams Then
		setArgOptional()
	Else
		setNoArg()
	End If

	init()
End Sub

Public Sub New( _
	inkey As String, _
	argType As EnumArgType _
)
	Keyword = inkey
	Name = inkey

	setArgType(argType)

	init()
End Sub

Private Sub init()
	If Keyword = "" Then Return 'XX

	HeaderBeginMark = "[" & Keyword
	Footer = "[/" & Keyword & "]"

	If isMustHaveArgs() Then
		HeaderBeginMark &= "="
	End If

	HeaderClosingMark = "]"
	CompactHeaderClosingMark = "/]" '!! not have the empty char
End Sub

'***************
'	Services
'
'***************

' Used by: program, imgex
'
'XX support param name like 'boxHeight='
Public Function getBoxStyle( _
	Optional isAutoCalc As Boolean = False, _
	Optional defidx As Integer = -1, _
	Optional more As String = "" _
) As String
	Dim rsltbh As String = ""
	Dim params As ArrayList = getParamList()

	Dim boxheight As String = getParam("boxh", defidx)
	If boxheight = "" And isAutoCalc Then
		Try
			Dim ctenth As Integer = CInt(getParam("h")) 'XX
			If ctenth > 0 Then boxheight = ctenth + 30
		Catch ex As Exception
		End Try
	End If

	If boxheight <> "" Then
		rsltbh = "style='height: " & boxheight & "px;" & more & "'" 'XX
	End If

	Return rsltbh
End Function

End Class 'XTag

End Namespace


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.householder.cam-control</groupId>
	<artifactId>cam-control</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Cam Controller</name>
	<description>JavaFx lib. for simple cam control</description>
	<url>http://householder.net/cam-control</url>

	<licenses>
		<license>
			<name>Apache License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<url>scm:git:https://github.com/QwaQ/cam-control/</url>
	</scm>

	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>

	</dependencies>

</project>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

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

    function get_ListOfOrg()
    {
        $this->db->select('*');
        $this->db->from('organizations');

        $query = $this->db->get();
        return $query->result_array();
    }

}
?>


text:
namespace cc {

namespace {

bool IsTestCaseSupported(PixelResourceTestCase test_case) {
  switch (test_case) {
    case SOFTWARE:
    case GL_GPU_RASTER_2D_DRAW:
    case GL_ZERO_COPY_2D_DRAW:
    case GL_ZERO_COPY_RECT_DRAW:
    case GL_ONE_COPY_2D_STAGING_2D_DRAW:
    case GL_ONE_COPY_RECT_STAGING_2D_DRAW:
      return true;
    case GL_ZERO_COPY_EXTERNAL_DRAW:
    case GL_ONE_COPY_EXTERNAL_STAGING_2D_DRAW:
      // These should all be enabled in practice.
      // TODO(enne): look into getting texture external oes enabled.
      return false;
  }

  NOTREACHED();
  return false;
}

}  // namespace

LayerTreeHostPixelResourceTest::LayerTreeHostPixelResourceTest(
    PixelResourceTestCase test_case)
    : draw_texture_target_(GL_INVALID_VALUE),
      raster_buffer_provider_type_(RASTER_BUFFER_PROVIDER_TYPE_BITMAP),
      texture_hint_(ResourceProvider::TEXTURE_HINT_IMMUTABLE),
      initialized_(false),
      test_case_(test_case) {
  InitializeFromTestCase(test_case);
}

LayerTreeHostPixelResourceTest::LayerTreeHostPixelResourceTest()
    : draw_texture_target_(GL_INVALID_VALUE),
      raster_buffer_provider_type_(RASTER_BUFFER_PROVIDER_TYPE_BITMAP),
      initialized_(false),
      test_case_(SOFTWARE) {}

void LayerTreeHostPixelResourceTest::InitializeFromTestCase(
    PixelResourceTestCase test_case) {
  DCHECK(!initialized_);
  initialized_ = true;
  switch (test_case) {
    case SOFTWARE:
      test_type_ = PIXEL_TEST_SOFTWARE;
      draw_texture_target_ = GL_INVALID_VALUE;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_BITMAP;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
    case GL_GPU_RASTER_2D_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_2D;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_GPU;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE_FRAMEBUFFER;
      return;
    case GL_ONE_COPY_2D_STAGING_2D_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_2D;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
    case GL_ONE_COPY_RECT_STAGING_2D_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_2D;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
    case GL_ONE_COPY_EXTERNAL_STAGING_2D_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_2D;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
    case GL_ZERO_COPY_2D_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_2D;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
    case GL_ZERO_COPY_RECT_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_RECTANGLE_ARB;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
    case GL_ZERO_COPY_EXTERNAL_DRAW:
      test_type_ = PIXEL_TEST_GL;
      draw_texture_target_ = GL_TEXTURE_EXTERNAL_OES;
      raster_buffer_provider_type_ = RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY;
      texture_hint_ = ResourceProvider::TEXTURE_HINT_IMMUTABLE;
      return;
  }
  NOTREACHED();
}

void LayerTreeHostPixelResourceTest::CreateResourceAndRasterBufferProvider(
    LayerTreeHostImpl* host_impl,
    std::unique_ptr<RasterBufferProvider>* raster_buffer_provider,
    std::unique_ptr<ResourcePool>* resource_pool) {
  base::SingleThreadTaskRunner* task_runner =
      task_runner_provider()->HasImplThread()
          ? task_runner_provider()->ImplThreadTaskRunner()
          : task_runner_provider()->MainThreadTaskRunner();
  DCHECK(task_runner);
  DCHECK(initialized_);

  ContextProvider* compositor_context_provider =
      host_impl->compositor_frame_sink()->context_provider();
  ContextProvider* worker_context_provider =
      host_impl->compositor_frame_sink()->worker_context_provider();
  ResourceProvider* resource_provider = host_impl->resource_provider();
  int max_bytes_per_copy_operation = 1024 * 1024;
  int max_staging_buffer_usage_in_bytes = 32 * 1024 * 1024;

  // Create resource pool.
  *resource_pool =
      ResourcePool::Create(resource_provider, task_runner, texture_hint_,
                           ResourcePool::kDefaultExpirationDelay);

  switch (raster_buffer_provider_type_) {
    case RASTER_BUFFER_PROVIDER_TYPE_BITMAP:
      EXPECT_FALSE(compositor_context_provider);
      EXPECT_EQ(PIXEL_TEST_SOFTWARE, test_type_);

      *raster_buffer_provider =
          BitmapRasterBufferProvider::Create(resource_provider);
      break;
    case RASTER_BUFFER_PROVIDER_TYPE_GPU:
      EXPECT_TRUE(compositor_context_provider);
      EXPECT_TRUE(worker_context_provider);
      EXPECT_EQ(PIXEL_TEST_GL, test_type_);

      *raster_buffer_provider = base::MakeUnique<GpuRasterBufferProvider>(
          compositor_context_provider, worker_context_provider,
          resource_provider, false, 0, false);
      break;
    case RASTER_BUFFER_PROVIDER_TYPE_ZERO_COPY:
      EXPECT_TRUE(compositor_context_provider);
      EXPECT_EQ(PIXEL_TEST_GL, test_type_);

      *raster_buffer_provider = ZeroCopyRasterBufferProvider::Create(
          resource_provider, PlatformColor::BestTextureFormat());
      break;
    case RASTER_BUFFER_PROVIDER_TYPE_ONE_COPY:
      EXPECT_TRUE(compositor_context_provider);
      EXPECT_TRUE(worker_context_provider);
      EXPECT_EQ(PIXEL_TEST_GL, test_type_);

      *raster_buffer_provider = base::MakeUnique<OneCopyRasterBufferProvider>(
          task_runner, compositor_context_provider, worker_context_provider,
          resource_provider, max_bytes_per_copy_operation, false,
          max_staging_buffer_usage_in_bytes, PlatformColor::BestTextureFormat(),
          false);
      break;
  }
}

void LayerTreeHostPixelResourceTest::RunPixelResourceTest(
    scoped_refptr<Layer> content_root,
    base::FilePath file_name) {
  if (!IsTestCaseSupported(test_case_))
    return;
  RunPixelTest(test_type_, content_root, file_name);
}

ParameterizedPixelResourceTest::ParameterizedPixelResourceTest()
    : LayerTreeHostPixelResourceTest(GetParam()) {
}

}  // namespace cc


text:
from webob.datetime_utils import *
from webob.request import *
from webob.response import *
from webob.util import html_escape

__all__ = [
    'Request', 'LegacyRequest', 'Response', 'UTC', 'day', 'week', 'hour',
    'minute', 'second', 'month', 'year', 'html_escape'
]

BaseRequest.ResponseClass = Response


text:
(function($, window, document, undefined){
	// 'use strict';

	$.fn.genieCollapse = function(target, directions, step_quantum, callback){
		window.genie.collapse(this[0], target[0], directions, step_quantum, callback);
		return this;
	};

	$.fn.genieExpand = function(target, directions, step_quantum, callback,callback2){
		window.genie.expand(this[0], target[0], directions, step_quantum, callback,callback2);
		return this;
	};

	$.fn.htmlGenieCollapse = function(target, directions, step_quantum, callback){
		var src = $(this);
		if(typeof step_quantum === "function"){
			callback = step_quantum;
			step_quantum = null;
		}
		html2canvas(src[0], {
			onrendered: function(canvas){
				var png = canvas.toDataURL("image/png"),
					width = src.outerWidth(),
					height = src.outerHeight(),
					top = src.position().top,
					img = $('

'),
					endCallback = function(){
						$(this).remove();
						if(typeof callback === "function")
							callback.call(src);
					};
				img.css({
					'height': height + 'px',
					'width': width + 'px',
					'background-image': "url('" + png + "')",
					'background-position': '0px 0px',
					'position': 'absolute',
					'top': top,
					'display': 'block'
				});
				src.replaceWith(img);
				img.genieCollapse(target, directions, step_quantum, endCallback);
			}
		});
		return this;
	};

	$.fn.htmlGenieExpand = function(target, element, directions, step_quantum, callback){
		var src = $(this);
		if(typeof step_quantum === "function"){
			callback = step_quantum;
			step_quantum = undefined;
		}
		html2canvas(element[0], {
			onrendered: function(canvas){
				var png = canvas.toDataURL("image/png"),
					width = element.outerWidth(),
					height = element.outerHeight(),
					img = $('

'),
					endCallback = function(){
						img.remove();
						target.css({
							'background-image': '',
							'background-position': ''
						});
						target[0].innerHTML = element.clone().html();
						if(typeof callback === "function"){
							callback.call(target);
						}
					};
				//console.log(png);
				img.css({
					'height': 'inherit',
					'width': 'inherit',
					'background-image': "url('" + png + "')",
					'background-position': '0px 0px',
				});
				target.empty();
				src.append(img);
				img.genieExpand(target, directions, step_quantum, endCallback);
			}
		});
		return this;
	};

	$.fn.urlGenieExpand = function(target, url, directions, step_quantum, callback){
		var src = $(this);
		if(typeof step_quantum === "function"){
			callback = step_quantum;
			step_quantum = undefined;
		}
		var img = $('

');
		img.css({
			'height': 'inherit',
			'width': 'inherit',
			'background-image': "url('" + url + "')",
			'background-position': '0px 0px',
		});
		target.empty();
		src.append(img);
		img.genieExpand(target, directions, step_quantum, function(){
			if(typeof callback === "function"){
				callback.call(target);
			}
		});

		return this;
	};
})(jQuery, window, document);


text:
<!DOCTYPE html>

		<title>three.js webgl - Multiple Render Targets</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

			threejs webgl - Multiple RenderTargets


text:
---
title: "Approaches to modern web development"
description: "This article provides tips for good modern web development."
synopsis: "I talk about some caveats and provide tips to create and maintain modern web applications."
date: "2017-05-24"
author: "Matt Finucane"
identifier: "blog"
sponsored: false
disqus: true
uniqueid: 4051171474
categories:
- Javascript
- PolymerJS
- MeteorJS
---

## Introduction
When it comes to building web applications, I have been using single page Javascript based frameworks. In this article I will cover their basic concepts, benefits and drawbacks.

## What are single page applications?
To explain this, I first need to explain how traditional web applications have always worked.

In the traditonal sense, a full stack server side application always needed to generate all the data for a website on the server, then send this down to the client before the page could be rendered.

Content would be fetched from a database, passed through a controller and then merged with a view template before it was sent.

This would manifest itself in the form of the page reloading each time you navigated a website or application. Javascript had a minimal role and was responsible for controlling small parts of the UI.

Five years ago, single page applications started becoming more popular. A single page application makes a request to the server for a skeleton of a HTML file, along with scripts and styles.

Subsequent requests are made to the server in the form of Ajax requests. The HTML content of the page itself is rendered using Javascript and styled with CSS.

As we navigate the site we only fetch a subset of the content we need as opposed to the entire page, meaning a faster UI and less server load.

These are the most popular Javascript based single page application frameworks:

- [PolymerJS](https://www.polymer-project.org/) which is a client side framework and wrapper for [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components).
- [MeteorJS](https://www.meteor.com) is a full stack framework backed by NodeJS and MongoDB. It uses Blaze, Angular and React for templating.
- [ReactJS](https://facebook.github.io/react/) is a componentised client side library for building web applications.
- [EmberJS](https://www.emberjs.com/) is a client side library for building web applications and uses the Handlebars templating engine.
- [AngularJS](https://angularjs.org/) is another client library that attaches to static HTML with a set of its own attributes for data binding.

Single page applications create boundaries between content, presentation and logic. For MVC frameworks, the whole point is separation of concerns. Loosely coupled components are easier to maintain.

Content is usually delivered in [JSON](www.json.org/) format using [REST](https://en.wikipedia.org/wiki/Representational_state_transfer).

Presentation is controlled by HTML templates that contain templating tags to carry out common tasks such as iterating over a dataset.

Controllers are responsible for handling requests and sending data back to the application. These requests are handled using HTTP and WebSockets.

## A small server side example
To demonstrate how this all works, this small example shows how we would fetch and render a list of users.

Let's start with the `server side controller` which will fetch the users and return a list of them in JSON format.
```
/**
 *	Users controller (NodeJS)
 */
const app = express(),

/**
 *	This function fetches users
 *	from the MongoDB collection
 */
const fetchUsers = (offset = 0, limit = 10) => {
	return new Promise((resolve, reject) => {
		Users.find({}, {
			$offset: offset,
			$limit: limit
		}).then((result) => {
			if(error) {
				reject(error);
			}
			else {
				resolve(result);
			}
		});
	});
};

/**
 *	This function returns a list
 *	of users in JSON format.
 */
app.get('/admin/users', (request, response) => {
	fetchUsers()
	.then((result) => {
		response.status(200).json(result);
	})
	.catch((error) => {
		response.status(500).json(error);
	});
});
```

If we make a request to the server to fetch some users from `https://my-server/admin/users` then we should expect the following response:

```
[
	{
		"name":"Matt",
		"location":"Berlin"
	},
	{
		"name":"Joe",
		"location":"Dublin"
	},
	{	"name":"Phil",
		"location":"London"
	},
	{	"name":"Damien",
		"location":"Toulouse"
	}
]
```

## How things work client side
If we were using a client side controller, it would look something like this:

```
Template.users = {
	/**
	 *	Array to store a list
	 *	of users.
	 */
	users: [],

	/**
	 *	This is an event that fires
	 *	when a template is ready.
	 */
	ready: () => {
		fetchUsers();
	},

	/**
	 *	Make an AJAX request to
	 *	fetch a list of users.
	 */
	fetchUsers: () => {
		let request = new XMLHttpRequest(),
			url 	= 'https://my-server/admin/users'

		/**
		 *	We make the request...
		 */
		request.open('GET', url, true);

		/**
		 *	When the request has completed...
		 */
		request.onload = () => {
			/**
			 *	We check the response status code
			 *	to make sure everything worked ok...
			 */
			if(request.status === 200) {
				/**
				 *	Then we assign the response
				 *	to the list of users.
				 */
				this.users = JSON.parse(request.responseText);
			}
		};
	}
};
```

To render a user, we would need to create a template for them that could look like the following:

```
<template name="user">
	<li>
		{{ name }} is in {{ location }}.
	</li>
</template>
```

Our view template to render a list of users might look like this:

```
<html>
	<head>
		<title>
			Single Page Application | Users
		</title>
	</head>
	<body>
		<ul class="list-of-users">
			{{ each users }}
				{{> user }}
			{{ end }}
		</ul>
	</body>
</html>
```

When the browser has initially rendered the template, it calls on the controller for that template to fetch the users. When the users have been fetched they are automatically rendered into a list.

## Concepts of single page applications
Here we will cover the basics of some of the concepts you will see if you are new to client side Javascript development.

### Controllers
In client side development, a controller is responsible for the managing the data between a server and the view it is attached to. It also contains functionality to deal with UI behaviours.

### Templates
Templates are HTML files that contain special tags to make it easier to render content. Standard HTML does not deal with rendering content in loops which makes sense considering it's not a language but a markup for presenting content.

### Views
Templates and views are almost the same, but a view is the overall collection of different component templates that are put together the whole page.

### Binding
Binding is a process where rendered content in a view updates automatically when the data inside the controller for that view changes. This is a feature provided by all of the frameworks mentioned above and is very useful, because it means we do not need to write code to make complex DOM queries and update HTML nodes.

### Routing
Navigating around an application does not reload the page, but there is still the need to deep link in to the different views. This is where client-side routing comes in - using a feature called HTML5 [pushState](https://developer.mozilla.org/en-US/docs/Web/API/History_API).

### Ajax requests
Ajax is a set of techniques that facilitate requests to a server to fetch fresh data without having to reload a page. It has been widely used since 2006 and without it, there would be no single page applications.

### WebSockets
WebSockets are an API used to establish persistent connections between a browser and web server, in contrast to the HTTP protocol which requests data and then disconnects.

This is very useful and efficient for real time applications because two way communication eliminates the need for polling the server at a timed interval to check for fresh data.

## Advantages of single page application frameworks

- Refreshing data without having to make a round trip to the server is good for UI responsiveness and server load.
- Most of these frameworks offer basic utilities to take the donkey-work out of common tasks (such as date formatting). This means you can do more with less code.
- More modern development techniques enforce or at least encourage good development practices. This makes testing and maintenance easier.
- The frameworks listed above are all Open-source and have thriving communities so finding the solution to a problem is easier.

## Any drawbacks?
While they are maturing nicely, there can be some drawbacks to creating single page applications as follows:

- SEO can be an issue, because most search engine bots cannot execute Javascript code. All they see when they crawl your application is an empty `<body>` tag with no content inside it. To address this, you can use a service called [Prerender.io](https://prerender.io) which will fetch your page, execute the Javascript on it, wait for everything to render and then deliver that content to search bots.
- Given all the client side logic is separated out from the server, the initial hit on loading times can be quite high. This is especially an issue for mobile devices. Try to cut down on the number of external dependencies your application uses and load essential content first, then other content afterward.
- Single page applications can be slower on older browsers. Their Javascript engines are not as fast as those in modern browsers.

## Do's and don'ts

- Don't be tempted to install plugins for everything you are trying to do. Your application will be bloated and take too long to load.
- From the above point, write Javascript using the ES7 standard and use [BabelJS](http://babeljs.io/) to transpile it for older browsers.
- Use a task runner such as [Gulp](http://gulpjs.com/), [Grunt](https://gruntjs.com/) or the [webpack](https://webpack.github.io/) module loader to concatenate and minify your scripts. Some frameworks will come with packaging tools to handle this for you.
- A large number of small and simple functions is much better than having a small number of very large functions.
- Make use of the latest Javascript standards and avail of [Promises](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise), [generator functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function*), [arrow functions](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) and the various [Array prototype functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). These features will make code much easier to write, maintain and test.
- When choosing a module check its Giuhub repository to see how often it is updated, how much support it has and how well documented it is.
- When you go live, use HTTP/2 and HTTPS to deliver your content. Follow these excellent tutorials to serve content over [HTTP/2 with nginx](https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-with-http-2-support-on-ubuntu-16-04) and to secure your content with [Let's Encrypt](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04).
- Need an external service to connect to your local development machine? Set up a free secure HTTP tunnel using [ngrok](https://ngrok.com/).
- Use [Docker Compose](https://docs.docker.com/compose/) when setting up your development environment. This will preserve your developent set up and it won't fall over when you do something like upgrade your operating system. I have covered this in my blog post about using [Docker for development](/blog/hugo-docker-setup).
- Use [CircleCI](https://circleci.com) for continuous integration. I have written about [using CircleCI](/blog/hugo-deployment) for my set up.

## Wrap up
In this article, we have listed the most popular Javascript frameworks and explored the basic concepts surrounding what they all have in common. Out of the above frameworks, I found that [MeteorJS](https://www.meteor.com) and [PolymerJS](https://www.polymer-project.org/) were the nicest to work with and I would highly recommend them.

If you want to see an example of a single page application written in MeteorJS, you could check out the code for [one of my Meteor projects](https://github.com/matfin/annachristoffer/tree/v1.0.0).


text:
# Contributing

Contributions are **welcome** and will be fully **credited**.

We accept contributions via Pull Requests on [Github](https://github.com/phpflo/phpflo).

## Tests

### Coding standards
- **Test function name format**

Use camelCase e.g. `testMethodName`

- **FQCN in tests**

Use the `::class` call to when using a fully qualified class namespace

- **Expected Exception**

Use method call `$this->expectException...` on the first lines of your test methods instead of annotation.

- **Class Dependencies bootstraping**

When bootstrapping dependencies of your tested class, mock them when they're interface. Don't use a concrete implementation of your interface.

Also put your basic bootstrap logic in the `setUp` function or in `@dataProvider` of your tested class. This gives a single point of modification if dependency signature changes.

- **`expects` method**

Use the `expects` method to  not only ensure what your tested class methods return but also their expected behavior.

```php
<?php

class CalculatorLooper {

    /** @var CalculatorInterface $calculator */
    private $calculator;

    public function __construct(CalculatorInterface $calculator){
        $this->calculator = $calculator;
    }

    public function add(int $loopMax) {
        $i = 1;
        while($i <= $loopMax) {
            $this->calculator->add();
            $i++;
        }

        return 'Addition loop is done!';
    }
}

class CalculatorLooperTest extends \PHPUnit\Framework\TestCase {

    // BAD !
    public function testLoopAdd() {
        $calculator = $this->createMock(CalculatorInterface::class);
        $calculatorLooper = new CalculatorLooper($calculator);

        $this->assetSame('Addition loop is done', $calculatorLooper->add(3));
    }

    // GOOD !
    public function testLoopAdd() {
        $calculator = $this->createMock(CalculatorInterface::class);
        $calculatorLooper = new CalculatorLooper($calculator);
        $calculator
            ->expects($this->at(3))
            ->method('add');

        $this->assertSame('Addition loop is done', $calculatorLooper->add(3));
    }
}
```

- **Tested class method's return check**

Use `assertSame` over `assertEquals` when possible to ensure strict type checking.

### Running
``` bash
$ bin/phpunit
```

**Happy coding**!


text:
#ifndef __XT_EVT_BINDER_POOL_H__
#define __XT_EVT_BINDER_POOL_H__

#include "xt_define.h"
#include "xt_alg_heap.h"
#include <event2/event_struct.h>
#include "xt_reactor_define.h"

/* Declaration */
class CXtEventHandler;

/* Binder struct */
typedef struct _tag_xt_evt_binder_t
{
	const CXtEventHandler	*evt_handler;
	struct event			_event;
}xt_evt_binder_t;
#define evt_binder_size		((sizeof(CXtEventHandler*)+event_get_struct_event_size()))

/* Binder Handle */
typedef xt_evt_binder_t**		xt_evt_binder_hnd_t;

#define make_evt_binder_ptr(heap_elem_ptr)			((xt_evt_binder_t*)(heap_elem_ptr))
#define binder_from_handle(hndBinder)				((xt_evt_binder_t*)(*hndBinder))

/*****************************************
 *			Class CXtEvtBinderPool
 *****************************************/
class CXtEvtBinderPool
{
public:

	/* Constructor & Destructor */
	CXtEvtBinderPool(void);
	~CXtEvtBinderPool(void);

	int						Init( xt_size_t nMaxCount );
	void					Release(void);

	xt_evt_binder_t*		AllocBinder( const CXtEventHandler *pEventHandler );
	/*void					FreeBinder( const CXtEventHandler *pEventHandler );*/
	xt_evt_binder_hnd_t		GetBinderHandle( const CXtEventHandler *pEventHandler );
	void					FreeBinder( xt_evt_binder_hnd_t hndEvtBinder );

	xt_evt_binder_t*		GetAt( xt_size_t nIdx );

	xt_size_t				Count(void)								{ return m_BinderHeap.count; }

	BOOL					IsFull(void)							{ return (m_BinderHeap.count!=m_BinderHeap.capacity); }
	BOOL					IsEmpty(void)							{ return (m_BinderHeap.count==0); }

protected:

	void					Reset(void);

	int						AllocPool( xt_size_t nMaxCount );
	void					FreePool(void);

	xt_heap_t				m_BinderHeap;

#define is_pool_valid		(m_BinderHeap.arr)

#define hnd_buf				((xt_evt_binder_hnd_t)(m_BinderHeap.arr))
#define binder_capacity		(m_BinderHeap.capacity)
#define binder_count		(m_BinderHeap.count)
#define binder_buf			(hnd_buf+binder_capacity)
private:
};

/*****************************************
 *			Class CXtEvtBinderPool END
 *****************************************/

#endif /*__XT_EVT_BINDER_POOL_H__*/


text:
[![CocoaPods](https://img.shields.io/cocoapods/v/Kml.swift.svg)](http://cocoapods.org/pods/Kml.swift)
[![GitHub license](https://img.shields.io/github/license/asus4/Kml.swift.svg)](https://github.com/asus4/Kml.swift/blob/master/LICENSE)

Simple KML parser for Swift.

![capture](https://cloud.githubusercontent.com/assets/357497/23339742/cb32971a-fc6b-11e6-9ec1-7415617285d2.png)

## Libraries

- [AEXML](https://github.com/tadija/AEXML) via cocoapods
- [UIColor-Hex-Swift](https://github.com/yeahdongcn/UIColor-Hex-Swift) includes

## Supporting TAGs

- Style
- StyleMap
- PolyStyle
- LineStyle
- MultiGeometry
- Polygon
- LineString
- Point
- Folder
- Placemark

## License

MIT


text:
default['mozilla-firefox-sync']['server']['path'] = '/srv/fx/sync-server'
default['mozilla-firefox-sync']['server']['version'] = 'c4c0fa033aeb08646008e4969519619178d4a12b'

default['mozilla-firefox-sync']['repository'] = 'https://github.com/mozilla-services/syncserver'

default['mozilla-firefox-sync']['auth_secret'] = nil
default['mozilla-firefox-sync']['certificate_databag_id'] = 'wildcard'
default['mozilla-firefox-sync']['ssl_certificate'] = "/etc/nginx/ssl/certs/#{node['fqdn']}.pem"
default['mozilla-firefox-sync']['ssl_certificate_key'] = "/etc/nginx/ssl/private/#{node['fqdn']}.key"

default['mozilla-firefox-sync']['logfile'] = '/var/log/mozilla-sync.log'
default['mozilla-firefox-sync']['allow_new_users'] = false


text:
anubuntu (ANdroid UBUNTU)
========

A Simple way to Run Ubuntu on Android Devices

More documentation forthcoming...

Copyright 2013 - Neal Hardesty - All Rights Reserved


text:
class ExpenseItem < ActiveRecord::Base
  belongs_to :expense
end


text:
DragSortListView

AOSP

ACRA

ColorPickerView

		DragSortListView

		Android Open Source Project

		/*

 		* Copyright (C) 2010 The Android Open Source Project

 		*

 		* Licensed under the Apache License, Version 2.0 (the "License");

 		* you may not use this file except in compliance with the License.

 		* You may obtain a copy of the License at

 		*

		*      http://www.apache.org/licenses/LICENSE-2.0

 		*

 		* Unless required by applicable law or agreed to in writing, software

 		* distributed under the License is distributed on an "AS IS" BASIS,

 		* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 		* See the License for the specific language governing permissions and

 		* limitations under the License.

 		*/

		ACRA

		/*

 		*  Copyright 2010 Emmanuel Astier & Kevin Gaudin

 		*

 		*  Licensed under the Apache License, Version 2.0 (the "License");

 		*  you may not use this file except in compliance with the License.

 		*  You may obtain a copy of the License at

 		*

 		*      http://www.apache.org/licenses/LICENSE-2.0

 		*

 		*  Unless required by applicable law or agreed to in writing, software

 		*  distributed under the License is distributed on an "AS IS" BASIS,

 		*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 		*  See the License for the specific language governing permissions and

 		*  limitations under the License.

 		*/

		ColorPickerView

		/*

 		* Copyright (C) 2010 Daniel Nilsson

 		*

 		* Licensed under the Apache License, Version 2.0 (the "License");

 		* you may not use this file except in compliance with the License.

 		* You may obtain a copy of the License at

 		*

 		*      http://www.apache.org/licenses/LICENSE-2.0

 		*

 		* Unless required by applicable law or agreed to in writing, software

 		* distributed under the License is distributed on an "AS IS" BASIS,

 		* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 		* See the License for the specific language governing permissions and

 		* limitations under the License.

 		*/


text:
This Is A Test
==============

This is to test the markdown extension.

    def go():
        pass

Hopefully this works!

*   It would be nice
*   and plesant

That is all


text: These documents cover setting up new funds, keeping servers running, and similar devops-y matters.


text:
#region license
// Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//     * Neither the name of Ayende Rahien nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using MbUnit.Framework;

namespace Rhino.Commons.Test
{
    [TestFixture]
    public class DateRangeTests
    {
        public static DateTime start = new DateTime(2005, 10, 8);
        public static DateTime end = new DateTime(2005, 12, 20);

        [Test]
        public void Ctor()
        {
            DateRange range = new DateRange(start, end);

            Assert.AreEqual(start, range.Start);
            Assert.AreEqual(end, range.End);

            TimeSpan span = end.Subtract(start);

            Assert.AreEqual(span, range.Span);
        }

        [Test]
        [ExpectedException(typeof(ArgumentException), "The start date cannot come after the end date")]
        public void EndBeforeStart()
        {
			new DateRange(end, start);
        }

        [Test]
        public void ForEachDay()
        {
            int count = 0;
            int dayCount = 73;
            DateTime[] dates = new DateTime[dayCount];
            DateTime tmp = start;
            for (int i = 0; i < dayCount; i++)
            {
                dates[i] = tmp;
                tmp = tmp.AddDays(1);
            }
            TimeSpan span = end.Subtract(start);

            DateRange range = new DateRange(start, end);
            range.ForEachDay(delegate(DateTime date)
                                 {
                                     if (count!=dates.Length)//skip last day
                                        Assert.AreEqual(dates[count], date);
                                     count++;
                                 });
            Assert.AreEqual(dayCount+1, count);
        }

        [Test]
        public void ForEachWeek()
        {
            int count = 0;
            int weekCount = 12;
            DateRange[] weeks = new DateRange[weekCount];
            DateRange range = new DateRange(start, end);
            weeks[0] = new DateRange(start, start);
            DateTime current = start.AddDays(1);
            for (int i = 1; i < weekCount-1; i++)
            {
                weeks[i] = new DateRange(current, current.AddDays(6));
                current = current.AddDays(7);
            }
            weeks[weekCount - 1] = new DateRange(current, end);
            range.ForEachWeek(delegate(DateRange week)
                                 {
                                      Assert.AreEqual(weeks[count], week);
                                     count++;
                                 });
            Assert.AreEqual(weekCount, count);
        }

        [Test]
        public void ForEachWeek_Full()
        {
            int count = 0;
            int weekCount = 2;
            DateRange[] weeks = new DateRange[weekCount];
            DateTime weekEnd = new DateTime(2005, 12, 17);
            DateTime weekStart = new DateTime(2005, 12, 4);
            DateRange range = new DateRange(weekStart, weekEnd);
            weeks[0] = new DateRange(weekStart,new DateTime(2005, 12, 10));
            weeks[1] = new DateRange(new DateTime(2005, 12,11), weekEnd);
            range.ForEachWeek(delegate(DateRange week)
                                 {
                                     Assert.AreEqual(weeks[count], week);
                                     count++;
                                 });
            Assert.AreEqual(weekCount, count);
        }

        [Test]
        public void ForEachWeek_Partial()
        {
            int count = 0;
            int weekCount = 1;
            DateRange[] weeks = new DateRange[weekCount];
            DateRange range = new DateRange(start, start);
            weeks[0] = new DateRange(start, start);
            range.ForEachWeek(delegate(DateRange week)
                                 {
                                     Assert.AreEqual(weeks[count], week);
                                     count++;
                                 });
            Assert.AreEqual(weekCount, count);
        }

        [Test]
        public void ForEachMonth()
        {
            int count = 0;
            int monthsCount = 3;
            DateRange[] months = new DateRange[monthsCount];
            months[0] = new DateRange(start, new DateTime(2005, 10, 31));
            months[1] = new DateRange(new DateTime(2005, 11, 1),
                                      new DateTime(2005, 11, 30));
            months[2] = new DateRange(new DateTime(2005, 12, 1), end);
            DateRange range = new DateRange(start, end);
            range.ForEachMonth(delegate(DateRange month)
                                 {
                                     Assert.AreEqual(months[count], month);
                                     count++;
                                 });
            Assert.AreEqual(monthsCount, count);
        }

        [Test]
        public void ForEachMonth_Full()
        {
            int count = 0;
            TimeSpan span = end.Subtract(start);

            DateRange range = new DateRange(new DateTime(2005, 10, 1), new DateTime(2005, 10, 31));
            range.ForEachMonth(delegate(DateRange month)
                                 {
                                     Assert.AreEqual(range, month);
                                     count++;
                                 });
            Assert.AreEqual(1, count);
        }

        [Test]
        public void ForEachMonth_SameDay()
        {
            int count = 0;
            TimeSpan span = end.Subtract(start);

            DateRange range = new DateRange(new DateTime(2005, 10, 1), new DateTime(2005, 10, 1));
            range.ForEachMonth(delegate(DateRange month)
                                 {
                                     Assert.AreEqual(range, month);
                                     count++;
                                 });
            Assert.AreEqual(1, count);
        }

        [Test]
        public void ForEachMonth_TwoPartialMonths()
        {
            int count = 0;
            int monthsCount = 2;
            DateRange[] months = new DateRange[monthsCount];
            DateTime start = new DateTime(2005, 10, 31);
            months[0] = new DateRange(start, start);
            DateTime end = new DateTime(2005, 11, 1);
            months[1] = new DateRange(end,
                                      end);
            DateRange range = new DateRange(start, end);
            range.ForEachMonth(delegate(DateRange month)
                                 {
                                     Assert.AreEqual(months[count], month);
                                     count++;
                                 });
            Assert.AreEqual(monthsCount, count);
        }
    }
}


text:
package org.springframework.transaction.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.transaction.TransactionDefinition;

/**
 * Describes transaction attributes on a method or class.
 *
 *
This annotation type is generally directly comparable to Spring's
 * {@link org.springframework.transaction.interceptor.RuleBasedTransactionAttribute}
 * class, and in fact {@link AnnotationTransactionAttributeSource} will directly
 * convert the data to the latter class, so that Spring's transaction support code
 * does not have to know about annotations. If no rules are relevant to the exception,
 * it will be treated like
 * {@link org.springframework.transaction.interceptor.DefaultTransactionAttribute}
 * (rolling back on runtime exceptions).
 *
 *
For specific information about the semantics of this annotation's attributes,
 * consider the {@link org.springframework.transaction.TransactionDefinition} and
 * {@link org.springframework.transaction.interceptor.TransactionAttribute} javadocs.
 *
 * @author Colin Sampaleanu
 * @author Juergen Hoeller
 * @since 1.2
 * @see org.springframework.transaction.interceptor.TransactionAttribute
 * @see org.springframework.transaction.interceptor.DefaultTransactionAttribute
 * @see org.springframework.transaction.interceptor.RuleBasedTransactionAttribute
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {

	/**
	 * A qualifier value for the specified transaction.
	 *
May be used to determine the target transaction manager,
	 * matching the qualifier value (or the bean name) of a specific
	 * {@link org.springframework.transaction.PlatformTransactionManager}
	 * bean definition.
	 */
	String value() default "";

	/**
	 * The transaction propagation type.
	 * Defaults to {@link Propagation#REQUIRED}.
	 * @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior()
	 */
	Propagation propagation() default Propagation.REQUIRED;

	/**
	 * The transaction isolation level.
	 * Defaults to {@link Isolation#DEFAULT}.
	 * @see org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLevel()
	 */
	Isolation isolation() default Isolation.DEFAULT;

	/**
	 * The timeout for this transaction.
	 * Defaults to the default timeout of the underlying transaction system.
	 * @see org.springframework.transaction.interceptor.TransactionAttribute#getTimeout()
	 */
	int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;

	/**
	 * {@code true} if the transaction is read-only.
	 * Defaults to {@code false}.
	 *
This just serves as a hint for the actual transaction subsystem;
	 * it will not necessarily cause failure of write access attempts.
	 * A transaction manager which cannot interpret the read-only hint will
	 * not throw an exception when asked for a read-only transaction.
	 * @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()
	 */
	boolean readOnly() default false;

	/**
	 * Defines zero (0) or more exception {@link Class classes}, which must be a
	 * subclass of {@link Throwable}, indicating which exception types must cause
	 * a transaction rollback.
	 *
This is the preferred way to construct a rollback rule, matching the
	 * exception class and subclasses.
	 *
Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)}
	 */
	Class<? extends Throwable>[] rollbackFor() default {};

	/**
	 * Defines zero (0) or more exception names (for exceptions which must be a
	 * subclass of {@link Throwable}), indicating which exception types must cause
	 * a transaction rollback.
	 *
This can be a substring, with no wildcard support at present.
	 * A value of "ServletException" would match
	 * {@link javax.servlet.ServletException} and subclasses, for example.
	 *
NB: Consider carefully how specific the pattern is, and whether
	 * to include package information (which isn't mandatory). For example,
	 * "Exception" will match nearly anything, and will probably hide other rules.
	 * "java.lang.Exception" would be correct if "Exception" was meant to define
	 * a rule for all checked exceptions. With more unusual {@link Exception}
	 * names such as "BaseBusinessException" there is no need to use a FQN.
	 *
Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)}
	 */
	String[] rollbackForClassName() default {};

	/**
	 * Defines zero (0) or more exception {@link Class Classes}, which must be a
	 * subclass of {@link Throwable}, indicating which exception types must not
	 * cause a transaction rollback.
	 *
This is the preferred way to construct a rollback rule, matching the
	 * exception class and subclasses.
	 *
Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)}
	 */
	Class<? extends Throwable>[] noRollbackFor() default {};

	/**
	 * Defines zero (0) or more exception names (for exceptions which must be a
	 * subclass of {@link Throwable}) indicating which exception types must not
	 * cause a transaction rollback.
	 *
See the description of {@link #rollbackForClassName()} for more info on how
	 * the specified names are treated.
	 *
Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)}
	 */
	String[] noRollbackForClassName() default {};

}