text:
"""
This module contains functions for plotting the results of evaluation experiments.
"""

import os

import matplotlib.pyplot as plt

def plot_config(base_dir, sub_dirs=[], prefix="", img_type="pdf"):
    """
    Configure where plots should be stored and which file type should be used.
    @param base_dir: The base dir where all plots should be stored, e.g. ../plots
    @param sub_dirs: A list of dirs that will be concatenated to create the actual plot dir,
    e.g. sub_dirs=["houseA","scatter"] and base_dir="../plots", the images will be stored in "../plots/houseA/scatter".
    @param prefix: A prefix to append to each plot file name.
    @param img_type: The file type to use for storing the plot image, must be supported by pyplot.
    @return: A function that can be called to get the full path for a plot file.
    """
    plot_dir = base_dir
    for sub_dir in sub_dirs:
        plot_dir = os.path.join(plot_dir, sub_dir)

    if not os.path.exists(plot_dir):
        os.makedirs(plot_dir)

    def full_plot_path(name):
        prefixed_name = "%s%s.%s" %(prefix, str(name), img_type)
        return os.path.join(plot_dir, prefixed_name)

    return full_plot_path

def plot_quality_comparison(results, metric, plot_path):
    """
    Create a lineplot, with one line for every evaluated classifier, showing the measured metric for this classifier.
    @param results: A pandas dataframe with one column for every classifier, containing measurements for the metric.
    @param metric: The metric to plot.
    @param plot_path: A function that can take a local file name and give back the full path to that file,
    @return: None
    """
    plt.figure(figsize=(6, 6), dpi=300)
    results.plot(marker=".", colormap="prism")
    if not metric == "# of recommendations":
        plt.ylim(0.0, 1.0)
    plt.xlim(1, plt.xlim()[1])
    plt.ylabel(metric, fontsize=18)
    plt.xlabel("Number of recommendations shown", fontsize=18)
    plt.legend(tuple(results.columns.values), loc=4)
    plt.savefig(plot_path(metric))
    plt.close()

def plot_train_size(results, metric, plot_path):
    """
    Create a lineplot, that shows how training size influences the given metric, with one line for every evaluated
    classifier.
    @param results: A pandas dataframe with one column for every classifier, containing measurements for the metric. The
    dataframe should have a multiIndex consisting of a tuple (size of training data, elapsed time).
    @param metric: The name of the metric that is to plot.
    @param plot_path:  A function that can take a local file name and give back the full path to that file.
    @return: None
    """
    #only want to have elapsed time as an index
    results.index = results.index.droplevel(0)

    plt.figure(figsize=(6, 6), dpi=300)
    plt.subplots_adjust(bottom=0.15)
    plt.ylabel(metric, fontsize=18)
    plt.xlabel('Elapsed training time (days)', fontsize=18)
    if not metric == "# of recommendations":
        plt.ylim(0.0, 1.0)
    plt.plot(results, marker=".")
    plt.legend(tuple(results.columns.values), loc=2)
    plt.savefig(plot_path(metric))
    plt.close()

def conflict_uncertainty_scatter(results, plot_path):
    """
    Create scatterplots of conflict vs uncertainty to be able to identify regions where the algorithm is more/less
    successful.
    @param results: A pandas dataframe with one column for each interesting cutoff. Each "1" in a column will be plotted
    as one cross in the scatterplot for this column, "0" values are ignored.
    @param plot_path: A function that can take a local file name and give back the full path to that file
    @return: None
    """

    #one scatterplot for each columnt
    for cutoff in results.columns:
        r = results[results[cutoff] == 1]
        conflict, uncertainty = zip(*r.index.tolist())
        plt.plot(conflict, uncertainty, 'x', color="#6dad22")
        plt.xticks([0.0, 0.5, 1.0], [0.0, 0.5, 1.0], fontsize=18)
        plt.yticks([0.5, 1.0], [0.5, 1.0], fontsize=18)
        plt.xlabel("conflict", fontsize=18)
        plt.ylabel("uncertainty", fontsize=18)
        plt.xlim(0, 1.0)
        plt.ylim(0, 1.0)
        f = plot_path(cutoff)
        plt.savefig(plot_path(cutoff))
        plt.close()

def comparison_histogram(results, plot_path):
    """
    Compare results (typically true positives) using a bar plot with one set of bars for every possible user action.
    The resulting plot allows to easier see for which actions an algorithm/algorithm setting is more successful.
    @param results: A pandas dataframe with one row for every user action and one column for every algorithm/setting to
    be compared.
    @param plot_path:
    @return:
    """

    results.plot(kind="bar", colormap="Greens")
    plt.subplots_adjust(bottom=0.4)
    plt.savefig(plot_path(""))

def plot_observations(source, observations, plot_path, plot_best=5):
    """
    Show which actions typically follow a given user action.
    @param source: The name of the last user action.
    @param observations: A pandas dataframe with one column for each following user action and one row for each bin
    used by the classifier. Each item in the matrix describes how often a user action has been observed in each bin.
    @param plot_path: function that can take a local file name and give back the full path to that file,
    @param plot_best: Only the plot-best number of actions with the most total number of observations in these bins will
    be shown in the resulting plot.
    @return:
    """
    #keep only actions with highest numbers of observations
    observations_per_action = observations.sum()
    observations_per_action.sort(ascending=False)
    most_observations = observations_per_action.index[0:plot_best]
    observations = observations[most_observations]

    #perform the plotting
    plt.figure()
    observations.plot(colormap="prism", marker=".")
    plt.xlabel("Time since setting changed [seconds]", fontsize=18)
    plt.ylabel("Observed actions (smoothed)", fontsize=18)
    plt.xlim(10, plt.xlim()[1])
    plt.savefig(plot_path(source))
    plt.close()


text:
package com.intellij.tasks.actions.context;

import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.command.undo.UndoableAction;
import com.intellij.openapi.command.undo.UnexpectedUndoException;
import com.intellij.openapi.project.Project;

/**
 * @author Dmitry Avdeev
 */
public class UndoableCommand {

  public static void execute(final Project project, final UndoableAction action, String name, String groupId) {
    CommandProcessor.getInstance().executeCommand(project, new Runnable() {
      public void run() {

        try {
          action.redo();
        }
        catch (UnexpectedUndoException e) {
          throw new RuntimeException(e);
        }
        UndoManager.getInstance(project).undoableActionPerformed(action);

      }
    }, name, groupId);

  }
}

redpajama_set_name: RedPajamaGithub


text:
class FactoryParams;

////////////////////////////////////////////////////////////////////
//       Class : RenderModeAttrib
// Description : Specifies how polygons are to be drawn.
////////////////////////////////////////////////////////////////////
class EXPCL_PANDA_PGRAPH RenderModeAttrib : public RenderAttrib {
PUBLISHED:
  enum Mode {
    M_unchanged,

    // Normal, filled polygons.
    M_filled,

    // Wireframe polygons, possibly with thickness.
    M_wireframe,

    // Points at vertices only, possibly with thickness and/or
    // perspective sizing.
    M_point,

    // Filled polygons, without any particular emphasis on perspective
    // correctness (a particularly useful designation for software
    // rendering sprites).
    M_filled_flat,

    // Filled polygons with wireframe rendered in front.
    // The wireframe is given a solid color.
    M_filled_wireframe
  };

private:
  INLINE RenderModeAttrib(Mode mode, PN_stdfloat thickness, bool perspective,
                          const LColor &wireframe_color = LColor::zero());

PUBLISHED:
  static CPT(RenderAttrib) make(Mode mode, PN_stdfloat thickness = 1.0f,
                                bool perspective = false,
                                const LColor &wireframe_color = LColor::zero());
  static CPT(RenderAttrib) make_default();

  INLINE Mode get_mode() const;
  INLINE PN_stdfloat get_thickness() const;
  INLINE bool get_perspective() const;
  INLINE const LColor &get_wireframe_color() const;

  INLINE int get_geom_rendering(int geom_rendering) const;

public:
  virtual void output(ostream &out) const;

protected:
  virtual int compare_to_impl(const RenderAttrib *other) const;
  virtual size_t get_hash_impl() const;
  virtual CPT(RenderAttrib) compose_impl(const RenderAttrib *other) const;

private:
  Mode _mode;
  PN_stdfloat _thickness;
  bool _perspective;
  LColor _wireframe_color;

PUBLISHED:
  static int get_class_slot() {
    return _attrib_slot;
  }
  virtual int get_slot() const {
    return get_class_slot();
  }

public:
  static void register_with_read_factory();
  virtual void write_datagram(BamWriter *manager, Datagram &dg);

protected:
  static TypedWritable *make_from_bam(const FactoryParams &params);
  void fillin(DatagramIterator &scan, BamReader *manager);

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    RenderAttrib::init_type();
    register_type(_type_handle, "RenderModeAttrib",
                  RenderAttrib::get_class_type());
    _attrib_slot = register_slot(_type_handle, 100, make_default);
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
  static int _attrib_slot;
};

#include "renderModeAttrib.I"

#endif


text:
package example;

import java.util.List;

import jp.ac.keio.sfc.ht.sox.protocol.*;
import jp.ac.keio.sfc.ht.sox.soxlib.*;
import jp.ac.keio.sfc.ht.sox.soxlib.event.SoxEvent;
import jp.ac.keio.sfc.ht.sox.soxlib.event.SoxEventListener;

public class Subscribe implements SoxEventListener {

	public static void main(String[] args) throws Exception {
		new Subscribe();
	}

	public Subscribe() throws Exception {

		//anonymous login
		SoxConnection con = new SoxConnection("sox.ht.sfc.keio.ac.jp","usera","takuro0928",true);

		//login with JID and password
		// SoxConnection con = new SoxConnection("sox.ht.sfc.keio.ac.jp",
		// "guest","miroguest", true);

		/** Create new device object from virtualized device **/
		SoxDevice exampleDevice = new SoxDevice(con, "whitelistTest");

		//you can specify another SOX server where the node exists
		// SoxDevice exampleDevice = new SoxDevice(con,
		// "testNode","takusox.ht.sfc.keio.ac.jp");

		/** Getting Device Meta Data **/
		Device deviceInfo = exampleDevice.getDevice();

		System.out.println("[Device Meta Info] ID:" + deviceInfo.getId()
				+ ", Name:" + deviceInfo.getName() + " Type:"
				+ deviceInfo.getDeviceType().toString());
		List<Transducer> transducerList = deviceInfo.getTransducers();
		for (Transducer t : transducerList) {
			System.out.println("[Transducer] Name:" + t.getName() + ", ID:"
					+ t.getId() + ", unit:" + t.getUnits() + ", minValue:"
					+ t.getMinValue() + ", maxValue:" + t.getMaxValue());
		}

		/**
		Data data = exampleDevice.getLastPublishData();
		List<TransducerValue> values = data.getTransducerValue();
		System.out.println("--last published data starts--");
		for (TransducerValue value : values) {
			System.out.println("TransducerValue[id:" + value.getId()
					+ ", rawValue:" + value.getRawValue() + ", typedValue:"
					+ value.getTypedValue() + ", timestamp:"
					+ value.getTimestamp() + "]");
		}
		System.out.println("--last published data ends --");
		**/

		exampleDevice.subscribe();
		exampleDevice.addSoxEventListener(this);

		/*
		 * If you close the program:
		 * exampleDevice.unsubscribe();
		 * exampleDevice.removeSoxEventListener();
		 * con.disconnect();
		 */
	}

