text:
namespace animus {

    struct http_response {
        bool error;
        uint16_t http_code;
        std::string data;
    };

    class http final {
    public:
        http(std::shared_ptr<animus_generated::http> http_impl, const std::shared_ptr<task_runner> & runner);
        void get(const std::string& url, std::function<void(http_response)>);
        void post(const std::string& url, const std::string& data, std::function<void(http_response)>);
        void put(const std::string& url, const std::string& data, std::function<void(http_response)>);
        void patch(const std::string& url, const std::string& data, std::function<void(http_response)>);
        void del(const std::string& url, std::function<void(http_response)>);
    private:
        class request final : public animus_generated::http_callback {
        public:
            request(std::function<void(http_response)> cb, const std::shared_ptr<task_runner> & on_thread);
            virtual void on_network_error();
            virtual void on_success(int16_t http_code, const std::string& data);
            void _cb_with(http_response resp);
        private:
            const std::shared_ptr<task_runner> callback_thread;
            const std::function<void(http_response)> callback;
        };
        const std::shared_ptr<task_runner> callback_thread;
        const std::shared_ptr<animus_generated::http> http_impl;
    };

}


text:
package com.nivler.android.wallpaperextractor.helper;

import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.util.Log;

public class MediaScannerNotifier implements MediaScannerConnectionClient {
    private MediaScannerConnection mConnection;
    private String mPath;
    private String mMimeType;

    private static final String TAG = "Wallpaper Extractor";

    Context mContext;

    public MediaScannerNotifier(Context context, String path, String mimeType) {
    	mContext = context;
    	mPath = path;
    	mMimeType = mimeType;
    	mConnection = new MediaScannerConnection(context, this);
    	mConnection.connect();
    }

    public void onMediaScannerConnected() {
        mConnection.scanFile(mPath, mMimeType);
    }

    public void onScanCompleted(String path, Uri uri) {
    	try {
            if (uri != null) {
            	Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(uri);
                mContext.startActivity(intent);
            	Log.i(TAG, "File successfully saved!");
            }
    	} finally {
    		 mConnection.disconnect();
             mContext = null;
    	}
    }
}

redpajama_set_name: RedPajamaGithub


text:
from runtime.pai.submitter_evaluate import submit_pai_evaluate as evaluate  # noqa
from runtime.pai.submitter_explain import submit_pai_explain as explain  # noqa
from runtime.pai.submitter_predict import submit_pai_predict as pred  # noqa
from runtime.pai.submitter_train import submit_pai_train as train  # noqa


