text:
A simple rest query framework. Web framework use flask, orm by peewee, form by wtform and query by [rest_query](https://github.com/dracarysX/rest_query). The framework implements custom [query](https://postgrest.com) api(like this: /?select=id,name&id=gte.20), save form data, model object serializer, APIMethodView(get, post, put,delete) and errorhandler.

## Select API

`select id, name, age from Author where name = '%dracarysX' and age >= 25`

    curl http://localhost/authors?select=id,age,name&name=like.dracarys&age=gte.25

`select Book.id, Book.name, Author.id, Author.name from Book inner join Author on Book.author_id = Author.id where Book.id = 10`

    curl http://localhost/books?select=id,name,author{id,name}&id=10

`select id, name from Book order by id desc limit 1, 2`

    curl http://localhost/books?select=id,name&page=1&limit=2&order=id.desc

## Installing and Testing

For now, i did not push this package to public repository. so you can install by source code.

Use `virtualenv`:

    > git clone https://github.com/dracarysX/flask_restapi.git
    > cd flask_restapi
    > virtualenv --no-site-packages venv
    > source venv/bin/activate
    > python setup.py install
    > python setup.py test

## Usage

### declare model

```python
class Author(UUIDBaseModel):
	id = PrimaryKeyField()
	name = CharField(max_length=50, unique=True)
	age = IntegerField(default=0)

	class Meta:
		db_table = 'Author'

	def __repr__(self):
		return u'<Author {}>'.format(self.name)
```

### declare form

```python
class AuthorForm(PeeweeForm):
	name = StringField(
		label='Name',
		validators=[DataRequired(), Length(max=50), Unique(
			field='name',
			message='author is exist'
		)]
	)
	age = IntegerField(
		label='Age',
		validators=[DataRequired(), NumberRange(0, 150)]
	)

	class Meta:
		model = Author
```

### declare view

```python
class AuthorView(APIMethodView):
	model = Author
	paginate_by = 10
	context_object_name = 'items'
	pk_url_kwarg = 'author_id'
	form_class = AuthorForm
```

After that we achieve create、update、select and delete for `Author`.

    > curl http://127.0.0.1:5000/authors
    {
		"status": {
			"message": "200 OK",
			"code": 0
		},
		"data": {
			"count": 0,
			"items": [],
			"limit": 10,
			"page": 1,
			"max_page": 0
			}
		}
	}
    # select * from Author where age > 25
    > curl http://127.0.0.1:5000/authors?age=gt.25
    # select * from Author where name = '%wwx'
    > curl http://127.0.0.1:5000/authors?name=like.wwx
    # select id from Author
    > curl http://127.0.0.1:5000/authors?select=id

## Example