	public void handlePublishedSoxEvent(SoxEvent e) {
		// TODO Auto-generated method stub

		System.out.println(":::::Received Data:::::");
		System.out.println("Message from: "+e.getOriginServer());
		List<TransducerValue> values = e.getTransducerValues();
		for (TransducerValue value : values) {
			System.out.println("TransducerValue[id:" + value.getId()
					+ ", rawValue:" + value.getRawValue() + ", typedValue:"
					+ value.getTypedValue() + ", timestamp:"
					+ value.getTimestamp() + "]");
		}

	}
}


text:
var sphereRadius = .2;
var spherePadding = .1;
var sphereGeometry;
function Grid(materials) {
	THREE.Object3D.call(this);
	sphereGeometry = sphereGeometry || new THREE.SphereGeometry(sphereRadius, 32, 32);
	var wrap = Math.ceil(Math.sqrt(materials.length));
	var spacing = sphereRadius * 2 + spherePadding;
	for (var i = 0; i < materials.length; i++) {
		var iX = i % wrap;
		var iY = ~~(i / wrap);
		var sphere = new THREE.Mesh(sphereGeometry, materials[i]);
		sphere.position.set(iX * spacing, iY * spacing, 0);
		this.add(sphere);
	};
};
Grid.prototype = Object.create(THREE.Object3D.prototype);

function Ring(materials) {
	THREE.Object3D.call(this);
	sphereGeometry = sphereGeometry || new THREE.SphereGeometry(sphereRadius, 32, 32);
	var ringCircumference = (materials.length * sphereRadius * 2 * 1.5);
	var ringRadius = ringCircumference / (2 * Math.PI);
	for (var i = 0, len = materials.length; i < len; i++) {
		var ratio = i / len * Math.PI * 2;
		var sphere = new THREE.Mesh(sphereGeometry, materials[i]);
		sphere.position.set(Math.cos(ratio) * ringRadius, .1, Math.sin(ratio) * ringRadius);
		this.add(sphere);
	};
}
Ring.prototype = Object.create(THREE.Object3D.prototype);