text:
"""
Copyright 2015 Rackspace

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import random

from functionaltests.api.v2.models.zone_model import ZoneModel
from functionaltests.api.v2.models.recordset_model import RecordsetModel
from functionaltests.api.v2.models.pool_model import PoolModel

def random_ip():
    return ".".join(str(random.randrange(0, 256)) for _ in range(4))

def random_ipv6():
    def hexes(n):
        return "".join(random.choice("1234567890abcdef") for _ in range(n))
    result = ":".join(hexes(4) for _ in range(8))
    return result.replace("0000", "0")

def random_string(prefix='rand', n=8, suffix=''):
    """Return a string containing random digits

    :param prefix: the exact text to start the string. Defaults to "rand"
    :param n: the number of random digits to generate
    :param suffix: the exact text to end the string
    """
    digits = "".join(str(random.randrange(0, 10)) for _ in range(n))
    return prefix + digits + suffix

def random_zone_data(name=None, email=None, ttl=None, description=None):
    """Generate random zone data, with optional overrides

    :return: A ZoneModel
    """
    if name is None:
        name = random_string(prefix='testdomain', suffix='.com.')
    if email is None:
        email = ("admin@" + name).strip('.')
    if description is None:
        description = random_string(prefix='Description ')
    if ttl is None:
        ttl = random.randint(1200, 8400),
    return ZoneModel.from_dict({
        'name': name,
        'email': email,
        'ttl': random.randint(1200, 8400),
        'description': description})

def random_recordset_data(record_type, zone_name, name=None, records=None,
                          ttl=None):
    """Generate random recordset data, with optional overrides

    :return: A RecordsetModel
    """
    if name is None:
        name = random_string(prefix=record_type, suffix='.' + zone_name)
    if records is None:
        records = [random_ip()]
    if ttl is None:
        ttl = random.randint(1200, 8400)
    return RecordsetModel.from_dict({
        'type': record_type,
        'name': name,
        'records': records,
        'ttl': ttl})

def random_a_recordset(zone_name, ip=None, **kwargs):
    if ip is None:
        ip = random_ip()
    return random_recordset_data('A', zone_name, records=[ip], **kwargs)

def random_aaaa_recordset(zone_name, ip=None, **kwargs):
    if ip is None:
        ip = random_ipv6()
    return random_recordset_data('AAAA', zone_name, records=[ip], **kwargs)

def random_cname_recordset(zone_name, cname=None, **kwargs):
    if cname is None:
        cname = zone_name
    return random_recordset_data('CNAME', zone_name, records=[cname], **kwargs)

def random_mx_recordset(zone_name, pref=None, host=None, **kwargs):
    if pref is None:
        pref = str(random.randint(0, 65535))
    if host is None:
        host = random_string(prefix='mail', suffix='.' + zone_name)
    data = "{0} {1}".format(pref, host)
    return random_recordset_data('MX', zone_name, records=[data], **kwargs)

def random_pool_data():
    ns_zone = random_zone_data().name
    data = {
        "name": random_string(),
    }
    ns_records = []
    for i in range(0, 2):
        ns_records.append("ns%s.%s" % (i, ns_zone))
    data["ns_records"] = []

    return PoolModel.from_dict(data)

def random_zonefile_data(name=None, ttl=None):
    """Generate random zone data, with optional overrides

    :return: A ZoneModel
    """
    zone_base = ('$ORIGIN &\n& # IN SOA ns.& nsadmin.& # # # # #\n'
                 '& # IN NS ns.&\n& # IN MX 10 mail.&\nns.& 360 IN A 1.0.0.1')
    if name is None:
        name = random_string(prefix='testdomain', suffix='.com.')
    if ttl is None:
        ttl = str(random.randint(1200, 8400))

    return zone_base.replace('&', name).replace('#', ttl)


text:
package com.sun.xml.internal.ws.api.pipe;

/**
 * Factory for (@link FiberContextSwitchInterceptor} instances
 *
 * @since 2.2.6
 */
public interface FiberContextSwitchInterceptorFactory {
        /**
         * Creates {@link FiberContextSwitchInterceptor} instance.
         * @return interceptor instance
         */
        public FiberContextSwitchInterceptor create();
}


text:
import {Mongo} from 'meteor/mongo';
import {SimpleSchema} from 'meteor/aldeed:simple-schema';
import {Util} from '../util.js';
import {Auth} from '../auth.js';
import {ChangeTracker} from '../change_tracker/change_tracker.js';
import {SchemaHelpers} from '../schema_helpers.js';

import {DSUtil} from './ds_util.js';
import {DatastoreDataTypeFields} from './datastore_data_type_fields.js';

/**
 * ============================================================================
 * DatastoreDataType
 * ============================================================================
 */
export const DatastoreDataType = new SimpleSchema({
  // Static ID field that will be constant across versions of the project
  staticId: {
    type: String,
    index: true,
    autoValue: SchemaHelpers.autoValueObjectId,
    denyUpdate: true
  },
  // Link to the project to which this field belongs
  projectId: {
    type: String,
    denyUpdate: true
  },
  // Link to the project version to which this field belongs
  projectVersionId: {
    type: String,
    denyUpdate: true
  },
  // Descriptive title
  title: {
    type: String
  },
  // Stored basic schema
  tableSchemaDef: {
    type: Object,
    blackbox: true,
    optional: true
  },
  // A code fragment to render an identifier for a row (Like assemble a name or whatever so you can select a row)
  renderRowSelector: {
    type: String,
    optional: true
  },
  // Standard tracking fields
  dateCreated: {
    type: Date,
    autoValue: SchemaHelpers.autoValueDateCreated,
    denyUpdate: true
  },
  createdBy: {
    type: String,
    autoValue: SchemaHelpers.autoValueCreatedBy,
    denyUpdate: true
  },
  dateModified: {
    type: Date,
    autoValue: SchemaHelpers.autoValueDateModified
  },
  modifiedBy: {
    type: String,
    autoValue: SchemaHelpers.autoValueModifiedBy
  }
});

export const DatastoreDataTypes = new Mongo.Collection("datastore_data_types");
DatastoreDataTypes.attachSchema(DatastoreDataType);
DatastoreDataTypes.deny(Auth.ruleSets.deny.ifNotTester);
DatastoreDataTypes.allow(Auth.ruleSets.allow.ifAuthenticated);
ChangeTracker.TrackChanges(DatastoreDataTypes, "datastore_data_types");

/**
 * Helpers
 */
DatastoreDataTypes.helpers({
  fields(){
    return DatastoreDataTypeFields.find({parentId: this.staticId, projectVersionId: this.projectVersionId}, {sort: {order: 1}});
  },
  updateTableSchema(){
    //console.log("DatastoreDataTypes.updateTableSchema:", this);
    let tableSchemaDef = {fields: []};

    // build up the schema
    this.fields().forEach(function (field) {
      tableSchemaDef.fields.push(DSUtil.tableFieldDef(field));
    });

    // store the schema
    DatastoreDataTypes.update({_id: this._id}, {$set: {tableSchemaDef: tableSchemaDef}});
  },
  rowRenderer(){
    return Function('row', this.renderRowSelector || 'return row ? row[0] : \'undefined\'');
  },
  renderRow(row){
    return this.rowRenderer()(row);
  },
  tableSchema(){
    if(this.tableSchemaDef){
      //console.log("DatastoreDataTypes.tableSchema via storage:", this);
      return this.tableSchemaDef;
    } else {
      console.log("DatastoreDataTypes.tableSchema via update:", this);
      return this.updateTableSchema();
    }
  },
  simpleSchema(){
    //console.log("DatastoreDataType.simpleSchema:", this);
    let simpleSchemaDef = {};
    this.fields().forEach((field) => {
      simpleSchemaDef[field.dataKey] = DSUtil.simpleFieldDef(field);
    });
    try {
      return new SimpleSchema(simpleSchemaDef);
    } catch(e) {
      console.error("Failed to generate simpleSchema for datastore:", simpleSchemaDef, e);
    }
  }
});


text:
1. Go to chrome://extensions/
2. Drag the .crx file to Chrome.

# Use

1. Click the icon
2. That's all! Enjoy your 'Dan Mu'

# License

MIT License


text:
title: Importing Assets Directly into Files
---

There are two major ways to import assets, such as images, fonts, and files, into a Gatsby site. The default path is to import the file directly into a Gatsby template, page, or component. The alternative path, which makes sense for some edge cases, is to use the [static folder](/docs/how-to/images-and-media/static-folder).

## Importing assets with webpack

With webpack you can **`import` a file right in a JavaScript module**. This tells webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This imported file's value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF.

To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a
[data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: `svg`, `jpg`, `jpeg`, `png`, `gif`, `mp4`, `webm`, `wav`, `mp3`, `m4a`, `aac`, and `oga`.

Here's an example:

```jsx
import React from "react"
import logo from "./logo.png" // Tell webpack this JS file uses this image

console.log(logo) // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />
}

export default Header
```

This ensures that when the project is built, webpack will correctly move the images into the public folder, and provide us with correct paths.

You can reference files in CSS to import them, too:

```css
.Logo {
  background-image: url(./logo.png);
}
```

webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by webpack from content hashes. If the file content changes in the future, webpack will give it a different name in production so you don't need to worry about long-term caching of assets.

If you're using SCSS the imports are relative to the entry SCSS file.

Please be advised that this is also a custom feature of webpack.

<EggheadEmbed
  lessonLink="https://egghead.io/lessons/gatsby-import-a-local-image-into-a-gatsby-component-with-webpack"
  lessonTitle="Import a Local Image into a Gatsby Component with webpack"
/>

### Additional resources

- More on [using an imported font](/docs/how-to/styling/using-local-fonts/).

## Querying for a `File` in GraphQL using gatsby-source-filesystem

You can also import files using GraphQL by querying for them in your data layer, which will trigger copying of those files to the public directory. Querying for the `publicURL` field of `File` nodes will provide URLs you can use in your JavaScript components, pages and templates.

### Examples

1. Copy all `.pdf` files you have in your data layer to your build directory and return URLs to them:

```graphql
{
  allFile(filter: { extension: { eq: "pdf" } }) {
    edges {
      node {
        publicURL
      }
    }
  }
}
```

Reference those PDF files in a page with useStaticQuery:

```jsx
import React from "react"
import { useStaticQuery, graphql } from "gatsby"

import Layout from "../components/layout"

const DownloadsPage = () => {
  const data = useStaticQuery(graphql`
    {
      allFile(filter: { extension: { eq: "pdf" } }) {
        edges {
          node {
            publicURL
            name
          }
        }
      }
    }
  `)
  return (
    <Layout>
      <h1>All PDF Downloads</h1>
      <ul>
        {data.allFile.edges.map((file, index) => {
          return (
            <li key={`pdf-${index}`}>
              <a href={file.node.publicURL} download>
                {file.node.name}
              </a>
            </li>
          )
        })}
      </ul>
    </Layout>
  )
}
export default DownloadsPage
```

2. Link to attachments in the frontmatter of your Markdown files:

```markdown
---
title: "Title of article"
attachments:
  - "./assets.zip"
  - "./presentation.pdf"
---

Hi, this is a great article.
```

In an article template component file, you can then query for the attachments:

```graphql
query ($slug: String!) {
  markdownRemark(fields: { slug: { eq: $slug } }) {
    html
    frontmatter {
      title
      attachments {
        publicURL
      }
    }
  }
}
```

Read more about querying for files in [`gatsby-source-filesystem`](/plugins/gatsby-source-filesystem/).


text:
module.exports = {
    imgurClientID: "clientid",
    imgurClientSecret: "clientsecret" //Currently unused
};


text:
/*	$FreeBSD: soc2013/dpl/head/sys/contrib/altq/altq/altq_cbq.c 241402 2012-09-08 06:41:54Z glebius $	*/
/*	$KAME: altq_cbq.c,v 1.19 2003/09/17 14:23:25 kjc Exp $	*/

/*
 * Copyright (c) Sun Microsystems, Inc. 1993-1998 All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the SMCC Technology
 *      Development Group at Sun Microsystems, Inc.
 *
 * 4. The name of the Sun Microsystems, Inc nor may not be used to endorse or
 *      promote products derived from this software without specific prior
 *      written permission.
 *
 * SUN MICROSYSTEMS DOES NOT CLAIM MERCHANTABILITY OF THIS SOFTWARE OR THE
 * SUITABILITY OF THIS SOFTWARE FOR ANY PARTICULAR PURPOSE.  The software is
 * provided "as is" without express or implied warranty of any kind.
 *
 * These notices must be retained in any copies of any part of this software.
 */

#if defined(__FreeBSD__) || defined(__NetBSD__)
#include "opt_altq.h"
#include "opt_inet.h"
#ifdef __FreeBSD__
#include "opt_inet6.h"
#endif
#endif /* __FreeBSD__ || __NetBSD__ */
#ifdef ALTQ_CBQ	/* cbq is enabled by ALTQ_CBQ option in opt_altq.h */

#include <sys/param.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/errno.h>
#include <sys/time.h>
#ifdef ALTQ3_COMPAT
#include <sys/uio.h>
#include <sys/kernel.h>
#endif

#include <net/if.h>
#include <netinet/in.h>

#include <net/pfvar.h>
#include <altq/altq.h>
#include <altq/altq_cbq.h>
#ifdef ALTQ3_COMPAT
#include <altq/altq_conf.h>
#endif

#ifdef ALTQ3_COMPAT
/*
 * Local Data structures.
 */
static cbq_state_t *cbq_list = NULL;
#endif

/*
 * Forward Declarations.
 */
static int		 cbq_class_destroy(cbq_state_t *, struct rm_class *);
static struct rm_class  *clh_to_clp(cbq_state_t *, u_int32_t);
static int		 cbq_clear_interface(cbq_state_t *);
static int		 cbq_request(struct ifaltq *, int, void *);
static int		 cbq_enqueue(struct ifaltq *, struct mbuf *,
			     struct altq_pktattr *);
static struct mbuf	*cbq_dequeue(struct ifaltq *, int);
static void		 cbqrestart(struct ifaltq *);
static void		 get_class_stats(class_stats_t *, struct rm_class *);
static void		 cbq_purge(cbq_state_t *);
#ifdef ALTQ3_COMPAT
static int	cbq_add_class(struct cbq_add_class *);
static int	cbq_delete_class(struct cbq_delete_class *);
static int	cbq_modify_class(struct cbq_modify_class *);
static int 	cbq_class_create(cbq_state_t *, struct cbq_add_class *,
				 struct rm_class *, struct rm_class *);
static int	cbq_clear_hierarchy(struct cbq_interface *);
static int	cbq_set_enable(struct cbq_interface *, int);
static int	cbq_ifattach(struct cbq_interface *);
static int	cbq_ifdetach(struct cbq_interface *);
static int 	cbq_getstats(struct cbq_getstats *);

static int	cbq_add_filter(struct cbq_add_filter *);
static int	cbq_delete_filter(struct cbq_delete_filter *);
#endif /* ALTQ3_COMPAT */

/*
 * int
 * cbq_class_destroy(cbq_mod_state_t *, struct rm_class *) - This
 *	function destroys a given traffic class.  Before destroying
 *	the class, all traffic for that class is released.
 */
static int
cbq_class_destroy(cbq_state_t *cbqp, struct rm_class *cl)
{
	int	i;

	/* delete the class */
	rmc_delete_class(&cbqp->ifnp, cl);

	/*
	 * free the class handle
	 */
	for (i = 0; i < CBQ_MAX_CLASSES; i++)
		if (cbqp->cbq_class_tbl[i] == cl)
			cbqp->cbq_class_tbl[i] = NULL;

	if (cl == cbqp->ifnp.root_)
		cbqp->ifnp.root_ = NULL;
	if (cl == cbqp->ifnp.default_)
		cbqp->ifnp.default_ = NULL;
#ifdef ALTQ3_COMPAT
	if (cl == cbqp->ifnp.ctl_)
		cbqp->ifnp.ctl_ = NULL;
#endif
	return (0);
}

/* convert class handle to class pointer */
static struct rm_class *
clh_to_clp(cbq_state_t *cbqp, u_int32_t chandle)
{
	int i;
	struct rm_class *cl;

	if (chandle == 0)
		return (NULL);
	/*
	 * first, try optimistically the slot matching the lower bits of
	 * the handle.  if it fails, do the linear table search.
	 */
	i = chandle % CBQ_MAX_CLASSES;
	if ((cl = cbqp->cbq_class_tbl[i]) != NULL &&
	    cl->stats_.handle == chandle)
		return (cl);
	for (i = 0; i < CBQ_MAX_CLASSES; i++)
		if ((cl = cbqp->cbq_class_tbl[i]) != NULL &&
		    cl->stats_.handle == chandle)
			return (cl);
	return (NULL);
}

static int
cbq_clear_interface(cbq_state_t *cbqp)
{
	int		 again, i;
	struct rm_class	*cl;

#ifdef ALTQ3_CLFIER_COMPAT
	/* free the filters for this interface */
	acc_discard_filters(&cbqp->cbq_classifier, NULL, 1);
#endif

	/* clear out the classes now */
	do {
		again = 0;
		for (i = 0; i < CBQ_MAX_CLASSES; i++) {
			if ((cl = cbqp->cbq_class_tbl[i]) != NULL) {
				if (is_a_parent_class(cl))
					again++;
				else {
					cbq_class_destroy(cbqp, cl);
					cbqp->cbq_class_tbl[i] = NULL;
					if (cl == cbqp->ifnp.root_)
						cbqp->ifnp.root_ = NULL;
					if (cl == cbqp->ifnp.default_)
						cbqp->ifnp.default_ = NULL;
#ifdef ALTQ3_COMPAT
					if (cl == cbqp->ifnp.ctl_)
						cbqp->ifnp.ctl_ = NULL;
#endif
				}
			}
		}
	} while (again);

	return (0);
}

static int
cbq_request(struct ifaltq *ifq, int req, void *arg)
{
	cbq_state_t	*cbqp = (cbq_state_t *)ifq->altq_disc;

	IFQ_LOCK_ASSERT(ifq);

	switch (req) {
	case ALTRQ_PURGE:
		cbq_purge(cbqp);
		break;
	}
	return (0);
}

/* copy the stats info in rm_class to class_states_t */
static void
get_class_stats(class_stats_t *statsp, struct rm_class *cl)
{
	statsp->xmit_cnt	= cl->stats_.xmit_cnt;
	statsp->drop_cnt	= cl->stats_.drop_cnt;
	statsp->over		= cl->stats_.over;
	statsp->borrows		= cl->stats_.borrows;
	statsp->overactions	= cl->stats_.overactions;
	statsp->delays		= cl->stats_.delays;

	statsp->depth		= cl->depth_;
	statsp->priority	= cl->pri_;
	statsp->maxidle		= cl->maxidle_;
	statsp->minidle		= cl->minidle_;
	statsp->offtime		= cl->offtime_;
	statsp->qmax		= qlimit(cl->q_);
	statsp->ns_per_byte	= cl->ns_per_byte_;
	statsp->wrr_allot	= cl->w_allotment_;
	statsp->qcnt		= qlen(cl->q_);
	statsp->avgidle		= cl->avgidle_;

	statsp->qtype		= qtype(cl->q_);
#ifdef ALTQ_RED
	if (q_is_red(cl->q_))
		red_getstats(cl->red_, &statsp->red[0]);
#endif
#ifdef ALTQ_RIO
	if (q_is_rio(cl->q_))
		rio_getstats((rio_t *)cl->red_, &statsp->red[0]);
#endif
}

int
cbq_pfattach(struct pf_altq *a)
{
	struct ifnet	*ifp;
	int		 s, error;

	if ((ifp = ifunit(a->ifname)) == NULL || a->altq_disc == NULL)
		return (EINVAL);
#ifdef __NetBSD__
	s = splnet();
#else
	s = splimp();
#endif
	error = altq_attach(&ifp->if_snd, ALTQT_CBQ, a->altq_disc,
	    cbq_enqueue, cbq_dequeue, cbq_request, NULL, NULL);
	splx(s);
	return (error);
}

int
cbq_add_altq(struct pf_altq *a)
{
	cbq_state_t	*cbqp;
	struct ifnet	*ifp;

	if ((ifp = ifunit(a->ifname)) == NULL)
		return (EINVAL);
	if (!ALTQ_IS_READY(&ifp->if_snd))
		return (ENODEV);

	/* allocate and initialize cbq_state_t */
	cbqp = malloc(sizeof(cbq_state_t), M_DEVBUF, M_NOWAIT | M_ZERO);
	if (cbqp == NULL)
		return (ENOMEM);
	CALLOUT_INIT(&cbqp->cbq_callout);
	cbqp->cbq_qlen = 0;
	cbqp->ifnp.ifq_ = &ifp->if_snd;	    /* keep the ifq */

	/* keep the state in pf_altq */
	a->altq_disc = cbqp;

	return (0);
}

int
cbq_remove_altq(struct pf_altq *a)
{
	cbq_state_t	*cbqp;

	if ((cbqp = a->altq_disc) == NULL)
		return (EINVAL);
	a->altq_disc = NULL;

	cbq_clear_interface(cbqp);

	if (cbqp->ifnp.default_)
		cbq_class_destroy(cbqp, cbqp->ifnp.default_);
	if (cbqp->ifnp.root_)
		cbq_class_destroy(cbqp, cbqp->ifnp.root_);

	/* deallocate cbq_state_t */
	free(cbqp, M_DEVBUF);

	return (0);
}

int
cbq_add_queue(struct pf_altq *a)
{
	struct rm_class	*borrow, *parent;
	cbq_state_t	*cbqp;
	struct rm_class	*cl;
	struct cbq_opts	*opts;
	int		i;

	if ((cbqp = a->altq_disc) == NULL)
		return (EINVAL);
	if (a->qid == 0)
		return (EINVAL);

	/*
	 * find a free slot in the class table.  if the slot matching
	 * the lower bits of qid is free, use this slot.  otherwise,
	 * use the first free slot.
	 */
	i = a->qid % CBQ_MAX_CLASSES;
	if (cbqp->cbq_class_tbl[i] != NULL) {
		for (i = 0; i < CBQ_MAX_CLASSES; i++)
			if (cbqp->cbq_class_tbl[i] == NULL)
				break;
		if (i == CBQ_MAX_CLASSES)
			return (EINVAL);
	}

	opts = &a->pq_u.cbq_opts;
	/* check parameters */
	if (a->priority >= CBQ_MAXPRI)
		return (EINVAL);

	/* Get pointers to parent and borrow classes.  */
	parent = clh_to_clp(cbqp, a->parent_qid);
	if (opts->flags & CBQCLF_BORROW)
		borrow = parent;
	else
		borrow = NULL;

	/*
	 * A class must borrow from it's parent or it can not
	 * borrow at all.  Hence, borrow can be null.
	 */
	if (parent == NULL && (opts->flags & CBQCLF_ROOTCLASS) == 0) {
		printf("cbq_add_queue: no parent class!\n");
		return (EINVAL);
	}

	if ((borrow != parent)  && (borrow != NULL)) {
		printf("cbq_add_class: borrow class != parent\n");
		return (EINVAL);
	}

	/*
	 * check parameters
	 */
	switch (opts->flags & CBQCLF_CLASSMASK) {
	case CBQCLF_ROOTCLASS:
		if (parent != NULL)
			return (EINVAL);
		if (cbqp->ifnp.root_)
			return (EINVAL);
		break;
	case CBQCLF_DEFCLASS:
		if (cbqp->ifnp.default_)
			return (EINVAL);
		break;
	case 0:
		if (a->qid == 0)
			return (EINVAL);
		break;
	default:
		/* more than two flags bits set */
		return (EINVAL);
	}

	/*
	 * create a class.  if this is a root class, initialize the
	 * interface.
	 */
	if ((opts->flags & CBQCLF_CLASSMASK) == CBQCLF_ROOTCLASS) {
		rmc_init(cbqp->ifnp.ifq_, &cbqp->ifnp, opts->ns_per_byte,
		    cbqrestart, a->qlimit, RM_MAXQUEUED,
		    opts->maxidle, opts->minidle, opts->offtime,
		    opts->flags);
		cl = cbqp->ifnp.root_;
	} else {
		cl = rmc_newclass(a->priority,
				  &cbqp->ifnp, opts->ns_per_byte,
				  rmc_delay_action, a->qlimit, parent, borrow,
				  opts->maxidle, opts->minidle, opts->offtime,
				  opts->pktsize, opts->flags);
	}
	if (cl == NULL)
		return (ENOMEM);

	/* return handle to user space. */
	cl->stats_.handle = a->qid;
	cl->stats_.depth = cl->depth_;

	/* save the allocated class */
	cbqp->cbq_class_tbl[i] = cl;

	if ((opts->flags & CBQCLF_CLASSMASK) == CBQCLF_DEFCLASS)
		cbqp->ifnp.default_ = cl;

	return (0);
}

int
cbq_remove_queue(struct pf_altq *a)
{
	struct rm_class	*cl;
	cbq_state_t	*cbqp;
	int		i;

	if ((cbqp = a->altq_disc) == NULL)
		return (EINVAL);

	if ((cl = clh_to_clp(cbqp, a->qid)) == NULL)
		return (EINVAL);

	/* if we are a parent class, then return an error. */
	if (is_a_parent_class(cl))
		return (EINVAL);

	/* delete the class */
	rmc_delete_class(&cbqp->ifnp, cl);

	/*
	 * free the class handle
	 */
	for (i = 0; i < CBQ_MAX_CLASSES; i++)
		if (cbqp->cbq_class_tbl[i] == cl) {
			cbqp->cbq_class_tbl[i] = NULL;
			if (cl == cbqp->ifnp.root_)
				cbqp->ifnp.root_ = NULL;
			if (cl == cbqp->ifnp.default_)
				cbqp->ifnp.default_ = NULL;
			break;
		}

	return (0);
}

int
cbq_getqstats(struct pf_altq *a, void *ubuf, int *nbytes)
{
	cbq_state_t	*cbqp;
	struct rm_class	*cl;
	class_stats_t	 stats;
	int		 error = 0;

	if ((cbqp = altq_lookup(a->ifname, ALTQT_CBQ)) == NULL)
		return (EBADF);

	if ((cl = clh_to_clp(cbqp, a->qid)) == NULL)
		return (EINVAL);

	if (*nbytes < sizeof(stats))
		return (EINVAL);

	get_class_stats(&stats, cl);

	if ((error = copyout((caddr_t)&stats, ubuf, sizeof(stats))) != 0)
		return (error);
	*nbytes = sizeof(stats);
	return (0);
}

/*
 * int
 * cbq_enqueue(struct ifaltq *ifq, struct mbuf *m, struct altq_pktattr *pattr)
 *		- Queue data packets.
 *
 *	cbq_enqueue is set to ifp->if_altqenqueue and called by an upper
 *	layer (e.g. ether_output).  cbq_enqueue queues the given packet
 *	to the cbq, then invokes the driver's start routine.
 *
 *	Assumptions:	called in splimp
 *	Returns:	0 if the queueing is successful.
 *			ENOBUFS if a packet dropping occurred as a result of
 *			the queueing.
 */

static int
cbq_enqueue(struct ifaltq *ifq, struct mbuf *m, struct altq_pktattr *pktattr)
{
	cbq_state_t	*cbqp = (cbq_state_t *)ifq->altq_disc;
	struct rm_class	*cl;
	struct pf_mtag	*t;
	int		 len;

	IFQ_LOCK_ASSERT(ifq);

	/* grab class set by classifier */
	if ((m->m_flags & M_PKTHDR) == 0) {
		/* should not happen */
		printf("altq: packet for %s does not have pkthdr\n",
		    ifq->altq_ifp->if_xname);
		m_freem(m);
		return (ENOBUFS);
	}
	cl = NULL;
	if ((t = pf_find_mtag(m)) != NULL)
		cl = clh_to_clp(cbqp, t->qid);
#ifdef ALTQ3_COMPAT
	else if ((ifq->altq_flags & ALTQF_CLASSIFY) && pktattr != NULL)
		cl = pktattr->pattr_class;
#endif
	if (cl == NULL) {
		cl = cbqp->ifnp.default_;
		if (cl == NULL) {
			m_freem(m);
			return (ENOBUFS);
		}
	}
#ifdef ALTQ3_COMPAT
	if (pktattr != NULL)
		cl->pktattr_ = pktattr;  /* save proto hdr used by ECN */
	else
#endif
		cl->pktattr_ = NULL;
	len = m_pktlen(m);
	if (rmc_queue_packet(cl, m) != 0) {
		/* drop occurred.  some mbuf was freed in rmc_queue_packet. */
		PKTCNTR_ADD(&cl->stats_.drop_cnt, len);
		return (ENOBUFS);
	}

	/* successfully queued. */
	++cbqp->cbq_qlen;
	IFQ_INC_LEN(ifq);
	return (0);
}

static struct mbuf *
cbq_dequeue(struct ifaltq *ifq, int op)
{
	cbq_state_t	*cbqp = (cbq_state_t *)ifq->altq_disc;
	struct mbuf	*m;

	IFQ_LOCK_ASSERT(ifq);

	m = rmc_dequeue_next(&cbqp->ifnp, op);

	if (m && op == ALTDQ_REMOVE) {
		--cbqp->cbq_qlen;  /* decrement # of packets in cbq */
		IFQ_DEC_LEN(ifq);

		/* Update the class. */
		rmc_update_class_util(&cbqp->ifnp);
	}
	return (m);
}

/*
 * void
 * cbqrestart(queue_t *) - Restart sending of data.
 * called from rmc_restart in splimp via timeout after waking up
 * a suspended class.
 *	Returns:	NONE
 */

static void
cbqrestart(struct ifaltq *ifq)
{
	cbq_state_t	*cbqp;
	struct ifnet	*ifp;

	IFQ_LOCK_ASSERT(ifq);

	if (!ALTQ_IS_ENABLED(ifq))
		/* cbq must have been detached */
		return;

	if ((cbqp = (cbq_state_t *)ifq->altq_disc) == NULL)
		/* should not happen */
		return;

	ifp = ifq->altq_ifp;
	if (ifp->if_start &&
	    cbqp->cbq_qlen > 0 && (ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0) {
	    	IFQ_UNLOCK(ifq);
		(*ifp->if_start)(ifp);
		IFQ_LOCK(ifq);
	}
}

static void cbq_purge(cbq_state_t *cbqp)
{
	struct rm_class	*cl;
	int		 i;

	for (i = 0; i < CBQ_MAX_CLASSES; i++)
		if ((cl = cbqp->cbq_class_tbl[i]) != NULL)
			rmc_dropall(cl);
	if (ALTQ_IS_ENABLED(cbqp->ifnp.ifq_))
		cbqp->ifnp.ifq_->ifq_len = 0;
}
#ifdef ALTQ3_COMPAT

static int
cbq_add_class(acp)
	struct cbq_add_class *acp;
{
	char		*ifacename;
	struct rm_class	*borrow, *parent;
	cbq_state_t	*cbqp;

	ifacename = acp->cbq_iface.cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	/* check parameters */
	if (acp->cbq_class.priority >= CBQ_MAXPRI ||
	    acp->cbq_class.maxq > CBQ_MAXQSIZE)
		return (EINVAL);

	/* Get pointers to parent and borrow classes.  */
	parent = clh_to_clp(cbqp, acp->cbq_class.parent_class_handle);
	borrow = clh_to_clp(cbqp, acp->cbq_class.borrow_class_handle);

	/*
	 * A class must borrow from it's parent or it can not
	 * borrow at all.  Hence, borrow can be null.
	 */
	if (parent == NULL && (acp->cbq_class.flags & CBQCLF_ROOTCLASS) == 0) {
		printf("cbq_add_class: no parent class!\n");
		return (EINVAL);
	}

	if ((borrow != parent)  && (borrow != NULL)) {
		printf("cbq_add_class: borrow class != parent\n");
		return (EINVAL);
	}

	return cbq_class_create(cbqp, acp, parent, borrow);
}

static int
cbq_delete_class(dcp)
	struct cbq_delete_class *dcp;
{
	char		*ifacename;
	struct rm_class	*cl;
	cbq_state_t	*cbqp;

	ifacename = dcp->cbq_iface.cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	if ((cl = clh_to_clp(cbqp, dcp->cbq_class_handle)) == NULL)
		return (EINVAL);

	/* if we are a parent class, then return an error. */
	if (is_a_parent_class(cl))
		return (EINVAL);

	/* if a filter has a reference to this class delete the filter */
	acc_discard_filters(&cbqp->cbq_classifier, cl, 0);

	return cbq_class_destroy(cbqp, cl);
}

static int
cbq_modify_class(acp)
	struct cbq_modify_class *acp;
{
	char		*ifacename;
	struct rm_class	*cl;
	cbq_state_t	*cbqp;

	ifacename = acp->cbq_iface.cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	/* Get pointer to this class */
	if ((cl = clh_to_clp(cbqp, acp->cbq_class_handle)) == NULL)
		return (EINVAL);

	if (rmc_modclass(cl, acp->cbq_class.nano_sec_per_byte,
			 acp->cbq_class.maxq, acp->cbq_class.maxidle,
			 acp->cbq_class.minidle, acp->cbq_class.offtime,
			 acp->cbq_class.pktsize) < 0)
		return (EINVAL);
	return (0);
}

/*
 * struct rm_class *
 * cbq_class_create(cbq_mod_state_t *cbqp, struct cbq_add_class *acp,
 *		struct rm_class *parent, struct rm_class *borrow)
 *
 * This function create a new traffic class in the CBQ class hierarchy of
 * given paramters.  The class that created is either the root, default,
 * or a new dynamic class.  If CBQ is not initilaized, the the root class
 * will be created.
 */
static int
cbq_class_create(cbqp, acp, parent, borrow)
	cbq_state_t *cbqp;
	struct cbq_add_class *acp;
	struct rm_class *parent, *borrow;
{
	struct rm_class	*cl;
	cbq_class_spec_t *spec = &acp->cbq_class;
	u_int32_t	chandle;
	int		i;

	/*
	 * allocate class handle
	 */
	for (i = 1; i < CBQ_MAX_CLASSES; i++)
		if (cbqp->cbq_class_tbl[i] == NULL)
			break;
	if (i == CBQ_MAX_CLASSES)
		return (EINVAL);
	chandle = i;	/* use the slot number as class handle */

	/*
	 * create a class.  if this is a root class, initialize the
	 * interface.
	 */
	if ((spec->flags & CBQCLF_CLASSMASK) == CBQCLF_ROOTCLASS) {
		rmc_init(cbqp->ifnp.ifq_, &cbqp->ifnp, spec->nano_sec_per_byte,
			 cbqrestart, spec->maxq, RM_MAXQUEUED,
			 spec->maxidle, spec->minidle, spec->offtime,
			 spec->flags);
		cl = cbqp->ifnp.root_;
	} else {
		cl = rmc_newclass(spec->priority,
				  &cbqp->ifnp, spec->nano_sec_per_byte,
				  rmc_delay_action, spec->maxq, parent, borrow,
				  spec->maxidle, spec->minidle, spec->offtime,
				  spec->pktsize, spec->flags);
	}
	if (cl == NULL)
		return (ENOMEM);

	/* return handle to user space. */
	acp->cbq_class_handle = chandle;

	cl->stats_.handle = chandle;
	cl->stats_.depth = cl->depth_;

	/* save the allocated class */
	cbqp->cbq_class_tbl[i] = cl;

	if ((spec->flags & CBQCLF_CLASSMASK) == CBQCLF_DEFCLASS)
		cbqp->ifnp.default_ = cl;
	if ((spec->flags & CBQCLF_CLASSMASK) == CBQCLF_CTLCLASS)
		cbqp->ifnp.ctl_ = cl;

	return (0);
}

static int
cbq_add_filter(afp)
	struct cbq_add_filter *afp;
{
	char		*ifacename;
	cbq_state_t	*cbqp;
	struct rm_class	*cl;

	ifacename = afp->cbq_iface.cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	/* Get the pointer to class. */
	if ((cl = clh_to_clp(cbqp, afp->cbq_class_handle)) == NULL)
		return (EINVAL);

	return acc_add_filter(&cbqp->cbq_classifier, &afp->cbq_filter,
			      cl, &afp->cbq_filter_handle);
}

static int
cbq_delete_filter(dfp)
	struct cbq_delete_filter *dfp;
{
	char		*ifacename;
	cbq_state_t	*cbqp;

	ifacename = dfp->cbq_iface.cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	return acc_delete_filter(&cbqp->cbq_classifier,
				 dfp->cbq_filter_handle);
}

/*
 * cbq_clear_hierarchy deletes all classes and their filters on the
 * given interface.
 */
static int
cbq_clear_hierarchy(ifacep)
	struct cbq_interface *ifacep;
{
	char		*ifacename;
	cbq_state_t	*cbqp;

	ifacename = ifacep->cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	return cbq_clear_interface(cbqp);
}

/*
 * static int
 * cbq_set_enable(struct cbq_enable *ep) - this function processed the
 *	ioctl request to enable class based queueing.  It searches the list
 *	of interfaces for the specified interface and then enables CBQ on
 *	that interface.
 *
 *	Returns:	0, for no error.
 *			EBADF, for specified inteface not found.
 */

static int
cbq_set_enable(ep, enable)
	struct cbq_interface *ep;
	int enable;
{
	int 	error = 0;
	cbq_state_t	*cbqp;
	char 	*ifacename;

	ifacename = ep->cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	switch (enable) {
	case ENABLE:
		if (cbqp->ifnp.root_ == NULL || cbqp->ifnp.default_ == NULL ||
		    cbqp->ifnp.ctl_ == NULL) {
			if (cbqp->ifnp.root_ == NULL)
				printf("No Root Class for %s\n", ifacename);
			if (cbqp->ifnp.default_ == NULL)
				printf("No Default Class for %s\n", ifacename);
			if (cbqp->ifnp.ctl_ == NULL)
				printf("No Control Class for %s\n", ifacename);
			error = EINVAL;
		} else if ((error = altq_enable(cbqp->ifnp.ifq_)) == 0) {
			cbqp->cbq_qlen = 0;
		}
		break;

	case DISABLE:
		error = altq_disable(cbqp->ifnp.ifq_);
		break;
	}
	return (error);
}

static int
cbq_getstats(gsp)
	struct cbq_getstats *gsp;
{
	char		*ifacename;
	int		i, n, nclasses;
	cbq_state_t	*cbqp;
	struct rm_class	*cl;
	class_stats_t	stats, *usp;
	int error = 0;

	ifacename = gsp->iface.cbq_ifacename;
	nclasses = gsp->nclasses;
	usp = gsp->stats;

	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);
	if (nclasses <= 0)
		return (EINVAL);

	for (n = 0, i = 0; n < nclasses && i < CBQ_MAX_CLASSES; n++, i++) {
		while ((cl = cbqp->cbq_class_tbl[i]) == NULL)
			if (++i >= CBQ_MAX_CLASSES)
				goto out;

		get_class_stats(&stats, cl);
		stats.handle = cl->stats_.handle;

		if ((error = copyout((caddr_t)&stats, (caddr_t)usp++,
		    sizeof(stats))) != 0)
			return (error);
	}

 out:
	gsp->nclasses = n;
	return (error);
}

static int
cbq_ifattach(ifacep)
	struct cbq_interface *ifacep;
{
	int		error = 0;
	char		*ifacename;
	cbq_state_t	*new_cbqp;
	struct ifnet 	*ifp;

	ifacename = ifacep->cbq_ifacename;
	if ((ifp = ifunit(ifacename)) == NULL)
		return (ENXIO);
	if (!ALTQ_IS_READY(&ifp->if_snd))
		return (ENXIO);

	/* allocate and initialize cbq_state_t */
	new_cbqp = malloc(sizeof(cbq_state_t), M_DEVBUF, M_WAITOK);
	if (new_cbqp == NULL)
		return (ENOMEM);
	bzero(new_cbqp, sizeof(cbq_state_t));
 	CALLOUT_INIT(&new_cbqp->cbq_callout);

	new_cbqp->cbq_qlen = 0;
	new_cbqp->ifnp.ifq_ = &ifp->if_snd;	    /* keep the ifq */

	/*
	 * set CBQ to this ifnet structure.
	 */
	error = altq_attach(&ifp->if_snd, ALTQT_CBQ, new_cbqp,
			    cbq_enqueue, cbq_dequeue, cbq_request,
			    &new_cbqp->cbq_classifier, acc_classify);
	if (error) {
		free(new_cbqp, M_DEVBUF);
		return (error);
	}

	/* prepend to the list of cbq_state_t's. */
	new_cbqp->cbq_next = cbq_list;
	cbq_list = new_cbqp;

	return (0);
}

static int
cbq_ifdetach(ifacep)
	struct cbq_interface *ifacep;
{
	char		*ifacename;
	cbq_state_t 	*cbqp;

	ifacename = ifacep->cbq_ifacename;
	if ((cbqp = altq_lookup(ifacename, ALTQT_CBQ)) == NULL)
		return (EBADF);

	(void)cbq_set_enable(ifacep, DISABLE);

	cbq_clear_interface(cbqp);

	/* remove CBQ from the ifnet structure. */
	(void)altq_detach(cbqp->ifnp.ifq_);

	/* remove from the list of cbq_state_t's. */
	if (cbq_list == cbqp)
		cbq_list = cbqp->cbq_next;
	else {
		cbq_state_t *cp;

		for (cp = cbq_list; cp != NULL; cp = cp->cbq_next)
			if (cp->cbq_next == cbqp) {
				cp->cbq_next = cbqp->cbq_next;
				break;
			}
		ASSERT(cp != NULL);
	}

	/* deallocate cbq_state_t */
	free(cbqp, M_DEVBUF);

	return (0);
}

/*
 * cbq device interface
 */

altqdev_decl(cbq);

int
cbqopen(dev, flag, fmt, p)
	dev_t dev;
	int flag, fmt;
#if (__FreeBSD_version > 500000)
	struct thread *p;
#else
	struct proc *p;
#endif
{
	return (0);
}

int
cbqclose(dev, flag, fmt, p)
	dev_t dev;
	int flag, fmt;
#if (__FreeBSD_version > 500000)
	struct thread *p;
#else
	struct proc *p;
#endif
{
	struct ifnet *ifp;
	struct cbq_interface iface;
	int err, error = 0;

	while (cbq_list) {
		ifp = cbq_list->ifnp.ifq_->altq_ifp;
		sprintf(iface.cbq_ifacename, "%s", ifp->if_xname);
		err = cbq_ifdetach(&iface);
		if (err != 0 && error == 0)
			error = err;
	}

	return (error);
}

int
cbqioctl(dev, cmd, addr, flag, p)
	dev_t dev;
	ioctlcmd_t cmd;
	caddr_t addr;
	int flag;
#if (__FreeBSD_version > 500000)
	struct thread *p;
#else
	struct proc *p;
#endif
{
	int	error = 0;

	/* check cmd for superuser only */
	switch (cmd) {
	case CBQ_GETSTATS:
		/* currently only command that an ordinary user can call */
		break;
	default:
#if (__FreeBSD_version > 700000)
		error = priv_check(p, PRIV_ALTQ_MANAGE);
#elsif (__FreeBSD_version > 400000)
		error = suser(p);
#else
		error = suser(p->p_ucred, &p->p_acflag);
#endif
		if (error)
			return (error);
		break;
	}

	switch (cmd) {

	case CBQ_ENABLE:
		error = cbq_set_enable((struct cbq_interface *)addr, ENABLE);
		break;

	case CBQ_DISABLE:
		error = cbq_set_enable((struct cbq_interface *)addr, DISABLE);
		break;

	case CBQ_ADD_FILTER:
		error = cbq_add_filter((struct cbq_add_filter *)addr);
		break;

	case CBQ_DEL_FILTER:
		error = cbq_delete_filter((struct cbq_delete_filter *)addr);
		break;

	case CBQ_ADD_CLASS:
		error = cbq_add_class((struct cbq_add_class *)addr);
		break;

	case CBQ_DEL_CLASS:
		error = cbq_delete_class((struct cbq_delete_class *)addr);
		break;

	case CBQ_MODIFY_CLASS:
		error = cbq_modify_class((struct cbq_modify_class *)addr);
		break;

	case CBQ_CLEAR_HIERARCHY:
		error = cbq_clear_hierarchy((struct cbq_interface *)addr);
		break;

	case CBQ_IF_ATTACH:
		error = cbq_ifattach((struct cbq_interface *)addr);
		break;

	case CBQ_IF_DETACH:
		error = cbq_ifdetach((struct cbq_interface *)addr);
		break;

	case CBQ_GETSTATS:
		error = cbq_getstats((struct cbq_getstats *)addr);
		break;

	default:
		error = EINVAL;
		break;
	}

	return error;
}

#if 0
/* for debug */
static void cbq_class_dump(int);

static void cbq_class_dump(i)
	int i;
{
	struct rm_class *cl;
	rm_class_stats_t *s;
	struct _class_queue_ *q;

	if (cbq_list == NULL) {
		printf("cbq_class_dump: no cbq_state found\n");
		return;
	}
	cl = cbq_list->cbq_class_tbl[i];

	printf("class %d cl=%p\n", i, cl);
	if (cl != NULL) {
		s = &cl->stats_;
		q = cl->q_;

		printf("pri=%d, depth=%d, maxrate=%d, allotment=%d\n",
		       cl->pri_, cl->depth_, cl->maxrate_, cl->allotment_);
		printf("w_allotment=%d, bytes_alloc=%d, avgidle=%d, maxidle=%d\n",
		       cl->w_allotment_, cl->bytes_alloc_, cl->avgidle_,
		       cl->maxidle_);
		printf("minidle=%d, offtime=%d, sleeping=%d, leaf=%d\n",
		       cl->minidle_, cl->offtime_, cl->sleeping_, cl->leaf_);
		printf("handle=%d, depth=%d, packets=%d, bytes=%d\n",
		       s->handle, s->depth,
		       (int)s->xmit_cnt.packets, (int)s->xmit_cnt.bytes);
		printf("over=%d\n, borrows=%d, drops=%d, overactions=%d, delays=%d\n",
		       s->over, s->borrows, (int)s->drop_cnt.packets,
		       s->overactions, s->delays);
		printf("tail=%p, head=%p, qlen=%d, qlim=%d, qthresh=%d,qtype=%d\n",
		       q->tail_, q->head_, q->qlen_, q->qlim_,
		       q->qthresh_, q->qtype_);
	}
}
#endif /* 0 */

#ifdef KLD_MODULE

static struct altqsw cbq_sw =
	{"cbq", cbqopen, cbqclose, cbqioctl};

ALTQ_MODULE(altq_cbq, ALTQT_CBQ, &cbq_sw);
MODULE_DEPEND(altq_cbq, altq_red, 1, 1, 1);
MODULE_DEPEND(altq_cbq, altq_rio, 1, 1, 1);

#endif /* KLD_MODULE */
#endif /* ALTQ3_COMPAT */

#endif /* ALTQ_CBQ */


text:
/**
 * Created by mihkelk on 16.02.2016.
 */

var foxApp = angular.module("fox", [
    'ngRoute',
    'ngSanitize',
    'swaggerUi',
    'pascalprecht.translate'
]);

foxApp.factory('requestInterceptor', function (FoxAlertService) {
    var defaultErrorHandler = function (response) {
        FoxAlertService.addError(response.statusText);
    };
    var defaultSuccessHandler = function (response) {
        FoxAlertService.clearInfos();
        return response;
    };
    return {
        request: defaultSuccessHandler,
        response: defaultSuccessHandler,
        responseError: defaultErrorHandler,
        requestError: defaultErrorHandler
    };
});

foxApp.config(function ($httpProvider) {
    $httpProvider.defaults.headers.common["Accept"] = "application/json";
    $httpProvider.defaults.headers.common["Content-Type"] = "application/json";
    $httpProvider.interceptors.push("requestInterceptor");
});

foxApp.constant("configConstant", {
    backendURL: 'http://localhost:9000/fox',
    loginURL: 'http://localhost:9000/login'
});

foxApp.config(function ($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/main.html',
            controller: 'RegisterController'
        })
        .when('/swagger', {
            templateUrl: 'views/swagger.html'
        })
        .when('/about', {
            templateUrl: 'views/about.html'
        })
        .otherwise({
            redirectTo: '/'
        });
});

foxApp.config(['$translateProvider', function ($translateProvider) {
    // add translation table
    var language = localStorage.language;
    if (!language) {
        language = 'en';
        localStorage.language = language;
    }

    $translateProvider.translations('en', translations_EN);
    $translateProvider.translations('et', translations_ET);
    $translateProvider.preferredLanguage(language);
}]);

foxApp.run(function ($rootScope, FoxAuthService) {
    $rootScope.isAuthenticated = FoxAuthService.isAuthenticated;
    $rootScope.getUser = FoxAuthService.getUser
});


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.schematic.annotation;

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

/**
 * Copyright (c) 2005 Brian Goetz and Tim Peierls.

 * Released under the Creative Commons Attribution License

 * (http://creativecommons.org/licenses/by/2.5)

 * Official home: http://www.jcip.net

 * Adopted from Java Concurrency in Practice.
 *

 * This annotation documents the class as being thread-safe. This means that no sequences of accesses (reads and writes to public
 * fields, calls to public methods) may put the object into an invalid state, regardless of the interleaving of those actions by
 * the runtime, and without requiring any additional synchronization or coordination on the part of the caller.
 *

 *
 * @see NotThreadSafe
 */
@Documented
@Target( ElementType.TYPE )
@Retention( RetentionPolicy.RUNTIME )
public @interface ThreadSafe {
}


text:
{% set page_title = 'Heart conditions' %}
{% set page_question = 'You don't need to tell DVLA about your ' %}

{% set go_next = '/condition/summary' %}

{% extends "layout.html" %}

{% block page_title %}{% if page_title %} {{ page_title | safe }} {% else %} {{ page_question | safe }} {% endif %}{% endblock %}

{% block head %}
    {% include "includes/head.html" %}
    {% include "includes/scripts.html" %}
{% endblock %}

{% block after_header %}
    {{ banner.input(noback='true') }}
{% endblock %}

{% block content %}

                {{ highlight({
                    "titleHtml": page_question
                }) }}

As you only drive a car or motorcycle, DVLA doesn't need to make any further medical enquiries.

What happens next?

In some some cases, you may need to take time off from driving.

Heart attack (myocardial infarction or acute coronary syndrome)

You should stop driving for at least 1 month.

Coronary artery bypass grafting

You should stop driving for at least 1 month.

Coronary angioplasty (percutaneous coronary intervention)

You should stop driving for at least 1 week.

Heart valve disease or replacement valve

You should stop driving for at least 1 month.

Angina

You may continue to drive if you have angina (even if you need medication) unless it happens while resting, driving, or with emotion. You must stop driving until your symptoms are under control.

                {% include "includes/warnings/time-off-driving.html" %}

                {% include "includes/text/if-your-condition-changes.html" %}

                {{ button({onclick: 'conditionSummaryNext()'}) }}

{% endblock %}

{% block body_end %}

{% endblock %}


text:
'use strict';

const funnel = require('broccoli-funnel');
const merge = require('broccoli-merge-trees');

const fontAwesome = funnel('node_modules/font-awesome', {
  include: [
    'fonts/fontawesome-webfont.eot',
    'fonts/fontawesome-webfont.svg',
    'fonts/fontawesome-webfont.ttf',
    'fonts/fontawesome-webfont.woff',
    'fonts/fontawesome-webfont.woff2',
    'fonts/FontAwesome.otf'
  ],
  destDir: 'assets'
});

module.exports = merge([
  fontAwesome
]);


text:
/* jshint evil: true */
'use strict';

var util = require('../util');

function renderPlaceholder(template, helpers, data, path) {

  var isBare = false;
  var result = template;
  var rHolder = /(?:.)?@([a-zA-Z_]\w*)(?:(\(.*\))(?!\)))?/g;

  template = template.replace(rHolder, function (input, methodName, argsString) {

    var isRaw = input[0] === '\\';
    var placeholder = '@' + methodName;

    argsString = argsString
      ? renderPlaceholder(argsString, helpers, data, path)
      : '';

    if (isRaw) {
      return placeholder + argsString;
    } else {

      var prefix = input.substr(0, input.indexOf(placeholder));
      var suffix = '';
      var args = argsString;

      // fix args
      if (argsString) {

        var matches = 1;

        for (var i = 1, l = argsString.length; i < l; i++) {

          var char = argsString[i];

          if (char === '(') {
            matches += 1;
          } else if (char === ')') {
            matches -= 1;
          }

          if (matches === 0) {
            args = argsString.substr(0, i + 1);
            suffix = argsString.substr(i + 1);
            break;
          }
        }

        if (matches !== 0) {
          return input + 'ERROR: [bad args]';
        }
      }

      var exeResult = exePlaceholder(input, methodName, args, helpers, data, path);

      // fully matched, template is barely a placeholder, so return the
      // data(data-type) of the placeholder function called.
      if (template === input && !prefix && !suffix) {
        isBare = true;
        result = exeResult;
      }

      return prefix + exeResult + suffix;
    }
  });

  return isBare
    ? result
    : template;
}

function exePlaceholder(template, methodName, argsString, helpers, data, path) {

  var ret = template;

  try {

    if (!argsString) {
      argsString = '()';
    }

    var fnBody = 'return ' + 'this.' + methodName + argsString + ';';
    var fn = new Function(fnBody);

    helpers.data = data;
    helpers.path = path;

    ret = fn.call(helpers);

    delete helpers.data;
    delete helpers.path;

  } catch (error) {
    ret += ' ERROR: [' + error + ']';
  }

  return ret;
}

function byCount(count, str, helpers, data, path) {

  var ret = '';

  count = Math.abs(count);

  if (str) {
    // repeat the template str by count
    while (count--) {
      ret += str;
    }
    ret = renderPlaceholder(ret, helpers, data, path);
  } else {
    // generate random str
    ret = count ? helpers.string(count) : str;
  }

  return ret;
}

function byRange(rule, str, helpers, data, path) {
  var range = util.isDRange(rule)
    ? util.getRange(rule, true)
    : util.getRange(rule, false);

  var count = helpers.int(range.min, range.max);

  return byCount(count, str, helpers, data, path);
}

exports.handle = function (rule, str, helpers, data, path) {

  return util.isBare(rule) ? byCount(1, str, helpers, data, path)
    : util.isCount(rule) ? byCount(rule.count, str, helpers, data, path)
    : util.isRang(rule) ? byRange(rule, str, helpers, data, path)
    : byCount(1, str, helpers, data, path);
};


text:
@interface RACOperatorIgnoreViewController ()

@property (strong, nonatomic) UITextField *textFieldOne;
@property (strong, nonatomic) UILabel *labelOne;

@end

@implementation RACOperatorIgnoreViewController

- (void)setupUI {

    self.textFieldOne = ({
        _textFieldOne = [UITextField new];
        [self.view addSubview:_textFieldOne];
        self.textFieldOne.backgroundColor = [UIColor whiteColor];
        self.textFieldOne.placeholder = @"Ignore char A";
        _textFieldOne;
    });

    self.labelOne = ({
        _labelOne = [UILabel new];
        [self.view addSubview:_labelOne];
        _labelOne.backgroundColor = [UIColor whiteColor];
        _labelOne.textColor = [UIColor blueColor];
        _labelOne.text = @"Ignore char A";
        _labelOne.textAlignment = NSTextAlignmentCenter;
        _labelOne.font = [UIFont systemFontOfSize:20];
        _labelOne;
    });

    [self.textFieldOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake([UIScreen hx_screenWidth] / 2.0, [UIScreen hx_screenHeight] / 10.0));
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).mas_offset([UIScreen hx_screenHeight] / 5.0);
    }];

    [self.labelOne mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake([UIScreen hx_screenWidth] / 2.0, [UIScreen hx_screenHeight] / 10.0));
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view.mas_top).mas_offset([UIScreen hx_screenHeight]  * 2 / 5.0);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor  = [UIColor hx_randomColor];
    [self setupUI];

    [self ignore];

}

- (void)ignore {
    //忽略完某些值的信号.
    //忽略A
    @weakify(self);
    [[[self.textFieldOne.rac_textSignal filter:^BOOL(id value) {
        return [value length] > 0;
    }] ignore:@"A"] subscribeNext:^(NSString *text) {
        @strongify(self);
        self.labelOne.text = text;
    }];

}

@end


text: body{content:'yep'}


text:
package com.sdl.ecommerce.hybris;

import com.sdl.ecommerce.api.ECommerceLinkResolver;
import com.sdl.ecommerce.api.ProductDetailResult;
import com.sdl.ecommerce.api.model.*;
import com.sdl.ecommerce.api.model.impl.GenericBreadcrumb;
import com.sdl.ecommerce.hybris.model.HybrisBreadcrumb;

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

/**
 * Hybris Detail Result
 *
 * @author nic
 */
public class HybrisDetailResult implements ProductDetailResult {

    private Product productDetail;

    public HybrisDetailResult(Product productDetail) {
        this.productDetail = productDetail;
    }

    @Override
    public List<Breadcrumb> getBreadcrumbs() {

        // TODO: This code is identical with the one in the Fredhopper version.
        // -> Do a common base class using default implementation of the interfaces
        List<Breadcrumb> breadcrumbs = new ArrayList<>();
        if ( this.productDetail.getCategories() != null ) {
            for ( Category category : this.productDetail.getCategories() ) {
                breadcrumbs.add(0, new GenericBreadcrumb(category.getName(), new CategoryRef(category)));
            }
        }
        return breadcrumbs;
    }

    @Override
    public Product getProductDetail() {
        return this.productDetail;
    }

    @Override
    public List<Promotion> getPromotions() {
        return new ArrayList<>();
    }
}


text:
import OperisUsersRoute from "ember-app/routes/operis-users";

var UsersRoute = OperisUsersRoute.extend({});

export default UsersRoute;


text:
export interface RangeSliderTooltipFormatter {
  to: (value: number) => string;
  from: (value: string) => number;
}

export type RangeSliderTooltip = boolean | RangeSliderTooltipFormatter;


text: __all__ = [ "frontend", "common", "error", "properties", "crawl" ]


text:
package org.docksidestage.remote.maihama.showbase.member.purchase.list;

import javax.validation.constraints.NotNull;

import org.lastaflute.core.util.Lato;
import org.lastaflute.web.validation.Required;

/**
 * The bean class as return for remote API of GET /member/purchase/list/{memberId}/{pageNumber}.
 * @author FreeGen
 */
public class RemoteMemberPurchaseListReturn extends org.docksidestage.bizfw.remoteapi.AbstractListGetReturn {

    /** The property of pageSize. (row count per one page) */
    @Required
    public Integer pageSize;

    /** The property of currentPageNumber. (number of current page) */
    @Required
    public Integer currentPageNumber;

    /** The property of allRecordCount. (count of all records) */
    @Required
    public Integer allRecordCount;

    /** The property of allPageCount. (count of all pages) */
    @Required
    public Integer allPageCount;

    /** The property of rows. (paging data for current page) */
    @NotNull
    @javax.validation.Valid
    public org.eclipse.collections.api.list.ImmutableList<MemberPurchaseSearchRowPart> rows;

    /**
     * The part class of MemberPurchaseSearchRowPart.
     * @author FreeGen
     */
    public static class MemberPurchaseSearchRowPart {

        /** The property of purchaseId. */
        @Required
        public Long purchaseId;

        /** The property of purchaseDatetime. */
        @Required
        public java.time.LocalDateTime purchaseDatetime;

        /** The property of productName. */
        @Required
        public String productName;

        /** The property of purchasePrice. */
        @Required
        public Integer purchasePrice;

        /** The property of purchaseCount. */
        @Required
        public Integer purchaseCount;

        /** The property of paymentComplete. */
        @Required
        public Boolean paymentComplete;
    }

    @Override
    public String toString() {
        return Lato.string(this);
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<widget id="TreeView.widget.TreeView" needsEntityContext="true" xmlns="http://www.mendix.com/widget/1.0/">
  <name>Tree View</name>
  <description>Advanced treegrid to browse and manipulate refences and referencesets</description>

  <icon>iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ
bWFnZVJlYWR5ccllPAAAAdVJREFUeNpi/P//PwMlgImBQsCS0vZGk5GRcTmQrQ/EF4EuigTi658v
ZsMV8epPZQCqwaqO6fv378t1lZj0Yz24GUA0iP/1Tj+KLSA+NnU/fvxgYPn8+ZO+pjwfw8+fPxk0
5ZkY9hz/pM/+5XYasgF/v9xm+IZFHTgMPn36cPHg6ecMINNANIj/k1Fq1p8/f2aBxEA0iI9NHRAz
MBqH7tD89+8f3G9MTEyRQL9e533dAbIA5JJZn0UrGID+xaqOBSh4/e/fvwYoIfv5IMOXL1/gfEbW
fQx/ee0x1DEzMzOwYIuaz482ovD/MX1n+Pv/N9AVfxGGMv4D4r+Y6eDL441A/31Cwf/4XaHRyHwB
iP9DaEZNsGtBxMsby4F4GdgAVlZWBi4uLriBv3//Zvh6qZFByrhzub+rnL6nnQzD9kNP9DfufgQK
DwNGrMmTiYmBhQVsti8w8CRBDB2/4zM7S1Tgasp77oB9gjUMgAHL8OvXL5CzNwMxWIyDgz/rwKkv
+hZ6LAwnLv0B8S9e3RPNwIykjxHqJTYgBvmBB4gFgC4QBmKxr28vXPjFHWhw8gqL2KNnv69e3Rtf
/vHF8feMaAYwQjMYMxbMhIRB6n6DUjkjpdkZIMAAECYEN0fYAvMAAAAASUVORK5CYII=</icon>

  <properties>
		<property key="blaat4" type="object" isList="true" required="true">

1) Entities

			<category>1) Tree configuration</category>
			<description>Define all the types of objects that are displayed in the treeview here. The object type of the context is required here is as well!</description>
			<properties>
				<property key="xentity" type="entity" required="true">

Entity type

					<category>1) Common</category>
					<description></description>
				</property>
				<property key="sortattr" type="attribute" entityProperty="xentity" required="true">

Sort attribute

					<category>1) Common</category>
					<description>Attribute to sort this type of objects on. If DnD is used, this should be a float.</description>
					<attributeTypes>
						<attributeType name="AutoNumber"/>
						<attributeType name="Boolean"/>
						<attributeType name="Decimal"/>
						<attributeType name="DateTime"/>
						<attributeType name="Enum"/>
						<attributeType name="Float"/>
						<attributeType name="Integer"/>
						<attributeType name="Long"/>
						<attributeType name="String"/>
					</attributeTypes>
				</property>
				<property key="sortdir" type="enumeration" defaultValue="asc">

Sort direction

					<category>1) Common</category>
					<description/>
					<enumerationValues>
						<enumerationValue key="asc">Ascending</enumerationValue>
						<enumerationValue key="desc">Descending</enumerationValue>
					</enumerationValues>
				</property>
				<property key="xburstattr" type="attribute" entityProperty="xentity" required="false">

Cache bust attribute

					<category>2) Advanced</category>
					<description>Depending on the value of this property, the children of an item will be reloaded. If this property is omitted, the widget tries to automatically discover which items need to be refreshed, but new objects with a from child assocation cannot be detected automatically.

					 !Important note!: If a cache bust attribute is set, this attribute needs to be update to show new children on assiations which are owned by children and use an xpath constraint. This way it can be assured that items do not slip past constraints by changing them.

					 Furthermore, the cache bust is used as hint when to expand items. If the cache bust of an item changes after invoking a microflow, it is assumed that there are new children to display. The item is expanded and the newest child will be selected.
					</description>
					<attributeTypes>
			            <attributeType name="DateTime"/>
						<attributeType name="Float"/>
						<attributeType name="Integer"/>
						<attributeType name="Decimal"/>
						<attributeType name="Long"/>
						<attributeType name="String"/>
					</attributeTypes>
				</property>
				<property key="entityclazz" type="string" defaultValue="" required="false">

Class

					<category>2) Advanced</category>
					<description></description>
				</property>
				<property key="entitystyle" type="string" multiline="true" defaultValue="" required="false">

Style

					<category>2) Advanced</category>
					<description>Define CSS properties here. Use newline or '|' to separate CSS properties (';') is not allowed!</description>
				</property>
				<property key="entitychannel" type="string" defaultValue="" required="false">

Formloader Channel

					<category>2) Advanced</category>
					<description>If provided, all formloaders listening to this channel will follow the current selection</description>
				</property>

			</properties>
		</property>

  		<property key="blaat" type="object" isList="true" required="true">

2) Relations

  			<category>1) Tree configuration</category>
  			<description>
<![CDATA[You can define the relations that are shown in the tree here. Relations are defined per relation per direction. The root object of the tree is always the context object.

Example: Domain model: Orderline *---orderline_order-->1 Order

Configuration to show all orderlines within an order (which is the context object):

Association owner: 'Orderline'
Association (reference): 'orderline_order'
Association direction: 'The association owner is the child'

It is allowed to add an additional relation, with association direction 'The association owner is the parent', to be able to expand from the orderline back to the order (which might make sense if an orderline would be related to multiple orders).
]]>
  			</description>
  			<properties>
				<property key="assoccaption" type="string" defaultValue="" required="true">

Name / caption

					<category>1) Define the relation</category>
					<description>Describe this relation</description>
				</property>
				<property key="entity" type="entity" required="true">

Association owner

					<category>1) Define the relation</category>
					<description></description>
				</property>
				<property key="parentassocsingle" type="entity" entityProperty="entity" isPath="optional" pathType="reference" required="false">

Association (reference)

					<category>1) Define the relation</category>
					<description>The association from owner entity type to the other entity</description>
				</property>
				<property key="parentassocmulti" type="entity" entityProperty="entity" isPath="optional" pathType="referenceSet" required="false">

Association (referenceSet)

					<category>1) Define the relation</category>
					<description>The association from owner entity type to the other entity</description>
				</property>
				<property key="assoctype" type="enumeration" defaultValue="fromchild">

Association direction

					<category>1) Define the relation</category>
					<description>
						This property describes whether the selected defines whether this association is from
						parent <-- child (default)
						or
						child --> parent
					</description>
					<enumerationValues>
						<enumerationValue key="fromchild">The association owner is the child</enumerationValue>
						<enumerationValue key="fromparent">The association owner is the parent</enumerationValue>
					</enumerationValues>
				</property>
				<property key="constraint" type="entityConstraint" entityProperty="entity"  required="false">

Constraint

					<category>1) Define the relation</category>
					<description>Optional constraint on the relation. Note that using constraints might introduce the need to use the burst attribute, as the treeview cannot predict reliable anymore in which parents should be updated if the parent association changes.</description>
				</property>
				<property key="showassocname" type="boolean" defaultValue="true">

Show relation name

					<category>2) Set additional options</category>
					<description>Show the name of the relation as a separate node, and group children in it. The style properties will affect this node if true.</description>
				</property>
				<property key="assocclazz" type="string" defaultValue="" required="false">

Class

					<category>2) Set additional options</category>
					<description></description>
				</property>
				<property key="assocstyle" type="string" multiline="true" defaultValue="" required="false">

Style

					<category>2) Set additional options</category>
					<description>Define CSS properties here. Use newline or '|' to separate CSS properties (';') is not allowed!</description>
				</property>
				<property key="allowdnd" type="boolean" defaultValue="false">

Allow drops

					<category>3) Drag and drop options</category>
					<description>Allow items to be dropped in this association</description>
				</property>
				<property key="allowdndcopy" type="boolean" defaultValue="false">

Allow drop copies

					<category>3) Drag and drop options</category>
					<description>Allow items to be dropped as a copy in this association (not supported for single references where fromparent is false)</description>
				</property>
				<property key="dropmf" type="microflow" required="false" entityProperty="entity">

On drop microflow

                    <category>3) Drag and drop options</category>
                    <description>
                    	This microflow is triggered if a drag and drop action of the user results in a change for this relation (for both add and remove (if referenceset)). The microflow is always invoked on the owner of the association. So if the association owner is the child (default) the microflow will be triggered for the item being dropped, but if the association owner is the parent, the microflow will be triggered on the item being dropped *ON* and the item being dropped *FROM* (if referenceset).
                    </description>
					<returnType type="Void"/>
				</property>
			</properties>
		</property>

		<property key="blaat2" type="object" isList="true" required="true">

3) Rendering

			<category>1) Tree configuration</category>
			<description></description>
			<properties>
				<property key="columnname" type="string" defaultValue="" required="false">

Caption

					<category>1) Basics</category>
					<description></description>
				</property>
				<property key="columnentity" type="entity" required="false">

Applies to type

					<category>1) Basics</category>
					<description></description>
				</property>

				<property key="columnrendermode" type="enumeration" defaultValue="attribute">

Display mode

					<category>1) Basics</category>
					<description></description>
					<enumerationValues>
						<enumerationValue key="attribute">Display attribute value</enumerationValue>
						<enumerationValue key="caption">Display caption</enumerationValue>
						<enumerationValue key="attributehtml">Display attribute as HTML</enumerationValue>
						<enumerationValue key="attributeimage">Display attribute as image</enumerationValue>
						<enumerationValue key="thumbnail">Display current object or referenced FileID attribute as thumbnail</enumerationValue>
						<enumerationValue key="systemimage">Display current object or referenced FileID attribute as image</enumerationValue>
					</enumerationValues>
				</property>

				<property key="columnattr" type="attribute" entityProperty="columnentity" required="false" isPath="optional" pathType="reference">

Attribute

					<category>1) Basics</category>
					<description>Attribute to display
					</description>
					<attributeTypes>
						<attributeType name="AutoNumber"/>
						<attributeType name="Boolean"/>
						<attributeType name="Decimal"/>
						<attributeType name="DateTime"/>
						<attributeType name="Enum"/>
						<attributeType name="Float"/>
						<attributeType name="Integer"/>
						<attributeType name="Long"/>
						<attributeType name="String"/>
					</attributeTypes>
				</property>
				<property key="columnimage" type="image" required="false">

(Default) Image

                    <category>1) Basics</category>
                    <description></description>
                </property>
                <property key="columnaction" type="string" defaultValue="" required="false">

On click action

					<category>3) Interaction</category>
					<description>The name of the action that should be invoked when this item is clicked. The name should refer to the name of an action as defined in step 4) Actions</description>
				</property>

				<property key="columnclazz" type="string" defaultValue="" required="false">

Class

					<category>2) Advanced</category>
					<description>The following classes are available by default: 'link', 'newline' (starts a newline before this value), 'right' (right align) 'separator', 'large' and 'small'</description>
				</property>
				<property key="columnstyle" type="string" multiline="true" defaultValue="" required="false">

Style

					<category>2) Advanced</category>
					<description>Define CSS properties here. Use newline or '|' to separate CSS properties (';') is not allowed!</description>
				</property>
				<property key="columndateformat" type="string" defaultValue="EEE dd MMM y" required="false">

Column date time format

					<category>2) Advanced</category>
					<description>The formatting of the date if a datetime attribute is displayed.</description>
				</property>

				<property key="columnprefix" type="string" required="false">

Prefix rendering

					<category>2) Advanced</category>
					<description></description>
				</property>
				<property key="columnpostfix" type="string" required="false">

Postfix rendering

					<category>2) Advanced</category>
					<description></description>
				</property>

				<property key="columntruecaption" type="translatableString" required="false">

'True' caption

					<category>3) Boolean rendering</category>
					<description></description>
				</property>
				<property key="columnfalsecaption" type="translatableString" required="false">

'False' caption

					<category>3) Boolean rendering</category>
					<description></description>
				</property>

			</properties>
		</property>

		<property key="blaat3" type="object" isList="true" required="false">

4) Actions

			<category>1) Tree configuration</category>
			<description></description>
			<properties>
				<property key="actname" type="string" defaultValue="" required="true">

Action name

					<category>1) Basics</category>
					<description>The name of this action, as can be refered to in step 3).</description>
				</property>
				<property key="actentity" type="entity" required="false">

Applies to type (or all)

					<category>1) Basics</category>
					<description></description>
				</property>
				<property key="actshowbutton" type="boolean" defaultValue="false">

Show as button in header

					<category>2) Button</category>
					<description></description>
				</property>
				<property key="actbuttoncaption" type="translatableString" required="false">

Button caption

					<category>2) Button</category>
					<description></description>
				</property>
				<property key="actbuttonimage" type="image" required="false">

Button image

					<category>2) Button</category>
					<description></description>
				</property>
				<property key="actautohide" type="boolean" defaultValue="true">

Hide if disabled

					<category>2) Button</category>
					<description>Whether to hide, or only disable the button when it can't be pressed.</description>
				</property>
				<property key="actmf" type="microflow" required="false" entityProperty="actentity">

Microflow

                    <category>1) Basics</category>
                    <description></description>
					<returnType type="Void"/>
				</property>
				<property key="actnoselectionmf" type="microflow" required="false">

Microflow (no selection)

                    <category>1) Basics</category>
                    <description></description>
					<returnType type="Void"/>
				</property>
				<property key="actisdefault" type="boolean" defaultValue="false">

Is default action

					<category>1) Basics</category>
					<description>If true, this action will be used as default action and be invoked if the item is doubleclicked or the return key is pressed.
					</description>
				</property>
				<property key="actconfirmtext" type="translatableString" required="false">

Confirmation message

					<category>1) Basics</category>
					<description>If set, users have to confirm this message before continuing</description>
				</property>
				<property key="actprogressmsg" type="translatableString" required="false">

Progress message

					<category>1) Basics</category>
					<description>If set, a progress bar will be shown when running this action</description>
				</property>

				<property key="actonselect" type="boolean" defaultValue="false">

Fire on selection change

					<category>2) Settings</category>
					<description>Invoke this action immediately when the current selection changes. For more information about retrieving the current selection, see the 'fine tuning > Selection reference' properties
					</description>
				</property>
            </properties>
		</property>

		<property key="blaat5" type="object" isList="true" required="false">

5) Selection References

			<category>1) Tree configuration</category>
			<description>Define all the necessary selection references here. </description>
			<properties>
				<property key="selectionref" type="entity" isPath="yes" pathType="reference" required="false">

Selection reference

					<category>Basics</category>
					<description>This reference is updated as soon as the selection changes. This is useful to determine the current selection if action that fires on selection changes is used (see actions). For that action, set a microflow for the context action. The value of the reference selected here will be updated before that action fires.</description>
				</property>
			</properties>
		</property>

		<property key="hiderootnode" type="boolean" defaultValue="false">

Hide root node

			<category>2) Settings</category>
			<description>If false, the root node is displayed. If true, the root node hidden and only its children are displayed </description>
		</property>
		<property key="expandmode" type="enumeration" defaultValue="arrow">

Expand mode

			<category>2) Settings</category>
			<description>
				How should the tree expand?
				Click Arrow : Expand items when an arrow is clicked
				Click Row : Expand items if a row is clicked somewhere
				Accordion: Expand items if a row is clicked somewhere, but collapse all other, not descendant items.
			</description>
			<enumerationValues>
				<enumerationValue key="arrow">When an arrow is clicked</enumerationValue>
				<enumerationValue key="row">When a row is clicked</enumerationValue>
				<enumerationValue key="accordion">Use accordion mode</enumerationValue>
			</enumerationValues>
		</property>
		<property key="expandall" type="integer" defaultValue="1">

Auto expand depth

			<category>2) Settings</category>
			<description>If true all items up to the selected depth will be expanded automatically. A higher number will increase the initial load time.</description>
		</property>
		<property key="prefetch" type="boolean" defaultValue="true">

Prefetch data

			<category>2) Settings</category>
			<description>If true, items at deeper levels of the tree will be prefetched. This improves the user experience, but requires more resources. Should be turned of for very large datasets. </description>
		</property>

  </properties>
</widget>


text:
'use strict';

// MODULES //

var mustache = require( 'mustache' );
var validate = require( './validate.js' );

// TEMPLATES //

var URL = 'https://travis-ci.org/{{owner}}/{{repo}}';
var IMAGE = 'https://img.shields.io/travis/{{owner}}/{{repo}}/{{branch}}.{{format}}?style={{style}}';

mustache.parse( URL );
mustache.parse( IMAGE );

// URLS //

/**
* FUNCTION: urls( options )
*	Creates Shields.io badge URLs.
*
* @param {Object} options - function options
* @param {String} options.owner - repository owner
* @param {String} options.repo - repository name
* @param {String} [options.branch="master"] - repository branch
* @param {String} [options.style="flat"] - badge style
* @param {String} [options.format="svg"] - badge format
* @returns {Object}
*/
function urls( options ) {
	var opts;
	var out;
	var err;

	opts = {};
	err = validate( opts, options );
	if ( err ) {
		throw err;
	}
	opts.branch = opts.branch || 'master';
	opts.style = opts.style || 'flat';
	opts.format = opts.format || 'svg';

	out = {};
	out.image = mustache.render( IMAGE, opts );
	out.url = mustache.render( URL, opts );

	return out;
} // end FUNCTION urls()

// EXPORTS //

module.exports = urls;


text:
To initiate discovery of network nodes:

1. Power on the nodes. They will PXE boot from the Crowbar admin node.
2. Verify nodes statuses in the Crow UI by navigating to *Nodes > Dashboard*, and then ensuring that all nodes' icons are blinking yellow. This indicates that the nodes are ready to be allocated, and utilized in an OpenStack or a Hadoop cluster.

>**Note:** This can take some time; please be patient.


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "Appender.h"

void WLog_Appender_Free(wLog* log, wLogAppender* appender)
{
	if (!appender)
		return;

	if (appender->Layout)
	{
		WLog_Layout_Free(log, appender->Layout);
		appender->Layout = NULL;
	}

	DeleteCriticalSection(&appender->lock);
	appender->Free(appender);
}

wLogAppender* WLog_GetLogAppender(wLog* log)
{
	if (!log)
		return NULL;

	if (!log->Appender)
		return WLog_GetLogAppender(log->Parent);

	return log->Appender;
}

BOOL WLog_OpenAppender(wLog* log)
{
	int status = 0;
	wLogAppender* appender;

	appender = WLog_GetLogAppender(log);

	if (!appender)
		return FALSE;

	if (!appender->Open)
		return TRUE;

	if (!appender->active)
	{
		status = appender->Open(log, appender);
		appender->active = TRUE;
	}

	return status;
}

BOOL WLog_CloseAppender(wLog* log)
{
	int status = 0;
	wLogAppender* appender;

	appender = WLog_GetLogAppender(log);

	if (!appender)
		return FALSE;

	if (!appender->Close)
		return TRUE;

	if (appender->active)
	{
		status = appender->Close(log, appender);
		appender->active = FALSE;
	}

	return status;
}

static wLogAppender* WLog_Appender_New(wLog* log, DWORD logAppenderType)
{
	wLogAppender* appender;

	if (!log)
		return NULL;

	switch (logAppenderType)
	{
		case WLOG_APPENDER_CONSOLE:
			appender = WLog_ConsoleAppender_New(log);
			break;
		case WLOG_APPENDER_FILE:
			appender = WLog_FileAppender_New(log);
			break;
		case WLOG_APPENDER_BINARY:
			appender = WLog_BinaryAppender_New(log);
			break;
		case WLOG_APPENDER_CALLBACK:
			appender = WLog_CallbackAppender_New(log);
			break;
#ifdef HAVE_SYSLOG_H
		case WLOG_APPENDER_SYSLOG:
			appender = WLog_SyslogAppender_New(log);
			break;
#endif
#ifdef HAVE_JOURNALD_H
		case WLOG_APPENDER_JOURNALD:
			appender = WLog_JournaldAppender_New(log);
			break;
#endif
		case WLOG_APPENDER_UDP:
			appender = (wLogAppender*)WLog_UdpAppender_New(log);
			break;
		default:
			fprintf(stderr, "%s: unknown handler type %" PRIu32 "\n", __FUNCTION__,
			        logAppenderType);
			appender = NULL;
			break;
	}

	if (!appender)
		appender = (wLogAppender*)WLog_ConsoleAppender_New(log);

	if (!appender)
		return NULL;

	if (!(appender->Layout = WLog_Layout_New(log)))
	{
		WLog_Appender_Free(log, appender);
		return NULL;
	}

	InitializeCriticalSectionAndSpinCount(&appender->lock, 4000);

	return appender;
}

BOOL WLog_SetLogAppenderType(wLog* log, DWORD logAppenderType)
{
	if (!log)
		return FALSE;

	if (log->Appender)
	{
		WLog_Appender_Free(log, log->Appender);
		log->Appender = NULL;
	}

	log->Appender = WLog_Appender_New(log, logAppenderType);
	return log->Appender != NULL;
}

BOOL WLog_ConfigureAppender(wLogAppender* appender, const char* setting, void* value)
{
	/* Just check the settings string is not empty */
	if (!appender || !setting || (strnlen(setting, 2) == 0))
		return FALSE;

	if (appender->Set)
		return appender->Set(appender, setting, value);
	else
		return FALSE;
}


text:
layout: post
title: Farewell ABC
---

I'm sad to write that this is my last day at ABC.  I started in ABC only last year and while it was only a short time I will look at my time at Aunty fondly.

I will miss the drive and energy of my team.  They've been firing on all cylinders and running lean from the get go.  Continuous deployments, regular sprints and a drive to be the best in the market.

They also had a blockbuster year at ABC shop, the new upgrades and strategies will pay off for years to come I hope.

Regular lunch outings with my lunch posse, while it put inches on my waistline it was great to have a regular group to chat to over spicy food.

Recently my team has been nominated for multiple 2 AIMIA awards and I'm certain that they're will be many more on the horizon.

Farewell ABC Commercial, I already miss you.


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using Sqloogle.Libs.NLog;
using Sqloogle.Libs.Rhino.Etl.Core.Exceptions;

namespace Sqloogle.Libs.Rhino.Etl.Core
{
    /// <summary>
    /// A base class that expose easily logging events
    /// </summary>
    public class WithLoggingMixin
    {
        private readonly Logger _log;
        readonly List<Exception> errors = new List<Exception>();

        /// <summary>
        /// Initializes a new instance of the <see cref="WithLoggingMixin"/> class.
        /// </summary>
        protected WithLoggingMixin()
        {
            _log = LogManager.GetCurrentClassLogger();
        }

        /// <summary>
        /// Logs an error message
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="format">The format.</param>
        /// <param name="args">The args.</param>
        protected void Error(Exception exception, string format, params object[] args)
        {
            string message = string.Format(CultureInfo.InvariantCulture, format, args);
            string errorMessage;
            if(exception!=null)
                errorMessage = string.Format("{0}: {1}", message, exception.Message);
            else
                errorMessage = message.ToString();
            errors.Add(new RhinoEtlException(errorMessage, exception));
            if (_log.IsErrorEnabled)
            {
                _log.Error(message, exception);
            }
        }

        /// <summary>
        /// Logs a warn message
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="args">The args.</param>
        protected void Warn(string format, params object[] args)
        {
            if (_log.IsWarnEnabled)
            {
                _log.Warn(format, args);
            }
        }

        /// <summary>
        /// Logs a debug message
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="args">The args.</param>
        protected void Debug(string format, params object[] args)
        {
            if (_log.IsDebugEnabled)
            {
                _log.Debug(format, args);
            }
        }

        /// <summary>
        /// Logs a notice message
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="args">The args.</param>
        protected void Trace(string format, params object[] args)
        {
            if (_log.IsTraceEnabled)
            {
                _log.Trace(format, args);
            }
        }

        /// <summary>
        /// Logs an information message
        /// </summary>
        /// <param name="format">The format.</param>
        /// <param name="args">The args.</param>
        protected void Info(string format, params object[] args)
        {
            if (_log.IsInfoEnabled)
            {
                _log.Info(format, args);
            }
        }

        /// <summary>
        /// Gets all the errors
        /// </summary>
        /// <value>The errors.</value>
        public Exception[] Errors
        {
            get { return errors.ToArray(); }
        }
    }
}


text:
package com.zipzap;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;

import com.zipzap.adapter.FragmentAdapter;
import com.zipzap.fragment.BackupFragment;

public class BackupActivity extends AppCompatActivity {

	public static BackupFragment frag_backup;

	private ViewPager viewPager;
	private ActionBar actionBar;
	private Toolbar toolbar;

	private SearchView search;
	private FloatingActionButton fab;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	private void onCreateProcess() {
		actionBar   = getSupportActionBar();
		viewPager   = (ViewPager) findViewById(R.id.viewpager);
		fab         = (FloatingActionButton) findViewById(R.id.fab);
		if (viewPager != null) {
			setupViewPager(viewPager);
		}

		initToolbar();

		fab.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				frag_backup.refresh(true);
			}
		});

		TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
		tabLayout.setupWithViewPager(viewPager);
		tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
			@Override
			public void onTabSelected(TabLayout.Tab tab) {

				viewPager.setCurrentItem(tab.getPosition());
				// close contextual action mode
				if(frag_backup.getActionMode() !=  null){
					frag_backup.getActionMode().finish();
				}

				if (tab.getPosition() == 0) {
					fab.show();
				}
				search.onActionViewCollapsed();
				supportInvalidateOptionsMenu();
			}

			@Override
			public void onTabUnselected(TabLayout.Tab tab) {
			}

			@Override
			public void onTabReselected(TabLayout.Tab tab) {
			}

		});

	}

	private void initToolbar(){
		toolbar = (Toolbar) findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);
		actionBar = getSupportActionBar();
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(false);
	}

	private void setupViewPager(ViewPager viewPager) {
		FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());

		if (frag_backup == null) {
			frag_backup = new BackupFragment();
		}
		adapter.addFragment(frag_backup, getString(R.string.tab_title_backup));
		viewPager.setAdapter(adapter);
	}

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

}


text:
using starboard::android::shared::JniEnvExt;
using starboard::android::shared::ScopedLocalJavaRef;

float SbWindowGetDiagonalSizeInInches(SbWindow window) {
  if (!SbWindowIsValid(window)) {
    SB_DLOG(ERROR) << __FUNCTION__ << ": Invalid window.";
    return 0.0f;
  }

  int32_t width_pixels = ANativeWindow_getWidth(window->native_window);
  int32_t height_pixels = ANativeWindow_getHeight(window->native_window);
  JniEnvExt* env = JniEnvExt::Get();
  ScopedLocalJavaRef<jobject> display_dpi(env->CallStarboardObjectMethodOrAbort(
      "getDisplayDpi", "()Landroid/util/SizeF;"));
  float xdpi =
      env->CallFloatMethodOrAbort(display_dpi.Get(), "getWidth", "()F");
  float ydpi =
      env->CallFloatMethodOrAbort(display_dpi.Get(), "getHeight", "()F");

  if (xdpi < 0.1f || ydpi < 0.1f) {
    SB_DLOG(ERROR) << __FUNCTION__ << ": Invalid display values.";
    return 0.0f;
  }

  float width_inches = width_pixels / xdpi;
  float height_inches = height_pixels / ydpi;
  float diagonal_inches = sqrt(pow(width_inches, 2) + pow(height_inches, 2));
  return diagonal_inches;
}


text:
using System;
using System.Globalization;
using System.Xml.Linq;

namespace SolrNet.Impl.FieldParsers {
    /// <summary>
    /// Parses a field of type <see cref="Money"/>
    /// </summary>
    public class MoneyFieldParser : ISolrFieldParser {
        /// <inheritdoc />
        public bool CanHandleSolrType(string solrType) {
            return solrType == "str";
        }

        /// <inheritdoc />
        public bool CanHandleType(Type t) {
            return t == typeof(Money);
        }

        /// <summary>
        /// Parses a field of type <see cref="Money"/>
        /// </summary>
        public static Money Parse(string v) {
            if (string.IsNullOrEmpty(v))
                return null;
            var m = v.Split(',');
            var currency = m.Length == 1 ? null : m[1];
            return new Money(decimal.Parse(m[0], CultureInfo.InvariantCulture), currency);
        }

        /// <inheritdoc />
        public object Parse(XElement field, Type t) {
            return Parse(field.Value);
        }
    }
}


text:
<?php

namespace common\models;

use Yii;
use yii\caching\TagDependency;

/**
 * This is the model class for table "meta_tag".
 *
 * @property integer  $id
 * @property string   $entity
 * @property integer  $status
 * @property string   $title
 * @property string   $keyword
 * @property string   $description
 *
 * @property Category $category
 * @property Post     $post
 * @property Note     $note
 */
class MetaTag extends \yii\db\ActiveRecord
{
	const STATUS_IN_ACTIVE = 0;
	const STATUS_ACTIVE    = 1;

	const CACHE_KEY      = 'modelMetaKey_';
	const CACHE_DURATION = 0;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        $this->setDefaultValues();
    }

    /**
     * Set default values
     */
    protected function setDefaultValues()
    {
        $this->status = self::STATUS_ACTIVE;
    }

	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return 'meta_tag';
	}

	/**
	 * @inheritdoc
	 */
	public function rules()
	{
		return [
			[['status'], 'required'],
			[['status'], 'integer'],
            [['status'], 'default', 'value'=> self::STATUS_ACTIVE],
			['link', 'unique'],
			[['entity', 'title', 'keyword', 'description'], 'string', 'max' => 255],
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels()
	{
		return [
			'id'          => Yii::t('admin', 'ID'),
			'entity'      => Yii::t('admin', 'Entity'),
			'status'      => Yii::t('admin', 'Status'),
			'title'       => Yii::t('admin', 'Title'),
			'keyword'     => Yii::t('admin', 'Key'),
			'description' => Yii::t('admin', 'Description'),
		];
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getCategory()
	{
		return $this->hasOne(Category::className(), ['meta_tag_id' => 'id'])
			->where('entity = :entity', [':entity' => Category::className()]);
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getPost()
	{
		return $this->hasOne(Post::className(), ['meta_tag_id' => 'id'])
			->where('entity = :entity', [':entity' => Post::className()]);
	}

	/**
	 * @return \yii\db\ActiveQuery
	 */
	public function getNote()
	{
		return $this->hasOne(Note::className(), ['meta_tag_id' => 'id'])
			->where('entity = :entity', [':entity' => Note::className()]);
	}

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        self::clearCacheModel();
    }

	/**
	 * @return mixed|static[]
	 */
	public static function getAllActive()
	{
		$keyCache = self::CACHE_KEY . 'all';
		$data     = Yii::$app->cacheFrontend->get($keyCache);

		if (!$data) {
			$model = self::findAll(['status' => self::STATUS_ACTIVE]);

			if ($model) {
				/** @var Category $item */
				foreach ($model as $item) {
					$data[$item->getPrimaryKey()] = $item;
				}

				Yii::$app->cacheFrontend->set(
					$keyCache, $data, self::CACHE_DURATION,
					new TagDependency(['tags' => self::CACHE_KEY])
				);
			}
		}

		return $data ? $data : [];
	}

	/**
	 * @param $link
	 *
	 * @return null|MetaTag
	 */
	public static function getActiveByLink($link)
	{
		$keyCache = self::CACHE_KEY . $link;
		$data     = Yii::$app->cacheFrontend->get($keyCache);

		if (!$data) {
			$data = self::findOne([
				'status' => self::STATUS_ACTIVE,
				'link'   => $link,
			]);

			Yii::$app->cacheFrontend->set(
			    $keyCache, $data, self::CACHE_DURATION,
                new TagDependency(['tags' => self::CACHE_KEY])
            );
		}

		return $data;
	}

	/**
	 * @param null|string|integer $subKey
	 *
	 * delete all: $subKey = "all"
	 * delete default: $subKey = "default"
	 * delete one: $subKey = $model->getPrimaryKey
	 */
	public static function clearCacheModel($subKey = null)
	{
		if ($subKey) {
			$keyCache = self::CACHE_KEY . $subKey;

			Yii::$app->cacheFrontend->delete($keyCache);
		} else {
			TagDependency::invalidate(Yii::$app->cacheFrontend, self::CACHE_KEY);
		}
	}
}


text:
#import "DDSuperAPI.h"

@interface DDUserOnlineStateAPI : DDSuperAPI<DDAPIScheduleProtocol>

@end


text:
/**
 *
 */
package cl.ml.ceppi.core.dao;

import java.util.List;

import cl.ml.ceppi.core.model.cuota.Cuota;
import cl.ml.ceppi.core.model.cuota.RegistroCuota;
import cl.ml.ceppi.core.model.cuota.ValorCuota;

/**
 * @author Maldonado León
 *
 */
public interface CuotaDao
{
	void save(Cuota cuota);
	void save(ValorCuota valorCuota);
	void save(RegistroCuota registroCuota);

	void update(Cuota cuota);
	void update(ValorCuota valorCuota);
	void update(RegistroCuota registroCuota);

	void delete(Cuota cuota);
	void delete(ValorCuota valorCuota);
	void delete(RegistroCuota registroCuota);

	List<Cuota> listaCuotas();
	List<ValorCuota> listaValorCuotas();
	List<RegistroCuota> listaRegistroCuotas(int idsocio, int anio);

	Cuota findCuotaById(int id);
	ValorCuota findValorCuotaById(int id);
	RegistroCuota findRegistroCuotaById(int id);
	ValorCuota findValorCuota(ValorCuota obj);
	RegistroCuota findRegistroCuota(String anio, String mes, int idsocio);
}


text:
if (typeof define === 'function' && define.amd) {
	define(function() {
		return nextTick
	})
} else if (typeof module === 'object' && module.exports) {
	module.exports = nextTick
} else {
	root.subsequent = nextTick
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;

namespace Poker.Test
{
    [TestClass]
    public class IsValidHandTests
    {
        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void IsValidHandShouldThrowIfHandIsNull()
        {
            var checker = new PokerHandsChecker();
            IHand hand = null;
            checker.IsValidHand(hand);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void IsValidHandShouldThrowIfNotValidHandCardsCountLow()
        {
            var checker = new PokerHandsChecker();
            var hand = new Hand(new List<ICard>
                {
                    new Card(CardFace.Queen,CardSuit.Hearts),
                    new Card(CardFace.Jack,CardSuit.Hearts),
                    new Card(CardFace.King,CardSuit.Clubs),
                });

            checker.IsValidHand(hand);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void IsValidHandShouldThrowIfNotValidHandCardsCountHigh()
        {
            var checker = new PokerHandsChecker();
            var hand = new Hand(new List<ICard>
                {
                    new Card(CardFace.Queen,CardSuit.Hearts),
                    new Card(CardFace.Jack,CardSuit.Hearts),
                    new Card(CardFace.King,CardSuit.Clubs),
                    new Card(CardFace.Queen,CardSuit.Diamonds),
                    new Card(CardFace.Four,CardSuit.Hearts),
                    new Card(CardFace.Two,CardSuit.Clubs)
                });

            checker.IsValidHand(hand);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void IsValidHandShouldThrowIfDuplicateCard()
        {
            var checker = new PokerHandsChecker();
            var hand = new Hand(new List<ICard>
                {
                    new Card(CardFace.Queen,CardSuit.Hearts),
                    new Card(CardFace.Jack,CardSuit.Hearts),
                    new Card(CardFace.King,CardSuit.Clubs),
                    new Card(CardFace.Queen,CardSuit.Hearts),
                    new Card(CardFace.Four,CardSuit.Hearts),
                    new Card(CardFace.Two,CardSuit.Clubs)
                });

            checker.IsValidHand(hand);
        }

        [TestMethod]
        public void IsValidHandShouldNotThrowIfValidHand()
        {
            var checker = new PokerHandsChecker();
            var hand = new Hand(new List<ICard>
                {
                    new Card(CardFace.Queen,CardSuit.Hearts),
                    new Card(CardFace.Jack,CardSuit.Hearts),
                    new Card(CardFace.King,CardSuit.Clubs),
                    new Card(CardFace.Two,CardSuit.Spades),
                    new Card(CardFace.Six,CardSuit.Diamonds)
                });

            Assert.IsTrue(checker.IsValidHand(hand));
        }
    }
}