text:
from argparse import ArgumentParser
from inspect import getmembers, isclass, isfunction, ismethod
from os import getcwd
# noinspection PyProtectedMember
from pydoc import ErrorDuringImport, safeimport
from sys import path

MODULE_FORMAT = "# *module* %s"
CLASS_FORMAT = "## *class* %s"
FUNCTION_FORMAT = "## *function* %s"
METHOD_FORMAT = "### *method* %s"
PARAMETERS_FORMAT = "**Parameters:**"
RETURN_FORMAT = "**Return:**"

PARAM = "@param"
RETURN = "@return"

def get_predicate(module_):
    """
    Creates a predicate function for the inspect.getmembers function.
    The created function will excepts a single arg and returns true if that
    arg is a class, function or method defined within the "module_" module.
    @param module_: {module or str} python module
    @return: {function} predicate function
    """
    if isinstance(module_, str):
        module_name = module_
    else:
        module_name = module_.__name__

    def predicate(value):
        return (isclass(value) or isfunction(value) or ismethod(value)) and value.__module__ == module_name
    return predicate

def member2markdown(name, value, title_format):
    """
    Creates the markdown for a member of the modules.
    @param name: {str} name of member
    @param value: {any} value of member
    @param title_format: {str} formatted string for the title of the member
    @return: {list} list of markdown strings
    """
    output, prefix, params, returns, suffix = [], [], [], [], []

    if value.__doc__ is not None:
        output.append(title_format % name)
        for line in value.__doc__.split("\n"):
            if PARAM in line:
                params.append(line.replace(PARAM, "*").strip())
            elif RETURN in line:
                returns.append(line.replace(RETURN, "").strip())
            elif params or returns:
                suffix.append(line.strip())
            else:
                prefix.append(line.strip())

        if prefix:
            output.extend([pre for pre in prefix])
            output.append("")

        if params:
            output.append("**Parameters:**")
            output.extend(params)
            output.append("")

        if returns:
            output.append("**Return:**")
            output.extend(returns)
            output.append("")

        if suffix:
            output.extend(suffix)
            output.append("")

    return output

def class2markdown(name, value):
    class_, methods, output = member2markdown(name, value, CLASS_FORMAT), [], []

    for name, value in getmembers(value, get_predicate(value.__module__)):
        if name[0] != "_":
            methods.extend(
                member2markdown(name, value, METHOD_FORMAT)
            )

    if not class_ and methods:
        class_.extend(
            [CLASS_FORMAT % name, ""]
        )

    return [*class_, *methods]

def module2markdown(module_):
    output = [MODULE_FORMAT % module_.__name__]

    if module_.__doc__:
        output.append(module_.__doc__)

    for name, value in getmembers(module_, get_predicate(module_)):
        if isfunction(value) and name[0] != "_":
            output.extend(
                member2markdown(name, value, FUNCTION_FORMAT)
            )
        elif isclass(value) and name[0] != "_":
            output.extend(
                class2markdown(name, value)
            )

    return "\n".join((str(x) for x in output))

def pydoc2markdown(module_):
    try:
        path.append(getcwd())
        module_ = safeimport(module_)
        if module_ is None:
            print("%s module not found" % module_)

        print(module2markdown(module_))
    except ErrorDuringImport:
        print("Error while importing %s" % module_)

if __name__ == "__main__":
    parser = ArgumentParser(description="Convert python (pycharm Epytext) docstrings to markdown")
    parser.add_argument("module", default="pydoc2markdown", type=str)
    parser.add_argument("-t", "--title", type=str)
    args, _ = parser.parse_known_args()

    pydoc2markdown(args.module)


text:
package jdepend.server.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import jdepend.framework.exception.JDependException;
import jdepend.framework.ui.component.TableSorter;
import jdepend.framework.ui.dialog.CooperDialog;
import jdepend.framework.util.BundleUtil;
import jdepend.server.service.user.UserDomainService;
import jdepend.server.service.user.UserActionItem;

public class UserActionListDialog extends CooperDialog {

	public UserActionListDialog(String username) {
		super();
		this.setLayout(new BorderLayout());

		getContentPane().setLayout(new BorderLayout());

		DefaultTableModel actionListModel = new DefaultTableModel() {
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}

		};

		TableSorter sorter = new TableSorter(actionListModel);

		JTable actionListTable = new JTable(sorter);

		sorter.setTableHeader(actionListTable.getTableHeader());

		actionListModel.addColumn("操作");
		actionListModel.addColumn("IP");
		actionListModel.addColumn("创建时间");
		actionListModel.addColumn("收集时间");

		try {
			Object[] row;
			for (UserActionItem item : new UserDomainService().getTheUserActions(username)) {
				row = new Object[4];
				row[0] = item.operation;
				row[1] = item.ip;
				row[2] = item.getCreatedate();
				row[3] = item.getGartherdate();

				actionListModel.addRow(row);
			}
		} catch (JDependException e) {
			e.printStackTrace();
		}

		this.add(BorderLayout.CENTER, new JScrollPane(actionListTable));

		JPanel buttonBar = new JPanel();
		buttonBar.add(createButton(BundleUtil.getString(BundleUtil.Command_Close)));

		this.add(BorderLayout.SOUTH, buttonBar);
	}

	private JButton createButton(String label) {
		JButton button = new JButton(label);
		button.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		return button;
	}

}

redpajama_set_name: RedPajamaGithub


text:
import IconBase from './IconBase';
import IconProvider from './IconProvider';

export default IconBase;
export { IconProvider };