module.exports = {
	Grid : Grid,
	Ring : Ring
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Stack.PHP: Member List</title>

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

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

Stack.PHP

A simple and easy to use PHP library for the Stack Exchange API.

Main Page

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

API Member List

This is the complete list of members for API, including all inherited members.

$cache_ttl	API	 [static]

$debug	API	 [static]

$key	API	 [static]

$user_agent	API	 [static]

AssociatedUsers($ids)	API	 [static]

DeauthenticateApplication($access_token)	API	 [static]

EnableDebugMode($enable_debug=TRUE)	API	 [static]

Errors($error=null)	API	 [static]

GetAPIRequests()	API	 [static]

GetAPIVersion()	API	 [static]

GetJSON($url, $include_total=FALSE)	API	 [static]

GetRawData($url, $post_data=null)	API	 [static]

GetTotalRequests()	API	 [static]

GetVersion()	API	 [static]

Inbox($access_token)	API	 [static]

InvalidateAccessTokens($access_token)	API	 [static]

Me($access_token)	API

ReadAccessTokens($access_token)	API	 [static]

SetCache($cache_instance, $cleanup=TRUE)	API	 [static]

Site($site_domain)	API	 [static]

Sites()	API	 [static]

 All Classes Functions Variables

<address class="footer">
Generated on Thu Mar 8 2012 09:27:48 for Stack.PHP by

 1.7.5.1
</address>


text:
package com.dbp.trigger.repositories;

import com.dbp.trigger.models.IpCounts;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

/**
 * Created by Administrator on 2016/2/22.
 */
@Repository
public interface IpCountsRepository extends JpaRepository<IpCounts, Long> {

     @Query("select i from IpCounts i where i.ipid = ?1")
     IpCounts findByIpid(long ipid);
}


text:
HTMLWrapper and ElementWrapper
==============================

.. warning::
   All the methods documented here require the target document to include the JS libraries.

.. py:module:: pycommunicate.proxies.dom.html

.. py:class:: HTMLWrapper

   This class allows you to get :py:class:`~pycommunicate.proxies.dom.element.ElementWrapper` instances, and check for
   their existance.

   Every controller and view has one, and these are not created by the user.

   .. py:method:: exists(selector)

      Ask the browser whether an element matching the given selector exists.
      This method will block.

      :param str selector: The selector to check
      :return: Whether or not the target element exists
      :rtype: bool

      .. versionchanged:: 0.0.8
         Renamed to exists.

   .. py:method:: element(selector)

      First call :py:meth:`~HTMLWrapper.exists` and if it returns True return an :py:class:`~pycommunicate.proxies.dom.element.ElementWrapper`
      instance tracking the element defined by selector. Otherwise return None

      :param str selector: The selector for the element
      :return: An :py:class:`~pycommunicate.proxies.dom.element.ElementWrapper` instance tracking the given selector or None if none is found.
      :rtype: pycommunicate.proxies.dom.element.ElementWrapper

      .. versionchanged::
         Renamed to element.

.. py:module:: pycommunicate.proxies.dom.element

.. py:class:: ElementWrapper

   This class tracks an element by selector, and provides many utility functions and properties for it.

   These are created by :py:class:`~pycommunicate.proxies.dom.html.HTMLWrapper` and should not be created manually.

   .. py:method:: prop(name, value=None)

      Wrapper around :py:meth:`~ElementWrapper.get_property()` and :py:meth:`~ElementWrapper.set_property()`. This is
      part of the new chainable API.

      Calling this without value or with value set to None will result in getting the property and returning its value.
      Calling this with a value will set the property to value, and return the element. You can chain calls in this way.

      :param str name: The name of the property to get/set
      :param object name: The value to set to, if None do a get.

      .. versionadded:: 0.0.8

   .. py:method:: get_property(property_name)

      Get a python representation of JS property named ``property_name``.
      This method will block

      :param str property_name: The name of the JS property to get
      :return: The value of the property, coverted to python types where possible

   .. py:method:: set_property(property_name, value)

      Set the JS property named ``property_name`` to a JS representation of ``value``

      .. warning::

         The get methods block until the value is received, but the set methods do not block at all. This can
         cause some odd things, like this:

         .. code-block:: python

            >>> my_element.set_property('value', 5)
            >>> my_element.get_property('value')
            None
            >>> # ???

         There is currently no way to prevent this, but this may change in a future version.

      :param str property_name: The name of JS property to set
      :param object value: The value to set it to
      :return: None

   .. py:method:: add_event_listener(event_name, handler)

      Add an event handler for the given JS event. The names are in chrome/firefox format, not IE.
      Some examples of events are ``click``, ``focus``, and ``blur``.

      ``handler()`` takes no parameters.

      :param str event_name: The JS name of the event
      :param function handler: An event handler function

   .. py:method:: add_after(element_type)

      Add a new element of type ``element_type`` after this element, and return it.

      :param str element_type: The type of the element, e.g. ``p`` or ``div``
      :return: The new element
      :rtype: pycommunicate.proxies.dom.element.ElementWrapper

      .. versionchanged:: 0.0.8
         Renamed to add_after and removed id parameter.

   .. py:method:: add_child(element_type)

      Add a new element of type ``element_type`` as a child of this element, and return it.

      :param str element_type: The type of the element, e.g. ``p`` or ``div``
      :return: The new element
      :rtype: pycommunicate.proxies.dom.element.ElementWrapper

      .. versionchanged:: 0.0.8
         Renamed to add_child and removed id parameter.

   .. py:method:: add_before(element_type)

      Add a new element of type ``element_type`` before of this element, and return it.

      :param str element_type: The type of the element, e.g. ``p`` or ``div``
      :return: The new element
      :rtype: pycommunicate.proxies.dom.element.ElementWrapper

      .. versionadded:: 0.0.8

   .. py:method:: delete()

      Delete this element.

      .. warning::

         After calling :py:meth:`~ElementWrapper.delete`, the instance should no longer be used.

   The following are wrappers for properties. They are actually descriptors, so you can just use them.

   .. versionchanged:: 0.0.8
      Removed old ``get()`` and ``set()`` api

   .. py:attribute:: content

      Wrapper for ``innerText``

   The following are properties that have more than one value. These use the following syntax (using
   :py:attr:`~ElementWrapper.style` as an example)

   .. code-block:: python

      >>> my_element.style['marginTop']
      '123px'
      >>> my_element.style['marginTop'] = '456px'

   .. py:attribute:: style

      Wrapper for ``style``


text:
jaro = function(str1, str2){
  var lenStr1 = str1.length,
      lenStr2 = str2.length,
      matchWindow = Math.max(lenStr1, lenStr2)/2-1,
      transpositions=0,
      matches=0,
      letter='';

  // Test if swapping strX & lenStrX if stra is longer then str2 for proformance ??
  // another option is to bail out of the stepping once we are outside of the context of the other string
  // the issue is that with string lengths of 11 & 2 you wouldn't want to go through the loop 11 times

  /* find matches & transpositions */
  for (var i in str2) {
    letter = str2[i];
    if(str1.slice(i,i+matchWindow).indexOf(letter) > -1) { /* match */
      matches++;
    } else if(str1.slice(i-matchWindow,i).indexOf(letter) > -1) { /* transposition */
      matches++; transpositions++;
    }
  };
  return (1/3*(matches/lenStr1+matches/lenStr2+(matches-transpositions)/matches));
};

jaroWinkler = function(str1, str2, p){
  p = p || 0.1;
  var dj = jaro(str1,str2), l=0;

  for(var i=0; i<4; i++) { /* find length of prefix match (max 4) */
    if(str1[i]==str2[i]){ l++; } else { break; }
  }

  return dj+(l*p*(1-dj));
};

String.prototype.score = function(abbreviation) {
  return jaroWinkler(this.toLowerCase(),abbreviation.toLowerCase());
};

// console.log('martha '+'martha'.score('marhta'));
// console.log('martha '+jaroWinkler('martha','marhta'));
// console.log('dwayne '+jaroWinkler('DWAYNE','DUANE'));


text:
/**
 * `editor` type prompt
 */

var util = require('util');
var chalk = require('chalk');
var ExternalEditor = require('external-editor');
var Base = require('./base');
var observe = require('../utils/events');
var rx = require('rx');

/**
 * Module exports
 */

module.exports = Prompt;

/**
 * Constructor
 */

function Prompt() {
  return Base.apply(this, arguments);
}
util.inherits(Prompt, Base);

/**
 * Start the Inquiry session
 * @param  {Function} cb      Callback when prompt is done
 * @return {this}
 */

Prompt.prototype._run = function (cb) {
  this.done = cb;

  this.editorResult = new rx.Subject();

  // Open Editor on "line" (Enter Key)
  var events = observe(this.rl);
  events.line.forEach(this.startExternalEditor.bind(this));

  // Trigger Validation when editor closes
  var validation = this.handleSubmitEvents(this.editorResult);
  validation.success.forEach(this.onEnd.bind(this));
  validation.error.forEach(this.onError.bind(this));

  // Prevents default from being printed on screen (can look weird with multiple lines)
  this.currentText = this.opt.default;
  this.opt.default = null;

  // Init
  this.render();

  return this;
};

/**
 * Render the prompt to screen
 * @return {Prompt} self
 */

Prompt.prototype.render = function (error) {
  var bottomContent = '';
  var message = this.getQuestion();

  if (this.status === 'answered') {
    message += chalk.dim('Received');
  } else {
    message += chalk.dim('Press <enter> to launch your preferred editor.');
  }

  if (error) {
    bottomContent = chalk.red('>> ') + error;
  }

  this.screen.render(message, bottomContent);
};

/**
 * Launch $EDITOR on user press enter
 */

Prompt.prototype.startExternalEditor = function () {
  // Pause Readline to prevent stdin and stdout from being modified while the editor is showing
  this.rl.pause();
  ExternalEditor.editAsync(this.currentText, this.endExternalEditor.bind(this));
};

Prompt.prototype.endExternalEditor = function (error, result) {
  this.rl.resume();
  if (error) {
    this.editorResult.onError(error);
  } else {
    this.editorResult.onNext(result);
  }
};

Prompt.prototype.onEnd = function (state) {
  this.editorResult.dispose();
  this.answer = state.value;
  this.status = 'answered';
  // Re-render prompt
  this.render();
  this.screen.done();
  this.done(this.answer);
};

Prompt.prototype.onError = function (state) {
  this.render(state.isValid);
};


text:
//
// Copyright (c) Microsoft.  All rights reserved.
//
// 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.
//

using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Conversion;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Registration.Models;

namespace Microsoft.Azure.Management.DataFactories
{
    public class ComputeTypeOperations : IServiceOperations<DataFactoryManagementClient>,
                                         IComputeTypeOperations
    {
        public DataFactoryManagementClient Client { get; private set; }

        internal ComputeTypeConverter Converter { get; private set; }

        internal ComputeTypeOperations(DataFactoryManagementClient client)
        {
            this.Client = client;
            this.Converter = new ComputeTypeConverter();
        }

        public async Task<LongRunningOperationResponse> BeginDeleteAsync(
            string resourceGroupName,
            string dataFactoryName,
            string computeTypeName,
            CancellationToken cancellationToken)
        {
            return await this.Client.InternalClient.ComputeTypes.BeginDeleteAsync(
                    resourceGroupName,
                    dataFactoryName,
                    computeTypeName,
                    cancellationToken);
        }

        public async Task<ComputeTypeCreateOrUpdateResponse> CreateOrUpdateAsync(
            string resourceGroupName,
            string dataFactoryName,
            ComputeTypeCreateOrUpdateParameters parameters,
            CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(parameters, "parameters");
            Ensure.IsNotNull(parameters.ComputeType, "parameters.ComputeType");

            Core.Registration.Models.ComputeType internalComputeType = this.Converter.ToCoreType(parameters.ComputeType);

            Core.Registration.Models.ComputeTypeCreateOrUpdateResponse response =
                await this.Client.InternalClient.ComputeTypes.CreateOrUpdateAsync(
                    resourceGroupName,
                    dataFactoryName,
                    new Core.Registration.Models.ComputeTypeCreateOrUpdateParameters(internalComputeType));

            return new ComputeTypeCreateOrUpdateResponse(response, this.Client);
        }

        public async Task<ComputeTypeCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(
            string resourceGroupName,
            string dataFactoryName,
            string computeTypeName,
            ComputeTypeCreateOrUpdateWithRawJsonContentParameters parameters,
            CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(parameters, "parameters");

            Core.Registration.Models.ComputeTypeCreateOrUpdateWithRawJsonContentParameters internalParameters =
                new Core.Registration.Models.ComputeTypeCreateOrUpdateWithRawJsonContentParameters(parameters.Content);

            Core.Registration.Models.ComputeTypeCreateOrUpdateResponse response =
                await this.Client.InternalClient.ComputeTypes.CreateOrUpdateWithRawJsonContentAsync(
                    resourceGroupName,
                    dataFactoryName,
                    computeTypeName,
                    internalParameters,
                    cancellationToken);

            return new ComputeTypeCreateOrUpdateResponse(response, this.Client);
        }

        public async Task<LongRunningOperationResponse> DeleteAsync(
            string resourceGroupName,
            string dataFactoryName,
            string computeTypeName,
            CancellationToken cancellationToken)
        {
            return await this.Client.InternalClient.ComputeTypes.DeleteAsync(
                    resourceGroupName,
                    dataFactoryName,
                    computeTypeName,
                    cancellationToken);
        }

        public async Task<ComputeTypeGetResponse> GetAsync(
            string resourceGroupName,
            string dataFactoryName,
            ComputeTypeGetParameters parameters,
            CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(parameters, "parameters");

            Core.Registration.Models.ComputeTypeGetParameters internalParameters =
                new Core.Registration.Models.ComputeTypeGetParameters(parameters.RegistrationScope,
                    parameters.ComputeTypeName);

            Core.Registration.Models.ComputeTypeGetResponse response =
                await this.Client.InternalClient.ComputeTypes.GetAsync(
                    resourceGroupName,
                    dataFactoryName,
                    internalParameters,
                    cancellationToken);

            return new ComputeTypeGetResponse(response, this.Client);
        }

        public async Task<ComputeTypeListResponse> ListAsync(
            string resourceGroupName,
            string dataFactoryName,
            ComputeTypeListParameters parameters,
            CancellationToken cancellationToken)
        {
            Ensure.IsNotNull(parameters, "parameters");

            Core.Registration.Models.ComputeTypeListParameters internalParameters =
                new Core.Registration.Models.ComputeTypeListParameters(parameters.RegistrationScope)
                {
                    ComputeTypeName = parameters.ComputeTypeName
                };

            Core.Registration.Models.ComputeTypeListResponse response =
                await this.Client.InternalClient.ComputeTypes.ListAsync(
                    resourceGroupName,
                    dataFactoryName,
                    internalParameters,
                    cancellationToken);

            return new ComputeTypeListResponse(response, this.Client);
        }

        public async Task<ComputeTypeListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
        {
            // Validate
            Ensure.IsNotNull(nextLink, "nextLink");

            Core.Registration.Models.ComputeTypeListResponse response =
                await this.Client.InternalClient.ComputeTypes.ListNextAsync(nextLink, cancellationToken);

            return new ComputeTypeListResponse(response, this.Client);
        }
    }
}


text:
  Editar encuesta

  Activo
  Inactivo

      <button data-ng-if="!view.form.active" type="button" data-ng-click="activeForm()" class="btn btn-primary">
        Activar
      </button>
      <button type="button" data-ng-click="remove()" class="btn btn-danger">
        Eliminar
      </button>

              Resumen

              Datos principales

              Editor


text:
Changelog
=========

Version 0.9.3 [2015-07-22]
--------------------------

- `04fd1bf <https://github.com/djangonauts/django-rest-framework-gis/commit/04fd1bf>`_: Added ``GeoJsonPagination``
- `fe47d86 <https://github.com/djangonauts/django-rest-framework-gis/commit/fe47d86>`_: Improved ``ValidationError`` message of ``GeometryField``
- `a3ddd3d <https://github.com/djangonauts/django-rest-framework-gis/commit/a3ddd3d>`_: **Improved serialization performance between 25% and 29%**
- `fb6ed36 <https://github.com/djangonauts/django-rest-framework-gis/commit/fb6ed36>`_: ``GeoModelSerializer`` deprecated because obsolete
- `#66 <https://github.com/djangonauts/django-rest-framework-gis/pull/66>`_: geometry now allows ``None`` values according to the **GeoJSON spec**
- `#67 <https://github.com/djangonauts/django-rest-framework-gis/pull/67>`_: discern ``False`` or empty string values from ``None`` in ``GeoFeatureModelSerializer``

Version 0.9.2 [2015-07-15]
--------------------------

- `#59 <https://github.com/djangonauts/django-rest-framework-gis/pull/59>`_: Added GeometrySerializerMethodField
- `3fa2354 <https://github.com/djangonauts/django-rest-framework-gis/commit/3fa2354>`_: removed broken/obsolete/untested code

Version 0.9.1 [2015-06-28]
--------------------------

- `#63 <https://github.com/djangonauts/django-rest-framework-gis/issues/63>`_: added compatibility with python 3.2 and updated compatibility table in README
- `#60 <https://github.com/djangonauts/django-rest-framework-gis/pull/60>`_: ensure GeoJSON is rendered correctly in browsable API when using python 2
- `#62 <https://github.com/djangonauts/django-rest-framework-gis/issues/62>`_: updated django-rest-framework requirement to 3.1.3

Version 0.9 [2015-05-31]
------------------------

- `#55 <https://github.com/djangonauts/django-rest-framework-gis/pull/55>`_: Fixed exception in ``DistanceToPointFilter`` in case of invalid point
- `#58 <https://github.com/djangonauts/django-rest-framework-gis/pull/58>`_: Fixed handling of ``None`` values in ``GeoFeatureModelSerializer`` to avoid problems with ``FileField`` and ``ImageField``
- `#57 <https://github.com/djangonauts/django-rest-framework-gis/pull/57>`_: Added support for GeoJSON Bounding Boxes in ``GeoFeatureModelSerializer``

Version 0.8.2 [2015-04-29]
--------------------------

- `#53 <https://github.com/djangonauts/django-rest-framework-gis/pull/53>`_: Added support for PATCH requests in ``GeoFeatureModelSerializer``

Version 0.8.1 [2015-03-25]
--------------------------

- Added compatibility with django-rest-framework 3.1.x
- Added compatibility with django 1.8 (RC1)

Version 0.8 [2015-03-03]
------------------------

- Added compatibility with django-rest-framework 3.x

Version 0.7 [2014-10-03]
------------------------

- upgraded development status classifer to Beta
- avoid empty string in textarea widget if value is None
- allow field definition in GeoFeatureModelSerializer to be list

Version 0.6 [2014-09-24]
------------------------

- Added compatibility to django-rest-framework 2.4.3

Version 0.5 [2014-09-07]
------------------------

- added TMSTileFilter
- added DistanceToPointFilter
- renamed InBBOXFilter to InBBoxFilter
- added compatibility with DRF 2.4.0

Version 0.4 [2014-08-25]
------------------------

- python3 compatibility
- improved DRF browsable API HTML widget (textarea instead of text input)

Version 0.3 [2014-07-07]
------------------------

- added compatibility with DRF 2.3.14

Version 0.2 [2014-03-18]
------------------------

- geofilter support
- README in restructured text for pypi
- updated python package info

Version 0.1 [2013-12-30]
------------------------

- first release


text:
const err = new Error('The message');
console.log(err.message); // 'The message'


text:
<?xml version="1.0" encoding="UTF-8" ?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-geofence-test" version="0.6.0">
    <name>Geofence plugin Tests</name>
    <license>Apache 2.0</license>

    <js-module src="tests.js" name="tests">
    </js-module>

    <platform name="ios">
        <hook type="before_run" src="hooks/fix-swift-paramedic.js" />
    </platform>
</plugin>


text:
class my_class {
public:
    my_class() {} // When you want to convert from msgpack::object to my_class,
                  // my_class should be default constractible.
    my_class(std::string const& name, int age):name_(name), age_(age) {}

    // my_class should provide getters for the data members you want to pack.
    std::string const& get_name() const { return name_; }
    int get_age() const { return age_; }

    friend bool operator==(my_class const& lhs, my_class const& rhs) {
        return lhs.name_ == rhs.name_ && lhs.age_ == rhs.age_;
    }

private:
    std::string name_;
    int age_;
};

// User defined class template specialization
namespace msgpack {
MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) {
namespace adaptor {

template<>
struct convert<my_class> {
    msgpack::object const& operator()(msgpack::object const& o, my_class& v) const {
        if (o.type != msgpack::type::ARRAY) throw msgpack::type_error();
        if (o.via.array.size != 2) throw msgpack::type_error();
        v = my_class(
            o.via.array.ptr[0].as<std::string>(),
            o.via.array.ptr[1].as<int>());
        return o;
    }
};

template<>
struct pack<my_class> {
    template <typename Stream>
    packer<Stream>& operator()(msgpack::packer<Stream>& o, my_class const& v) const {
        // packing member variables as an array.
        o.pack_array(2);
        o.pack(v.get_name());
        o.pack(v.get_age());
        return o;
    }
};

template <>
struct object_with_zone<my_class> {
    void operator()(msgpack::object::with_zone& o, my_class const& v) const {
        o.type = type::ARRAY;
        o.via.array.size = 2;
        o.via.array.ptr = static_cast<msgpack::object*>(
            o.zone.allocate_align(sizeof(msgpack::object) * o.via.array.size));
        o.via.array.ptr[0] = msgpack::object(v.get_name(), o.zone);
        o.via.array.ptr[1] = msgpack::object(v.get_age(), o.zone);
    }
};

} // namespace adaptor
} // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS)
} // namespace msgpack