View [Example](https://github.com/dracarysX/flask_restapi/blob/master/example/README.md)

## Contact

Email: `huiquanxiong@gmail.com`

## License

MIT


text:
// ~> Library
// ~A Scott Smereka

var isInit = false, log;

/* Get Date Difference
 * Returns the difference between two dates.
 * A Postitive number is a date in the future where negative is in the past.
 */
function getDateDiff(date1, date2) {
  if( ! (date1 instanceof Date) || ! (date2 instanceof Date))
    return undefined
  return (date1.getTime() - date2.getTime());
}

var lib = {

  diff: function diff(date1, date2) {
    return diff[date1, date2] || (diff[date1, date2] = function(req, res, next) {
      return getDateDiff(date1, date2);
    });
  },

  diffMilliseconds: function diffMilliseconds(date1, date2) {
    return diffMilliseconds[date1, date2] || (diffMilliseconds[date1, date2] = function(req, res, next) {
      return getDateDiff(date1, date2);
    });
  },

  diffSeconds: function diffSeconds(date1, date2) {
    return diffSeconds[date1, date2] || (diffSeconds[date1, date2] = function(req, res, next) {
      return getDateDiff(date1, date2) / 1000;
    });
  },

  diffMinutes: function diffMinutes(date1, date2) {
    return diffMinutes[date1, date2] || (diffMinutes[date1, date2] = function(req, res, next) {
      return getDateDiff(date1, date2) / (1000 * 60);
    });
  },

  diffHours: function diffHours(date1, date2) {
    return diffHours[date1, date2] || (diffHours[date1, date2] = function(req, res, next) {
      return getDateDiff(date1, date2) / (1000 * 60 * 60);
    });
  },

  diffDays: function diffDays(date1, date2) {
    return diffDays[date1, date2] || (diffDays[date1, date2] = function(req, res, next) {
      return getDateDiff(date1, date2) / (1000 * 60 * 60 * 24);
    });
  }
}

/* ************************************************** *
 * ******************** Initialization Method
 * ************************************************** */

var init = function(config) {
  if(isInit) {
    return lib;
  } else {
    log      = require(config.paths.serverLibFolder + "log")(config);
    isInit   = true;
    return lib;
  }
}

// Export the library function.
exports = module.exports = init;

redpajama_set_name: RedPajamaGithub


text:
package cn.edu.hhu.reg.api;

import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import cn.edu.hhu.reg.entity.Department;
import cn.edu.hhu.reg.entity.Doctor;
import cn.edu.hhu.reg.entity.Registration;
import cn.edu.hhu.reg.entity.UserLogin;
import cn.edu.hhu.reg.entity.UserProfile;

public class  ResponseUtils{

	private static JsonParser jsonParser = new JsonParser();
	private static Gson gson= new Gson();

	public static  SimpleResponse<Object> SimpleResponse(String response) throws Exception{
		SimpleResponse<Object> simpleResponse = null;
		try {
			JsonElement jsonElement = jsonParser.parse(response);
			Type type = new TypeToken<SimpleResponse<Object>>(){}.getType();
			simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}
	public static SimpleResponse<UserLogin> loginResponse(String response) throws Exception{
		SimpleResponse<UserLogin> simpleResponse  = null;
		try {
		JsonElement jsonElement = jsonParser.parse(response);
		Type type = new TypeToken<SimpleResponse<UserLogin>>(){}.getType();
		simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}
	public static SimpleResponse<UserProfile> proflileResponse(String response) throws Exception{
		SimpleResponse<UserProfile> simpleResponse  = null;
		try {
		JsonElement jsonElement = jsonParser.parse(response);
		Type type = new TypeToken<SimpleResponse<UserProfile>>(){}.getType();
		simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}

	public static SimpleResponse<ArrayList<Department>> departmentListResponse(String response) throws Exception{
		SimpleResponse<ArrayList<Department>> simpleResponse  = null;
		try {
		JsonElement jsonElement = jsonParser.parse(response);
		Type type = new TypeToken<SimpleResponse<ArrayList<Department>>>(){}.getType();
		simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}

	public static SimpleResponse<ArrayList<Doctor>> doctorListResponse(String response) throws Exception{
		SimpleResponse<ArrayList<Doctor>> simpleResponse  = null;
		try {
		JsonElement jsonElement = jsonParser.parse(response);
		Type type = new TypeToken<SimpleResponse<ArrayList<Doctor>>>(){}.getType();
		simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}

	public static SimpleResponse<Registration> registrationResponse(String response) throws Exception{
		SimpleResponse<Registration> simpleResponse  = null;
		try {
		JsonElement jsonElement = jsonParser.parse(response);
		Type type = new TypeToken<SimpleResponse<Registration>>(){}.getType();
		simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}

	public static SimpleResponse<ArrayList<Registration>> registrationListResponse(String response) throws Exception{
		SimpleResponse<ArrayList<Registration>> simpleResponse  = null;
		try {
		JsonElement jsonElement = jsonParser.parse(response);
		Type type = new TypeToken<SimpleResponse<ArrayList<Registration>>>(){}.getType();
		simpleResponse = gson.fromJson(jsonElement, type);
		} catch (Exception e) {
			throw new Exception("返回值错误!");
		}
		return simpleResponse;
	}
}


text:
@implementation GLKApplication
// From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
// This works around an AppKit bug, where key up events while holding
// down the command key don't get sent to the key window.
- (void)sendEvent:(NSEvent *)event {
    if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask))
        [[self keyWindow] sendEvent:event];
    else
        [super sendEvent:event];
}

@end


text:
def user(): return dict(form=auth())
def download(): return response.download(request,db)
def call(): return service()
### end requires
import actions, getNewData, os

@auth.requires_membership('admin')
def delCharts():
    if actions.delCharts(os,request.folder):
        return 'jQuery(".flash").html("Charts Folder is now Empty!")\
           .slideDown().delay(1000).slideUp();'

@auth.requires_membership('admin')
def updateCharts():
    print "Update Charts.."
    session.forget(response)
    scheduler.queue_task('updateCharts', task_name='new', timeout=300)
    #actions.updateGraphs(os,db,request.folder)
    return 'jQuery(".flash").html("Charts Update: job sent").slideDown().delay(2000).slideUp();'

@auth.requires_membership('admin')
def updateMap2():
    session.forget(response)
    scheduler.queue_task('updateMaps', task_name='new', timeout=300)

@auth.requires_membership('admin')
def updateStations():
    for station in db(db.stations).select():
        item = getNewData.station(station.noa_url,station.data_to)
        actions.updateRain(db, session, station.id, vars(item)['_data'])
        actions.updateTemp(db, session, station.id, vars(item)['_data'])
        db(db.stations.id == station.id).update(data_to=vars(item)['_info']['to'])
    actions.calc_data(db, session, redirect, URL, request)
    msg = "OK"
    return 'jQuery(".flash").html("Stations Update: ' + msg + '").slideDown().delay(2000).slideUp();'

@auth.requires_membership('admin')
def clearAll():
    try:
        db(db.stations).delete()
        db(db.emydata).delete()
        db(db.noadata).delete()
        db(db.alldata).delete()
        db(db.temp_noadata).delete()
        db(db.temp_emydata).delete()
        db(db.temp_alldata).delete()
        db(db.current).delete()
        actions.delCharts(os,request.folder)
        msg = "OK"
    except:
        msg = "FAIL"
    return 'jQuery(".flash").html("Clearing GDM: ' \
           + msg + '").slideDown().delay(2000).slideUp();'

@auth.requires_membership('admin')
def index():
    #redirect(URL('default', 'index'))
    allItems = []

    update_charts = BUTTON('update charts', _id='btn1', _onclick="ajax('"+URL('updateCharts')+"',['btn1'],':eval')")
    allItems.append(update_charts)

    clear_db = BUTTON('clear charts', _id="btn2", _onclick="ajax('"+URL('delCharts')+"',['btn2'],':eval')")
    allItems.append(clear_db)

    update_maps = BUTTON('update maps', _id="btn3", _onclick="ajax('"+URL('updateMap')+"',['btn3'],':eval')")
    allItems.append(update_maps)

    update_current = BUTTON('update current', _id="btn4", _onclick="ajax('"+URL('updateCurrent')+"',['btn4'],':eval')")
    allItems.append(update_current)

    return dict(allItems=allItems)

@auth.requires_membership('admin')
def panel():
    allItems = []
    update_stations = BUTTON('Update Stations', _id="btn4", _onclick="ajax('"+URL('admin', 'updateStations')+"',[''],':eval');jQuery('.flash').html('Please Wait...').slideDown();")
    allItems.append(update_stations)
    update_charts = BUTTON('Update Charts', _id='btn1', _onclick="ajax('"+URL('admin', 'updateCharts')+"',[''],':eval');jQuery('.flash').html('Please Wait...').slideDown();")
    allItems.append(update_charts)
    update_maps = BUTTON('Update Estimation/Map', _id="btn3", _onclick="ajax('"+URL('admin', 'updateMap2')+"', ['header'],':eval');jQuery('.flash').html('Please Wait...').slideDown().delay(2000).slideUp();;")
    allItems.append(update_maps)

    if auth.user.username == "atzorvas" or auth.user.username == "stavrosana":
        clear_app = BUTTON('Clear App', _id='btn1', _onclick="ajax('"+URL('admin', 'clearAll')+"',[''],':eval');jQuery('.flash').html('Please Wait...').slideDown();")
        allItems.append(clear_app)
    return dict(items=allItems)

@auth.requires_membership('admin')
def list_users():
    btn = lambda row: A("Edit", _href=URL('editUser', args=row.auth_user.id))
    db.auth_user.edit = Field.Virtual(btn)
    rows = db(db.auth_user).select()
    headers = ["ID", "Username", "Name", "Last Name", "Email", "Edit"]
    fields = ['id', "username", 'first_name', 'last_name', "email", "edit"]
    table = TABLE(THEAD(TR(*[B(header) for header in headers])),
                  TBODY(*[TR(*[TD(row[field]) for field in fields]) \
                        for row in rows]))
    table["_class"] = "table table-striped table-bordered table-condensed"
    return dict(usersTable=table)

@auth.requires_membership('admin')
def editUser():
    this_user = db.auth_user(db.auth_user.id==request.args(0))
    res = db.auth_membership(db.auth_membership.user_id==request.args(0))
    this_role = res.group_id
    form = SQLFORM.factory(Field('firstName', default=this_user.first_name, label="First Name"),
                            Field('lastName', default=this_user.last_name, label="Last Name"),
                            #Field('password', 'password', default=this_user.password, label="Password"),
                            Field('role', requires=IS_IN_DB(db(db.auth_group.description=="custom group"),
                                          db.auth_group, '%(role)s', orderby=db.auth_group.id),
                                          default=this_role, widget=SQLFORM.widgets.radio.widget))
    form.add_button('All Users', URL('admin', 'list_users'))
    form.add_button('Admin Panel', URL('admin', 'panel'))
    if form.process(formname='form_two').accepted:
        response.flash = 'user profile changed'
        db(db.auth_user.id == this_user.id).update(first_name=request.vars.firstName, last_name=request.vars.lastName)
        db.auth_membership.update_or_insert(db.auth_membership.user_id==this_user.id, user_id=this_user.id, group_id=request.vars.role)
        #print len(res)
        redirect(URL('editUser', args=this_user.id))
    return dict(form=form)


text:
require 'rails_helper'

RSpec.describe Award, type: :model do
  it { is_expected.to validate_presence_of :name }
  it { is_expected.to belong_to :award_type }
  it { is_expected.to belong_to :branch }
  it { is_expected.to have_many(:personas).through :award_recipients }
end


text:
package views;

import java.awt.Color;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;

public class LoginView extends JFrame {

	private JPanel contentPane;
	private JTextField txtUsername;
	private JPasswordField txtPassword;
	private JButton btnLogin;
	private JButton btnCancel;

	public LoginView() {
		setTitle("Login");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 402, 182);
		setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblUsername = new JLabel("Username: ");
		lblUsername.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblUsername.setBounds(44, 40, 79, 14);
		contentPane.add(lblUsername);

		JLabel lblPassword = new JLabel("Password:");
		lblPassword.setFont(new Font("Tahoma", Font.BOLD, 11));
		lblPassword.setBounds(44, 81, 79, 14);
		contentPane.add(lblPassword);

		txtUsername = new JTextField();
		txtUsername.setBounds(111, 37, 188, 20);
		contentPane.add(txtUsername);
		txtUsername.setColumns(10);

		txtPassword = new JPasswordField();
		txtPassword.setBounds(111, 78, 188, 20);
		contentPane.add(txtPassword);
		txtPassword.setColumns(10);

		btnLogin = new JButton("Log In");
		btnLogin.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnLogin.setBounds(180, 121, 91, 23);
		contentPane.add(btnLogin);

		btnCancel = new JButton("Cancel");
		btnCancel.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnCancel.setBounds(293, 121, 91, 23);
		contentPane.add(btnCancel);
	}

	public String getUsername()
	{
		return txtUsername.getText();
	}

	public String getPassword()
	{
		return new String(txtPassword.getPassword());
	}

	public void addConfirmListener(ActionListener listenForConfirm)
	{
		btnLogin.addActionListener(listenForConfirm);
	}

	public void addCancelListener(ActionListener listenForCancel)
	{
		btnCancel.addActionListener(listenForCancel);
	}

	public void setUsername(String string) {
		// TODO Auto-generated method stub
		txtUsername.setText(string);
	}

	public void setPassword(String string) {
		// TODO Auto-generated method stub
		txtPassword.setText(string);
	}

}


text:
module.exports = {
    'func-names': 'off',
    'require-await': 'off',
    'no-return-await': 'off',
    'no-process-exit': 'off',
    'no-underscore-dangle': 'off',
    'max-lines-per-function': 'off',

    'promise/always-return': 'off',
    'promise/no-callback-in-promise': 'off',

    'import/exports-last': 'off',
    'import/group-exports': 'off',
    'import/no-absolute-path': 'off',
    'import/max-dependencies': 'off',
    'import/no-unused-modules': 'off',
    'import/prefer-default-export': 'off',
    'import/no-anonymous-default-export': 'off',

    'unicorn/no-null': 'off',
    'unicorn/import-style': 'off',
    'unicorn/no-empty-file': 'off',
    'unicorn/prefer-spread': 'off',
    'unicorn/prefer-module': 'off',
    'unicorn/no-process-exit': 'off',
    'unicorn/no-array-reduce': 'off',
    'unicorn/no-array-for-each': 'off',
    'unicorn/prefer-node-protocol': 'off',
    'unicorn/no-unused-properties': 'off',
    'unicorn/prefer-query-selector': 'off',
    'unicorn/prefer-dom-node-remove': 'off',

    '@typescript-eslint/return-await': 'off',
    '@typescript-eslint/no-type-alias': 'off',
    '@typescript-eslint/member-ordering': 'off',
    '@typescript-eslint/no-restricted-imports': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/restrict-template-expressions': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'off',
};


text:
package org.opensaml.samlext.saml2mdquery.impl;

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

import javax.xml.namespace.QName;

import org.opensaml.saml2.metadata.Endpoint;
import org.opensaml.samlext.saml2mdquery.AuthnQueryDescriptorType;

/**
 * Concrete implementation of {@link AuthnQueryDescriptorType}.
 */
public class AuthnQueryDescriptorTypeImpl extends QueryDescriptorTypeImpl implements AuthnQueryDescriptorType{

    /**
     * Constructor.
     *
     * @param namespaceURI the namespace the element is in
     * @param elementLocalName the local name of the XML element this Object represents
     * @param namespacePrefix the prefix for the given namespace
     */
    protected AuthnQueryDescriptorTypeImpl(String namespaceURI, String elementLocalName, String namespacePrefix) {
        super(namespaceURI, elementLocalName, namespacePrefix);
    }

    /** {@inheritDoc} */
    public List<Endpoint> getEndpoints() {
        return new ArrayList<Endpoint>();
    }

    /** {@inheritDoc} */
    public List<Endpoint> getEndpoints(QName type) {
        return null;
    }
}


text:
package com.thoughtworks.go.server.view.artifacts;

import com.thoughtworks.go.domain.JobIdentifier;
import com.thoughtworks.go.server.service.ArtifactsService;
import com.thoughtworks.go.server.service.ConsoleService;
import com.thoughtworks.go.server.web.ArtifactFolder;
import com.thoughtworks.go.server.web.ArtifactFolderViewFactory;
import com.thoughtworks.go.server.web.FileModelAndView;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;

import static com.thoughtworks.go.util.ArtifactLogUtil.isConsoleOutput;

public class LocalArtifactsView implements ArtifactsView {
    private ArtifactsService artifactsService;
    private final JobIdentifier translatedId;
    private ConsoleService consoleService;
    protected ArtifactFolderViewFactory folderViewFactory;

    public LocalArtifactsView(ArtifactFolderViewFactory folderViewFactory, ArtifactsService artifactsService,
                              JobIdentifier translatedId, ConsoleService consoleService) {
        this.folderViewFactory = folderViewFactory;
        this.artifactsService = artifactsService;
        this.translatedId = translatedId;
        this.consoleService = consoleService;
    }

    @Override
    public final ModelAndView createView(String filePath, String sha) throws Exception {
        //return the artifact itself if this is a single file
        File file = isConsoleOutput(filePath) ? consoleService.consoleLogFile(translatedId)
                : artifactsService.findArtifact(translatedId, filePath);

        if (file.exists() && file.isFile()) {
            return FileModelAndView.createFileView(file, sha);
        }

        //return the contents of the specified directory formatted as required
        //NOTE THAT THIS IS ONLY CALLED FOR JSON OR HTML
        String convertedURL = filePath.replaceFirst("\\.(html|json|zip)$", "");
        File directory = artifactsService.findArtifact(translatedId, convertedURL);
        if (directory.exists() && directory.isDirectory()) {
            ArtifactFolder folder = new ArtifactFolder(translatedId, directory, convertedURL);
            return folderViewFactory.createView(translatedId, folder);
        }

        return FileModelAndView.fileNotFound(filePath);

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<person>
    <name>
        <full><![CDATA[Dr. Billy D Intern IX]]></full>
        <title>
            <text><![CDATA[Dr.]]></text>

                <value><![CDATA[1337]]></value>
                <family><![CDATA[Title]]></family>
                <type><![CDATA[Title]]></type>
                <version><![CDATA[Version 117]]></version>

        </title>
        <first><![CDATA[Billy]]></first>
        <middle><![CDATA[D]]></middle>
        <last><![CDATA[Intern]]></last>
        <suffix>
            <text><![CDATA[IX]]></text>

                <value><![CDATA[9]]></value>
                <family><![CDATA[Suffix]]></family>
                <type><![CDATA[Suffix]]></type>
                <version><![CDATA[Version 1]]></version>

        </suffix>
    </name>
    <organization><![CDATA[Microsoft]]></organization>
    <professional-training><![CDATA[Internship]]></professional-training>
    <id><![CDATA[N7]]></id>
    <contact>
        <address>
            <description><![CDATA[Home Address]]></description>
            <is-primary>true</is-primary>
            <street><![CDATA[123 Fake Ave]]></street>
            <city><![CDATA[Faketon]]></city>
            <state><![CDATA[FA]]></state>
            <postcode><![CDATA[00700]]></postcode>
            <country><![CDATA[United States]]></country>
            <county><![CDATA[Fake]]></county>
        </address>
        <phone>
            <description><![CDATA[Home Phone]]></description>
            <is-primary>true</is-primary>
            <number><![CDATA[555-555-5555]]></number>
        </phone>
        <email>
            <description><![CDATA[Personal]]></description>
            <is-primary>true</is-primary>
            <address><![CDATA[billy@theintern.com]]></address>
        </email>
    </contact>
    <type>
        <text><![CDATA[Person]]></text>

            <value><![CDATA[3]]></value>
            <family><![CDATA[Type]]></family>
            <type><![CDATA[Type]]></type>
            <version><![CDATA[Version 4]]></version>

    </type>
</person>


text:
package role

import (
	"context"
	"flag"

	"github.com/vmware/govmomi/govc/cli"
	"github.com/vmware/govmomi/govc/permissions"
)

type create struct {
	*permissions.PermissionFlag
}

func init() {
	cli.Register("role.create", &create{})
}

func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
	cmd.PermissionFlag, ctx = permissions.NewPermissionFlag(ctx)
	cmd.PermissionFlag.Register(ctx, f)
}

func (cmd *create) Process(ctx context.Context) error {
	if err := cmd.PermissionFlag.Process(ctx); err != nil {
		return err
	}
	return nil
}

func (cmd *create) Usage() string {
	return "NAME [PRIVILEGE]..."
}

func (cmd *create) Description() string {
	return `Create authorization role.

Optionally populate the role with the given PRIVILEGE(s).

Examples:
  govc role.create MyRole
  govc role.create NoDC $(govc role.ls Admin | grep -v Datacenter.)`
}

func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
	if f.NArg() == 0 {
		return flag.ErrHelp
	}

	m, err := cmd.Manager(ctx)
	if err != nil {
		return err
	}

	_, err = m.AddRole(ctx, f.Arg(0), f.Args()[1:])
	return err
}


text:
package org.xander.spring.springIdol.minimizingXMLConfiguration.autoDiscoveringBeans;

import org.springframework.stereotype.Component;

@Component
public interface Instrument {
    void play();
}


text:
feedbot
=======

.. image:: https://travis-ci.org/liavkoren/feedbot.svg?branch=app
    :target: https://travis-ci.org/liavkoren/feedbot

.. image:: https://readthedocs.org/projects/feedbot/badge/?version=latest
    :target: https://feedbot.readthedocs.org.

A Python jabberbot project to monitor RSS feeds in a chatroom.

-  Free software: Apache License
-  Documentation: https://feedbot.readthedocs.org.

Description
-----------

Feedbot is a Jabberbot based chatbot that will sit in your chatroom and monitor
RSS and Atom feeds for you. It currently provides a set of simple commands to
blacklist terms from feeds, and a simple interface to add, remove and read
feeds and stories.

Installing
----------
Feedbot runs as an `application rather than a library`_  because it has concrete dependencies on versions of Jabberbot and xmpppy that are not available on the Cheeseshop.

.. _application rather than a library: https://caremad.io/2013/07/setup-vs-requirement/

Having said that, installation is still straightforward.

``$ git clone https://github.com/liavkoren/feedbot.git``

followed by

``$ python pip install -r requirements.txt``

If you would like to work on Feedbot, simply install the test_requirments from test_requirements.txt. Docs can be build from the ``doc/`` directory with

``$ make html``

Quickstart
----------

A minimal install requires setting up a script that will launch Feedbot with the correct settings:

Eg:

.. code:: python

    import logging
    from feedbot import bot

    BOT_NICKNAME = 'Feedbot'
    BOT_PASSWORD = 'l33t'
    BOT_USERNAME = 'feedbot@botbot.org'
    CHATROOM = 'bot-party@conference.bot.org'
    SERVER_IP = '0.0.0.0'

    if __name__ == '__main__':
        feedbot = bot.FeedBot(
            CHATROOM,
            BOT_USERNAME,
            BOT_PASSWORD,
            server=SERVER_IP,
        )

        logging.info("Feedbot is alive")
        feedbot.muc_join_room(CHATROOM, BOT_NICKNAME)
        feedbot.serve_forever()
        logging.info("Feedbot is dead")

Settings
--------

FeedBot has a few user-definable settings. To override the default settings,
simply create an environment variable with the correct settings-key and value.

-  FEED\_HISTORY\_QUEUE\_LENGTH: Every feed stores a history of entries
   that have already been shown in the channel. This settings controls
   how many entries that queue holds. Default is 200.
-  FEEDBOT\_DATA\_DIRECTORY: The location on disk where the FeedBot will
   save feeds data. Feed data is saved as human readable JSON. By
   default FeedBot will attempt to find the current user's home
   directory and create a ~/.feedbot directory there. If ``$HOME`` is
   not set, FeedBot will issue a warning and attempt to create a
   directory in /tmp/feedbot
-  FEEDBOT\_DATA\_FILENAME: Name of the FeedBot data file. Default is
   ``feedbot.conf``

Credits
-------

Built at VM Farms, by Liav Koren using Feedparser and Jabberbot. Tests
are built with pytest and mock. Packaging was done with Cookiecutter and
Jeff Knupp's excellent walk-through:
http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/


text:
'use strict';

var legacy = require('./legacy-stuff');

module.exports = function performImports(importer, ui, packages) {
  packages.forEach(function(pkg) {
    var config = pkg.config();
    if (!config || !config.import) { return; }

    if (legacy.hasImportsWithOptions(config.import)) {
      ui.writeDeprecateLine(
        '[ember-cli-node-assets] Defining complex imports inline is now deprecated. ' +
        'Instead, you can add the files to your `vendor` config for this package and ' +
        'import them explicitly. See the ember-cli-node-assets README for details.'
      );
      legacy.importPackageFilesWithOptions(importer, config.import);
    } else {
      importPackageFiles(importer, config);
    }
  });
}

function importPackageFiles(importer, config) {
  config.import.include.forEach(function(path) {
    importer.import('vendor/' + config.import.destDir + '/' + path);
  });
}


text: Project Documetation


text:
namespace Caliburn_AdvancedDemo.Entities
{
    public class News
    {
        public string Title { get; set; }
        public string Summary { get; set; }
    }
}


text:
@class NSArray;

UIKIT_EXPORT_CLASS
@interface UILocalizedIndexedCollation : NSObject

@property (nonatomic, readonly) NSArray* sectionTitles;
@property (nonatomic, readonly) NSArray* sectionIndexTitles;

+ (id)currentCollation;

- (NSInteger)sectionForSectionIndexTitleAtIndex:(NSInteger)indexTitleIndex;
- (NSArray*)sortedArrayFromArray:(NSArray*)array collationStringSelector:(SEL)selector;
- (NSInteger)sectionForObject:(id)object collationStringSelector:(SEL)selector;

@end


text:
package transformer

import (
	"fmt"
	"strings"
	"testing"
)

func TestFormatProviderName(t *testing.T) {
	if formatProviderName("openshift") != "OpenShift" {
		t.Errorf("Got %s, expected OpenShift", formatProviderName("openshift"))
	}
	if formatProviderName("kubernetes") != "Kubernetes" {
		t.Errorf("Got %s, expected Kubernetes", formatProviderName("kubernetes"))
	}
}

// When passing "z" or "Z" we expect "" back.
func TestZParseVolumeLabeling(t *testing.T) {
	testCase := "/foobar:/foobar:Z"
	_, _, _, mode, err := ParseVolume(testCase)
	if err != nil {
		t.Errorf("In test case %q, returned unexpected error %v", testCase, err)
	}
	if mode != "" {
		t.Errorf("In test case %q, returned mode %s, expected \"\"", testCase, mode)
	}
}

func TestParseVolume(t *testing.T) {
	name1 := "datavolume"
	host1 := "./cache"
	host2 := "~/configs"
	container1 := "/tmp/cache"
	container2 := "/etc/configs/"
	mode := "rw"

	tests := []struct {
		test, volume, name, host, container, mode string
	}{
		{
			"name:host:container:mode",
			fmt.Sprintf("%s:%s:%s:%s", name1, host1, container1, mode),
			name1,
			host1,
			container1,
			mode,
		},
		{
			"host:container:mode",
			fmt.Sprintf("%s:%s:%s", host2, container2, mode),
			"",
			host2,
			container2,
			mode,
		},
		{
			"name:container:mode",
			fmt.Sprintf("%s:%s:%s", name1, container1, mode),
			name1,
			"",
			container1,
			mode,
		},
		{
			"name:host:container",
			fmt.Sprintf("%s:%s:%s", name1, host1, container1),
			name1,
			host1,
			container1,
			"",
		},
		{
			"host:container",
			fmt.Sprintf("%s:%s", host1, container1),
			"",
			host1,
			container1,
			"",
		},
		{
			"container:mode",
			fmt.Sprintf("%s:%s", container2, mode),
			"",
			"",
			container2,
			mode,
		},
		{
			"name:container",
			fmt.Sprintf("%s:%s", name1, container1),
			name1,
			"",
			container1,
			"",
		},
		{
			"container",
			fmt.Sprintf("%s", container2),
			"",
			"",
			container2,
			"",
		},
	}

	for _, test := range tests {
		name, host, container, mode, err := ParseVolume(test.volume)
		if err != nil {
			t.Errorf("In test case %q, returned unexpected error %v", test.test, err)
		}
		if name != test.name {
			t.Errorf("In test case %q, returned volume name %s, expected %s", test.test, name, test.name)
		}
		if host != test.host {
			t.Errorf("In test case %q, returned host path %s, expected %s", test.test, host, test.host)
		}
		if container != test.container {
			t.Errorf("In test case %q, returned container path %s, expected %s", test.test, container, test.container)
		}
		if mode != test.mode {
			t.Errorf("In test case %q, returned access mode %s, expected %s", test.test, mode, test.mode)
		}
	}
}

func TestGetComposeFileDir(t *testing.T) {
	output, err := GetComposeFileDir([]string{"foobar/docker-compose.yaml"})
	if err != nil {
		t.Errorf("Error with GetComposeFileDir %v", err)
	}
	if !strings.Contains(output, "foobar") {
		t.Errorf("Expected $PWD/foobar, got %v", output)
	}
}


text:
package com.example.achuan.teamsystem.ui.admin.conversation.activity;

import com.example.achuan.teamsystem.R;
import com.example.achuan.teamsystem.base.SimpleActivity;
import com.example.achuan.teamsystem.ui.admin.conversation.fragment.MyChatFragment;

/**
 * Created by achuan on 17-3-17.
 * 功能:在官方例程的基础上扩展实现自己的聊天界面
 */

public class MyChatActivity extends SimpleActivity {

    private MyChatFragment mMyChatFragment;
    String toChatUsername;

    @Override
    protected int getLayout() {
        return R.layout.my_activity_chat;
    }

    @Override
    protected void initEventAndData() {

        //get user id or group id
        toChatUsername = getIntent().getExtras().getString("userId");
        //use EaseChatFratFragment
        mMyChatFragment=new MyChatFragment();
        //pass parameters to chat fragment
        mMyChatFragment.setArguments(getIntent().getExtras());

        //添加碎片到内容区域
        addFragment(R.id.container,mMyChatFragment);

    }
}


text:
namespace web {

class WebFrame;

// Stores and provides access to all WebFrame objects associated with a
// particular WebState.
// NOTE: Code that store references to WebFrames must clear them in
// WebStateObserver::WebFrameWillBecomeUnavailable, which is emitted when
// WebFrames in current page become invalid and will be removed from
// WebFramesManager (e.g. A new navigation is committed or failed, the web
// process crashed, etc.).
class WebFramesManager {
 public:
  WebFramesManager(const WebFramesManager&) = delete;
  WebFramesManager& operator=(const WebFramesManager&) = delete;

  virtual ~WebFramesManager() {}

  // Returns a list of all the web frames associated with WebState.
  // NOTE: Due to the asynchronous nature of renderer, this list may be
  // outdated.
  virtual std::set<WebFrame*> GetAllWebFrames() = 0;
  // Returns the web frame for the main frame associated with WebState or null
  // if unknown.
  // NOTE: Due to the asynchronous nature of JavaScript to native messsaging,
  // this object may be outdated.
  virtual WebFrame* GetMainWebFrame() = 0;
  // Returns the web frame with |frame_id|, if one exists.
  // NOTE: Due to the asynchronous nature of JavaScript to native messsaging,
  // this object may be outdated and the WebFrame returned by this method may
  // not back a real frame in the web page.
  virtual WebFrame* GetFrameWithId(const std::string& frame_id) = 0;

 protected:
  WebFramesManager() {}
};

}  // namespace web

#endif  // IOS_WEB_PUBLIC_JS_MESSAGING_WEB_FRAMES_MANAGER_H_


text:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/main_menu_background"
    android:cacheColorHint="@android:color/transparent"
    android:choiceMode="singleChoice"
    android:divider="@null"
    android:dividerHeight="0dp"
    tools:context=".NavigationDrawerFragment"
    tools:listitem="@layout/item_main_menu" />


text:
var assert = chai.assert,
    Router = Susanin;
    module = {};


text:
package com.tomgibara.storage;

import static com.tomgibara.storage.Stores.immutableException;

import java.util.Arrays;

import com.tomgibara.bits.BitStore;
import com.tomgibara.bits.BitWriter;
import com.tomgibara.bits.Bits;
import com.tomgibara.storage.StoreAccessors.StoreInts;

abstract class SmallValueStore extends AbstractStore<Integer> implements StoreInts {

	// statics - ternary packing

	private static final byte[] TERNARY_PACK = new byte[1024];
	private static final int[] TERNARY_UNPACK = new int[243];

	private static byte tPack(int value) {
		int sum = 0;
		for (int i = 0; i < 5; i++) {
			sum = 3 * sum + (value & 3);
			value >>= 2;
		}
		return (byte) sum;
	}

	private static int tUnpack(byte value) {
		int v = value & 0xff;
		int bits = 0;
		for (int i = 0; i < 5; i++) {
			bits = (bits << 2) | (v % 3);
			v /= 3;
		}
		return bits;
	}

	static {
		for (int i = 0; i < 243; i++) {
			byte p = (byte) i;
			int u = tUnpack(p);
			TERNARY_PACK[u] = p;
			TERNARY_UNPACK[i] = u;
		}
	}

	// statics - quinary packing

	private static final int[] QUINARY_PACK = new int[512];
	private static final int[] QUINARY_UNPACK = new int[125];

	private static byte qPack(int value) {
		int sum = 0;
		for (int i = 0; i < 3; i++) {
			sum = 5 * sum + (value & 7);
			value >>= 3;
		}
		return (byte) sum;
	}

	private static int qUnpack(int v) {
		int bits = 0;
		for (int i = 0; i < 3; i++) {
			bits = (bits << 3) | (v % 5);
			v /= 5;
		}
		return bits;
	}

	static {
		for (int i = 0; i < 125; i++) {
			int u = qUnpack(i);
			QUINARY_PACK[u] = i;
			QUINARY_UNPACK[i] = u;
		}
	}

	// statics

	static Storage<Integer> newStorage(int range, StoreType<Integer> type) {
		if (type.nullGettable) {
			return SmallValueStore.newNullStorage(range);
		}
		if (type.nullSettable) {
			int nv = type.nullValue;
			if (nv < 0) throw new IllegalArgumentException("negative nullValue");
			if (nv >= range) throw new IllegalArgumentException("nullValue meets or exceeds range");
		}

		return SmallValueStore.newNonNullStorage(range, type);
	}

	// type must not be null gettable
	static SmallValueStorage newNonNullStorage(int range, StoreType<Integer> type) {
		int nullValue = type.nullSettable ? type.nullValue : -1;
		switch (range) {
		case 1:  return new SmallValueStorage(type, (size, value) -> new UnaryStore(checkedSize(size), nullValue, value));
		case 2:  return new SmallValueStorage(type, (size, value) -> new BinaryStore(checkedSize(size), nullValue, value));
		case 3:  return new SmallValueStorage(type, (size, value) -> new TernaryStore(checkedSize(size), nullValue, value));
		case 5:  return new SmallValueStorage(type, (size, value) -> new QuinaryStore(checkedSize(size), nullValue, value));
		default: return new SmallValueStorage(type, (size, value) -> new ArbitraryStore(checkedSize(size), nullValue, range, value));
		}
	}

	static NullSmallStorage newNullStorage(int range) {
		switch (range) {
		case 1:  return (size, value) -> new ZeroOrNullStore(checkedSize(size), value);
		case 2:  return (size, value) -> new NullableStore(new TernaryStore(checkedSize(size), 0, value));
		case 4:  return (size, value) -> new NullableStore(new QuinaryStore(checkedSize(size), 0, value));
		default: return (size, value) -> new NullableStore(new ArbitraryStore(checkedSize(size), 0, range + 1, value));
		}
	}

	private static int checkedSize(int size) {
		if (size < 0) throw new IllegalArgumentException("negative size");
		return size;
	}

	// fields

	final int size;
	// -1 indicates not settable
	final int nullValue;

	// constructors

	SmallValueStore(int size, int nullValue) {
		this.size = size;
		this.nullValue = nullValue;
	}

	// methods

	@Override
	public StoreType<Integer> type() {
		return nullValue < 0 ? StoreType.INT.settingNullDisallowed() : StoreType.INT.settingNullToValue(nullValue);

	}

	@Override
	public int size() {
		return size;
	}

	@Override
	public boolean isNull(int index) {
		if (index < 0 || index >= size) throw new IllegalArgumentException("invalid index");
		return false;
	}

	@Override
	public BitStore population() {
		return Bits.oneBits(size);
	}

	@Override
	public abstract SmallValueStore mutableCopy();

	@Override
	public abstract SmallValueStore immutableCopy();

	@Override
	public abstract SmallValueStore immutableView();

	@Override
	public abstract SmallValueStore resizedCopy(int newSize);

	@Override
	public void transpose(int i, int j) {
		checkIndex(i);
		checkIndex(j);
		if (i == j) return;
		setImpl(j, setImpl(i, getImpl(j)));
	}

	@Override
	boolean fastFill(int from, int to, Integer value) {
		if (from == 0 && to == size) {
			fillImpl(value);
		} else {
			fillImpl(from, to, value);
		}
		return true;
	}

	// store ints methods

	@Override
	public boolean isInt(int index) {
		return true;
	}

	@Override
	public int getInt(int index) {
		checkIndex(index);
		return getImpl(index);
	}

	@Override
	public void setInt(int index, int value) {
		checkIndex(index);
		checkImpl(value);
		if (!isMutable()) throw new IllegalStateException("immutable");
		setImpl(index, value);
	}

	// for extension

	abstract int range();

	// note: caller responsible for checking value is valid
	abstract int setImpl(int index, int value);

	// note: caller responsible for checking value is valid
	abstract int getImpl(int index);

	// note: caller responsible for checking value is valid
	abstract void fillImpl(int value);

	// note: caller responsible for checking value is valid
	abstract void fillImpl(int from, int to, int value);

	abstract void checkImpl(int value);

	// helper methods

	void checkIndex(int index) {
		if (index < 0) throw new IllegalArgumentException("negative index");
		if (index >= size) throw new IllegalArgumentException("index too large");
	}

	void checkNewSize(int newSize) {
		if (newSize < 0) throw new IllegalArgumentException("negative newSize");
		if (nullValue < 0 && newSize > size) throw new IllegalArgumentException("cannot create copy with greater size, no null value");
	}

	void initCheck(Integer initialValue) {
		if (initialValue == null && nullValue < 0 && size > 0) throw new IllegalArgumentException("cannot create sized store, no null value");
	}

	// assumes initCheck has already been performed
	void initFill(Integer initialValue) {
		int i = initialValue == null ? nullValue : initialValue.intValue();
		if (i > 0) fillImpl(i);
	}

	int settableValue(Object value) {
		if (value == null) return nullValue;
		return value instanceof Integer ? (Integer) value : -1;
	}

	// inner classes

	static final class SmallValueStorage implements Storage<Integer> {

		interface Factory { SmallValueStore newStore(int size, Integer value); }

		private final StoreType<Integer> type;
		private final Factory newStore;

		SmallValueStorage(StoreType<Integer> type, Factory newStore) {
			this.type = type;
			this.newStore = newStore;
		}

		@Override
		public StoreType<Integer> type() { return type; }

		@Override
		//TODO optimize other storage methods?
		public SmallValueStore newStore(int size, Integer value) {
			return newStore.newStore(size, value);
		}

	}

	private final static class UnaryStore extends SmallValueStore {

		private final boolean mutable;

		UnaryStore(int size, int nullValue, Integer initialValue) {
			super(size, nullValue);
			initCheck(initialValue);
			mutable = true;
			initFill(initialValue);
		}
		UnaryStore(int size, int nullValue, boolean mutable) {
			super(size, nullValue);
			this.mutable = mutable;
		}

		@Override
		public Integer get(int index) {
			checkIndex(index);
			return 0;
		}

		@Override
		public Integer set(int index, Integer value) {
			checkIndex(index);
			checkValue(value);
			checkMutable();
			return 0;
		}

		@Override
		public boolean isSettable(Object value) {
			return settableValue(value) == 0;
		}

		@Override
		public BitStore population() {
			return Bits.oneBits(size);
		}

		@Override
		public void fill(Integer value) {
			checkValue(value);
			checkMutable();
			fillImpl(value);
		}

		@Override
		public boolean isMutable() { return mutable; }

		@Override
		public UnaryStore mutableCopy() { return new UnaryStore(size, nullValue, true); }

		@Override
		public UnaryStore immutableCopy() { return new UnaryStore(size, nullValue, false); }

		@Override
		public UnaryStore immutableView() { return new UnaryStore(size, nullValue, false); }

		@Override
		public UnaryStore resizedCopy(int newSize) {
			checkNewSize(newSize);
			return new UnaryStore(newSize, nullValue, true);
		}

		@Override
		public <W extends Integer> void setStore(int position, Store<W> store) {
			int from = 0;
			int to = checkSetStore(position, store);
			if (store instanceof RangeStore<?>) {
				RangeStore<W> range = (RangeStore<W>) store;
				store = range.store;
				from = range.from;
				to = range.to;
			}
			if (store instanceof UnaryStore) {
				/* no op */
			} else {
				setStoreImpl(position, store, from, to);
			}
		}

		@Override
		public void transpose(int i, int j) {
			checkIndex(i);
			checkIndex(j);
			checkMutable();
		}

		private void checkValue(Integer value) {
			if (value == null) {
				if (nullValue < 0) StoreType.failNull();
			} else {
				checkImpl(value);
			}
		}

		private void checkMutable() {
			if (!mutable) throw immutableException();
		}

		@Override
		int range() { return 1; }

		@Override
		int getImpl(int index) { return 0; }

		@Override
		int setImpl(int index, int value) { return 0; }

		@Override
		void fillImpl(int value) { }

		@Override
		void fillImpl(int from, int to, int value) { }

		@Override
		void checkImpl(int value) {
			if (value != 0) throw new IllegalArgumentException("non-zero value");
		}

	}

	private final static class BinaryStore extends SmallValueStore {

		private final BitStore bits;

		BinaryStore(int size, int nullValue, Integer initialValue) {
			super(size, nullValue);
			initCheck(initialValue);
			bits = Bits.store(size);
			initFill(initialValue);
		}

		BinaryStore(BitStore bits, int nullValue) {
			super(bits.size(), nullValue);
			this.bits = bits;
		}

		@Override
		public Integer get(int index) {
			checkIndex(index);
			return valueOf( bits.getBit(index) );
		}

		@Override
		public Integer set(int index, Integer value) {
			checkIndex(index);
			boolean v = checkedValue(value);
			return valueOf( bits.getThenSetBit(index, v) );
		}

		@Override
		public boolean isSettable(Object value) {
			int i = settableValue(value);
			return i == 0 || i == 1;
		}

		@Override
		public void fill(Integer value) {
			bits.setAll(checkedValue(value));
		}

		@Override
		public boolean isMutable() { return bits.isMutable(); }

		@Override
		public BinaryStore mutableCopy() { return new BinaryStore(bits.mutableCopy(), nullValue); }

		@Override
		public BinaryStore immutableCopy() { return new BinaryStore(bits.immutableCopy(), nullValue); }

		@Override
		public BinaryStore immutableView() { return new BinaryStore(bits.immutable(), nullValue); }

		@Override
		public BinaryStore resizedCopy(int newSize) {
			checkNewSize(newSize);
			BitStore newBits = Bits.resizedCopyOf(bits, newSize, false);
			if (newSize > size && nullValue == 1) newBits.range(size, newSize).fill();
			return new BinaryStore(newBits, nullValue);
		}

		@Override
		public <W extends Integer> void setStore(int position, Store<W> store) {
			int from = 0;
			int to = checkSetStore(position, store);
			if (store instanceof RangeStore<?>) {
				RangeStore<W> range = (RangeStore<W>) store;
				store = range.store;
				from = range.from;
				to = range.to;
			}
			if (store instanceof BinaryStore) {
				bits.setStore(position, ((BinaryStore) store).bits.range(from, to));
			} else {
				setStoreImpl(position, store, from, to);
			}
		}

		@Override
		public void transpose(int i, int j) {
			bits.permute().transpose(i, j);
		}

		@Override
		int range() { return 2; }

		@Override
		int getImpl(int index) {
			return valueOf( bits.getBit(index) );
		}

		@Override
		int setImpl(int index, int value) {
			return valueOf( bits.getThenSetBit(index, value != 0) );
		}

		@Override
		void fillImpl(int value) {
			bits.setAll(value != 0);
		}

		@Override
		void fillImpl(int from, int to, int value) {
			bits.range(from, to).setAll(value != 0);
		}

		@Override
		void checkImpl(int value) {
			if (value != 0 && value != 1) throw new IllegalArgumentException("value not 0 or 1");
		}

		private boolean checkedValue(Integer value) {
			if (value == null) {
				if (nullValue < 0) StoreType.failNull();
				return nullValue > 0;
			}
			switch (value) {
			case 0 : return false;
			case 1 : return true;
			default: throw new IllegalArgumentException("value not 0 or 1");
			}
		}

		private int valueOf(boolean v) {
			return v ? 1 : 0;
		}

	}

	private final static class TernaryStore extends SmallValueStore {

		private final byte[] data;
		private final boolean mutable;

		TernaryStore(int size, int nullValue, Integer initialValue) {
			super(size, nullValue);
			initCheck(initialValue);
			int length = (size + 4) / 5;
			data = new byte[length];
			mutable = true;
			initFill(initialValue);
		}

		TernaryStore(int size, int nullValue, byte[] data, boolean mutable) {
			super(size, nullValue);
			this.data = data;
			this.mutable = mutable;
		}

		@Override
		public Integer get(int index) {
			checkIndex(index);
			return getImpl(index);
		}

		@Override
		public Integer set(int index, Integer value) {
			checkIndex(index);
			return setImpl(index, checkedValue(value));
		}

		@Override
		public boolean isSettable(Object value) {
			int i = settableValue(value);
			return i >= 0 && i < 3;
		}

		@Override
		public void fill(Integer value) {
			fillImpl(checkedValue(value));
		}

		@Override
		public boolean isMutable() {
			return mutable;
		}

		@Override
		public TernaryStore mutableCopy() {
			return new TernaryStore(size, nullValue, data.clone(), true);
		}

		@Override
		public TernaryStore immutableCopy() {
			return new TernaryStore(size, nullValue, data.clone(), false);
		}

		@Override
		public TernaryStore immutableView() {
			return new TernaryStore(size, nullValue, data, false);
		}

		@Override
		public TernaryStore resizedCopy(int newSize) {
			checkNewSize(newSize);
			int newLength = (newSize + 4) / 5;
			byte[] newData = Arrays.copyOfRange(data, 0, newLength);
			TernaryStore store = new TernaryStore(newSize, nullValue, newData, true);
			if (newSize > size) {
				int limit = Math.min(size / 5 * 5 + 5, newSize);
				for (int i = size; i < limit; i++) store.setImpl(i, nullValue);
				if (newLength > data.length) {
					Arrays.fill(newData, data.length, newLength, fiveCopies(nullValue));
				}
			}
			return store;
		}

		@Override
		int range() { return 3; }

		@Override
		int getImpl(int index) {
			int i = index / 5;
			int j = index % 5;
			byte p = data[i];
			int u = tUnpack(p);
			int d = (4-j) << 1;
			return (u >> d) & 3;
		}

		@Override
		int setImpl(int index, int value) {
			int i = index / 5;
			int j = index % 5;
			byte p = data[i];
			int u = tUnpack(p);
			int d = (4-j) << 1;
			int v = (u >> d) & 3;
			u &= ~(3 << d);
			u |= value << d;
			data[i] = tPack(u);
			return v;
		}

		@Override
		void fillImpl(int value) {
			Arrays.fill(data, fiveCopies(value));
		}

		@Override
		void fillImpl(int from, int to, int value) {
			for (int i = from; i < to; i++) {
				setImpl(i, value);
			}
		}

		@Override
		void checkImpl(int value) {
			if (value < 0) throw new IllegalArgumentException("negative value");
			if (value >= 3) throw new IllegalArgumentException("value too large");
		}

		private int checkedValue(Integer value) {
			if (value == null) {
				if (nullValue < 0) StoreType.failNull();
				return nullValue;
			}
			checkImpl(value);
			return value;
		}

		private byte fiveCopies(int value) {
			int u = 0;
			for (int i = 0; i < 5; i++) {
				u <<= 2;
				u |= value;
			}
			return tPack(u);
		}
	}

	private final static class QuinaryStore extends SmallValueStore {

		private final BitStore bits;

		QuinaryStore(int size, int nullValue, Integer initialValue) {
			super(size, nullValue);
			initCheck(initialValue);
			bits = Bits.store((size + 2) / 3 * 7);
			initFill(initialValue);
		}

		QuinaryStore(int size, int nullValue, BitStore bits) {
			super(size, nullValue);
			this.bits = bits;
		}

		@Override
		public Integer get(int index) {
			checkIndex(index);
			return getImpl(index);
		}

		@Override
		public Integer set(int index, Integer value) {
			checkIndex(index);
			return setImpl(index, checkedValue(value));
		}

		@Override
		public boolean isSettable(Object value) {
			int i = settableValue(value);
			return i >= 0 && i < 5;
		}

		@Override
		public void fill(Integer value) {
			fillImpl(checkedValue(value));
		}

		@Override
		public boolean isMutable() {
			return bits.isMutable();
		}

		@Override
		public QuinaryStore mutableCopy() {
			return new QuinaryStore(size, nullValue, bits.mutableCopy());
		}

		@Override
		public QuinaryStore immutableCopy() {
			return new QuinaryStore(size, nullValue, bits.immutableCopy());
		}

		@Override
		public QuinaryStore immutableView() {
			return new QuinaryStore(size, nullValue, bits.immutable());
		}

		@Override
		public QuinaryStore resizedCopy(int newSize) {
			checkNewSize(newSize);
			BitStore newBits = Bits.resizedCopyOf(bits, newSize * 7, false);
			QuinaryStore store = new QuinaryStore(newSize, nullValue, newBits);
			if (size < newSize) {
				int limit = Math.min(size / 3 * 3 + 3, newSize);
				for (int i = size; i < limit; i++) {
					store.setImpl(i, nullValue);
				}
				int nbs = newBits.size();
				int obs = bits.size();
				if (nbs > obs) {
					int p = fiveCopies(nullValue);
					BitWriter w = newBits.openWriter(obs, nbs);
					for (int i = (nbs - obs) / 7; i > 0; i--) w.write(p, 7);
					w.flush();
				}
			}
			return store;
		}

		@Override
		int range() { return 5; }

		@Override
		int getImpl(int index) {
			int i = index / 3;
			int j = index % 3;
			int p = getBits(i);
			int u = qUnpack(p);
			int d = (2-j) * 3;
			return (u >> d) & 7;
		}

		@Override
		int setImpl(int index, int value) {
			int i = index / 3;
			int j = index % 3;
			int p = getBits(i);
			int u = qUnpack(p);
			int d = (2-j) * 3;
			int v = (u >> d) & 7;
			u &= ~(7 << d);
			u |= value << d;
			setBits(i, qPack(u));
			return v;
		}

		@Override
		void fillImpl(int value) {
			if (value == 0) {
				bits.clear();
			} else {
				int p = fiveCopies(value);
				BitWriter w = bits.openWriter();
				int limit = bits.size() / 7;
				for (int i = 0; i < limit; i++) {
					w.write(p, 7);
				}
				w.flush();
			}
		}

		@Override
		void fillImpl(int from, int to, int value) {
			for (int i = from; i < to; i++) {
				setImpl(i, value);
			}
		}

		@Override
		void checkImpl(int value) {
			if (value < 0) throw new IllegalArgumentException("negative value");
			if (value >= 5) throw new IllegalArgumentException("value too large");
		}

		private int checkedValue(Integer value) {
			if (value == null) {
				if (nullValue < 0) StoreType.failNull();
				return nullValue;
			}
			checkImpl(value);
			return value;
		}

		private int getBits(int index) {
			return (int) bits.getBits(index * 7, 7);
		}

		private void setBits(int index, int value) {
			bits.setBits(index * 7, value, 7);
		}

		private int fiveCopies(int value) {
			int u = 0;
			for (int i = 0; i < 3; i++) {
				u <<= 3;
				u |= value;
			}
			return qPack(u);
		}
	}

	private final static class ArbitraryStore extends SmallValueStore /* implements StoreInts */ {

		private final int range;
		private final int count;
		private final BitStore bits;

		ArbitraryStore(int size, int nullValue, int range, Integer initialValue) {
			super(size, nullValue);
			initCheck(initialValue);
			this.range = range;
			count = 32 - Integer.numberOfLeadingZeros(range - 1);
			bits = Bits.store(size * count);
			initFill(initialValue);
		}

		ArbitraryStore(ArbitraryStore that, BitStore bits) {
			super(bits.size() / that.count, that.nullValue);
			this.range = that.range;
			this.count = that.count;
			this.bits = bits;
		}

		@Override
		public Integer get(int index) {
			checkIndex(index);
			return getImpl(index);
		}

		@Override
		public Integer set(int index, Integer value) {
			checkIndex(index);
			return setImpl(index, checkedValue(value));
		}

		@Override
		public boolean isSettable(Object value) {
			int i = settableValue(value);
			return i >= 0 && i < range;
		}

		@Override
		public void fill(Integer value) {
			fillImpl(checkedValue(value));
		}

		@Override
		public boolean isMutable() { return bits.isMutable(); }

		@Override
		public ArbitraryStore mutableCopy() { return new ArbitraryStore(this, bits.mutableCopy()); }

		@Override
		public ArbitraryStore immutableCopy() { return new ArbitraryStore(this, bits.immutableCopy()); }

		@Override
		public ArbitraryStore immutableView() { return new ArbitraryStore(this, bits.immutable()); }

		@Override
		public ArbitraryStore resizedCopy(int newSize) {
			checkNewSize(newSize);
			BitStore newBits = Bits.resizedCopyOf(bits, newSize * count, false);
			ArbitraryStore store = new ArbitraryStore(this, newBits);
			if (size < newSize) {
				BitWriter w = newBits.openWriter(size * count, newSize * count);
				for (int i = size; i < newSize; i++) {
					w.write(nullValue, count);
				}
				w.flush();
			}
			return store;
		}

		@Override
		public <W extends Integer> void setStore(int position, Store<W> store) {
			int from = 0;
			int to = checkSetStore(position, store);
			if (store instanceof RangeStore<?>) {
				RangeStore<W> range = (RangeStore<W>) store;
				store = range.store;
				from = range.from;
				to = range.to;
			}
			if (store instanceof ArbitraryStore) {
				bits.setStore(position * count, ((ArbitraryStore) store).bits.range(from * count, to * count));
			} else {
				setStoreImpl(position, store, from, to);
			}
		}

		@Override
		int range() {
			return range;
		}

		@Override
		int setImpl(int index, int value) {
			int position = index * count;
			int v = (int) bits.getBits(position, count);
			bits.setBits(position, value, count);
			return v;
		}

		@Override
		int getImpl(int index) {
			return (int) bits.getBits(index * count, count);
		}

		@Override
		void fillImpl(int value) {
			writeFill(bits, value);
		}

		@Override
		void fillImpl(int from, int to, int value) {
			writeFill(bits.range(from * count, to * count), value);
		}

		@Override
		void checkImpl(int value) {
			if (value < 0) throw new IllegalArgumentException("negative value");
			if (value >= range) throw new IllegalArgumentException("value too large");
		}

		private int checkedValue(Integer value) {
			if (value == null) {
				if (nullValue < 0) StoreType.failNull();
				return nullValue;
			}
			checkImpl(value);
			return value;
		}

		private void writeFill(BitStore bits, int value) {
			if (value == 0) {
				bits.clear();
			} else if (value == (1 << count) - 1) {
				bits.fill();
			} else {
				int length = bits.size() / count;
				BitWriter w = bits.openWriter();
				for (int i = 0; i < length; i++) {
					w.write(value, count);
				}
				w.flush();
			}
		}
	}

	// nullable stores

	interface NullSmallStorage extends Storage<Integer> {
		@Override default public StoreType<Integer> type() { return StoreType.INT; }
	}

	static class ZeroOrNullStore extends AbstractStore<Integer> implements StoreInts {

		private static final Integer ZERO = 0;
		private final int size;
		private final BitStore bits;

		ZeroOrNullStore(int size, Integer initialValue) {
			this.size = size;
			bits = Bits.store(size);
			if (initialValue != null) {
				bits.setAll(true);
			}
		}

		ZeroOrNullStore(BitStore bits) {
			this.size = bits.size();
			this.bits = bits;
		}

		@Override
		public StoreType<Integer> type() {
			return StoreType.INT;
		}

		public int size() {
			return size;
		}

		public Class<Integer> valueType() {
			return Integer.class;
		}

		@Override
		public Integer get(int index) {
			checkIndex(index);
			return bits.getBit(index) ? 0 : null;
		}

		@Override
		public boolean isNull(int index) {
			checkIndex(index);
			return !bits.getBit(index);
		}

		@Override
		public Integer set(int index, Integer value) {
			checkIndex(index);
			boolean v = checkedValue(value);
			return bits.getThenSetBit(index, v) ? 0 : null;
		}

		@Override
		public boolean isSettable(Object value) {
			return value == null || ZERO.equals(value);
		}

		@Override
		public void clear() {
			bits.clear();
		}

		@Override
		public BitStore population() {
			return bits.immutableView();
		}

		@Override
		public void fill(Integer value) {
			bits.setAll(checkedValue(value));
		}

		@Override
		public Store<Integer> resizedCopy(int newSize) {
			return new ZeroOrNullStore(Bits.resizedCopyOf(bits, newSize, false));
		}

		@Override
		public <W extends Integer> void setStore(int position, Store<W> store) {
			int from = 0;
			int to = checkSetStore(position, store);
			if (store instanceof RangeStore<?>) {
				RangeStore<W> range = (RangeStore<W>) store;
				store = range.store;
				from = range.from;
				to = range.to;
			}
			if (store instanceof ZeroOrNullStore) {
				bits.setStore(position, ((ZeroOrNullStore) store).bits.range(from, to));
			} else {
				setStoreImpl(position, store, from, to);
			}
		}

		@Override
		public boolean isMutable() { return bits.isMutable(); }

		@Override
		public Store<Integer> mutableCopy() { return new ZeroOrNullStore(bits.mutableCopy()); }

		@Override
		public Store<Integer> immutableCopy() { return new ZeroOrNullStore(bits.immutableCopy()); }

		@Override
		public Store<Integer> immutableView() { return new ZeroOrNullStore(bits.immutable()); }

		@Override
		public void transpose(int i, int j) {
			bits.permute().transpose(i, j);
		}

		// store ints

		@Override
		public boolean isInt(int index) {
			return !isNull(index);
		}

		@Override
		public int getInt(int index) {
			checkIndex(index);
			if (!bits.getBit(index)) throw new RuntimeException("null, not an int");
			return 0;
		}

		@Override
		public void setInt(int index, int value) {
			checkIndex(index);
			if (value != 0) throw new IllegalArgumentException("value not zero");
			bits.setBit(index, true);
		}

		// private helper methods

		private void checkIndex(int index) {
			if (index < 0) throw new IllegalArgumentException("negative index");
			if (index >= size) throw new IllegalArgumentException("index too large");
		}

		private boolean checkedValue(Integer value) {
			if (value == null) return false;
			if (value == 0) return true;
			throw new IllegalArgumentException("value not null or zero");
		}
	}

	private static class NullableStore extends AbstractStore<Integer> implements StoreInts {

		private final SmallValueStore wrapped;

		NullableStore(SmallValueStore wrapped) {
			this.wrapped = wrapped;
		}

		@Override
		public StoreType<Integer> type() {
			return StoreType.INT;
		}

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

		@Override
		public Integer get(int index) {
			wrapped.checkIndex(index);
			return unwrap(wrapped.getImpl(index));
		}

		@Override
		public boolean isNull(int index) {
			wrapped.checkIndex(index);
			return wrapped.getImpl(index) == 0;
		}

		@Override
		public Integer set(int index, Integer value) {
			wrapped.checkIndex(index);
			return unwrap( wrapped.setImpl(index, wrap(value)) );
		}

		@Override
		public boolean isSettable(Object value) {
			if (value == null) return true;
			if (!(value instanceof Integer)) return false;
			int i = ((Integer) value) + 1;
			return i >= 1 && i < wrapped.range();
		}

		@Override
		public void clear() {
			wrapped.fillImpl(0);
		}

		@Override
		public void fill(Integer value) {
			wrapped.fillImpl(wrap(value));
		}

		@Override
		public Store<Integer> resizedCopy(int newSize) {
			return new NullableStore(wrapped.resizedCopy(newSize));
		}

		@Override
		public <W extends Integer> void setStore(int position, Store<W> store) {
			if (store instanceof NullableStore) {
				wrapped.setStore(position, ((NullableStore) store).wrapped);
			} else {
				super.setStore(position, store);
			}
		}

		@Override
		public boolean isMutable() {
			return wrapped.isMutable();
		}

		@Override
		public Store<Integer> mutableCopy() {
			return new NullableStore(wrapped.mutableCopy());
		}

		@Override
		public Store<Integer> immutableCopy() {
			return new NullableStore(wrapped.immutableCopy());
		}

		@Override
		public Store<Integer> immutableView() {
			return new NullableStore(wrapped.immutableView());
		}

		@Override
		public void transpose(int i, int j) {
			wrapped.transpose(i, j);
		}

		// store ints

		@Override
		public boolean isInt(int index) {
			return !isNull(index);
		}

		@Override
		public int getInt(int index) {
			wrapped.checkIndex(index);
			int value = wrapped.getImpl(index);
			if (value == 0) throw new RuntimeException("null, not an int");
			return value - 1;
		}

		@Override
		public void setInt(int index, int value) {
			if (!wrapped.isMutable()) throw new IllegalStateException("immutable");
			wrapped.checkIndex(index);
			wrapped.setImpl(index, wrapImpl(value));
		}

		// private helper methods

		private Integer unwrap(int value) {
			return value == 0 ? null : value - 1;
		}

		private int wrap(Integer value) {
			return value == null ? 0 : wrapImpl(value);
		}

		private int wrapImpl(int value) {
			if (value < 0) throw new IllegalArgumentException("negative value");
			if (++value >= wrapped.range()) throw new IllegalArgumentException("value too large");
			return value;
		}
	}
}


text:
<!DOCTYPE html>

Foo

Bar

Baz


text:
package org.drools.guvnor.client.rpc;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.user.client.rpc.IsSerializable;

import org.jboss.errai.common.client.api.annotations.Portable;

@Portable
public class PathImpl implements Path, IsSerializable {

    private String uri = null;
    private String fileName = null;
    private HashMap<String, Object> attributes = null;

    private String uuid;

    public PathImpl() {
    }

    public PathImpl(final String uri) {
        this(null, uri, null);
    }

    public PathImpl(final String fileName, final String uri) {
        this(fileName, uri, null);
    }

    public PathImpl(final String fileName, final String uri, final Map<String, Object> attrs) {
        this.fileName = fileName;
        this.uri = uri;
        if (attrs == null){
            this.attributes = new HashMap<String, Object>();
        } else {
            this.attributes = new HashMap<String, Object>(attrs);
        }
    }

    @Override
    public String getFileName() {
        return fileName;
    }

    @Override
    public String toURI() {
        return uri;
    }

    public Map<String, Object> getAttributes() {
        return attributes;
    }

    public String getUUID() {
		return uuid;
	}

	public void setUUID(String uuid) {
		this.uuid = uuid;
	}

	public int compareTo(org.uberfire.backend.vfs.Path another) {
		//TODO: compare using path
		if(another instanceof PathImpl) {
			PathImpl anotherPathImpl = (PathImpl)another;
			return this.getUUID().compareTo(anotherPathImpl.getUUID());
		}
		return -1;
	}

	public boolean equals(final Object object) {
        if (object == null) {
            return false;
        }

        if (object instanceof PathImpl) {
            return this.getUUID().equals(((PathImpl)object).getUUID());
        }

        return false;
	}

	@Override
    public String toString() {
        return "PathImpl{" +
                "uuid='" + uuid + '\'' +
                ", uri='" + uri + '\'' +
                ", fileName='" + fileName + '\'' +
                ", attrs=" + attributes +
                '}';
    }
}


text:
namespace pangolin {

template<typename T>
inline double DefaultIncrementForType(double min, double max) {
    return (std::is_integral<T>::value) ? 1.0 : (max - min) / 100.0;
}

template <typename T, typename S>
typename std::enable_if<is_streamable<S>::value && is_streamable<T>::value, std::shared_ptr<VarValueT<T>>>::type
Wrapped(const std::shared_ptr<VarValueT<S>>& src) noexcept
{
    return std::make_shared<VarWrapper<T,S>>(src);
}

template <typename T, typename S>
typename std::enable_if<!(is_streamable<S>::value && is_streamable<T>::value), std::shared_ptr<VarValueT<T>>>::type
Wrapped(const std::shared_ptr<VarValueT<S>>&)
{
    throw std::runtime_error("Unable to wrap Var");
}

template<typename T>
typename std::enable_if<!is_streamable<T>::value, std::shared_ptr<VarValue<T>>>::type
InitialiseFromPreviouslyGenericVar(const std::shared_ptr<VarValueGeneric>& v)
{
    // We can't initialize this variable from a 'generic' string type.
    throw BadInputException();
}
template<typename T>
typename std::enable_if<is_streamable<T>::value, std::shared_ptr<VarValue<T>>>::type
InitialiseFromPreviouslyGenericVar(const std::shared_ptr<VarValueGeneric>& v)
{
    return std::make_shared<VarValue<T>>( Convert<T,std::string>::Do( v->str->Get() ) );
}

// Initialise from existing variable, obtain data / accessor
template<typename T>
std::shared_ptr<VarValueT<T>> InitialiseFromPreviouslyTypedVar(const std::shared_ptr<VarValueGeneric>& v)
{
    // Macro hack to prevent code duplication
#   define PANGO_VAR_TYPES(x)                            \
    x(bool) x(int8_t) x(uint8_t) x(int16_t) x(uint16_t)  \
    x(int32_t) x(uint32_t) x(int64_t) x(uint64_t)        \
    x(float) x(double)

    if( !strcmp(v->TypeId(), typeid(T).name()) ) {
        // Same type
        return std::dynamic_pointer_cast<VarValueT<T>>(v);
    }else if( std::is_same<T,std::string>::value ) {
        // Use types string accessor
        return std::dynamic_pointer_cast<VarValueT<T>>(v->str);
    }else
#       define PANGO_CHECK_WRAP(x)                                                       \
    if( !strcmp(v->TypeId(), typeid(x).name() ) ) {                                      \
        std::shared_ptr<VarValueT<x>> xval = std::dynamic_pointer_cast<VarValueT<x>>(v); \
        return Wrapped<T,x>(xval);                                                       \
    }else
    PANGO_VAR_TYPES(PANGO_CHECK_WRAP)
    {
        // other types: have to go via string
        // Wrapper, owned by this object
        return Wrapped<T,std::string>(v->str);
    }
#undef PANGO_VAR_TYPES
#undef PANGO_CHECK_WRAP
}

}


text:
<?php

namespace Magento\Wishlist\Test\Block\Adminhtml\Customer\Edit\Tab\Wishlist;

use Magento\Mtf\Client\Locator;
use Magento\Mtf\Client\Element\SimpleElement;

/**
 * Class Grid
 * Grid on Wishlist tab in customer details on backend
 */
class Grid extends \Magento\Backend\Test\Block\Widget\Grid
{
    /**
     * Grid fields map
     *
     * @var array
     */
    protected $filters = [
        'product_name' => [
            'selector' => 'input[name="product_name"]',
        ],
        'qty_from' => [
            'selector' => 'input[name="qty[from]"]',
        ],
        'qty_to' => [
            'selector' => 'input[name="qty[to]"]',
        ],
        'options' => [
            'selector' => 'td//*[dt[contains(.,"%option_name%")]/following-sibling::dd[contains(.,"%value%")]]',
            'strategy' => 'xpath',
        ],
    ];

    /**
     * Delete link selector
     *
     * @var string
     */
    protected $deleteLink = 'a[onclick*="removeItem"]';

    /**
     * Configure link selector
     *
     * @var string
     */
    protected $configureLink = 'a[onclick*="configureItem"]';

    /**
     * Secondary part of row locator template for getRow() method with strict option.
     *
     * @var string
     */
    protected $rowTemplateStrict = 'td[contains(.,normalize-space("%s"))]';

    /**
     * Selector for confirm.
     *
     * @var string
     */
    protected $confirmModal = '.confirm._show[data-role=modal]';

    /**
     * Delete product
     *
     * @return void
     */
    protected function delete()
    {
        $this->_rootElement->find($this->rowItem . ' ' . $this->deleteLink)->click();
        $element = $this->browser->find($this->confirmModal);
        /** @var \Magento\Ui\Test\Block\Adminhtml\Modal $modal */
        $modal = $this->blockFactory->create('Magento\Ui\Test\Block\Adminhtml\Modal', ['element' => $element]);
        $modal->acceptAlert();
    }

    /**
     * Configure product
     *
     * @return void
     */
    protected function configure()
    {
        $this->_rootElement->find($this->rowItem . ' ' . $this->configureLink)->click();
    }

    /**
     * Search item product and action it
     *
     * @param array $filter
     * @param string $action
     * @return void
     */
    public function searchAndAction(array $filter, $action)
    {
        $this->search($filter);
        $this->{ucfirst($action)}();
        $this->waitLoader();
    }

    /**
     * Check if specific row exists in grid.
     *
     * @param array $filter
     * @param bool $isSearchable
     * @param bool $isStrict
     * @return bool
     */
    public function isRowVisible(array $filter, $isSearchable = true, $isStrict = true)
    {
        if (isset($filter['options'])) {
            unset($filter['options']);
        }
        return parent::isRowVisible($filter, $isSearchable, $isStrict);
    }

    /**
     * Obtain specific row in grid
     *
     * @param array $filter
     * @param bool $isStrict [optional]
     * @return SimpleElement
     */
    protected function getRow(array $filter, $isStrict = true)
    {
        $options = [];
        if (isset($filter['options'])) {
            $options = $filter['options'];
            unset($filter['options']);
        }
        $location = '//tr[';
        $rowTemplate = ($isStrict) ? $this->rowTemplateStrict : $this->rowTemplate;
        $rows = [];
        foreach ($filter as $value) {
            $rows[] = sprintf($rowTemplate, $value);
        }
        if (!empty($options) && is_array($options)) {
            foreach ($options as $value) {
                $rows[] = str_replace(
                    '%value%',
                    $value['value'],
                    str_replace('%option_name%', $value['option_name'], $this->filters['options']['selector'])
                );
            }
        }

        return $this->_rootElement->find($location . implode(' and ', $rows) . ']', Locator::SELECTOR_XPATH);
    }
}


text:
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')

require 'strftime_logger'
require 'parallel'
require 'timecop'
require 'test/unit'

Timecop.scale(24 * 60 * 60)

$proc_num = 2
$execute_num = 10000

logger = StrftimeLogger.new("#{__dir__}/test.log.%Y%m%d")
Parallel.map(['a', 'b'], :in_processes => $proc_num) do |letter|
  $execute_num.times do
  logger.info letter * 5000
  end
end

$total_num = `LANG=C wc -l #{__dir__}/test.log.*`.split("\n").map(&:strip).grep(/\stotal\z/).first.split(' ').first.to_i
p "Actually total line num #{$total_num}"
p "Expected total line num #{$execute_num * $proc_num}"

class StrftimeLoggerTC < Test::Unit::TestCase
  def test_logger
    assert_equal($execute_num * $proc_num, $total_num)
  end
  def teardown
    p 'rm -rf #{__dir__}/test.log.*'
  end
end

=begin
% ruby example/rotate_process_safe_check.rb
no warn!!!
=end


text:
<?php
require_once('config_tinybrowser.php');
require_once('fns_tinybrowser.php');

// delay script if set
if($tinybrowser['delayprocess']>0) sleep($tinybrowser['delayprocess']);

// Initialise files array and error vars
$files = array();
$good = 0;
$bad = 0;
$dup = 0;
$total = (isset($_GET['filetotal']) ? $_GET['filetotal'] : 0);

// Assign get variables
$folder = $tinybrowser['docroot'].urldecode($_GET['folder']);
$foldernow = urlencode(str_replace($tinybrowser['path'][$_GET['type']],'',urldecode($_GET['folder'])));
$passfeid = (isset($_GET['feid']) ? '&feid='.$_GET['feid'] : '');

if ($handle = opendir($folder))
	{
	while (false !== ($file = readdir($handle)))
		{
		if ($file != "." && $file != ".." && substr($file,-1)=='_')
			{
			//-- File Naming
			$tmp_filename = $folder.$file;
			$dest_filename	 = $folder.rtrim($file,'_');

			//-- Duplicate Files
			if(file_exists($dest_filename)) { unlink($tmp_filename); $dup++; continue; }

			//-- Bad extensions
			$nameparts = explode('.',$dest_filename);
			$ext = end($nameparts);

			if(!validateExtension($ext, $tinybrowser['prohibited'])) { unlink($tmp_filename); continue; }

			//-- Rename temp file to dest file
			rename($tmp_filename, $dest_filename);
			$good++;

			//-- if image, perform additional processing
			if($_GET['type']=='image')
				{
				//-- Good mime-types
				$imginfo = getimagesize($dest_filename);
	   		if($imginfo === false) { unlink($dest_filename); continue; }
				$mime = $imginfo['mime'];

				// resize image to maximum height and width, if set
				if($tinybrowser['imageresize']['width'] > 0 || $tinybrowser['imageresize']['height'] > 0)
					{
					// assign new width and height values, only if they are less than existing image size
					$widthnew  = ($tinybrowser['imageresize']['width'] > 0 && $tinybrowser['imageresize']['width'] < $imginfo[0] ? $tinybrowser['imageresize']['width'] : $imginfo[0]);
					$heightnew = ($tinybrowser['imageresize']['height'] > 0 && $tinybrowser['imageresize']['height'] < $imginfo[1] ? $tinybrowser['imageresize']['height'] :  $imginfo[1]);

					// only resize if width or height values are different
					if($widthnew != $imginfo[0] || $heightnew != $imginfo[1])
						{
						$im = convert_image($dest_filename,$mime);
						resizeimage($im,$widthnew,$heightnew,$dest_filename,$tinybrowser['imagequality'],$mime);
						imagedestroy($im);
						}
					}

				// generate thumbnail
				$thumbimg = $folder.'_thumbs/_'.rtrim($file,'_');
				if (!file_exists($thumbimg))
					{
					$im = convert_image($dest_filename,$mime);
					resizeimage	($im,$tinybrowser['thumbsize'],$tinybrowser['thumbsize'],$thumbimg,$tinybrowser['thumbquality'],$mime);
					imagedestroy ($im);
					}
				}

      	}
		}
	closedir($handle);
	}
$bad = $total-($good+$dup);

// Check for problem during upload
if($total>0 && $bad==$total) Header('Location: ./upload.php?type='.$_GET['type'].$passfeid.'&permerror=1&total='.$total);
else Header('Location: ./upload.php?type='.$_GET['type'].$passfeid.'&folder='.$foldernow.'&badfiles='.$bad.'&goodfiles='.$good.'&dupfiles='.$dup);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta http-equiv="Pragma" content="no-cache" />
		<title>TinyBrowser :: Process Upload</title>

Sorry, there was an error processing file uploads.


text:
package com.sinyuk.yuk.utils.lists;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by Sinyuk on 16.1.21.
 */
public class ListItemMarginDecoration extends RecyclerView.ItemDecoration {
    private int spanCount;
    private int mSpace;
    private boolean includeEdge;

    public ListItemMarginDecoration(int spanCount, int resId, boolean includeEdge, Context context) {
        this.mSpace = context.getResources().getDimensionPixelOffset(resId);
        this.spanCount = spanCount;
        this.includeEdge = includeEdge;
    }

    public ListItemMarginDecoration(int spanCount, int mSpace, boolean includeEdge) {
        this.spanCount = spanCount;
        this.mSpace = mSpace;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view); // item position
        int column = position % spanCount; // item column 列数

        if (includeEdge) { // 如果边缘也要有边距
            outRect.left = mSpace - column * mSpace / spanCount; // mSpace - column * ((1f / spanCount) * mSpace)
            outRect.right = (column + 1) * mSpace / spanCount; // (column + 1) * ((1f / spanCount) * mSpace)

            if (position < spanCount) { // top edge
                outRect.top = mSpace;
            }
            outRect.bottom = mSpace; // item bottom
        } else {
            outRect.left = column * mSpace / spanCount; // column * ((1f / spanCount) * mSpace)
            outRect.right = mSpace - (column + 1) * mSpace / spanCount; // mSpace - (column + 1) * ((1f /    spanCount) * mSpace)
            if (position >= spanCount) {
                outRect.top = mSpace; // item top
            }
        }
    }
}


text:
require_dependency "epm_catalog/application_controller"

module EpmCatalog
  class DashboardStatsController < ApplicationController
    before_filter :authenticate_user!

    def index

    end

    # removing as no longer needed because the advisory group process is over, also not very effecient
    #def advisory_group_stats
    #  advisory_group = User.all_advisory_group_and_admin
    #  @advisory_group_stats = []
    #  advisory_group.each do |u|
    #    @stats={}
    #    up_votes = down_votes = 0
    #    up_votes = Measure.where('up_votes.user_id' => u.id.to_s).all.count
    #    down_votes = Measure.where('down_votes.user_id' => u.id.to_s).all.count
    #    @stats[:user_name] = u.name
    #    @stats[:user_id] = u.id
    #    @stats[:touched] = up_votes + down_votes
    #    @stats[:up_votes] = up_votes
    #    @stats[:down_votes] = down_votes
    #    @advisory_group_stats << @stats
    #  end
    #
    #  render json: @advisory_group_stats
    #end
  end
end


text:
namespace CicOData
{
    using System;
    using System.Collections.Generic;

    public partial class IWrkgrpQueueStats
    {
        public int StatisticsSet { get; set; }
        public string cName { get; set; }
        public string cReportGroup { get; set; }
        public string cHKey3 { get; set; }
        public string cHKey4 { get; set; }
        public string cType { get; set; }
        public System.DateTime dIntervalStart { get; set; }
        public System.DateTime dIntervalStartUTC { get; set; }
        public int nDuration { get; set; }
        public Nullable<int> nEnteredAcd { get; set; }
        public Nullable<int> nAbandonedAcd { get; set; }
        public Nullable<int> nGrabbedAcd { get; set; }
        public Nullable<int> nLocalDisconnectAcd { get; set; }
        public Nullable<int> nLocalDisconnectAgentAlertAcd { get; set; }
        public Nullable<int> nLocalDisconnectAgentAcd { get; set; }
        public Nullable<int> nAlertedAcd { get; set; }
        public Nullable<int> nAnsweredAcd { get; set; }
        public Nullable<int> nAnswered { get; set; }
        public Nullable<int> nAcdSvcLvl { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl1 { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl2 { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl3 { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl4 { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl5 { get; set; }
        public Nullable<int> nAnsweredAcdSvcLvl6 { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl1 { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl2 { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl3 { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl4 { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl5 { get; set; }
        public Nullable<int> nAbandonAcdSvcLvl6 { get; set; }
        public Nullable<int> tGrabbedAcd { get; set; }
        public Nullable<int> tAnsweredAcd { get; set; }
        public Nullable<int> mtAnsweredAcd { get; set; }
        public Nullable<int> tAbandonedAcd { get; set; }
        public Nullable<int> tTalkAcd { get; set; }
        public Nullable<int> tTalkCompleteAcd { get; set; }
        public Nullable<int> nHoldAcd { get; set; }
        public Nullable<int> tHoldAcd { get; set; }
        public Nullable<int> nSuspendedAcd { get; set; }
        public Nullable<int> tSuspendedAcd { get; set; }
        public Nullable<int> nHeldSpanAcd { get; set; }
        public Nullable<int> nAcw { get; set; }
        public Nullable<int> tAcw { get; set; }
        public Nullable<int> tAcwComplete { get; set; }
        public Nullable<int> nExternToInternCalls { get; set; }
        public Nullable<int> nExternToInternAcdCalls { get; set; }
        public Nullable<int> nInternToExternCalls { get; set; }
        public Nullable<int> nInternToExternAcdCalls { get; set; }
        public Nullable<int> nInternToInternCalls { get; set; }
        public Nullable<int> nInternToInternAcdCalls { get; set; }
        public Nullable<int> tExternToInternCalls { get; set; }
        public Nullable<int> tExternToInternAcdCalls { get; set; }
        public Nullable<int> tInternToExternCalls { get; set; }
        public Nullable<int> tInternToExternAcdCalls { get; set; }
        public Nullable<int> tInternToInternCalls { get; set; }
        public Nullable<int> tInternToInternAcdCalls { get; set; }
        public Nullable<int> nAcwCalls { get; set; }
        public Nullable<int> tAcwCalls { get; set; }
        public Nullable<int> nTransferedAcd { get; set; }
        public Nullable<int> nNotAnsweredAcd { get; set; }
        public Nullable<int> tAlertedAcd { get; set; }
        public Nullable<int> nFlowOutAcd { get; set; }
        public Nullable<int> tFlowOutAcd { get; set; }
        public Nullable<int> nStartWaitAlertAcdCalls { get; set; }
        public Nullable<int> nStartActiveAcdCalls { get; set; }
        public Nullable<int> nStartHeldAcdCalls { get; set; }
        public Nullable<int> nEndWaitAlertAcdCalls { get; set; }
        public Nullable<int> nEndActiveAcdCalls { get; set; }
        public Nullable<int> nEndHeldAcdCalls { get; set; }
        public Nullable<int> nTransferWithinAcdCalls { get; set; }
        public Nullable<int> nTransferOutAcdCalls { get; set; }
        public Nullable<int> nDisconnectAcd { get; set; }
        public Nullable<int> tAgentLoggedIn { get; set; }
        public Nullable<int> tAgentAvailable { get; set; }
        public Nullable<int> tAgentTalk { get; set; }
        public Nullable<int> tAgentOtherBusy { get; set; }
        public Nullable<int> tAgentOnAcdCall { get; set; }
        public Nullable<int> tAgentOnOtherAcdCall { get; set; }
        public Nullable<int> tAgentInAcw { get; set; }
        public Nullable<int> tAgentOnNonAcdCall { get; set; }
        public Nullable<int> tAgentDnd { get; set; }
        public Nullable<int> tAgentNotAvailable { get; set; }
        public Nullable<int> tAgentAcdLoggedIn { get; set; }
        public Nullable<int> tAgentAcdLoggedIn2 { get; set; }
        public Nullable<int> tAgentStatusDnd { get; set; }
        public Nullable<int> tAgentStatusAcw { get; set; }
        public Nullable<int> tAgentLoggedInDiluted { get; set; }
        public Nullable<int> tStatusGroupFollowup { get; set; }
        public Nullable<int> tStatusGroupBreak { get; set; }
        public Nullable<int> tStatusGroupTraining { get; set; }
        public Nullable<int> CustomValue1 { get; set; }
        public Nullable<int> CustomValue2 { get; set; }
        public Nullable<int> CustomValue3 { get; set; }
        public Nullable<int> CustomValue4 { get; set; }
        public Nullable<int> CustomValue5 { get; set; }
        public Nullable<int> CustomValue6 { get; set; }
        public short SiteId { get; set; }
        public int SubSiteId { get; set; }
        public System.DateTime I3TimeStampGMT { get; set; }
        public int DimensionSet { get; set; }
        public Nullable<int> SummDimensionSet { get; set; }
        public int ConfigurationSet { get; set; }
        public int nServiceLevel { get; set; }
        public string cServiceLevels { get; set; }
        public byte SchemaMajorVersion { get; set; }
        public byte SchemaMinorVersion { get; set; }
    }
}


text:
package com.talis.hbase.rdf.layout.simple;

public class TableDescPredicates extends TableDescSimpleCommon
{
	protected static final String PREDICATE_TBL_NAME = "-predicates" ;

    public static String name() { return PREDICATE_TBL_NAME ; }

    public TableDescPredicates() { this( PREDICATE_TBL_NAME ) ; }

    public TableDescPredicates( String tName ) { super( tName ) ; }
}


text:
 The key to performance is elegance, not battalions of special cases.

  --Jon Bentley and Doug McIlroy [
  source]


text:
+++
title = "That one thing about Indian education"
date = 2019-01-06T21:59:54+01:00
draft = false

# Tags and categories
# For example, use `tags = []` for no tags, or the form `tags = ["A Tag", "Another Tag"]` for one or more tags.
tags = ["education","india","science", "life"]
categories = ["science"]

# Featured image
# Place your image in the `static/img/` folder and reference its filename below, e.g. `image = "example.jpg"`.
[header]
image = ""
caption = ""

+++
India's higher education seems to be going through a substantial overhaul. Through
the 5 years I pursued my PhD, from 2010 to 2015, the stipend increased three folds.
Major institutions are opening up to attract foreign faculty and there are now
scholarship programs paying on par with a job in a multinational company.
However, in every field of education, there exists a huge chasm between the tier
1 institutes such as the IITs and IISc and the rest. The top ranked institutions
which are often in constant
academic exchange with foreign institutions make original
contributions of high quality. As we
move down the rankings, the decline in quality is alarming. There are academic networks where
a thesis that merely
passes a plagiarism test will earn you a PhD.
The extra resources our government pumps into the tier 1 institutes may or may
not *trickle down* to the rest of the country just as we are unsure of an economic trickle down.
Clearly, the brilliant minds of the country are far larger than the limited
positions in tier 1 institutions picked through their *one-dimensional* screening process.
What then is preventing the best minds of our country affiliated with the ordinary
institutions of India from motivating themselves and improving their standards
when all the material resources are in place? Is there a common factor
in our inherent teaching methods that make us not win a Nobel Prize? I believe there
is at least one. Loyalty.

Remember the first time you learned Newton's first law, when you were taught
word by word that an object travelling with a *constant* velocity in a *straight* line
continues to *remain* unless you intervene? You lost a point for missing each
of those key words in an exam. Our teachers believed in phrasing it right
because it is one among the laws of nature as they were taught. However,
we learned later that this law is applicable within
a *classical* framework and outside of this the law loses its generality and that
space and time can curve we don't even know if anything ever truly travels in a
straight line. Ever.
Yet we continue to call it a law. Similarly we have several scientific 'discoveries'
until they stop remaining discoveries or get modified as we inquire closer.
While the Indian mind beats itself in succumbing to this loyalty to the *laws* and
*discoveries*, the rest of the world does not seem to take these words literally. Somehow,
a high school student in Germany understands that any equation in a text book is simply a model
that holds true only within the limits of our understanding at that point in time.
That freshman in the US tests the theory of evolution in his backyard as if
he did not believe it when his text books called it a discovery.  But the
graduate student in India is downright
 loyal. If something
is a law or a discovery, how can we probe it? Law is supposed to be obeyed and
a discovery is a truth. There is immense trust on the source of these.
We believe our
success and acceptance in the world depends on this loyalty. But we were only
trying to understand, you may argue. Tell me, is education more about following
an idea than improving it?

Can we escape this loyalty? How are we to commit a student to an idea first
and encourage him/her to probe it subsequently? If loyalty is removed, would
pseudo-science take its
place? These are questions I ponder over. I had a revelation when I was in my
sixth grade. It was by sheer luck that I encountered a book called *The history of
mathematics* in my mother's little math library. In this book I was intrigued by
the history of the number theory.
The development of the idea of a fraction to the conclusion that the number of fractional
numbers is countable was presented with the names and periods of the contributing mathematicians.
The book showed me how Cantor, a German mathematician, in 1880 showed that all of the
fractions (rational numbers) could be counted using a simple sequence through the
numbers, even though they are infinite. Fraction were first used by the Egyptians 4000 years ago.
Every small formal addition to the
idea of fractions since then were documented in this little book.  Treading through these developments,
they not only became understandable concepts to me but
also appeared simply as a sequence of common sense improvements to a previous idea. I could see
how a complex theory was indeed many small improvements that happened over decades
and even centuries. My mathematics text book of that time simply dictated rational numbers,
forcing me to be a slave to the idea. However I felt free knowing their history.
Ever since this moment, I searched for the historical development
of every idea that I came across. Of course there are geniuses among us who gave
us more than just common sense, and they
deserve all our respect. But they were born with a human brain. Recently I was
in a classroom on non-equilibrium thermodynamics taught by a distinguished professor.
To my pleasant surprise, after writing down every equation on the board, he would
mark the year of the equation's origin and make a passing comment about the scientist
or the thought process. The course made me imagine those brilliant minds. Soon
I felt I was walking among them, even having conversations and raised questions.
Soon enough, I realized that the history of an idea is an immense source of encouragement
that is often missing in our Indian classrooms. Perhaps, it is time to balance
some of that loyalty with a bit of historical background.


text:
import {
  realmDeleteHelper,
  realmDeleteAllHelper,
  realmObjectHelper,
  allRealmObjectsHelper,
  realmObjectIsInvalidHelper,
} from '../realm';

import { AudioContent } from './audioContent';

export class TourStop {
  static NAME = 'TourStop'

  static schema = {
    name: TourStop.NAME,
    primaryKey: 'uuid',
    properties: {
      uuid: { type: 'string' },
      order: { type: 'int' },
      floor: { type: 'int' },
      shortTitle: { type: 'string' },
      longTitle: { type: 'string' },
      shortCreditAccessibilityLabel: { type: 'string', optional: true },
      regions: { type: 'string' }, // Stored as String, but converted from Array
      imageURL: { type: 'string', optional: true },
      imageAccessibilityLabel: { type: 'string', optional: true },
      imageWidth: { type: 'int' },
      imageHeight: { type: 'int' },
      shortCredit: { type: 'string' },
      longCredit: { type: 'string' },
      tags: { type: 'string' }, // Stored as String, but converted from Array
      initialAudio: { type: 'string' },
      audioContent: { type: 'list', objectType: 'AudioContent' },
    },
  }

  // inserting is omitted on purpose because realm inserts are expensive
  // so should be done as a single block.

  static realmDelete(uuidKey) {
    return realmDeleteHelper(TourStop.NAME, uuidKey);
  }

  static realmDeleteAll() {
    return realmDeleteAllHelper(TourStop.NAME);
  }

  static realmObject(uuidKey) {
    return realmObjectHelper(TourStop.NAME, uuidKey);
  }

  static allRealmObjects() {
    return allRealmObjectsHelper(TourStop.NAME);
  }

  static jsonAudioContent(realmObject) {
    return realmObject.audioContent
      .map((content) => {
        return AudioContent.json(content);
      });
  }

  static json(uuidKey) {
    const realmObject = TourStop.realmObject(uuidKey);

    if (realmObjectIsInvalidHelper(realmObject)) {
      return {};
    }

    return {
      uuid: realmObject.uuid,
      order: realmObject.order,
      floor: realmObject.floor,
      shortTitle: realmObject.shortTitle,
      longTitle: realmObject.longTitle,
      shortCreditAccessibilityLabel: realmObject.shortCreditAccessibilityLabel,
      regions: realmObject.regions.split(','),
      imageURL: realmObject.imageURL,
      imageAccessibilityLabel: realmObject.imageAccessibilityLabel,
      imageWidth: realmObject.imageWidth,
      imageHeight: realmObject.imageHeight,
      shortCredit: realmObject.shortCredit,
      longCredit: realmObject.longCredit,
      tags: realmObject.tags.split(','),
      initialAudio: realmObject.initialAudio,
      audioContent: TourStop.jsonAudioContent(realmObject),
    };
  }
}