text:
FTGLES is a C++ library for rendering fonts on mobile operating systems with OpenGL ES 1.1.  It is a port of [FTGL](http://homepages.paradise.net.nz/henryj/code/#FTGL).  It currently targets the iPhone and iPad, with plans to port to Android in the very near future.  iOS 4.2 is currently supported.

From the FTGL notes:

"Unlike other OpenGL font libraries FTGL uses standard font file formats so doesn't need a preprocessing step to convert the high quality font data into a lesser quality, proprietary format."

"FTGL uses the [Freetype](http://www.freetype.org) font library to open and 'decode' the fonts. It then takes that output and stores it in a format most efficient for OpenGL rendering."

OpenGL ES 2.0 support has not yet been added to the main branch.  Please see the [gles2 branch](https://github.com/cdave1/ftgles/tree/gles2) for an experimental version of FTGLES that supports OpenGL ES 2.0.

## QUICK INSTALL

	git clone git@github.com:cdave1/ftgles.git
	git clone git@github.com:cdave1/freetype2-ios.git
	cd freetype2-ios/
	bash install.sh
	cd ../ftgles
	ln -s ../freetype2-ios freetype2
	cd Xcode
	bash install.sh

At this point, it should be possible to compile and run the Xcode projects in your ftgles/Demos/iOS folder.

## INSTALL

See [INSTALL NOTES](http://github.com/cdave1/ftgles/blob/master/INSTALL.md) for instructions on how to add FTGLES to your Xcode project or build using automake.

## USAGE

Include the library in your code:

	#include "FTGL/ftgles.h"

Create a font from a truetype file or opentype font:

	FTFont *font = new FTTextureFont("/path/to/myfont.ttf");
	FTFont *font2 = new FTTextureFont("/path/to/myotherfont.otf");
	font->FaceSize(72);

To render the text within your render loop (fonts are rendered at the origin along the positive x-axis):

	glColor4f(0.0f, 0.0f, 0.0f, 1.0f); // Black text
	font->Render("Lorem ipsum dolor sit amet");

The [Hello World Demo](http://github.com/cdave1/ftgles/blob/master/Demos/iOS/HelloWorld/Classes/Delegate.mm) example class shows a minimal implementation of a render loop.

See the [Demos](http://github.com/cdave1/ftgles/tree/master/iPhone/) folder for several comprehensive sample iPhone apps.  The demo apps include a unicode demo, as well as a demonstration of how to use layouts to easily align and position your text.

## Differences between FTGL and FTGLES

FTGLES 0.1 supports the following font types from the original FTGL library:

 - FTBufferFont
 - FTGLOutlineFont
 - FTGLPolygonFont
 - FTGLTextureFont

Extrusion and pixmap rendering from the original FTGL library are currently not supported.  Bitmap font support is currently in progress.

## Performance Notes

If you need to render large amounts of text, Texture fonts are preferable, and also currently look much better than other font types.  Texture fonts allow you to render a full screen of text without any appreciable drop in frame rate.

For Polygon and Outline fonts, rendering speeds depend very much on the type face being rendered.  More complex glyphs will almost always contain more vertices, and thus FTGLES will need to draw more polygons or lines.

While you may get acceptable results by switching to a simple typeface, it is generally recommended that you avoid excessive use of Polygon and Outline fonts in iOS applications.  Expect to see large drops in frame rate when drawing any more than 100-200 Polygon or Outline glyphs on screen.

Performance of the SimpleLayout class was previously very slow, but was recently improved in a recent build.

There is a [Performance test application](https://github.com/cdave1/ftgles/tree/master/Demos/iOS/PerformanceTest/) that will show the framerate of a screen full of text rendered using the SimpleLayout class, along with several font faces.

## Licenses

 - FTGLES License [here](http://github.com/cdave1/ftgles/blob/master/LICENSE.md)
 - Original FTGL License [here](https://github.com/cdave1/ftgles/blob/master/ftgles/COPYING)
 - Freetype 2 License [here](http://www.freetype.org/FTL.TXT)


text:
import React from 'react'
import Spinner from 'react-ions/lib/components/Spinner'

const ExampleSpinnerCircular = () => (
  <Spinner loading={true} type='spinner-circular' color='#3C97D3' size='24' />
)

export default ExampleSpinnerCircular


text:
/****************************************************************
 * IMPORT
 ****************************************************************/

#include "timer.h"

/****************************************************************
 * ROUTINES
 ****************************************************************/

/* 	Installs a handler branch on the interrupt vector */
void install_handler (unsigned handler_routine_address, unsigned *vector_address);


text:
package org.jfw.core.code.webmvc.handler.buildParam;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.jfw.core.code.utils.Utils;

public class HeaderTransferFactory {
 private final static String  RESOURCE="jfw_webmvc_reqHeader_transfer.properties";

    private final static Map<String,Class<RequestHeaderTransfer>> transfers = new HashMap<String,Class<RequestHeaderTransfer>>();

    @SuppressWarnings("unchecked")
    private final static void loadTransfer() {
        try {
            Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(RESOURCE);
            while(en.hasMoreElements()){
                URL url = en.nextElement();
                URLConnection con = url.openConnection();
                InputStream in =con.getInputStream();
                try
                {
                    Properties props = new Properties();
                    props.load(in);
                    for(Map.Entry<Object,Object> entry:props.entrySet())
                    {
                        String key  = (String)entry.getKey();
                        String val =(String)entry.getValue();
                        try{
                        transfers.put(key, (Class<RequestHeaderTransfer>)Class.forName(val));
                        }catch(Exception e){
                            throw new RuntimeException(e);
                        }

                    }
                }finally{
                    try{
                    in.close();}catch(IOException e){}
                }
            }

        } catch (IOException e) {

        }
    }
    public static Class<RequestHeaderTransfer> getRequestHeaderTransfer(Type clazz)
    {
        if(transfers.isEmpty()) loadTransfer();
        StringBuilder sb = new StringBuilder();
        Utils.writeNameOfType(clazz, sb);
        return  transfers.get(sb.toString());
    }
}


text:
import StateAttrs from '../src/xing-frontend-utils/components/stateAttrs/stateAttrs.js';
import {xpath, stringAtXpath} from "../test-help/xpath.js";
import setupUiRouteLogging from "../src/xing-frontend-utils/ui-route-logger.js";
import {bootstrap} from "a1atscript";

describe('xngStateAttrs directive', function() {
  var $compile, $rootScope, $state;

  beforeEach(function() {
    bootstrap(StateAttrs);
    angular.mock.module(`stateAttrs`, "ui.router.state", function($stateProvider) {
      $stateProvider.state('root', {url: "/", template: "<ui-view xng-state-attrs label='r'></ui-view>"});
      $stateProvider.state('root.inner', {url: "/ri", template: "
"});
      $stateProvider.state('root.other', {url: "/ro", template: "
"});
    })
  });

  beforeEach(inject(function(_$state_, _$compile_, _$rootScope_){
    $state = _$state_;
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  describe('in a current state', function() {
    var element;

    beforeEach(function() {
      $state.go('root.inner');
      $rootScope.$apply();
      element = $compile("

Before
<ui-view xng-state-attrs label='t'></ui-view>
After

")($rootScope);

      $rootScope.$digest();
    });

    it('should have an element with an id like "root" and a class with "root"', function() {
      expect(xpath(element, ".//*[@label='r-i']").snapshotLength).toBeGreaterThan(0);
      expect(xpath(element, ".//*[@id='root'][@label='t']").snapshotLength).toBeGreaterThan(0);
      expect(xpath(element, ".//*[contains(@class, 'root')][@label='t']").snapshotLength).toBeGreaterThan(0);
    });

    it('should have an element with an id like "root_inner"', function() {
      expect(xpath(element, ".//*[@id='root_inner'][@label='r']").snapshotLength).toBeGreaterThan(0);
      expect(xpath(element, ".//*[contains(@class, 'inner')][@label='r']").snapshotLength).toBeGreaterThan(0);
    });

    it('update attrs when state changes', function() {
      expect(xpath(element, ".//*[@label='r-i']").snapshotLength).toBeGreaterThan(0);

      expect(xpath(element, ".//*[@id='root_other']").snapshotLength).toEqual(0);
      expect(xpath(element, ".//*[contains(@class, 'other')]").snapshotLength).toEqual(0);

      $state.go('root.other');
      $rootScope.$apply();

      expect(xpath(element, ".//*[@label='r-i']").snapshotLength).toEqual(0);
      expect(xpath(element, ".//*[contains(@class, 'inner')]").snapshotLength).toEqual(0);
      expect(xpath(element, ".//*[@id='root_inner']").snapshotLength).toEqual(0);

      expect(xpath(element, ".//*[@id='root_other'][@label='r']").snapshotLength).toBeGreaterThan(0);
      expect(xpath(element, ".//*[contains(@class, 'other')][@label='r']").snapshotLength).toBeGreaterThan(0);
    });
  });
});


text:
package com.amazonaws.services.ec2.model;

import java.io.Serializable;

/**
 *

 * Describes a reservation.
 *

 */
public class Reservation implements Serializable, Cloneable {

    /**
     *

     * The ID of the reservation.
     *

     */
    private String reservationId;
    /**
     *

     * The ID of the AWS account that owns the reservation.
     *

     */
    private String ownerId;
    /**
     *

     * The ID of the requester that launched the instances on your behalf (for
     * example, AWS Management Console or Auto Scaling).
     *

     */
    private String requesterId;
    /**
     *

     * [EC2-Classic only] One or more security groups.
     *

     */
    private com.amazonaws.internal.SdkInternalList<GroupIdentifier> groups;
    /**
     *

     * One or more instances.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Instance> instances;
    /**
     *

     * One or more security group names.
     *

     */
    private com.amazonaws.internal.SdkInternalList<String> groupNames;

    /**
     *

     * The ID of the reservation.
     *

     *
     * @param reservationId
     *        The ID of the reservation.
     */

    public void setReservationId(String reservationId) {
        this.reservationId = reservationId;
    }

    /**
     *

     * The ID of the reservation.
     *

     *
     * @return The ID of the reservation.
     */

    public String getReservationId() {
        return this.reservationId;
    }

    /**
     *

     * The ID of the reservation.
     *

     *
     * @param reservationId
     *        The ID of the reservation.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withReservationId(String reservationId) {
        setReservationId(reservationId);
        return this;
    }

    /**
     *

     * The ID of the AWS account that owns the reservation.
     *

     *
     * @param ownerId
     *        The ID of the AWS account that owns the reservation.
     */

    public void setOwnerId(String ownerId) {
        this.ownerId = ownerId;
    }

    /**
     *

     * The ID of the AWS account that owns the reservation.
     *

     *
     * @return The ID of the AWS account that owns the reservation.
     */

    public String getOwnerId() {
        return this.ownerId;
    }

    /**
     *

     * The ID of the AWS account that owns the reservation.
     *

     *
     * @param ownerId
     *        The ID of the AWS account that owns the reservation.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withOwnerId(String ownerId) {
        setOwnerId(ownerId);
        return this;
    }

    /**
     *

     * The ID of the requester that launched the instances on your behalf (for
     * example, AWS Management Console or Auto Scaling).
     *

     *
     * @param requesterId
     *        The ID of the requester that launched the instances on your behalf
     *        (for example, AWS Management Console or Auto Scaling).
     */

    public void setRequesterId(String requesterId) {
        this.requesterId = requesterId;
    }

    /**
     *

     * The ID of the requester that launched the instances on your behalf (for
     * example, AWS Management Console or Auto Scaling).
     *

     *
     * @return The ID of the requester that launched the instances on your
     *         behalf (for example, AWS Management Console or Auto Scaling).
     */

    public String getRequesterId() {
        return this.requesterId;
    }

    /**
     *

     * The ID of the requester that launched the instances on your behalf (for
     * example, AWS Management Console or Auto Scaling).
     *

     *
     * @param requesterId
     *        The ID of the requester that launched the instances on your behalf
     *        (for example, AWS Management Console or Auto Scaling).
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withRequesterId(String requesterId) {
        setRequesterId(requesterId);
        return this;
    }

    /**
     *

     * [EC2-Classic only] One or more security groups.
     *

     *
     * @return [EC2-Classic only] One or more security groups.
     */

    public java.util.List<GroupIdentifier> getGroups() {
        if (groups == null) {
            groups = new com.amazonaws.internal.SdkInternalList<GroupIdentifier>();
        }
        return groups;
    }

    /**
     *

     * [EC2-Classic only] One or more security groups.
     *

     *
     * @param groups
     *        [EC2-Classic only] One or more security groups.
     */

    public void setGroups(java.util.Collection<GroupIdentifier> groups) {
        if (groups == null) {
            this.groups = null;
            return;
        }

        this.groups = new com.amazonaws.internal.SdkInternalList<GroupIdentifier>(
                groups);
    }

    /**
     *

     * [EC2-Classic only] One or more security groups.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setGroups(java.util.Collection)} or
     * {@link #withGroups(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param groups
     *        [EC2-Classic only] One or more security groups.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withGroups(GroupIdentifier... groups) {
        if (this.groups == null) {
            setGroups(new com.amazonaws.internal.SdkInternalList<GroupIdentifier>(
                    groups.length));
        }
        for (GroupIdentifier ele : groups) {
            this.groups.add(ele);
        }
        return this;
    }

    /**
     *

     * [EC2-Classic only] One or more security groups.
     *

     *
     * @param groups
     *        [EC2-Classic only] One or more security groups.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withGroups(java.util.Collection<GroupIdentifier> groups) {
        setGroups(groups);
        return this;
    }

    /**
     *

     * One or more instances.
     *

     *
     * @return One or more instances.
     */

    public java.util.List<Instance> getInstances() {
        if (instances == null) {
            instances = new com.amazonaws.internal.SdkInternalList<Instance>();
        }
        return instances;
    }

    /**
     *

     * One or more instances.
     *

     *
     * @param instances
     *        One or more instances.
     */

    public void setInstances(java.util.Collection<Instance> instances) {
        if (instances == null) {
            this.instances = null;
            return;
        }

        this.instances = new com.amazonaws.internal.SdkInternalList<Instance>(
                instances);
    }

    /**
     *

     * One or more instances.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setInstances(java.util.Collection)} or
     * {@link #withInstances(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param instances
     *        One or more instances.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withInstances(Instance... instances) {
        if (this.instances == null) {
            setInstances(new com.amazonaws.internal.SdkInternalList<Instance>(
                    instances.length));
        }
        for (Instance ele : instances) {
            this.instances.add(ele);
        }
        return this;
    }

    /**
     *

     * One or more instances.
     *

     *
     * @param instances
     *        One or more instances.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withInstances(java.util.Collection<Instance> instances) {
        setInstances(instances);
        return this;
    }

    /**
     *

     * One or more security group names.
     *

     *
     * @return One or more security group names.
     */

    public java.util.List<String> getGroupNames() {
        if (groupNames == null) {
            groupNames = new com.amazonaws.internal.SdkInternalList<String>();
        }
        return groupNames;
    }

    /**
     *

     * One or more security group names.
     *

     *
     * @param groupNames
     *        One or more security group names.
     */

    public void setGroupNames(java.util.Collection<String> groupNames) {
        if (groupNames == null) {
            this.groupNames = null;
            return;
        }

        this.groupNames = new com.amazonaws.internal.SdkInternalList<String>(
                groupNames);
    }

    /**
     *

     * One or more security group names.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setGroupNames(java.util.Collection)} or
     * {@link #withGroupNames(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param groupNames
     *        One or more security group names.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withGroupNames(String... groupNames) {
        if (this.groupNames == null) {
            setGroupNames(new com.amazonaws.internal.SdkInternalList<String>(
                    groupNames.length));
        }
        for (String ele : groupNames) {
            this.groupNames.add(ele);
        }
        return this;
    }

    /**
     *

     * One or more security group names.
     *

     *
     * @param groupNames
     *        One or more security group names.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public Reservation withGroupNames(java.util.Collection<String> groupNames) {
        setGroupNames(groupNames);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getReservationId() != null)
            sb.append("ReservationId: " + getReservationId() + ",");
        if (getOwnerId() != null)
            sb.append("OwnerId: " + getOwnerId() + ",");
        if (getRequesterId() != null)
            sb.append("RequesterId: " + getRequesterId() + ",");
        if (getGroups() != null)
            sb.append("Groups: " + getGroups() + ",");
        if (getInstances() != null)
            sb.append("Instances: " + getInstances() + ",");
        if (getGroupNames() != null)
            sb.append("GroupNames: " + getGroupNames());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof Reservation == false)
            return false;
        Reservation other = (Reservation) obj;
        if (other.getReservationId() == null ^ this.getReservationId() == null)
            return false;
        if (other.getReservationId() != null
                && other.getReservationId().equals(this.getReservationId()) == false)
            return false;
        if (other.getOwnerId() == null ^ this.getOwnerId() == null)
            return false;
        if (other.getOwnerId() != null
                && other.getOwnerId().equals(this.getOwnerId()) == false)
            return false;
        if (other.getRequesterId() == null ^ this.getRequesterId() == null)
            return false;
        if (other.getRequesterId() != null
                && other.getRequesterId().equals(this.getRequesterId()) == false)
            return false;
        if (other.getGroups() == null ^ this.getGroups() == null)
            return false;
        if (other.getGroups() != null
                && other.getGroups().equals(this.getGroups()) == false)
            return false;
        if (other.getInstances() == null ^ this.getInstances() == null)
            return false;
        if (other.getInstances() != null
                && other.getInstances().equals(this.getInstances()) == false)
            return false;
        if (other.getGroupNames() == null ^ this.getGroupNames() == null)
            return false;
        if (other.getGroupNames() != null
                && other.getGroupNames().equals(this.getGroupNames()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime
                * hashCode
                + ((getReservationId() == null) ? 0 : getReservationId()
                        .hashCode());
        hashCode = prime * hashCode
                + ((getOwnerId() == null) ? 0 : getOwnerId().hashCode());
        hashCode = prime
                * hashCode
                + ((getRequesterId() == null) ? 0 : getRequesterId().hashCode());
        hashCode = prime * hashCode
                + ((getGroups() == null) ? 0 : getGroups().hashCode());
        hashCode = prime * hashCode
                + ((getInstances() == null) ? 0 : getInstances().hashCode());
        hashCode = prime * hashCode
                + ((getGroupNames() == null) ? 0 : getGroupNames().hashCode());
        return hashCode;
    }

    @Override
    public Reservation clone() {
        try {
            return (Reservation) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
import GP4_Compile, GP4_PyParse
from GP4_Utilities import *
from pyparsing import ParseException
import GP4_Exceptions

## Compile a GP4 program given as a single string.
# @param program : string. The GP4 program
# @param debug : debug vector integer
# @return p4 object or None if error
def compile_string(program, debug=0, ):
    ''' Creates a new parser and compiler object.
        Runs the parser on the given program, and then
        runs the compiler on the generated AST,
        returning a P4 object that contains the
        specified P4 program.
    '''

    if debug:
        print program

    parser = GP4_PyParse.new_GP4_parser()

    try:
        parsed_data = parser.parseString(program, True)

    except ParseException as err:

        show_source_loc(err.line, err.column)
        raise GP4_Exceptions.SyntaxError, "Syntax error line %s  column %s" % (str(err.line), str(err.column))

    # Compile the parse tree

    compiler = GP4_Compile.Compiler( )
    p4 = compiler.compile_parse_tree( parsed_data )

    return p4


text:
using System;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;

namespace Microsoft.Xna.Framework.Graphics
{
    [DataContract]
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
	public struct VertexPositionColor : IVertexType
	{
        [DataMember]
		public Vector3 Position;

        [DataMember]
		public VertexElementColor Color;

		public static readonly VertexDeclaration VertexDeclaration;

		public VertexPositionColor (Vector3 position, Color color)
		{
			this.Position = position;
			Color = color;
		}

		VertexDeclaration IVertexType.VertexDeclaration {
			get {
				return VertexDeclaration;
			}
		}

		public override int GetHashCode ()
		{
			// TODO: Fix gethashcode
			return 0;
		}

		public override string ToString ()
		{
			return string.Format ("{{Position:{0} Color:{1}}}", new object[] { this.Position, this.Color });
		}

		public static bool operator == (VertexPositionColor left, VertexPositionColor right)
		{
			return ((left.Color == right.Color) && (left.Position == right.Position));
		}

		public static bool operator != (VertexPositionColor left, VertexPositionColor right)
		{
			return !(left == right);
		}

		public override bool Equals (object obj)
		{
			if (obj == null) {
				return false;
			}
			if (obj.GetType () != base.GetType ()) {
				return false;
			}
			return (this == ((VertexPositionColor)obj));
		}

		static VertexPositionColor ()
		{
			VertexElement[] elements = new VertexElement[] { new VertexElement (0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0), new VertexElement (12, VertexElementFormat.Color, VertexElementUsage.Color, 0) };
			VertexDeclaration declaration = new VertexDeclaration (elements);
			VertexDeclaration = declaration;
		}
	}
}


text:
from StringIO import StringIO
from hashlib import sha1

from flask import request
from sqlalchemy import func, select, and_, not_
import networkx as nx

from grano.lib.exc import BadRequest
from grano.lib.args import arg_int
from grano.core import db
from grano.model import Entity, Relation, Schema, Property

# TODO: Make the set of properties retrieved for entities
#       and relations configurable.
# TODO: Does it make sense to do a count first?
# TODO: Check what the last-modified entity/relation is.
# TODO: Possibly aggregate relations with the same props
#       into a weight.

class GraphExtractor(object):

    def __init__(self, project_id=None, root_id=None):
        self.root_id = root_id
        self.project_id = project_id
        self._rows = []
        self._seen = set()
        self._rel_ids = set()
        self._G = None

        for i in range(self.depth):
            ids = self.sweep_ids()
            self.query_adjacency(sources=ids)
            self.query_adjacency(targets=ids)

    @property
    def depth(self):
        if self.root_id is None:
            return 1
        depth = arg_int('depth', 1)
        return max(1, min(depth, 3))

    @property
    def format(self):
        fmt = request.args.get('format', 'json').lower().strip()
        if fmt not in ['json', 'gexf']:
            raise BadRequest('Invalid format name: %s' % fmt)
        return fmt

    def query_adjacency(self, sources=None, targets=None):
        filters, fields = [], []

        relation = Relation.__table__.alias('relation')
        schema = Schema.__table__.alias('relation_schema')
        filters.append(relation.c.schema_id==schema.c.id)

        if len(self._rel_ids):
            filters.append(not_(relation.c.id.in_(self._rel_ids)))
        if self.project_id is not None:
            filters.append(relation.c.project_id==self.project_id)

        fields.append(relation.c.id.label('relation.id'))
        fields.append(schema.c.name.label('relation.schema.name'))
        fields.append(schema.c.label.label('relation.schema.label'))

        source_fields, source_filters, source_tables = \
            self.query_entity('source', sources)
        target_fields, target_filters, target_tables = \
            self.query_entity('target', targets)

        filters.append(relation.c.source_id==source_tables[0].c.id)
        filters.append(relation.c.target_id==target_tables[0].c.id)

        fields = fields + source_fields + target_fields
        filters = filters + source_filters + target_filters
        tables = [relation, schema] + source_tables + target_tables

        #print select(fields,  and_(*filters), tables)
        rp = db.session.execute(select(fields,  and_(*filters), tables))
        for row in rp.fetchall():
            self._rel_ids.add(row['relation.id'])
            self._rows.append(dict(row.items()))

    def query_entity(self, name, include):
        filters, fields = [], []
        table = Entity.__table__.alias(name)
        fields.append(table.c.id.label(name + '.id'))
        if include is not None:
            filters.append(table.c.id.in_(include))

        property_name = Property.__table__.alias(name + '_property_name')
        filters.append(table.c.id==property_name.c.entity_id)
        filters.append(property_name.c.active==True)
        filters.append(property_name.c.name=='name')
        fields.append(property_name.c.value_string.label(name + '.property.name'))
        return (fields, filters, [table, property_name])

    def sweep_ids(self):
        if self.root_id is None:
            return None
        if not len(self._rows):
            ids = set([self.root_id])
        else:
            ids = set()
            for row in self._rows:
                for field in ['source.id', 'target.id']:
                    if row.get(field) not in self._seen:
                        ids.add(row.get(field))
        self.seen = self._seen.union(ids)
        return ids

    def to_hash(self):
        hasch = sha1()
        for row in self._rows:
            hasch.update(row.get('source.id'))
            hasch.update(row.get('target.id'))
            hasch.update(row.get('relation.id'))
        return hasch.hexdigest()

    def to_networkx(self):
        if self._G is None:
            G = nx.MultiDiGraph()
            for row in self._rows:
                if row.get('source.id') not in G:
                    G.add_node(row.get('source.id'), label=row.get('source.property.name'))
                if row.get('target.id') not in G:
                    G.add_node(row.get('target.id'), label=row.get('target.property.name'))
                G.add_edge(row.get('source.id'), row.get('target.id'), key=row.get('relation.id'),
                    schema_name=row.get('relation.schema.name'),
                    schema_label=row.get('relation.schema.label'))
            self._G = G
        return self._G

    def to_gexf(self):
        G = self.to_networkx()
        sio = StringIO()
        nx.write_gexf(G, sio)
        return sio.getvalue()

    def to_dict(self):
        relations, entities = [], {}
        for row in self._rows:
            relations.append({
                'id': row.get('relation.id'),
                'source': row.get('source.id'),
                'target': row.get('target.id'),
                'schema.name': row.get('relation.schema.name'),
                'schema.label': row.get('relation.schema.label'),
            })
            for ent in ['source', 'target']:
                if row.get(ent + '.id') not in entities:
                    entities[row.get(ent + '.id')] = {
                        #'id': row.get(ent + '.id'),
                        'property.name': row.get(ent + '.property.name')
                    }
        return {
            'relations': relations,
            'entities': entities,
            'root': self.root_id,
            'depth': self.depth
            }

if __name__ == '__main__':
    G = extract('783a709133447710b')
    nx.write_gexf(G, "graph.gexf")


text:
<?php

/**
 * Adds skill to database
 */

require '../db.php';
//header('Content-type: application/json');

$this_userID = isset($_COOKIE['userID']) ? $_COOKIE['userID'] : $_SESSION['userID'];
$userID = $db->real_escape_string(isset($_GET['userID']) ? $_GET['userID'] : $_POST['userID']);
$skillID = $db->real_escape_string(isset($_GET['skillID']) ? $_GET['skillID'] : $_POST['skillID']);
$levelID = $db->real_escape_string(isset($_GET['levelID']) ? $_GET['levelID'] : $_POST['levelID']);

if ($skillID == '' || $levelID == '' || $userID == '') {
    echo json_encode(array("success" => false, "msg" => "Please provide all the required fields"));
    return false;
}

if ($userID != $this_userID) {
    echo json_encode(array("success" => false, "msg" => "Trying to remove details for a different user"));
    return false;
}

$query = "SELECT skillID FROM user_skills WHERE userID = $userID AND skillID = $skillID AND levelID = $levelID";
if ($result = $db->query($query)) {
  /* fetch object array */
  if (!$row = $result->fetch_row()) {
      echo json_encode(array("success" => false, "msg" => "No such skill found in the database"));
      return false;
  }
  /* free result set */
  $result->close();
}

$query = "DELETE FROM user_skills WHERE userID = $userID AND skillID = $skillID AND levelID = $levelID";
if ($result = $db->query($query)) {
    $db->commit();
    echo json_encode(array("success" => true, "msg" => "Skill deleted", "href" => "window.location"));
    return true;
    /* free result set */
    $result->close();
} else {
    echo json_encode(array("success" => false, "msg" => "Failed to remove skill to database"));
    return false;
    /* free result set */
    $result->close();
}

?>


text:
/**
 * Created by vijanny on 2016/6/14.
 */
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('you are in  user miniMasterApp');
});

//用户注册
router.post('/singUp',function(req,res,next){

});
//用户登录
router.post('/login',function(req,res,next){

});

module.exports = router;


text: export import type = require("A");


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `TDynBenchFn` trait in crate `test`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, TDynBenchFn">

    <title>test::TDynBenchFn - Rust</title>

    <link rel="stylesheet" type="text/css" href="../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

test

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait test::<wbr>TDynBenchFn<wbr>Unstable
            [-] [+]
        [src]

pub trait TDynBenchFn {
    fn run(&self, harness: &mut Bencher);
}

Represents a benchmark function.

Required Methods

fn run(&self, harness: &mut Bencher)

Implementors

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
// PR target/29487
// { dg-do run { xfail "hppa*-hp-hpux11.*" } }
// { dg-require-weak "" }
// { dg-additional-sources "weak1-a.cc" }
// { dg-options "-O2" }

extern __attribute__((weak))
void f() {
}

int main () {
  try {
    f();
    return 1;
  } catch (int i) {
    /* Although the implementation of f in this file does not throw
       any exceptions, it is weak, and may therefore be replaced at
       link time.  Therefore, the compiler must not optimize away this
       catch clause.  */
    if (i != 7)
      return 2;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.hadoop.yarn.server.webproxy (hadoop-yarn-server-web-proxy 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.yarn.server.webproxy

Classes

AppReportFetcher

ProxyUriUtils

WebAppProxy

WebAppProxyServer

WebAppProxyServlet


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

class Home extends MY_Controller
{

    public function index()
    {
        $this->load_home();
    }

    public function load_home()
    {

        // autoload models, translations and return views to be loaded later.
        // We only need configurations, models, views and tranlations here.
        $preprocessed_data =
            $this->auto_init_needed_resources(__CLASS__, __FUNCTION__, array('configurations', 'models', 'translations', 'views'));

        /* Starting to prepare data to be passed to the views */
        /* Building up all the needed data to pass to the views */
        $offer_alt_img_text = $this->lang->line('offer_alt_img');
        $offer_title_img_text = $this->lang->line('offer_title_img');

        /**
         * @param $list_of_joined_classes multidimensional array in the following format:
         *                                      - key: next class to be joined with the
         *                                               current class
         *                                      - value: array of:
         *                                                - 'join_type': type of join
         *                                                - 'sub_list': array of sub list of joined
         *                                               classes in the same format.
         *                                               Empty or null if no sub list
         *
         *
         * @param $conditions : multidimensional array with the following format:
         *   array(
         * array( // condition group 1
         * 'condition_table1' => $condition_table1, // table to apply 1º condition, empty if literal
         * 'condition_table2' => $condition_table2, // table to apply 2º condition, empty if literal
         * 'condition_1' => $condition_1, // 1º column or literal to apply
         * 'operation_condition' => $operation_condition, // the condition itself
         * 'condition_2' => $condition_2, // 2º column or literal to apply
         * 'ocurrence_condition_1' => $ocurrence_condition_1, // occurrence number of the table in the join list, default value is 1
         * 'ocurrence_condition_2' => $ocurrence_condition_2 // occurrence number of the table in the join list, default value is 1
         * ),
         *       array ( // condition group 2
         *           ...
         */
        /*
        public function getAllJoinedData($list_of_joined_classes, $limit = null, $offset = 0,
                                         $order_by = null, $ordenation = 'ASC',
                                         $conditions = null){

        */
        //  $merchant_data_list = Merchant::getList(array('active' => true), 20, 0 , 'name');

        $join_list = array('ImageGroup' =>
            array('join_type' => 'inner',
                'sub_list' =>
                    array('Image' => array('join_type' => 'inner')
                    )
            )
        );
        $conditions = array(
            array( // condition group 1
                'condition_table1' => 'Image',
                'condition_table2' => '', // literal
                'condition_1' => 'active',
                'condition_2' => true,
                'operation_condition' => '=',
                'ocurrence_condition_1' => 1, // not needed
                // (not passed ocurrence_condition_2 as not needed in order to test)
            ),
            array( // condition group 1
                'condition_table1' => 'Image',
                'condition_table2' => '', // literal
                'condition_1' => 'img_description',
                'condition_2' => 'logo',
                'operation_condition' => '=',
                'ocurrence_condition_1' => 1, // not needed
                // (not passed ocurrence_condition_2 as not needed in order to test)
            ),
            array( // condition group 2
                'condition_table1' => 'ImageGroup',
                'condition_table2' => '', // literal
                'condition_1' => 'active',
                'condition_2' => true,
                'operation_condition' => '=',
                // 'ocurrence_condition_1' => 1, // ommited in order to test
                // (not passed ocurrence_condition_2 as not needed in order to test)
            ),
            array( // condition group 3
                'condition_table1' => 'Merchant',
                'condition_table2' => '', // literal
                'condition_1' => 'active',
                'condition_2' => true,
                'operation_condition' => '=',
                // 'ocurrence_condition_1' => 1, // ommited in order to test
                // (not passed ocurrence_condition_2 as not needed in order to test)
            )
        );
        /*
         * @param $ordenation: array of quaternions in the following format:
         * 'ordenation_column' => column,
         * 'column_table' => name_of_the_table_whose_column_belongs_to
         * 'order_in_join_list' => number of the aparition in the join list. default = 1
         * 'ordenation_type => 'ASC' or 'DESC'
         *
         */
        $ordenation = array( // stacked ordenations are possible, they have to be ordered in this array
            array(
                'ordenation_column' => 'name',
                'ordenation_type' => 'ASC',
                'column_table' => 'merchant',
                'order_in_join_list' => 1
            ),
            array(
                'ordenation_column' => 'order',
                'ordenation_type' => 'ASC',
                'column_table' => 'image',
                'order_in_join_list' => 1
            )
        );

        /*
        public function getAllJoinedData($list_of_joined_classes, $limit = null, $offset = 0,
                                         $ordenation,
                                         $conditions = null){

        */
        $merchant_data_list = Merchant::getAllJoinedData($join_list, 20, 0, $ordenation, $conditions);

/*
        foreach ($merchant_data_list as &$merchant_data) {
            $merchant_data['imgalt'] = $offer_alt_img_text . ' ' . $merchant_data['name'];
            $merchant_data['imgtitle'] = $offer_title_img_text . ' ' . $merchant_data['name'];
        }
*/

        /* Collecting all the data all the views need in a $data array */
        $data = array('merchant_list' => $merchant_data_list, 'configurations' => $preprocessed_data['configurations']);
        /* End of data preparation to be passed to the views */

        // autoload views, it couldn't be autoloaded without data in the other method
        $this->autoload_views($preprocessed_data['views'], $data);

    }

}


text:
@implementation Book
@dynamic auther;

+ (NSString *)tableName
{
    return @"Book";
}

+ (Class)usersThroughClass
{
    return NSClassFromString(@"UserHasBooks");
}

@end


text:
using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace charls;

namespace CharLSUnitTest
{
    TEST_CLASS(JpegStreamReaderTest)
    {
    public:
        TEST_METHOD(ReadHeaderFromToSmallInputBuffer)
        {
            uint8_t buffer[1];

            ByteStreamInfo byteStream = FromByteArray(buffer, 0);
            JpegStreamReader reader(byteStream);

            try
            {
                reader.ReadHeader();
            }
            catch (const system_error &error)
            {
                Assert::AreEqual(static_cast<int>(ApiResult::CompressedBufferTooSmall), error.code().value());
                return;
            }

            Assert::Fail();
        }

        TEST_METHOD(ReadHeaderFromBufferPrecededWithFillBytes)
        {
            vector<uint8_t> buffer;
            buffer.push_back(0xFF);
            buffer.push_back(0xFF);
            buffer.push_back(0xD8);
            buffer.push_back(0xFF);
            buffer.push_back(0xFF);
            buffer.push_back(0xDA); // SOS: Marks the start of scan.

            ByteStreamInfo byteStream = FromByteArray(&(buffer[0]), 6);
            JpegStreamReader reader(byteStream);

            reader.ReadHeader(); // if it doesn´t throw test is passed.
        }

        TEST_METHOD(ReadHeaderFromBufferNotStartingWithFFShouldThrow)
        {
            vector<uint8_t> buffer;
            buffer.push_back(0x0F);
            buffer.push_back(0xFF);
            buffer.push_back(0xD8);
            buffer.push_back(0xFF);
            buffer.push_back(0xFF);
            buffer.push_back(0xDA); // SOS: Marks the start of scan.

            ByteStreamInfo byteStream = FromByteArray(&(buffer[0]), 6);
            JpegStreamReader reader(byteStream);

            try
            {
                reader.ReadHeader();
            }
            catch (const system_error &error)
            {
                Assert::AreEqual(static_cast<int>(ApiResult::MissingJpegMarkerStart), error.code().value());
                return;
            }

            Assert::Fail();
        }
    };
}


text:
#include "data_loader_machine.hpp"

DataLoaderStateMachine::DataLoaderStateMachine(bool isCloudSaveEnabled, char *savePath) {
    mIsCloudSaveEnabled = isCloudSaveEnabled;
    int len = strlen(savePath) + strlen(SAVE_FILE_NAME) + 2;
    mSaveFileName = new char[len];
    strcpy(mSaveFileName, savePath);
    strcat(mSaveFileName, "/");
    strcat(mSaveFileName, SAVE_FILE_NAME);
    mLevelLoaded = 0;
    mCurrentState = LOAD_NOT_STARTED;
}

DataLoaderStateMachine::~DataLoaderStateMachine() {
    delete mSaveFileName;
}

int DataLoaderStateMachine::getTotalSteps() {
    return DATA_LOADED;
}

int DataLoaderStateMachine::getStepsCompleted() {
    return mCurrentState;
}

bool DataLoaderStateMachine::isLoadingDataCompleted() {
    // At the beginning, we assume that the level 0 has been loaded
    return mCurrentState == DATA_LOADED || mCurrentState == LOAD_NOT_STARTED;
}

int DataLoaderStateMachine::getLevelLoaded() {
    return mLevelLoaded;
}

void DataLoaderStateMachine::init() {
    MY_ASSERT(mCurrentState == LOAD_NOT_STARTED || mCurrentState == DATA_LOADED);
    ALOGI("Loading data initialized.");
    mCurrentState = DATA_INITIALIZED;
}

void DataLoaderStateMachine::authenticationCompleted() {
    MY_ASSERT(mCurrentState == CLOUD_USER_AUTHENTICATED - 1);
    ALOGI("Cloud authentication completed, searching saved cloud data.");
    mCurrentState = CLOUD_USER_AUTHENTICATED;
}

void DataLoaderStateMachine::savedStateCloudDataFound() {
    MY_ASSERT(mCurrentState == CLOUD_DATA_FOUND - 1);
    ALOGI("Cloud saved data found, continuing reading data.");
    mCurrentState = CLOUD_DATA_FOUND;
}

void DataLoaderStateMachine::savedStateLoadingCompleted(int level) {
    MY_ASSERT(mIsCloudSaveEnabled && mCurrentState == DATA_LOADED - 1);
    ALOGI("Using cloud save data. Level loaded: %d", level);
    mLevelLoaded = level;
    mCurrentState = DATA_LOADED;
}

void DataLoaderStateMachine::authenticationFailed() {
    ALOGE("Error authenticating the user. Using local data instead.");
    LoadLocalProgress();
}

void DataLoaderStateMachine::savedStateSnapshotNotFound() {
    ALOGI("Cloud saved data not found. Using local data instead.");
    LoadLocalProgress();
}

void DataLoaderStateMachine::savedStateLoadingFailed() {
    ALOGE("Error on loading cloud data. Using local data instead.");
    LoadLocalProgress();
}

void DataLoaderStateMachine::LoadLocalProgress() {
    ALOGI("Attempting to load locally: %s", mSaveFileName);
    mLevelLoaded = 0;
    FILE *f = fopen(mSaveFileName, "r");
    if (f) {
        ALOGI("Local file found. Loading data.");
        if (1 != fscanf(f, "v1 %d", &mLevelLoaded)) {
            ALOGE("Error parsing save file.");
            mLevelLoaded = 0;
        } else {
            ALOGI("Loaded. Level = %d", mLevelLoaded);
        }
        fclose(f);
    } else {
        ALOGI("Save file not present.");
    }
    mCurrentState = DATA_LOADED;
}

void DataLoaderStateMachine::SaveLocalProgress(int level) {
    mLevelLoaded = level;
    ALOGI("Saving progress (level %d) to file: %s", level, mSaveFileName);
    FILE *f = fopen(mSaveFileName, "w");
    if (!f) {
        ALOGE("Error writing to save game file.");
        return;
    }
    fprintf(f, "v1 %d", level);
    fclose(f);
    ALOGI("Save file written.");
}


text:
/**
 *
 * '||''|.                            '||
 *  ||   ||    ....  .... ...   ....   ||    ...   ... ...  ... ..
 *  ||    || .|...||  '|.  |  .|...||  ||  .|  '|.  ||'  ||  ||' ''
 *  ||    || ||        '|.|   ||       ||  ||   ||  ||    |  ||
 * .||...|'   '|...'    '|     '|...' .||.  '|..|'  ||...'  .||.
 *                                                  ||
 * --------------- By Display:inline ------------- '''' -----------
 *
 * Notification plugin
 *
 * Structural good practices from the article from Addy Osmani 'Essential jQuery plugin patterns'
 * @url http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
 */

/*
 * The semi-colon before the function invocation is a safety
 * net against concatenated scripts and/or other plugins
 * that are not closed properly.
 */
;(function($, window, document, undefined)
{
	/*
	 * undefined is used here as the undefined global variable in ECMAScript 3 is mutable (i.e. it can
	 * be changed by someone else). undefined isn't really being passed in so we can ensure that its value is
	 * truly undefined. In ES5, undefined can no longer be modified.
	 */

	/*
	 * window and document are passed through as local variables rather than as globals, because this (slightly)
	 * quickens the resolution process and can be more efficiently minified.
	 */

	// Objects cache
	var doc = $(document);

	/**
	 * Internal reference: the div holding top notifications
	 * @var jQuery
	 */
	var _topNotificationDiv = false;

	/**
	 * Internal function: retrieve the div holding top notifications
	 *
	 * @return jQuery the div selection
	 */
	function _getTopNotificationDiv()
	{
		if (!_topNotificationDiv)
		{
			_topNotificationDiv = $('

').appendTo(document.body);
		}

		return _topNotificationDiv;
	};

	/**
	 * Internal reference: the div holding bottom notifications
	 * @var jQuery
	 */
	var _bottomNotificationDiv = false;

	/**
	 * Internal function: retrieve the div holding bottom notifications
	 *
	 * @return jQuery the div selection
	 */
	function _getBottomNotificationDiv()
	{
		if (!_bottomNotificationDiv)
		{
			_bottomNotificationDiv = $('

').appendTo(document.body);
		}

		return _bottomNotificationDiv;
	};

	/**
	 * Internal function: output archived notifications
	 *
	 * @param jQuery element the archive element
	 * @param int max the max number of output messages
	 * @param object settings the notify options
	 * @return boolean true if there are some more notifications, else false
	 */
	function _releaseNotices(element, max, settings)
	{
		var archive = element.data('notifications-archive') || [],
			releaseCount = (max > 0) ? Math.min(archive.length, max) : archive.length,
			i, archived;

		// Release messages
		for (i = 0; i < releaseCount; ++i)
		{
			archived = archive.shift();
			window.notify(archived.title, archived.message, $.extend(archived.options, { delay: i*100 }), true);
		}

		// If archive is now empty, clear waiting message block
		if (archive.length === 0)
		{
			element.remove();
			return false;
		}
		else
		{
			// Update number of waiting messages
			archiveSize = archive.length;
			element.text((archiveSize > 1) ? settings.textSeveralMore.replace('%d', archiveSize) : settings.textOneMore);
			return true;
		}
	};

	/**
	 * Internal function: activate notification auto close
	 *
	 * @param jQuery element the notification element
	 * @param int delay delay before the notification closes
	 * @return void
	 */
	function _activateNoticeAutoClose(element, delay)
	{
		// Timer
		element.data('notification-timeout', setTimeout(function() { element.fadeAndRemove().trigger('close'); }, delay));

		// Prevent closing when hover
		element.hover(function()
		{
			clearTimeout(element.data('notification-timeout'));

		}, function()
		{
			element.data('notification-timeout', setTimeout(function() { element.fadeAndRemove().trigger('close'); }, delay));
		});
	};

	/**
	 * Display a notification. If the page is not yet ready, delay the notification until it is ready.
	 *
	 * @var string title the title - can be omitted
	 * @var string message a text or html message to display
	 * @var object options an object with any options for the message - optional (see defaults for more details)
	 * @var boolean rotate force deletion of older element before inserting new one - optional (internal mostly, but can be used if relevant)
	 * @return void
	 */
	window.notify = function(title, message, options, rotate)
	{
		// Parameters
		if (message == undefined || typeof message === 'object')
		{
			options = message || {};
			message = title;
			title = '';
		}

		// Defaults
		options = options || {};
		rotate = rotate || false;

		// If the document is not ready or we want some delay
		if (!$.isReady || (options != undefined && options.delay > 0))
		{
			// Delay action
			var delay = (options != undefined) ? (options.delay || 40) : 40;
			setTimeout(function() { window.notify(title, message, $.extend(options, { delay: 0 }), rotate); }, delay);
		}
		else
		{
			// Position defaults
			if (!options.vPos)
			{
				options.vPos = window.notify.defaults.vPos;
			}
			if (!options.hPos)
			{
				options.hPos = window.notify.defaults.hPos;
			}

			var settings = $.extend({},
							// Global defaults
							window.notify.defaults,
							// Defaults for vertical position
							window.notify.defaults[options.vPos.toLowerCase()],
							// Defaults for horizontal position
							window.notify.defaults[options.hPos.toLowerCase()],
							// Defaults for final position
							window.notify.defaults[options.vPos.toLowerCase()+options.hPos.toLowerCase()],
							// User options
							options);

			// System notification
			if (settings.system && window.notify.hasNotificationPermission())
			{
				var notifTitle = ($.trim(title).length > 0) ? title : document.title,
					notification = window.webkitNotifications.createNotification(settings.icon || '', notifTitle, message);

				// Display event
				if (settings.autoClose || settings.onDisplay)
				{
					notification.ondisplay = function()
					{
						// Callback
						if (settings.onDisplay)
						{
							settings.onDisplay.call(notification);
						}

						// Auto-close after delay
						if (settings.autoClose)
						{
							setTimeout(function () { notification.cancel(); }, settings.closeDelay);
						}
					};
				}

				// Click event
				if ((settings.link && settings.link.length > 0) || settings.onClick)
				{
					notification.onclick = function()
					{
						// Callback
						if (settings.onClick)
						{
							settings.onClick.call(notification);
						}

						// Redirection
						if (settings.link && settings.link.length > 0)
						{
							notification.cancel();
							document.location.href = settings.link;
						}
					};
				}

				// Close event
				if (settings.onClose)
				{
					notification.onclose = function()
					{
						// Callback
						settings.onClose.call(notification);
					};
				}

				// Error handling
				notification.onerror = function()
				{
					// If a callback is provided
					if (settings.onError)
					{
						if (settings.onError.call(notification) === false)
						{
							return;
						}
					}

					// Fallback on standard notification
					window.notify(title, message, $.extend(settings, { system: false }), rotate);
				};

				// Show notification
				notification.show();

				// Done for now
				return;
			}

			var classes = ['notification'].concat(settings.classes),
				listId = 'notifications-'+settings.vPos.toLowerCase()+'-'+settings.hPos.toLowerCase(),
				list = $('#'+listId),
				icon = (settings.icon && settings.icon.length > 0) ? '' : '',
				iconArrowSide = (settings.hPos.toLowerCase() === 'left') ? 'right' : 'left',
				iconArrow = (icon.length > 0 && settings.iconOutside) ? '' : '',
				closeButton = settings.closeButton ? '✕' : '',
				elementTitle = ($.trim(title).length > 0) ? '
'+title+'
' : '',
				altTitle = (settings.title.length > 0) ? ' title="'+settings.title+'"' :'',
				wrapperOpen = (settings.link.length > 0) ? '' :'
',
				wrapperClose = (settings.link.length > 0) ? '' :'
',
				postponed = false,
				more = list.children('.more-notifications'),
				siblings, block, element, effectMargins;

			// Target list
			if (list.length === 0)
			{
				// Create list
				list = $('

').appendTo((settings.vPos.toLowerCase() === 'top') ? _getTopNotificationDiv() : _getBottomNotificationDiv());
			}

			// List of current messages
			siblings = list.children().not('.closing').not('.more-notifications');

			// If grouping similar messages, check if another one is still displayed
			if (settings.groupSimilar)
			{
				siblings.each(function(i)
				{
					var previous = $(this),
						data = previous.data('notification-data'),
						extras, timeout, archive, archiveSize;

					// Compare messages
					if (data.title === title.toLowerCase() && data.message === message.toLowerCase())
					{
						// Get or create the extra messages block
						extras = previous.children('.extra-notifications');
						if (extras.length > 0)
						{
							// Retrieve existing archive
							archive = extras.data('notifications-archive') || [];
						}
						else
						{
							// Create element and archive
							extras = $('

').appendTo(previous);
							archive = [];
						}

						// Stop autoClose
						timeout = previous.data('notification-timeout');
						if (timeout)
						{
							clearTimeout(timeout);
							previous.off('mouseenter');
							previous.off('mouseleave');
						}

						// Re-apply if required
						if (!settings.stickGrouped && (timeout || settings.autoClose))
						{
							_activateNoticeAutoClose(previous, settings.closeDelay);
						}

						// Add message to queue
						archive.push({
							title: title,
							message: message,
							options: options
						});

						// Number of waiting messages
						archiveSize = archive.length;
						extras.text((archiveSize > 1) ? settings.textSeveralSimilars.replace('%d', archiveSize) : settings.textOneSimilar);

						// Save archive
						extras.data('notifications-archive', archive);

						// Effect
						if (!previous.is(':animated'))
						{
							previous.shake((doc.width() >= 768) ? 15 : 5);
						}

						// Done
						postponed = true;
						return false;
					}
				});
			}

			// Check if we exceed the simultaneous messages limit
			if (!postponed && settings.limit > 0 && siblings.length >= settings.limit)
			{
				// If rotation
				if (rotate || settings.rotate)
				{
					// Remove first
					siblings.eq(0).addClass('closing').foldAndRemove();
				}
				else
				{
					// Get or create the waiting messages block
					if (more.length > 0)
					{
						// Retrieve existing archive
						archive = more.data('notifications-archive') || [];
					}
					else
					{
						// Create element and archive
						more = $('

').appendTo(list);
						archive = [];

						// Behavior
						more.click(function(event)
						{
							_releaseNotices(more, settings.releaseLimit, settings);
						});
					}

					// Add message to queue
					archive.push({
						title: title,
						message: message,
						options: options
					});

					// Number of waiting messages
					archiveSize = archive.length;
					more.text((archiveSize > 1) ? settings.textSeveralMore.replace('%d', archiveSize) : settings.textOneMore);

					// Save archive
					more.data('notifications-archive', archive);

					// Done
					postponed = true;
				}
			}

			// If put in a waiting list, exit
			if (postponed)
			{
				return;
			}

			// If no title
			if ($.trim(title).length === 0)
			{
				classes.push('no-title');
			}

			// Append message
			element = $('
'+icon+iconArrow+wrapperOpen+elementTitle+message+wrapperClose+closeButton+'
');
			if (more.length > 0)
			{
				element.insertBefore(more).hide().slideDown();
			}
			else
			{
				element.appendTo(list).hide().fadeIn('slow');
			}

			// Display callback
			if (settings.onDisplay)
			{
				settings.onDisplay.call(element[0]);
			}

			// Function on click
			if (settings.onClick)
			{
				element.children(':first').on('click', settings.onClick);
			}

			// Save some data
			element.data('notification-data', {
				title: title.toLowerCase(),
				message: message.toLowerCase(),
				closeDelay: settings.closeDelay
			});

			// Watch close button
			element.on('close', function()
			{
				// Mark as closing to prevent similar messages to be added
				element.addClass('closing');

				// Check if queued messages
				var more = list.children('.more-notifications');
				if (more.length > 0)
				{
					// Change fade effect to folding
					element.stop(true).foldAndRemove();

					// Release next notification
					_releaseNotices(more, 1, settings);
				}
			});
			if (settings.onClose)
			{
				element.on('close', settings.onClose);
			}

			// If closing
			if (settings.autoClose)
			{
				_activateNoticeAutoClose(element, settings.closeDelay);
			}
		}
	};

	/**
	 * Check if the Notification API is available
	 * @return boolean true if available, else false
	 */
	window.notify.hasNotificationAPI = function()
	{
		return !!window.webkitNotifications;
	};

	/**
	 * Check if the Notification API permission is set
	 * @return boolean true if available, else false
	 */
	window.notify.isNotificationPermissionSet = function()
	{
		return (window.notify.hasNotificationAPI() && window.webkitNotifications.checkPermission() != 1); // 1 is PERMISSION_NOT_ALLOWED
	};

	/**
	 * Check if the Notification API permission is granted
	 * @return boolean true if available, else false
	 */
	window.notify.hasNotificationPermission = function()
	{
		return (window.notify.hasNotificationAPI() && window.webkitNotifications.checkPermission() == 0); // 0 is PERMISSION_ALLOWED
	};

	/**
	 * Display a message asking the user to grant permission to use the notification API
	 * Note: require the developr.message lib is required if target is not defined
	 * @param jQuery|string target the element which will be clicked to trigger the notification, or a string for a message that will be created on top of #main
	 * @param function callback a function to be called when the permission is set, granted or not (optional)
	 * @return void
	 */
	window.notify.showNotificationPermission = function(target, callback)
	{
		var message = false;

		// If not available or already granted
		if (!window.notify.hasNotificationAPI())
		{
			return;
		}

		// If no target, create a message
		if (typeof target === 'string')
		{
			if (!$.fn.message)
			{
				return;
			}

			message = $('#main').message(target, {
				node:		'a',
				classes:	['align-center', 'green-gradient'],
				simpler:	true,
				inset:		true
			});
			target = message;
		}

		// Behavior
		target.click(function(event)
		{
			// Only for target element (should no be triggered by the close button)
			if (event.target !== this)
			{
				return;
			}

			event.preventDefault();
			window.webkitNotifications.requestPermission(function()
			{
				// Remove message if needed
				if (message)
				{
					message.fadeAndRemove();
				}

				// User callback
				if (callback && typeof callback === 'function')
				{
					callback();
				}
			});
		});
	};

	/**
	 * Notify function defaults
	 * @var object
	 */
	window.notify.defaults = {
		/**
		 * Use system notification if available, else fallback on standard notifications
		 * @var boolean
		 */
		system: false,

		/**
		 * Vertical position ('top' or 'bottom')
		 * @var string
		 */
		vPos: 'top',

		/**
		 * Horizontal position ('left', 'center' or 'right')
		 * Note: ignored in mobile screens (the notification takes the full screen width)
		 * @var string
		 */
		hPos: 'right',

		/**
		 * Extra classes (colors...)
		 * @var array
		 */
		classes: [],

		/**
		 * Link on the notification
		 * @var string
		 */
		link: '',

		/**
		 * Title on hover
		 * @var string
		 */
		title: '',

		/**
		 * Icon path
		 * @var string
		 */
		icon: '',

		/**
		 * Icon should show out of the notification block? (ignored for mobile layouts)
		 * @var boolean
		 */
		iconOutside: true,

		/**
		 * Add a close button to the notification
		 * @var boolean
		 */
		closeButton: true,

		/**
		 * Show the close button only on hover
		 * @var boolean
		 */
		showCloseOnHover: true,

		/**
		 * Notice will close after (closeDelay) ms
		 * @var boolean
		 */
		autoClose: true,

		/**
		 * Delay before notification closes
		 * @var int
		 */
		closeDelay: 8000,

		/**
		 * Delay before showing the notification
		 * @var int
		 */
		delay: 0,

		/**
		 * Group similar notifications in a stack
		 * @var boolean
		 */
		groupSimilar: true,

		/**
		 * Prevent autoClose on grouped notifications
		 * @var boolean
		 */
		stickGrouped: false,

		/**
		 * Text when one similar notification is found
		 * @var boolean
		 */
		textOneSimilar: 'One similar notification',

		/**
		 * Text when several similar notifications are found
		 * Note: use %d in your string to get the final count
		 * @var boolean
		 */
		textSeveralSimilars: '%d similar notifications',

		/**
		 * Maximum number of notifications displayed at the same time in one stack
		 * Note: use 0 for no limit, but use with caution!
		 * @var int
		 */
		limit: 7,

		/**
		 * Force rotation (remove older messages) when reaching limit
		 * @var boolean
		 */
		rotate: false,

		/**
		 * Text when one similar notification is found
		 * @var boolean
		 */
		textOneMore: 'One more notification',

		/**
		 * Text when several similar notifications are found
		 * Note: use %d in your string to get the final count
		 * @var boolean
		 */
		textSeveralMore: '%d more notifications',

		/**
		 * Number of notifications released when clicking on an similiar/archive block
		 * Note: use 0 for no limit, but use with caution!
		 * @var int
		 */
		releaseLimit: 5,

		/**
		 * Options for top notifications
		 * @var object
		 */
		top: {},

		/**
		 * Options for bottom notifications
		 * @var object
		 */
		bottom: {},

		/**
		 * Options for left notifications
		 * @var object
		 */
		left: {},

		/**
		 * Options for center notifications
		 * @var object
		 */
		center: {},

		/**
		 * Options for right notifications
		 * @var object
		 */
		right: {},

		/**
		 * Options for top left notifications
		 * @var object
		 */
		topleft: {},

		/**
		 * Options for top center notifications
		 * @var object
		 */
		topcenter: {},

		/**
		 * Options for top right notifications
		 * @var object
		 */
		topright: {},

		/**
		 * Options for bottom left notifications
		 * @var object
		 */
		bottomleft: {},

		/**
		 * Options for bottom center notifications
		 * @var object
		 */
		bottomcenter: {},

		/**
		 * Options for bottom right notifications
		 * @var object
		 */
		bottomright: {},

		/**
		 * Callback when the notification is shown
		 * @var function
		 */
		onDisplay: null,

		/**
		 * Callback when the notification is clicked
		 * @var function
		 */
		onClick: null,

		/**
		 * Callback when the notification is closed
		 * @var function
		 */
		onClose: null,

		/**
		 * Callback (if using the Notification API system only) if the notification triggers an error.
		 * By default, the lib will fallback on a standard notification, the callback may return false to prevent this.
		 * @var function
		 */
		onError: null
	};

})(jQuery, window, document);


text:
import Ember from 'ember';
import CattleTransitioningController from 'ui/mixins/cattle-transitioning-controller';

export default Ember.Controller.extend(CattleTransitioningController, {
  availableActions: function() {
    var a = this.get('model.actions');

    return [
      { label: 'Delete',        icon: 'ss-trash', action: 'promptDelete', enabled: this.get('model.canDelete'), altAction: 'delete' },
      { divider: true },
      { label: 'Restore',       icon: '',         action: 'restore',      enabled: !!a.restore },
      { label: 'Purge',         icon: '',         action: 'purge',        enabled: !!a.purge },
    ];
  }.property('model.actions.{restore,purge}','model.canDelete'),
});


text:
import pytest
from plenum.client.wallet import Wallet
from plenum.common.constants import CURRENT_PROTOCOL_VERSION
from plenum.common.exceptions import InsufficientSignatures
from plenum.common.request import Request
from plenum.common.util import getTimeBasedId
from plenum.server.client_authn import CoreAuthNr
from plenum.test.helper import randomOperation
from stp_core.crypto.util import randomSeed

def add_and_sign(signersNum=10):
    beforeSignTimeBasedId = getTimeBasedId()
    wallet = Wallet("shared wallet")
    idrs = []
    for i in range(signersNum):
        identifier = "signer_{}".format(i)
        idrs.append(identifier)
        wallet.addIdentifier(identifier)
    for idr in idrs:
        signed = wallet.signOp(op={}, identifier=idr)
        afterSignTimeBasedId = getTimeBasedId()
        assert beforeSignTimeBasedId < signed.reqId < afterSignTimeBasedId

def test_wallet_uses_store():
    add_and_sign(signersNum=1)

def test_wallet_used_with_multiple_signers():
    add_and_sign(signersNum=10)

def test_wallet_multisig():
    wallet = Wallet()
    idr1, signer1 = wallet.addIdentifier()
    idr2, signer2 = wallet.addIdentifier()
    idr3, signer3 = wallet.addIdentifier()
    authnr = CoreAuthNr([], [], [])
    for idr, signer in [(idr1, signer1), (idr2, signer2), (idr3, signer3)]:
        authnr.addIdr(idr, signer.verkey)

    def serz(req):
        return {k: v for k, v in req.as_dict.items()
                if k not in authnr.excluded_from_signing}

    op = randomOperation()
    request = Request(reqId=Request.gen_req_id(), operation=op,
                      protocolVersion=CURRENT_PROTOCOL_VERSION, identifier=idr1)
    req = wallet.sign_using_multi_sig(request=request, identifier=idr1)
    assert len(req.signatures) == 1
    req_data = serz(req)
    assert set(authnr.authenticate_multi(req_data, req.signatures, 1)) == {idr1, }
    with pytest.raises(InsufficientSignatures):
        authnr.authenticate_multi(req_data, req.signatures, 2)

    req = wallet.sign_using_multi_sig(request=req, identifier=idr2)
    assert len(req.signatures) == 2
    req_data = serz(req)
    assert set(authnr.authenticate_multi(req_data, req.signatures, 2)) == {idr1,
                                                                           idr2}
    with pytest.raises(InsufficientSignatures):
        authnr.authenticate_multi(req_data, req.signatures, 3)

    wallet.do_multi_sig_on_req(req, identifier=idr3)
    assert len(req.signatures) == 3
    req_data = serz(req)
    assert set(authnr.authenticate_multi(req_data, req.signatures, 3)) == {idr1,
                                                                           idr2,
                                                                           idr3}


text:
require 'logger'

module Rack
  class Cors
    def initialize(app, opts={}, &block)
      @app = app
      @logger = opts[:logger]
      @debug_mode = !!opts[:debug]

      if block_given?
        if block.arity == 1
          block.call(self)
        else
          instance_eval(&block)
        end
      end
    end

    def allow(&block)
      all_resources << (resources = Resources.new)

      if block.arity == 1
        block.call(resources)
      else
        resources.instance_eval(&block)
      end
    end

    def call(env)
      env['HTTP_ORIGIN'] = 'file://' if env['HTTP_ORIGIN'] == 'null'
      env['HTTP_ORIGIN'] ||= env['HTTP_X_ORIGIN']

      cors_headers = nil
      if env['HTTP_ORIGIN']
        debug(env) do
          [ 'Incoming Headers:',
            "  Origin: #{env['HTTP_ORIGIN']}",
            "  Access-Control-Request-Method: #{env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']}",
            "  Access-Control-Request-Headers: #{env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
            ].join("\n")
        end
        if env['REQUEST_METHOD'] == 'OPTIONS' and env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
          if headers = process_preflight(env)
            debug(env) do
              "Preflight Headers:\n" +
                  headers.collect{|kv| "  #{kv.join(': ')}"}.join("\n")
            end
            return [200, headers, []]
          end
        else
          cors_headers = process_cors(env)
        end
      end
      status, headers, body = @app.call env
      if cors_headers
        headers = headers.merge(cors_headers)

        # http://www.w3.org/TR/cors/#resource-implementation
        unless headers['Access-Control-Allow-Origin'] == '*'
          vary = headers['Vary']
          headers['Vary'] = ((vary ? vary.split(/,\s*/) : []) + ['Origin']).uniq.join(', ')
        end
      end
      [status, headers, body]
    end

    protected
      def debug(env, message = nil, &block)
        if @debug_mode
          logger = @logger || env['rack.logger'] || begin
            @logger = ::Logger.new(STDOUT).tap {|logger| logger.level = ::Logger::Severity::INFO}
          end
          logger.debug(message, &block)
        end
      end

      def all_resources
        @all_resources ||= []
      end

      def process_preflight(env)
        resource = find_resource(env['HTTP_ORIGIN'], env['PATH_INFO'],env)
        resource && resource.process_preflight(env)
      end

      def process_cors(env)
        resource = find_resource(env['HTTP_ORIGIN'], env['PATH_INFO'],env)
        resource.to_headers(env) if resource
      end

      def find_resource(origin, path, env)
        all_resources.each do |r|
          if r.allow_origin?(origin, env) and found = r.find_resource(path)
            return found
          end
        end
        nil
      end

      class Resources
        def initialize
          @origins = []
          @resources = []
          @public_resources = false
        end

        def origins(*args,&blk)
          @origins = args.flatten.collect do |n|
            case n
            when Regexp, /^https?:\/\// then n
            when 'file://'              then n
            when '*'                    then @public_resources = true; n
            else                        ["http://#{n}", "https://#{n}"]
            end
          end.flatten
          @origins.push(blk) if blk
        end

        def resource(path, opts={})
          @resources << Resource.new(public_resources?, path, opts)
        end

        def public_resources?
          @public_resources
        end

        def allow_origin?(source,env = {})
          return true if public_resources?
          return !! @origins.detect do |origin|
            if origin.is_a?(Proc)
              origin.call(source,env)
            else
              origin === source
            end
          end
        end

        def find_resource(path)
          @resources.detect{|r| r.match?(path)}
        end
      end

      class Resource
        attr_accessor :path, :methods, :headers, :expose, :max_age, :credentials, :pattern

        def initialize(public_resource, path, opts={})
          self.path        = path
          self.methods     = ensure_enum(opts[:methods]) || [:get]
          self.credentials = opts[:credentials].nil? ? true : opts[:credentials]
          self.max_age     = opts[:max_age] || 1728000
          self.pattern     = compile(path)
          @public_resource = public_resource

          self.headers = case opts[:headers]
          when :any then :any
          when nil then nil
          else
            [opts[:headers]].flatten.collect{|h| h.downcase}
          end

          self.expose = opts[:expose] ? [opts[:expose]].flatten : nil
        end

        def match?(path)
          pattern =~ path
        end

        def process_preflight(env)
          return nil if invalid_method_request?(env) || invalid_headers_request?(env)
          {'Content-Type' => 'text/plain'}.merge(to_preflight_headers(env))
        end

        def to_headers(env)
          x_origin = env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
          h = {
            'Access-Control-Allow-Origin'     => origin_for_response_header(env['HTTP_ORIGIN']),
            'Access-Control-Allow-Methods'    => methods.collect{|m| m.to_s.upcase}.join(', '),
            'Access-Control-Expose-Headers'   => expose.nil? ? '' : expose.join(', '),
            'Access-Control-Max-Age'          => max_age.to_s }
          h['Access-Control-Allow-Credentials'] = 'true' if credentials
          h
        end

        protected
          def public_resource?
            @public_resource
          end

          def origin_for_response_header(origin)
            return '*' if public_resource? && !credentials
            origin == 'file://' ? 'null' : origin
          end

          def to_preflight_headers(env)
            h = to_headers(env)
            if env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
              h.merge!('Access-Control-Allow-Headers' => env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])
            end
            h
          end

          def invalid_method_request?(env)
            request_method = env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
            request_method.nil? || !methods.include?(request_method.downcase.to_sym)
          end

          def invalid_headers_request?(env)
            request_headers = env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
            request_headers && !allow_headers?(request_headers)
          end

          def allow_headers?(request_headers)
            return false if headers.nil?
            headers == :any || begin
              request_headers = request_headers.split(/,\s*/) if request_headers.kind_of?(String)
              request_headers.all?{|h| headers.include?(h.downcase)}
            end
          end

          def ensure_enum(v)
            return nil if v.nil?
            [v].flatten
          end

          def compile(path)
            if path.respond_to? :to_str
              special_chars = %w{. + ( )}
              pattern =
                path.to_str.gsub(/((:\w+)|[\*#{special_chars.join}])/) do |match|
                  case match
                  when "*"
                    "(.*?)"
                  when *special_chars
                    Regexp.escape(match)
                  else
                    "([^/?&#]+)"
                  end
                end
              /^#{pattern}$/
            elsif path.respond_to? :match
              path
            else
              raise TypeError, path
            end
          end
      end

  end
end


text:
/* Dooba Firmware - avr8
 * Moka Mobile Phone
 *
 * by Eresse <eresse@dooba.io>
 */

// External Includes
#include <stdlib.h>
#include <ssd1306/menu.h>
#include <trill/sdcard.h>

// Internal Includes
#include "ui.h"
#include "img.h"
#include "ui/menu.h"
#include "ui/dialog.h"
#include "views/home.h"
#include "views/shdn.h"
#include "views/main_menu.h"
#include "views/sdcard_menu.h"
#include "views/config/music_config.h"
#include "views/config/notif_config.h"
#include "views/system_menu.h"

// Enter System Menu
void moka_system_menu_enter()
{
	// Setup Menu
	ssd1306_menu_init(&moka_menu, SSD1306_MENU_STYLE_LINE16, moka_menu_items, MOKA_MENU_BUF_SIZE);
	ssd1306_menu_add_item(&moka_menu, "Notification", MOKA_SYSTEM_MENU_NOTIF, moka_icon_led);
	ssd1306_menu_add_item(&moka_menu, "Music", MOKA_SYSTEM_MENU_MUSIC, moka_icon_music);
	if(trill_sdcard_ok)																			{ ssd1306_menu_add_item(&moka_menu, "SD Card", MOKA_SYSTEM_MENU_SDCARD, moka_icon_microsd); }
	ssd1306_menu_add_item(&moka_menu, "Shutdown", MOKA_SYSTEM_MENU_SHDN, moka_icon_shdn);

	// Enter Menu State
	moka_menu_enter(moka_system_menu_event);
}

// System Menu Event Callback
void moka_system_menu_event(uint8_t event)
{
	// Check Event
	if(event == MOKA_MENU_EVENT_SELECT)
	{
		// Item Selected - Enter Sub-menu
		if(moka_menu_items[moka_menu.selected].user == MOKA_SYSTEM_MENU_SHDN)					{ moka_dialog_enter("Your phone will shut down.      Are you sure?", MOKA_DIALOG_BTNSTYLE_YES_NO, moka_system_menu_shdn_confirm, moka_system_menu_enter); }
		else if(moka_menu_items[moka_menu.selected].user == MOKA_SYSTEM_MENU_SDCARD)			{ moka_sdcard_menu_enter(); }
		else if(moka_menu_items[moka_menu.selected].user == MOKA_SYSTEM_MENU_MUSIC)				{ moka_music_config_menu_enter(); }
		else if(moka_menu_items[moka_menu.selected].user == MOKA_SYSTEM_MENU_NOTIF)				{ moka_notif_config_menu_enter(); }
		else																					{ /* NoOp */ }
	}
	else if(event == MOKA_MENU_EVENT_BACK)														{ moka_main_menu_enter(); }
	else if(event == MOKA_MENU_EVENT_CANCEL)													{ moka_home_enter(); }
	else																						{ /* NoOp */ }
}

// Shutdown Confirmation (Dialog Event Callback)
void moka_system_menu_shdn_confirm()
{
	// Enter Shutdown
	moka_shdn_enter();
}


text:
{{menu.currentPage|humanizeDoc}}

<md-button> is a button directive with optional ink ripples (default enabled).

If you supply a href or ng-href attribute, it will become an <a> element. Otherwise, it will
become a <button> element.

As per the material design spec
the FAB button is in the accent color by default. The primary color palette may be used with
the md-primary class.

Usage

    <hljs lang="html">
 <md-button>
   Flat Button
 </md-button>
 <md-button href="http://google.com">
   Flat link
 </md-button>
 <md-button class="md-raised">
   Raised Button
 </md-button>
 <md-button ng-disabled="true">
   Disabled Button
 </md-button>
 <md-button class="md-fab" aria-label="FAB">
   <md-icon md-svg-src="your/icon.svg"></md-icon>
 </md-button>
 <md-button class="md-fab md-mini" aria-label="Mini FAB">
   <md-icon md-svg-src="your/icon.svg"></md-icon>
 </md-button>
 <md-button class="md-icon-button" aria-label="Custom Icon Button">
   <md-icon md-svg-icon="path/to/your.svg"></md-icon>
 </md-button>
</hljs>

      Attributes

      Parameter
      Type
      Description

          md-no-ink

boolean

boolean

If present, disable ripple ink effects.

          ng-disabled

expression

expression

En/Disable based on the expression

          md-ripple-size

string

string

Overrides the default ripple size logic. Options: full, partial, auto

          aria-label

string

string

Adds alternative text to button for accessibility, useful for icon buttons.
If no default text is found, a warning will be logged.


text:
package com.amazonaws.services.workdocs.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RemoveAllResourcePermissionsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API.
     *

     */
    private String authenticationToken;
    /**
     *

     * The ID of the resource.
     *

     */
    private String resourceId;

    /**
     *

     * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API.
     *

     *
     * @param authenticationToken
     *        Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the
     *        API.
     */

    public void setAuthenticationToken(String authenticationToken) {
        this.authenticationToken = authenticationToken;
    }

    /**
     *

     * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API.
     *

     *
     * @return Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the
     *         API.
     */

    public String getAuthenticationToken() {
        return this.authenticationToken;
    }

    /**
     *

     * Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the API.
     *

     *
     * @param authenticationToken
     *        Amazon WorkDocs authentication token. Not required when using AWS administrator credentials to access the
     *        API.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public RemoveAllResourcePermissionsRequest withAuthenticationToken(String authenticationToken) {
        setAuthenticationToken(authenticationToken);
        return this;
    }

    /**
     *

     * The ID of the resource.
     *

     *
     * @param resourceId
     *        The ID of the resource.
     */

    public void setResourceId(String resourceId) {
        this.resourceId = resourceId;
    }

    /**
     *

     * The ID of the resource.
     *

     *
     * @return The ID of the resource.
     */

    public String getResourceId() {
        return this.resourceId;
    }

    /**
     *

     * The ID of the resource.
     *

     *
     * @param resourceId
     *        The ID of the resource.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public RemoveAllResourcePermissionsRequest withResourceId(String resourceId) {
        setResourceId(resourceId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAuthenticationToken() != null)
            sb.append("AuthenticationToken: ").append("***Sensitive Data Redacted***").append(",");
        if (getResourceId() != null)
            sb.append("ResourceId: ").append(getResourceId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof RemoveAllResourcePermissionsRequest == false)
            return false;
        RemoveAllResourcePermissionsRequest other = (RemoveAllResourcePermissionsRequest) obj;
        if (other.getAuthenticationToken() == null ^ this.getAuthenticationToken() == null)
            return false;
        if (other.getAuthenticationToken() != null && other.getAuthenticationToken().equals(this.getAuthenticationToken()) == false)
            return false;
        if (other.getResourceId() == null ^ this.getResourceId() == null)
            return false;
        if (other.getResourceId() != null && other.getResourceId().equals(this.getResourceId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getAuthenticationToken() == null) ? 0 : getAuthenticationToken().hashCode());
        hashCode = prime * hashCode + ((getResourceId() == null) ? 0 : getResourceId().hashCode());
        return hashCode;
    }

    @Override
    public RemoveAllResourcePermissionsRequest clone() {
        return (RemoveAllResourcePermissionsRequest) super.clone();
    }

}


text:
package com.kanomiya.steward.model.assets.resource;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Iterator;

import com.google.gson.Gson;
import com.kanomiya.steward.model.assets.resource.type.ResourceType;

/**
 * @author Kanomiya
 *
 */
public class ResourceSaver<R extends IResource> {

	protected ResourceType<R> type;
	protected ResourceRegistry<R> registry;

	public ResourceSaver(ResourceType<R> type, ResourceRegistry defaulz)
	{
		this.type = type;
		if (defaulz == null) defaulz = new ResourceRegistry<R>();
		registry = defaulz;
	}

	public ResourceSaver<R> save(File saveBaseDir, Gson gson) throws IOException
	{
		if (! type.enableSave()) return this;

		File baseDir = new File(saveBaseDir, type.getDirName());
		if (baseDir.exists())
		{

			FileVisitor<Path> deleter = new SimpleFileVisitor<Path>() {
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
				{
					file.toFile().delete();

					return FileVisitResult.CONTINUE;
				}
			};

			Files.walkFileTree(baseDir.toPath(), deleter);
		}

		baseDir.mkdirs();

		Iterator<R> resItr = registry.values().iterator();

		while (resItr.hasNext())
		{
			R resource = resItr.next();

			type.save(resource, baseDir, gson);
		}

		return this;
	}

}


text:
using System.Threading;
using System.Threading.Tasks;

namespace TIKSN.Data.AzureStorage
{
    public interface IAzureBlobStorageRepositoryInitializer
    {
        Task InitializeAsync(CancellationToken cancellationToken);
    }
}