void print(std::string const& buf) {
    for (std::string::const_iterator it = buf.begin(), end = buf.end();
         it != end;
         ++it) {
        std::cout
            << std::setw(2)
            << std::hex
            << std::setfill('0')
            << (static_cast<int>(*it) & 0xff)
            << ' ';
    }
    std::cout << std::dec << std::endl;
}

int main() {
    {   // pack, unpack
        my_class my("John Smith", 42);
        std::stringstream ss;
        msgpack::pack(ss, my);

        print(ss.str());

        msgpack::unpacked unp;
        msgpack::unpack(unp, ss.str().data(), ss.str().size());
        msgpack::object obj = unp.get();
        std::cout << obj << std::endl;
        assert(obj.as<my_class>() == my);
    }
    {   // create object with zone
        my_class my("John Smith", 42);
        msgpack::zone z;
        msgpack::object obj(my, z);
        std::cout << obj << std::endl;
        assert(obj.as<my_class>() == my);
    }
}


text:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <ns2:authenticateResponse xmlns:ns2="http://v1_0.ws.user.example.com">
         <return>
            <authenticationValue>
              <token>a68d1d6379b62ff339a0e0c69ed4d9cf</token>
              <tokenHash>AAAJxA;cIedoT;mY10ExZwG6JuKgp2OYKxow==</tokenHash>
              <client>radclient</client>
            </authenticationValue>
            <success>true</success>
         </return>
      </ns2:authenticateResponse>
   </soap:Body>
</soap:Envelope>


text:
std::vector<Environment> BacktrackingSolver::solve(CspProblem& problem) {
    counter = 0;
    this->constraintMachines = &problem.constraintMachines;
    this->backtracking(problem.environment, problem.environment.begin());
    return solutions;
}

bool BacktrackingSolver::backtracking(Environment& state, const EnvIt& envIt)  {
    counter++;

    auto result = evaluateMachines(*constraintMachines, state);

    if (result) {
        if (result.get()) {
            solutions.push_back(state);
            return true;
        } else {
            return false;
        }
    }

    auto nextIt = ++EnvIt(envIt);
    while(envIt->second.hasNextValueFromDomain()) {
        envIt->second.nextValueFromDomain();

        if (backtracking(state, nextIt) && !findAll)
            return true;

        if (nextIt != state.end()) {
            nextIt->second.reset();
        }
    }
    return false;
}

BacktrackingSolver::BacktrackingSolver(bool findAll) : Solver(findAll) { }


text:
package cgeo.geocaching.enumerations;

import cgeo.geocaching.R;

import android.content.res.Resources;

public enum StatusCode {

    NO_ERROR(R.string.err_none),
    LOG_SAVED(R.string.info_log_saved),
    LOGIN_PARSE_ERROR(R.string.err_parse),
    CONNECTION_FAILED(R.string.err_server),
    CONNECTION_FAILED_EC(R.string.err_server_ec),
    NO_LOGIN_INFO_STORED(R.string.err_login),
    UNKNOWN_ERROR(R.string.err_unknown),
    COMMUNICATION_ERROR(R.string.err_comm),
    WRONG_LOGIN_DATA(R.string.err_wrong),
    UNAPPROVED_LICENSE(R.string.err_license),
    UNVALIDATED_ACCOUNT(R.string.err_unvalidated_account),
    UNPUBLISHED_CACHE(R.string.err_unpublished),
    PREMIUM_ONLY(R.string.err_premium_only),
    MAINTENANCE(R.string.err_maintenance),
    LOG_POST_ERROR(R.string.err_log_post_failed),
    LOG_POST_ERROR_EC(R.string.err_log_post_failed_ec),
    NO_LOG_TEXT(R.string.warn_log_text_fill),
    NOT_LOGGED_IN(R.string.init_login_popup_failed),
    LOGIMAGE_POST_ERROR(R.string.err_logimage_post_failed);

    final private int error_string;

    StatusCode(int error_string) {
        this.error_string = error_string;
    }

    public int getErrorString() {
        return error_string;
    }

    public String getErrorString(final Resources res) {
        return res.getString(error_string);
    }

}


text:
package edu.mines.jtk.dsp;

/**
 * An interface for 3D tensors used in anisotropic 3D image processing.
 * Each tensor is a symmetric positive-semidefinite 3-by-3 matrix:
 *

 *     |a11 a12 a13|
 * A = |a12 a22 a23|
 *     |a13 a23 a33|
 *

 *
 * @author Dave Hale, Colorado School of Mines
 * @version 2008.07.28
 */
public interface Tensors3 {

  /**
   * Gets tensor elements for specified indices.
   * @param i1 index for 1st dimension.
   * @param i2 index for 2nd dimension.
   * @param i3 index for 3rd dimension.
   * @param a array {a11,a12,a13,a22,a23,a33} of tensor elements.
   */
  public void getTensor(int i1, int i2, int i3, float[] a);
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<libraryInfos>
<libraryInfo home="/home/firzhan/installations/java/jdk1.7.0_55" version="1.7.0_55">
<bootpath>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/resources.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/rt.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/sunrsasign.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/jsse.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/jce.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/charsets.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/jfr.jar"/>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/classes"/>
</bootpath>
<extensionDirs>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/ext"/>
<entry path="/usr/java/packages/lib/ext"/>
</extensionDirs>
<endorsedDirs>
<entry path="/home/firzhan/installations/java/jdk1.7.0_55/jre/lib/endorsed"/>
</endorsedDirs>
</libraryInfo>
</libraryInfos>


text:
.order-wrapper { padding: 50px 15px; }

.grid.order {
  background: #fff;
  border-radius: 4px;
  -webkit-box-shadow: 0px 0px 15px #bbb;
     -moz-box-shadow: 0px 0px 15px #bbb;
          box-shadow: 0px 0px 15px #bbb;
  color: #333;
  padding: 25px;
}

.letter-head-logo {
  color: #333;
  font-family: 'Engagement';
  font-size: 60px;
  text-decoration: none;
  -webkit-transition: color 0.3s ease-in-out;
     -moz-transition: color 0.3s ease-in-out;
          transition: color 0.3s ease-in-out;
  text-align: center;
}

.letter-head-logo:visited { color: #333; }
.letter-head-logo:hover { color: #68be79; }

.title {
  font-family: 'Open Sans Condensed', Helvetica, Arial, sans-serif;
  font-size: 40px;
  text-align: center;
}

.order-preview-img {
  width: 100%;
}

.row.confirmation-grid-header {
  font-family: 'Open Sans Condensed', Helvetica, Arial, sans-serif;
  font-size: 24px;
  margin-top: 25px;
}

@media screen and (max-width: 480px) {
  .row.confirmation-grid-header { display: none; }
  .row.order-item.first { margin-top: 25px; }
}

.row.order-item {
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
  font-size: 16px;
}

.row.order-table {
  border-top: 1px solid #ccc;
}

.row.order-table.order-item:hover {
  background: rgb(245, 245, 245);
}

.col.item-desc {
  color: #555;
}

.order-table-val {
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
}

.order-table-val.total { font-size: 24px; }

input.bcd-link-btn.cancel-order {
  font-size: 14px;
  line-height: 20px;
}

.order-table-lbl {
  font-size: 24px;
  font-family: 'Open Sans Condensed', Helvetica, Arial, sans-serif;
}

.email-notice-wrapper {
  background: #eee;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
  font-family: 'Open Sans', Helvetica, Arial, sans-serif;
  font-size: 22px;
  text-align: center;
}


text:
(function() {
    "use strict";

    angular
        .module("yapp.settings")
        .controller("PersonalData", PersonalData);

    PersonalData.$inject = ["$scope", "$auth", "StateRouter", "DSUser"];

    function PersonalData($scope, $auth, StateRouter, DSUser) {
        $scope.personalData = {
            name: "",
            email: ""
        };

        $scope.changeData = changeData;

        ////////////////////

        function changeData() {
            /*$rootScope.yUser = {
                name: $scope.personalData.name,
                email: $scope.personalData.email
            };
            StateRouter.goAndForget("yapp.dashboard");*/
            var data = { account_attributes: {} },
                yUser = DSUser.getUser(),
                key = yUser.role == "parent" ? "manager" : "child",
                name = $scope.personalData.name,
                email = $scope.personalData.email;
            if (!name && !email) { return; }
            data.id = yUser.id;
            if (name) {
                data.account_attributes.name = name;
            }
            if (email) {
                data.account_attributes.email = email;
            }
            // $auth.updateAccount(data).then(onUpdateSuccess, onUpdateError);
        }

        function onUpdateSuccess(resp) {
            resp = resp.data.data;
            resp.role = resp.children_ids != null ? "parent" : "child";
            console.log("UPDATED", resp);
            DSUser.putUser(resp);
            StateRouter.goAndForget("yapp.settings");
        }

        function onUpdateError(resp) {
            console.error("error authenticating", resp);
            StateRouter.goAndForget("yapp.settings");
        }
    }
})();


text:
- log4net extensions

  - log4net ElasticSearchAppender
  - Log4NetHelper

- `Log4NetLoggerProvider`for Microsoft.Extensions.Logging

- `Log4NetLogHelperProvider` for WeihanLi.Common.Logging

## Use log4net only

1. log4net init

    ``` csharp
    Log4NetHelper.LogInit(); // log4net.config for default

    Log4NetHelper.LogInit(log4netConfigFilePath);
    ```

2. GetLogger

    ``` csharp
    var genericLogger = Log4NetHelper.GetLogger<ClassName>();

    var typeLogger = Log4NetHelper.GetLogger(typeof(Program));

    var logger = Log4NetHelper.GetLogger("LoggerName");
    ```

3. Log message

    ``` csharp
    logger.Debug(msg);
    logger.Info(msg);
    logger.Info(msg, exception);
    logger.Warn(msg);
    logger.Warn(msg, exception);
    logger.Error(msg);
    logger.Error(msg, exception);
    logger.Fatal(msg);
    logger.Fatal(msg, exception);
    ```

4. log4net config sample

``` xml
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file type="log4net.Util.PatternString" value="./Log/systemLog.%date{yyyy-MM-dd}.log" />
      <appendToFile value="true" />
      <encoding value="unicodeFFFE" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="100" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />
      <connectionString value="data source=.;initial catalog=WebLog;integrated security=false;persist security info=True;User ID=[***];Password=[***]" />
      <commandText value="INSERT INTO [dbo].[TestLog]([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES(@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
      <filter type="log4net.Filter.LevelRangeFilter">
        <!--<param name="LevelMin" value="DEBUG" />
        <param name="LevelMax" value="ERROR" />-->
        <param name="LevelMin" value="WARN" />
      </filter>
    </appender>
    <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
      <mapping>
        <level value="ERROR" />
        <foreColor value="White" />
        <backColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="DEBUG" />
        <backColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <authentication value="Basic" />
      <username value="ben121011@126.com" />
      <password value="*******" />
      <to value="w***@outlook.com" />
      <from value="ben121011@126.com" />
      <subject value="logging message test" />
      <smtpHost value="smtp.126.com" />
      <bufferSize value="512" />
      <!--  超长是否丢弃 -->
      <lossy value="true" />
      <!-- 下面的定义, 就是 日志级别 大于 ERROR 的, 才发邮件.  -->
      <filter type="log4net.Filter.LevelRangeFilter">
        <levelMin value="ERROR" />
        <levelMax value="FATAL" />
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%newline %date  %newline [%thread] %newline %-5level %logger  %newline - %message" />
      </layout>
    </appender>
    <appender name="ElasticSearchAppender" type="WeihanLi.Common.Logging.Log4Net.ElasticSearchAppender, WeihanLi.Common.Logging.Log4Net">
      <bufferSize value="2" />
      <ElasticSearchUrl value="http://localhost:9200" />
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="TraceAppender" />
      <appender-ref ref="ConsoleAppender" />
      <appender-ref ref="RollingLogFileAppender" />
      <!--
      <appender-ref ref="ColoredConsoleAppender" />
      <appender-ref ref="AdoNetAppender" />
      <appender-ref ref="SmtpAppender" />
      <appender-ref ref="ElasticSearchAppender" />
      -->
    </root>
  </log4net>
</configuration>
```

## use Log4NetLoggerProvider

``` csharp
ILoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddLog4Net(); // loggerFactory.AddLog4Net(log4netConfigFilePath);
```

you can config in asp.net core use code like below in your `Startup`:

``` csharp
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();

            // ...
        }
```

## use Log4NetLogHelperProvider

``` csharp
LogHelper.AddLogProvider(new ILogHelperProvider[] {
                new WeihanLi.Common.Logging.Log4Net.Log4NetLogHelperProvider()
            });
```


text:
<?php declare(strict_types=1);

namespace PHPUnit\Framework\Constraint;

/**
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
 */
final class LogicalOr extends BinaryOperator
{
    /**
     * Returns the name of this operator.
     */
    public function operator(): string
    {
        return 'or';
    }

    /**
     * Returns this operator's precedence.
     *
     * @see https://www.php.net/manual/en/language.operators.precedence.php
     */
    public function precedence(): int
    {
        return 24;
    }

    /**
     * Evaluates the constraint for parameter $other. Returns true if the
     * constraint is met, false otherwise.
     */
    public function matches(mixed $other): bool
    {
        foreach ($this->constraints() as $constraint) {
            if ($constraint->evaluate($other, '', true)) {
                return true;
            }
        }

        return false;
    }
}


text:
<?php
namespace NewRelicTest\Listener;

use NewRelic\ClientInterface;
use NewRelic\Listener\ResponseListener;
use NewRelic\ModuleOptions;
use PHPUnit\Framework\TestCase;
use Zend\Http\Request as HttpRequest;
use Zend\Mvc\MvcEvent;
use Zend\Stdlib\Request;
use Zend\Stdlib\Response;

class ResponseListenerTest extends TestCase
{
    /**
     * @var ModuleOptions
     */
    protected $moduleOptions;

    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var ResponseListener
     */
    protected $listener;

    /**
     * @var MvcEvent
     */
    protected $event;

    public function setUp(): void
    {
        $this->client = $this->createMock(ClientInterface::class);
        $this->moduleOptions = new ModuleOptions();
        $this->listener = new ResponseListener($this->client, $this->moduleOptions);

        $this->event = new MvcEvent();
    }

    public function testOnResponseWithoutAutoInstrument()
    {
        $this->moduleOptions
            ->setBrowserTimingEnabled(true)
            ->setBrowserTimingAutoInstrument(false);

        $this->client
            ->expects($this->once())
            ->method('getBrowserTimingHeader')
            ->will($this->returnValue('

'));
        $this->client
            ->expects($this->once())
            ->method('getBrowserTimingFooter')
            ->will($this->returnValue('

'));

        $request = new HttpRequest();
        $this->event->setRequest($request);

        $response = new Response();
        $response->setContent('');
        $this->event->setResponse($response);
        $this->listener->onResponse($this->event);

        $content = $response->getContent();
        $this->assertContains('

', $content);
        $this->assertContains('

', $content);
    }

    public function testOnResponseWithBrowserTimingDisabled()
    {
        $this->moduleOptions->setBrowserTimingEnabled(false);

        $this->client
            ->expects($this->once())
            ->method('disableAutorum');
        $this->client
            ->expects($this->never())
            ->method('getBrowserTimingHeader');
        $this->client
            ->expects($this->never())
            ->method('getBrowserTimingFooter');

        $this->listener->onResponse($this->event);
    }

    public function testOnResponseNotInHttpRequestContext()
    {
        $this->moduleOptions->setBrowserTimingEnabled(true);

        $this->client
            ->expects($this->once())
            ->method('disableAutorum');
        $this->client
            ->expects($this->never())
            ->method('getBrowserTimingHeader');
        $this->client
            ->expects($this->never())
            ->method('getBrowserTimingFooter');

        $request = new Request();
        $this->event->setRequest($request);

        $this->listener->onResponse($this->event);
    }

    public function testOnResponseInAjaxHttpRequestContext()
    {
        $this->moduleOptions->setBrowserTimingEnabled(true);

        $this->client
            ->expects($this->once())
            ->method('disableAutorum');
        $this->client
            ->expects($this->never())
            ->method('getBrowserTimingHeader');
        $this->client
            ->expects($this->never())
            ->method('getBrowserTimingFooter');

        $request = $this->createMock(HttpRequest::class);
        $request
            ->expects($this->once())
            ->method('isXmlHttpRequest')
            ->will($this->returnValue(true));
        $this->event->setRequest($request);

        $this->listener->onResponse($this->event);
    }
}


text:
<?php

namespace Weavora;

class TestCase  extends \PHPUnit_Framework_TestCase
{
    public function tearDown()
    {
        \Mockery::close();
    }
}


text:
import { animationend, promise, requestAnimationFrame, isUndefined } from './index'

export const isRtl = document.documentElement.getAttribute('dir') === 'rtl'

export const Animation = {
  in (element, animation, duration, origin) {
    return animate(element, animation, duration, origin, false)
  },
  out (element, animation, duration, origin) {
    return animate(element, animation, duration, origin, true)
  },
  inProgress (element) {
    return hasClass(element, 'uk-animation-enter') || hasClass(element, 'uk-animation-leave')
  },
  cancel (element) {
    // var e = $.Event(animationend || 'animationend')
    // $(element).triggerHandler(e)
    // return e.promise || promise.resolve()
  }
}

export function animate (element, animation, duration = 200, origin, out) {
  var p = promise(resolve => {
    var cls = out ? 'uk-animation-leave' : 'uk-animation-enter'

    if (animation.lastIndexOf('uk-animation-', 0) === 0) {
      if (origin) {
        animation += ` uk-animation-${origin}`
      }
      if (out) {
        animation += ' uk-animation-reverse'
      }
    }

    reset()

    one(element, animationend || 'animationend', e => {
      e.promise = p
      p.then(reset)
      resolve()
    })
    css(element, 'animation-duration', `${duration}ms`)
    addClass(element, animation)
    addClass(element, cls)

    if (!animationend) {
      requestAnimationFrame(() => Animation.cancel(element))
    }

    function reset () {
      css(element, 'animation-duration', '')
      removeClass(element, `${cls} ${animation}`)
    }
  })

  return p
}

/* Add/Remove class */

export function hasClass (el, className) {
  return el.classList.contains(className)
}

export function addClass (el, classes) {
  return sanitizeClasses(classes).forEach(className => _addClass(el, className))
}

function _addClass (el, className) {
  el.classList.add(className)
}

export function removeClass (el, classes) {
  return sanitizeClasses(classes).forEach(className => _removeClass(el, className))
}

export function _removeClass (el, className) {
  el.classList.remove(className)
}

// export function attrFilter (element, attr, pattern, replacement) {
//   element = $(element)
//   return element.attr(attr, (i, value) => value ? value.replace(pattern, replacement) : value)
// }
//
// export function removeClass (element, cls) {
//   return attrFilter(element, 'class', new RegExp(`(^|\\s)${cls}(?!\\S)`, 'g'), '')
// }

function sanitizeClasses (classes) {
  return classes.split(' ').filter(c => c)
}

/* Retrieve style */

export function css (el, style, value) {
  // retrieve
  if (isUndefined(value)) {
    return window.getComputedStyle(el)[style]
  }
  // or add style
  el.style[style] = value
}

/* Events */

var boundEvents = []

// add event listener shorthand
export function on (el, type, listener, namespace = 'default') {
  boundEvents[namespace] = boundEvents[namespace] || []
  boundEvents[namespace].push({ el, type, listener })
  el.addEventListener(type, listener)
}

export function off (el, type, namespace = 'default') {
  const event = boundEvents[namespace].find(bound => {
    return bound.el === el && bound.type === type
  })
  if (event) {
    el.removeEventListener(type, event.listener)
  }
}

export function one (el, type, listener) {
  const finalCallback = e => {
    listener(e)
    el.removeEventListener(type, finalCallback)
  }
  el.addEventListener(type, finalCallback)
}

export function offAll (namespace = 'default') {
  if (boundEvents[namespace] !== undefined) {
    for (let i = 0; i < boundEvents[namespace].length; ++i) {
      const { el, event, handler } = boundEvents[namespace][i]
      el.removeEventListener(event, handler)
    }
  }
}


text:
package uk.gov.dvsa.ui.views;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import uk.gov.dvsa.domain.model.AeDetails;
import uk.gov.dvsa.domain.model.Site;
import uk.gov.dvsa.domain.model.User;
import uk.gov.dvsa.ui.DslTest;
import uk.gov.dvsa.ui.pages.error.PageNotFoundPage;
import uk.gov.dvsa.ui.pages.error.YouDontHavePremissionPage;

import java.io.IOException;

public class ErrorPagesTests extends DslTest {

    @Test(groups = {"Regression"}, dataProvider = "pageNotFoundDataProvider")
    public void testUnhandled404ExceptionIsTranslatedToNotFoundPage(User areaOfficeUser) throws IOException {
        step("When I go to a page, that throws 404 exception from API ");
        PageNotFoundPage pageNotFoundPage = motUI.organisation.goToNonexistentAe(areaOfficeUser);

        step("Then I should see 404 not found error");
        Assert.assertTrue(pageNotFoundPage.isErrorMessageDisplayed());
    }

    @Test(groups = {"Regression"}, dataProvider = "youDontHavePermissionDataProvider")
    public void testUnhandled403ExceptionIsTranslatedToYouDontHavePermissionPage(User tester, String aeId) throws IOException {
        step("When I go to a page, that throws 403 exception from API ");
        YouDontHavePremissionPage youDontHavePremissionPage = motUI.organisation
            .goToAeWithoutPermission(tester, aeId);

        step("Then I should see 'you dont have premission page'");
        Assert.assertTrue(youDontHavePremissionPage.isErrorMessageDisplayed());
    }

    @Test(groups = {"Regression"}, dataProvider = "pageNotFoundDataProvider")
    public void testPageNotFoundErrorPage(User user) throws IOException {
        step("When I go to a page, that doesn't exist");
        PageNotFoundPage pageNotFound = pageNavigator
            .navigateToPage(user, "/some-page-that-for-sure-desnt-exist", PageNotFoundPage.class);

        step("Then I should see 404 not found error");
        Assert.assertTrue(pageNotFound.isErrorMessageDisplayed());
    }

    @DataProvider(name = "pageNotFoundDataProvider")
    public Object[][] pageNotFoundDataProvider() throws IOException {
        return new Object[][]{
            {motApi.user.createUserAsAreaOfficeOneUser("dv")}
        };
    }

    @DataProvider(name = "youDontHavePermissionDataProvider")
    public Object[][] youDontHavePermissionDataProvider() throws IOException {
        AeDetails ae = aeData.createNewAe("TestQuality AE", 100);
        AeDetails ae2 = aeData.createNewAe("TestQuality AE without permissions", 100);
        Site site = siteData.createNewSite(ae.getId(), "TestQuality Site");

        return new Object[][]{
            {motApi.user.createTester(site.getId()), ae2.getIdAsString()}
        };
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/llvm-bcanalyzer.dir/llvm-bcanalyzer.cpp.o"
  "../../bin/llvm-bcanalyzer.pdb"
  "../../bin/llvm-bcanalyzer"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/llvm-bcanalyzer.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
package pack3;

import pack2.BankCard;
import pack2.Sum1;

public class Client {

    // Compositions
    Sum1 sum = new Sum1();
    Account acc1 = new Account();
    BankCard bankCard1 = new BankCard();

    // Variables

    private String surname;  // regarding to passport
    private String name; // regarding to passport
    private String middleName; // regarding to passport
    private String numPassport;

   // Gettery Settery

    public void setSurname(String surname) {
        this.surname = surname;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public void setNumPassport(String numPassport) {
        this.numPassport = numPassport;
    }

    //Constructors

    public  Client () {}

    public Client (String surnamePar, String namePar, String middleNamePar)
    {
                    this.surname = surnamePar;
                    this.name = namePar;
                    this.middleName = middleNamePar;
    }

    // main

    public static void main(String[] args) {

        Client objCl = new Client();

    }
}


text:
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.listitems.listitem import ListItem
from tests import test_client_credentials, test_team_site_url

def retrieve_default_view_items(context):
    """
    :type context: ClientContext
    """
    lib = context.web.default_document_library()
    items = lib.default_view.get_items().execute_query()
    for item in items:  # type: ListItem
        print(item.id)

def retrieve_custom_view_items(context):
    """
    :type context: ClientContext
    """
    view = context.web.lists.get_by_title("Contacts_Large").views.get_by_title("All contacts")
    items = view.get_items().top(5).execute_query()
    for item in items:  # type: ListItem
        print(item.id)

ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
retrieve_default_view_items(ctx)
#retrieve_custom_view_items(ctx)


text:
/* SPDX-License-Identifier: LGPL-2.1 WITH Linux-syscall-note */
/* taskstats.h - exporting per-task statistics
 *
 * Copyright (C) Shailabh Nagar, IBM Corp. 2006
 *           (C) Balbir Singh,   IBM Corp. 2006
 *           (C) Jay Lan,        SGI, 2006
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of version 2.1 of the GNU Lesser General Public License
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it would be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

#ifndef _LINUX_TASKSTATS_H
#define _LINUX_TASKSTATS_H

#include <linux/types.h>

/* Format for per-task data returned to userland when
 *	- a task exits
 *	- listener requests stats for a task
 *
 * The struct is versioned. Newer versions should only add fields to
 * the bottom of the struct to maintain backward compatibility.
 *
 *
 * To add new fields
 *	a) bump up TASKSTATS_VERSION
 *	b) add comment indicating new version number at end of struct
 *	c) add new fields after version comment; maintain 64-bit alignment
 */

#define TASKSTATS_VERSION	8
#define TS_COMM_LEN		32	/* should be >= TASK_COMM_LEN
					 * in linux/sched.h */

struct taskstats {

	/* The version number of this struct. This field is always set to
	 * TAKSTATS_VERSION, which is defined in <linux/taskstats.h>.
	 * Each time the struct is changed, the value should be incremented.
	 */
	__u16	version;
	__u32	ac_exitcode;		/* Exit status */

	/* The accounting flags of a task as defined in <linux/acct.h>
	 * Defined values are AFORK, ASU, ACOMPAT, ACORE, and AXSIG.
	 */
	__u8	ac_flag;		/* Record flags */
	__u8	ac_nice;		/* task_nice */

	/* Delay accounting fields start
	 *
	 * All values, until comment "Delay accounting fields end" are
	 * available only if delay accounting is enabled, even though the last
	 * few fields are not delays
	 *
	 * xxx_count is the number of delay values recorded
	 * xxx_delay_total is the corresponding cumulative delay in nanoseconds
	 *
	 * xxx_delay_total wraps around to zero on overflow
	 * xxx_count incremented regardless of overflow
	 */

	/* Delay waiting for cpu, while runnable
	 * count, delay_total NOT updated atomically
	 */
	__u64	cpu_count __attribute__((aligned(8)));
	__u64	cpu_delay_total;

	/* Following four fields atomically updated using task->delays->lock */

	/* Delay waiting for synchronous block I/O to complete
	 * does not account for delays in I/O submission
	 */
	__u64	blkio_count;
	__u64	blkio_delay_total;

	/* Delay waiting for page fault I/O (swap in only) */
	__u64	swapin_count;
	__u64	swapin_delay_total;

	/* cpu "wall-clock" running time
	 * On some architectures, value will adjust for cpu time stolen
	 * from the kernel in involuntary waits due to virtualization.
	 * Value is cumulative, in nanoseconds, without a corresponding count
	 * and wraps around to zero silently on overflow
	 */
	__u64	cpu_run_real_total;

	/* cpu "virtual" running time
	 * Uses time intervals seen by the kernel i.e. no adjustment
	 * for kernel's involuntary waits due to virtualization.
	 * Value is cumulative, in nanoseconds, without a corresponding count
	 * and wraps around to zero silently on overflow
	 */
	__u64	cpu_run_virtual_total;
	/* Delay accounting fields end */
	/* version 1 ends here */

	/* Basic Accounting Fields start */
	char	ac_comm[TS_COMM_LEN];	/* Command name */
	__u8	ac_sched __attribute__((aligned(8)));
					/* Scheduling discipline */
	__u8	ac_pad[3];
	__u32	ac_uid __attribute__((aligned(8)));
					/* User ID */
	__u32	ac_gid;			/* Group ID */
	__u32	ac_pid;			/* Process ID */
	__u32	ac_ppid;		/* Parent process ID */
	__u32	ac_btime;		/* Begin time [sec since 1970] */
	__u64	ac_etime __attribute__((aligned(8)));
					/* Elapsed time [usec] */
	__u64	ac_utime;		/* User CPU time [usec] */
	__u64	ac_stime;		/* SYstem CPU time [usec] */
	__u64	ac_minflt;		/* Minor Page Fault Count */
	__u64	ac_majflt;		/* Major Page Fault Count */
	/* Basic Accounting Fields end */

	/* Extended accounting fields start */
	/* Accumulated RSS usage in duration of a task, in MBytes-usecs.
	 * The current rss usage is added to this counter every time
	 * a tick is charged to a task's system time. So, at the end we
	 * will have memory usage multiplied by system time. Thus an
	 * average usage per system time unit can be calculated.
	 */
	__u64	coremem;		/* accumulated RSS usage in MB-usec */
	/* Accumulated virtual memory usage in duration of a task.
	 * Same as acct_rss_mem1 above except that we keep track of VM usage.
	 */
	__u64	virtmem;		/* accumulated VM  usage in MB-usec */

	/* High watermark of RSS and virtual memory usage in duration of
	 * a task, in KBytes.
	 */
	__u64	hiwater_rss;		/* High-watermark of RSS usage, in KB */
	__u64	hiwater_vm;		/* High-water VM usage, in KB */

	/* The following four fields are I/O statistics of a task. */
	__u64	read_char;		/* bytes read */
	__u64	write_char;		/* bytes written */
	__u64	read_syscalls;		/* read syscalls */
	__u64	write_syscalls;		/* write syscalls */
	/* Extended accounting fields end */

#define TASKSTATS_HAS_IO_ACCOUNTING
	/* Per-task storage I/O accounting starts */
	__u64	read_bytes;		/* bytes of read I/O */
	__u64	write_bytes;		/* bytes of write I/O */
	__u64	cancelled_write_bytes;	/* bytes of cancelled write I/O */

	__u64  nvcsw;			/* voluntary_ctxt_switches */
	__u64  nivcsw;			/* nonvoluntary_ctxt_switches */

	/* time accounting for SMT machines */
	__u64	ac_utimescaled;		/* utime scaled on frequency etc */
	__u64	ac_stimescaled;		/* stime scaled on frequency etc */
	__u64	cpu_scaled_run_real_total; /* scaled cpu_run_real_total */

	/* Delay waiting for memory reclaim */
	__u64	freepages_count;
	__u64	freepages_delay_total;
};

/*
 * Commands sent from userspace
 * Not versioned. New commands should only be inserted at the enum's end
 * prior to __TASKSTATS_CMD_MAX
 */

enum {
	TASKSTATS_CMD_UNSPEC = 0,	/* Reserved */
	TASKSTATS_CMD_GET,		/* user->kernel request/get-response */
	TASKSTATS_CMD_NEW,		/* kernel->user event */
	__TASKSTATS_CMD_MAX,
};

#define TASKSTATS_CMD_MAX (__TASKSTATS_CMD_MAX - 1)

enum {
	TASKSTATS_TYPE_UNSPEC = 0,	/* Reserved */
	TASKSTATS_TYPE_PID,		/* Process id */
	TASKSTATS_TYPE_TGID,		/* Thread group id */
	TASKSTATS_TYPE_STATS,		/* taskstats structure */
	TASKSTATS_TYPE_AGGR_PID,	/* contains pid + stats */
	TASKSTATS_TYPE_AGGR_TGID,	/* contains tgid + stats */
	TASKSTATS_TYPE_NULL,		/* contains nothing */
	__TASKSTATS_TYPE_MAX,
};

#define TASKSTATS_TYPE_MAX (__TASKSTATS_TYPE_MAX - 1)

enum {
	TASKSTATS_CMD_ATTR_UNSPEC = 0,
	TASKSTATS_CMD_ATTR_PID,
	TASKSTATS_CMD_ATTR_TGID,
	TASKSTATS_CMD_ATTR_REGISTER_CPUMASK,
	TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK,
	__TASKSTATS_CMD_ATTR_MAX,
};

#define TASKSTATS_CMD_ATTR_MAX (__TASKSTATS_CMD_ATTR_MAX - 1)

/* NETLINK_GENERIC related info */

#define TASKSTATS_GENL_NAME	"TASKSTATS"
#define TASKSTATS_GENL_VERSION	0x1

#endif /* _LINUX_TASKSTATS_H */


text:
(function() {

  const Cc = Components.classes;
  const Ci = Components.interfaces;

  const MRTWEET_ID = "mrtweet@mrtweet.com";
  const MRTWEET_URL = "about:mrtweet";

  const VERSION_PREF ="extensions.mrtweet.version";
  const ACTIVATED_PREF = "extensions.mrtweet.activated";

  //When the user first installs the extension, we show the about:mrtweet page
  var currVersion = Application.prefs.getValue(VERSION_PREF, "firstrun");
  var realVersion = Application.extensions.get(MRTWEET_ID).version;

  if (currVersion != realVersion) {
    Application.prefs.setValue(VERSION_PREF, realVersion);
    if(currVersion == "firstrun"){
      //NOTE: For some reason, FUEL doesn't work here, presumably because Firefox's just starting up
      //Application.activeWindow.open(MrTweetExt.url(MRTWEET_URL)).focus();
      window.addEventListener(
        "load",
        function onWindowLoad() {
          window.removeEventListener("load", onWindowLoad, false);
          var tabbrowser = window.getBrowser();
          tabbrowser.addEventListener(
            "load",
            function onBrowserLoad() {
              tabbrowser.removeEventListener("load", onBrowserLoad, false);
              var tab = tabbrowser.addTab(MRTWEET_URL);
              tabbrowser.selectedTab = tab;
            },
            false
          );
        },
        false
      );
    }
  }

  var MrTweetExt = {
    // Utility function to convert URL strings to nsURI
    url : function url(spec) {
      var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
      return ios.newURI(spec, null, null);
    },
    openMrTweetWebsite : function openMrTweetWebsite(){
      var activated = Application.prefs.getValue(ACTIVATED_PREF, false);
      if(activated){
        Application.activeWindow.open(this.url('http://www.mrtweet.com')).focus();
      }else{
        Application.activeWindow.open(this.url(MRTWEET_URL)).focus();
      }
    },
    _appendToFile: function _appendToFile(file, data){
      var foStream = Cc["@mozilla.org/network/file-output-stream;1"]
                     .createInstance(Ci.nsIFileOutputStream);
      foStream.init(file, 0x02 | 0x10, 0666, 0);
      foStream.write(data, data.length);
      foStream.close();
    },
    logToFile: function logToFile(data){
      var nativeJSON = Cc["@mozilla.org/dom/json;1"]
                       .createInstance(Ci.nsIJSON);
      var em = Cc["@mozilla.org/extensions/manager;1"]
                       .getService(Ci.nsIExtensionManager);
      var file = em.getInstallLocation(MRTWEET_ID)
                  .getItemFile(MRTWEET_ID, "content/logs/log.txt");
      this._appendToFile(file, nativeJSON.encode(data) + "\n\n");
    },
    showNoDataMsg: function showNoDataMsg(doc){
      $(doc).find("#mrtweet-stats").empty().append("No MrTweet data available yet. Working on it!");
    }
  }

  function JSONify(obj){
    var nativeJSON = Cc["@mozilla.org/dom/json;1"]
                     .createInstance(Ci.nsIJSON);
    return nativeJSON.decode(obj);
  }

  function onPageLoad(aEvent){
    var doc = aEvent.originalTarget;
    var url = doc.location.href;
    //Check if the page *might* Twitter
    if(url.indexOf("twitter.com") != -1){
      //Get the username of the profile you are looking at
      var cur_user = $.trim($(doc).find("h2.thumb").text());
      //It might be the /home page
      //where the username is stored in a different place
      if(!cur_user){
        cur_user = $.trim($(doc).find("#me_name").text());
        //If there's no username still, return (might be a settings page, etc.)
        if(!cur_user){
          return;
        }
      }

      try{

        var newDiv = doc.createElement("div");
        var html_str = "
" +
                      "
MrTweet Statistics
" +
                      "
";

        var activated = Application.prefs.getValue(ACTIVATED_PREF, false);
        if(activated){
          html_str +=  "Loading…

";
          newDiv.innerHTML = html_str;
          $(doc).find("#primary_nav").before(newDiv);
        }else{
          html_str +=  "Please login on the about:mrtweet page to start seeing stats.

";
          newDiv.innerHTML = html_str;
          $(doc).find("#primary_nav").before(newDiv);
          return;
        }

        $.ajax({
          type: "GET",
          url: "http://api.mrtweet.com/v1/profile/"+ cur_user + "/bc973dc90bb020f46123278c7fe16c9df206bd95.json",
          success: function(data){
            data = JSONify(data);
            try{
              MrTweetExt.logToFile({"user": cur_user, "data" : data});
            }catch(e){
              //do nothing
            }

            if(data.status != "success"){
              MrTweetExt.showNoDataMsg(doc);
              return;
            }

            function mapIntervalsToDesc(intervals, descriptors, tips, value){
              for(var i=0;i<descriptors.length;i++){
                if(value >= intervals[i] & value < intervals[i+1]){
                  return [descriptors[i], tips[i]];
                }
              }
            }

            var conversation_ratio = data.profile.conversation ? data.profile.conversation : false;
            var link_ratio = data.profile.links ? data.profile.links : false;
            var num_recs = data.profile.recommendations;
            var freq = data.profile.frequency ? data.profile.frequency.toFixed(2) : false;

            var statsData = {"stats" : [], "cur_user" : cur_user};
            //Process all the data, add descriptors, tooltips, etc.
            if(freq){

              var comp_freq = Math.ceil(freq/2.53);
              var freq_desc = "(" + comp_freq + "X more than Twitter founders)";

              if(freq >= 2.53 && freq < 4){
                freq_desc = "(tweets as much as the Twitter founders)";
              }

              if(freq < 2.53){
                freq_desc = "";
              }

              var freq_tooltip = "";

              if(conversation_ratio){
               freq_tooltip = Math.round(conversation_ratio * 100) + "% of her/his tweets are @replies";
              }

              statsData.stats.push({"num" : freq,
                                    "text" : "tweets/day " + freq_desc,
                                    "tooltip" :  freq_tooltip});
            }

            if(conversation_ratio){
              var conversation_desc = mapIntervalsToDesc(
                                        [0, 0.01, 0.15, 0.31, 0.63, 2],
                                        ["(way below average)", "(below average)", "(average)", "(above average)", "(way above average)"],
                                        ["Soliloquist", "Contemplative", "Conversational", "Engaging", "Very engaging"],
                                        conversation_ratio
                                      );
              //num, text, tooltip
              statsData.stats.push({"num" : Math.round(conversation_ratio * 100) + "%",
                                    "text" :  "conversations " + conversation_desc[0],
                                    "tooltip" :  conversation_desc[1]});
            }

            if(link_ratio){
              var link_desc = mapIntervalsToDesc(
                                [0, 0.01, 0.15, 0.51, 2],
                                ["(below average)", "(average)", "(above average)", "(way above average)"],
                                ["Non linker", "Links selectively", "Good connector", "Hyperlinked"],
                                link_ratio
                              );

              statsData.stats.push({"num" : Math.round(link_ratio * 100) + "%",
                                    "text" :  "links " + link_desc[0],
                                    "tooltip" :  link_desc[1]});
            }

            if(num_recs >= 0){

              var rec_desc = (num_recs == 1) ? "recommendation" : "recommendations";
              var rec_tooltip = "View all recommendations at mrtweet.com";
              statsData.stats.push({"num" : num_recs,
                                    "text" : rec_desc,
                                    "tooltip" :  rec_tooltip});
            }

            var tplStr = ("
{for stat in stats}" +
                            "
" +
                            "" +
                            "${stat.num} ${stat.text}
" +
                          "{/for}
").process(statsData);

            newDiv = doc.createElement("div");
            newDiv.innerHTML = tplStr;

            if(statsData.stats.length == 0){
              MrTweetExt.showNoDataMsg(doc);
              return;
            }
            //Get recommendations, if any
            if(num_recs > 0){

              newDiv.innerHTML += "
Loading recommendation…
";

              $.ajax({
                type: "GET",
                url: "http://api.mrtweet.com/v1/recommendations/" + cur_user + "/bc973dc90bb020f46123278c7fe16c9df206bd95.json",
                success: function(data2){
                  data2 = JSONify(data2);
                  if(data2.status != "success"){
                    $(doc).find("#mrtweet-rec").empty();
                  }else{
                    $(doc).find("#mrtweet-rec").empty().append(
                      "
@" +
                      data2.recommendations[0]["name"] + " recommends:

" +
                      data2.recommendations[0]["text"] +
                      "

view all recommendations
");
                  }
                },
                error: function(data){
                  data = JSONify(data);
                  $(doc).find("#mrtweet-rec").empty();
                }
              });

            }

            $(doc).find("#mrtweet-stats").empty().append(newDiv);
          },
          error : function(data){
            data = JSONify(data);
            MrTweetExt.showNoDataMsg(doc);
          }
        });
      }catch(e){
        //Do nothing
      }
    }
  }

  window.mrTweetExt = MrTweetExt;
  window.document.getElementById("appcontent").addEventListener("DOMContentLoaded", onPageLoad, true);

})();


text:
using Microsoft.Extensions.Logging;
using SpecDrill.Infrastructure;
using System;
using System.Diagnostics;

namespace SpecDrill.AutomationScopes
{
    public sealed class BenchmarkScope : IDisposable
    {
        private readonly ILogger Logger = DI.GetLogger<BenchmarkScope>();

        private readonly Stopwatch stopwatch;
        private readonly string description;

        public BenchmarkScope(string description)
        {
            this.description = description;
            stopwatch = new Stopwatch();

            Logger.LogInformation(string.Format("Starting Stopwatch for {0}", description));

            stopwatch.Start();
        }

        public TimeSpan Elapsed
        {
            get { return stopwatch.Elapsed; }
        }

        public void Dispose()
        {
            stopwatch.Stop();
            Logger.LogInformation(string.Format("Stopped Stopwatch for {0}. Elapsed = {1}", description, stopwatch.Elapsed));
        }
    }
}


text:
import Handlebars from 'handlebars'
import HandlebarsIntl from 'handlebars-intl'
import handlebarsHelperSlugify from 'handlebars-helper-slugify'
import markdown from 'helper-markdown'

/* Handlebar utilities */
import attrAbe from './handlebars/attrAbe'
import className from './handlebars/className'
import cleanTab from './handlebars/cleanTab'
import ifCond from './handlebars/ifCond'
import ifIn from './handlebars/ifIn'
import isTrue from './handlebars/isTrue'
import eachGroup from './handlebars/eachGroup'
import math from './handlebars/math'
import moduloIf from './handlebars/moduloIf'
import notEmpty from './handlebars/notEmpty'
import printJson from './handlebars/printJson'
import translate from './handlebars/translate'
import times from './handlebars/times'
import lowercase from './handlebars/lowercase'
import uppercase from './handlebars/uppercase'
import setVariable from './handlebars/setVariable'
import isAuthorized from './handlebars/isAuthorized'
import concat from './handlebars/concat'
import getCurrentuserRole from './handlebars/getCurrentuserRole'

import * as template from './template'
import * as prepare from './prepare'
import * as assets from './assets'
import encodeAbeTagAsComment from './encodeAbeTagAsComment'
import insertDebugtoolUtilities from './insertDebugtoolUtilities'

/* Register utilities */
require('handlebars-helpers')({
  handlebars: Handlebars
});
Handlebars.registerHelper('markdown', markdown())
Handlebars.registerHelper('attrAbe', attrAbe)
Handlebars.registerHelper('className', className)
Handlebars.registerHelper('cleanTab', cleanTab)
Handlebars.registerHelper(
  'slugify',
  handlebarsHelperSlugify({Handlebars: Handlebars}).slugify
)
Handlebars.registerHelper('ifCond', ifCond)
Handlebars.registerHelper('ifIn', ifIn)
Handlebars.registerHelper('isTrue', isTrue)
Handlebars.registerHelper('eachGroup', eachGroup)
Handlebars.registerHelper('math', math)
Handlebars.registerHelper('moduloIf', moduloIf)
Handlebars.registerHelper('notEmpty', notEmpty)
Handlebars.registerHelper('printJson', printJson)
Handlebars.registerHelper('i18nAbe', translate)
Handlebars.registerHelper('times', times)
Handlebars.registerHelper('lowercase', lowercase)
Handlebars.registerHelper('uppercase', uppercase)
Handlebars.registerHelper('setVariable', setVariable)
Handlebars.registerHelper('isAuthorized', isAuthorized)
Handlebars.registerHelper('concat', concat)
Handlebars.registerHelper('getCurrentuserRole', getCurrentuserRole)

HandlebarsIntl.registerWith(Handlebars)

export {
  Handlebars,
  template,
  prepare,
  assets,
  encodeAbeTagAsComment,
  insertDebugtoolUtilities,
  attrAbe,
  className,
  cleanTab,
  ifCond,
  ifIn,
  isTrue,
  eachGroup,
  lowercase,
  uppercase,
  setVariable,
  isAuthorized,
  concat,
  getCurrentuserRole,
  math,
  moduloIf,
  notEmpty,
  printJson,
  translate,
  times
}


text:
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.

package org.usfirst.frc1735.Steamworks2017.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc1735.Steamworks2017.Robot;

/**
 *
 */
public class TurretWithLimits extends Command {

    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS

    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
    public TurretWithLimits(double magDir) {

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING

        // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
        requires(Robot.turret);

    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	if (Robot.m_isBlue) {//Robot.allianceChooser.getSelected().toString().equals("Blue")) {
    		m_magDir = -m_magDir; // Save the desired magnitude and direction, but reverse it for the Blue side (autonomous programming assumes red)
    		System.out.println("We are Blue and our magDir is "+ m_magDir);
    	}
    	else {
    		System.out.println("We are Red and our magDir is "+ m_magDir);
    	}
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.turret.directDrive(m_magDir);

    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
    	double currentPosition = Robot.turret.getPosition();
    	if (m_magDir < 0) { // If turning left
    		return (currentPosition <= Robot.turret.getLeftLimit());
    	}
    	else { // Turning right
    		return (currentPosition >= Robot.turret.getRightLimit());
    	}
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.turret.directDrive(0);

    	// If we inverted the drive direction for 'blue", put it back to the "red" default.  This allows us to run autonomous multiple times in the pits without restarting/reinitializing robot code...
       	if (Robot.m_isBlue) {//Robot.allianceChooser.getSelected().toString().equals("Blue")) {
    		m_magDir = -m_magDir;
       	}

    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }

    // Member variables
    double m_magDir;
}


text:
/*
 * 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 com.facebook.presto.operator.aggregation;

import com.facebook.presto.operator.aggregation.state.LongAndDoubleState;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.StandardTypes;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.type.SqlType;
import com.google.common.collect.ImmutableList;

import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;

@AggregationFunction("avg")
public final class AverageAggregations
{
    public static final InternalAggregationFunction LONG_AVERAGE = new AggregationCompiler().generateAggregationFunction(AverageAggregations.class, DOUBLE, ImmutableList.<Type>of(BIGINT));
    public static final InternalAggregationFunction DOUBLE_AVERAGE = new AggregationCompiler().generateAggregationFunction(AverageAggregations.class, DOUBLE, ImmutableList.<Type>of(DOUBLE));

    private AverageAggregations() {}

    @InputFunction
    public static void input(LongAndDoubleState state, @SqlType(StandardTypes.BIGINT) long value)
    {
        state.setLong(state.getLong() + 1);
        state.setDouble(state.getDouble() + value);
    }

    @InputFunction
    public static void input(LongAndDoubleState state, @SqlType(StandardTypes.DOUBLE) double value)
    {
        state.setLong(state.getLong() + 1);
        state.setDouble(state.getDouble() + value);
    }

    @CombineFunction
    public static void combine(LongAndDoubleState state, LongAndDoubleState otherState)
    {
        state.setLong(state.getLong() + otherState.getLong());
        state.setDouble(state.getDouble() + otherState.getDouble());
    }

    @OutputFunction(StandardTypes.DOUBLE)
    public static void output(LongAndDoubleState state, BlockBuilder out)
    {
        long count = state.getLong();
        if (count == 0) {
            out.appendNull();
        }
        else {
            double value = state.getDouble();
            DOUBLE.writeDouble(out, value / count);
        }
    }
}