text:
package com.example.shuaizheng.bufferdemo;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.fab) FloatingActionButton fab;
    @Bind(R.id.toolbar) Toolbar toolbar;
    @OnClick(R.id.fab) void submit(View view){
        Snackbar.make(view,"One",Snackbar.LENGTH_SHORT).setAction("Action",null).show();
    }

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

        setSupportActionBar(toolbar);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
layout: post
title:  "Use randomly permuted features during model prototyping"
date:   2016-05-08 17:00:00 +0100
categories: [Machine Learning]
keywords: "Machine Learning,Feature Selection"
tags: [Machine Learning, Feature Selection]
comments: True
tldr: You can address overfitting and get a sense for individual feature significances by adding randomly permuted features to your machine learning model
---

__TLDR: You can address overfitting and get a sense for individual feature significances by adding randomly permuted features to your machine learning model__

---

# Machine learning finds patterns in the data

Machine learning originates from the field of pattern recognition. [^1] Therefore it is no wonder that related algorithms learn/extract pattern from  data sources to fulfil prediction, classification or clustering tasks. Often the found patterns are fitting mathematical descriptions of the real world causal relations.

# Overfitting results in finding noise patterns

However, when the data is noisy, the learned patterns can describe the noise instead of the relevant, underlying causal connections. This is denoted by the term overfitting. Overfitting is really bad for your model performance because it means that your algorithm is not generalizing properly beyond the given data.

 The blue polynomial is overfitting the red data points. It is not captoring the linear connection between X and Y

Therefore, during the deployment of machine learning models, one has to make sure that the found patterns are general and not data set depended. Some machine learning algorithms such as Support Vector Machines, Neural Networks, bagged/boosted models etc. have a strong black box character that makes it hard to address the quality of the found patterns. In such black box models the saved patterns are represented by complex mathematical models that are powerful but also hidden from view.

# Cross validation addresses overfitting

An important machine learning paradigm to deal with the black box character and the missing understandment of the found patterns is to always evaluate the performance of an algorithm on data that has not been used to train the algorithm. This is called cross validation and is used to address the quality of the whole model. But in addition to the hollistic model performance, the statistical power of individual features are also of interest.

# Add permuted feature versions

Hence, to address both the problem of overfitting in general and to address the individual feature significance, I propose to

*"Always add randomly permuted versions of the features to your model".*
{: style="text-align: center"}

What do I mean by this? After extracting features from the unstructured data sources, add permuted versions of the original features to your model. Then do your statistical analyses, model fitting, plotting etc. on the union of both original and altered features.

## Benefits

There are two benefits to this:

*    It will help you to address the significance of features. If some of your features are ranked of lower importance than the randomized versions, you can probably consider them as not important for the task at hand.
*    If the randomized features are a core ingredient to the inspected algorithm, you have to overthink your whole machine learning pipeline. Hence, they work as an overfitting monitoring / alerting mechanism.  This is because the permuted feature versions cannot have any causal relation to the target as they are statistically independent.

# Example: Linear regression

In the following, we fit a linear regression model for a group of 10 real valued features $$ X_1,\ldots, X_m $$ to predict the real valued target variable $$ Y $$:

$$ \hat y \approx \sum_{i=1}^m a_i X_i + a_0$$

When all variables are standardized, the importance of a feature can be associated with the absolute value of the coefficients $$ \mid a_i \mid $$. Higher values of the coefficient correspond to a higher influence of the feature on the target variable.

# Plotting of the linear regression coefficients

So we start up iPython and load the necessary packages. We will use the diabets data set from sklearn:

```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.preprocessing import scale

# Load and standardize the diabetes dataset
diabetes = datasets.load_diabetes()
X = scale(diabetes.data)
y = diabetes.target
y = (y-np.mean(y))*1.0/np.std(y)
```

Afterwards we fit a linear regression model on the features and plot the values of the coefficients for the 10 features.

```python
# Create and train the linear regression object
regr = linear_model.LinearRegression()
regr.fit(X, y)

# Plot the coefficients
plt.figure(figsize=[10,10])
plt.bar(np.arange(len(regr.coef_))-0.5, regr.coef_, color=["blue"]*10)
plt.xlim([-1,10])
plt.xlabel("Feature", fontsize=16)
plt.ylabel("Coefficient", fontsize=16)
plt.show()
```
This results in the following figure:

![Coefficients of the linear regression model ]({{ site.img_path }}/add_permuted_features_1.png){:rel="nofollow"}

From this plot, I would assume that feature 1 - due to its low coefficient - does not have a linear correlation to the target and is therefore not of importance in the linear regression model. However, those values seem somehow arbitrary, I am not able to compare them to some kind of baseline coefficient.

### Plotting of the linear regression coefficients with randomly permuted features

Now we add 10 new features $$ X_{11}, \ldots, X_{20}$$ that are randomly permuted versions of the existing features to your model. We train our linear regression model again und plot the 20 coefficients:

```python
# Shuffle each column independently
Xp = X.copy()
np.random.seed(42)
for i in range(Xp.shape[1]):
    np.random.shuffle(Xp[:,i])

# Add permuted features
X_ext = np.c_[ X, Xp]

# Create and train the linear regression object
regr_ext = linear_model.LinearRegression()
regr_ext.fit(X_ext, y)

# Plot the coefficients
plt.figure(figsize=[10,10])
plt.bar(np.arange(len(regr_ext.coef_))-0.5, regr_ext.coef_, color=["blue"]*10+["red"]*10)
plt.xlim([-1,20])
plt.xlabel("Feature", fontsize=16)
plt.ylabel("Coefficient", fontsize=16)
plt.show()
```
This results in the following plot:

![The Coefficients of the linear model with permuted features]({{ site.img_path }}/add_permuted_features_2.png){:rel="nofollow"}

The red bars denote the coefficients of the randomly permuted features. They are statistically independent from the target and state a baseline influence niveau.
In such a situation, all features that have a lower absolute coefficient value than the maximum of the permuted versions should be examined critically.
Here, on a first sight features, 3, 5, 6 and 9 can be considered as (possibly) significant because the absolute value of their importance is higher than the randomly permuted versions.

# Boruta algorithm is based on this principle

The Boruta feature selection algorithm is based on this principle of adding permuted versions of the original features to a model [^2]. It repeatedly trains random forests on both original and permuted features. Afterwards it compares how often the randomized and original features were selected.  When the permuted versions were selected too often, the Boruta algorithm assumes the respective feature to be unimportant.

# Conclusion

During prototyping and proof-of-concept type projects, especially when it is not clear how much evidence is contained in the data and resulting features I always add permuted versions of the original features.
This helps to address both overfitting and uncertainty of individual feature significances.

-----
[^1]: See the introduction of *"Pattern recognition and machine learning"* by Christopher M. Bishop

[^2]: See the paper *"Boruta – A System for Feature Selection."*  by Miron B. Kursa, Aleksander Jankowski , Witold R. Rudnicki or the Scikit-learn compatible [python implementation](https://github.com/danielhomola/boruta_py){:rel="nofollow"} by Daniel Homola

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Text;
using System.IO;
using System.Reflection.Emit;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis.Emit;

namespace RoslynTest46
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //private Assembly dynamicAssembly;
        private AppDomain otherDomain;

        public MainWindow()
        {
            Microsoft.CodeAnalysis.CSharp.Scrip
            InitializeComponent();
            otherDomain = AppDomain.CreateDomain("Other");
            otherDomain.DefineDynamicAssembly(new AssemblyName("Fiddle.dll"), AssemblyBuilderAccess.RunAndCollect);
            otherDomain.AssemblyLoad += Executor.CurrentDomain_AssemblyLoad;
        }

        ~MainWindow()
        {
            AppDomain.Unload(otherDomain);
        }

        private static readonly Guid assemblyGuid = Guid.NewGuid();

        private void button_Click(object sender, RoutedEventArgs e)
        {
            otherDomain.DoCallBack(Executor.ExecuteNew);
        }
    }

    [Serializable]
    public class Executor : MarshalByRefObject
    {
        public override object InitializeLifetimeService()
        {
            return null;
        }

        public static void ExecuteNew()
        {
            new Executor().Execute();
        }

        public static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
        {
            if (args.L)
        }

        public void Execute()
        {
            Assembly fiddle = null;
            using (var scriptFile = File.Open(Path.Combine(Environment.CurrentDirectory, @"Scripts\test.cs"), FileMode.Open, FileAccess.Read,
                FileShare.ReadWrite))
            {
                var text = SourceText.From(scriptFile);

                var assemblyLocations = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
                                        {
                                            typeof(Object).Assembly.Location,
                                            typeof(Debug).Assembly.Location
                                        };
                var newAssemblyName = "Fiddle.dll";
                var assemblyName = new AssemblyName(newAssemblyName);
                var moduleName = "FiddleModule";
                try
                {
                    var syntaxTree = SyntaxFactory.ParseSyntaxTree(text);
                    var compilation = CSharpCompilation.Create(assemblyName.Name)
                                                       .AddReferences(assemblyLocations.Select(a => MetadataReference.CreateFromFile(a)))
                                                       .AddSyntaxTrees(syntaxTree)
                                                       .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

                    EmitResult result;
                    using (var compilationStream = new MemoryStream())
                    using (var debugStream = new MemoryStream())
                    {
                        result = compilation.Emit(compilationStream, debugStream);

                        if (result.Success)
                        {
                            fiddle = Assembly.Load(compilationStream.GetBuffer(), debugStream.GetBuffer());
                        }
                    }
                    if (!result.Success)
                    {
                        foreach (var diagnostic in result.Diagnostics)
                        {
                            Debug.WriteLine(diagnostic.ToString());
                        }
                        MessageBox.Show("Failed to compile fiddle: \r\n"
                                        + String.Join(Environment.NewLine + "\t", result.Diagnostics.Select(d => d.ToString())));
                    }
                    else if (fiddle != null)
                        fiddle.GetType("System.Fiddle").GetMethod("Execute").Invoke(null, null);
                }
                finally { }
            }
        }
    }
}


text:
clouds模块(https://github.com/leizongmin/clouds )的可选控制器

## 安装

```bash
$ npm install clouds-controller --save
```

## 使用

### 1、配置`clouds`客户端

```javascript
var clouds = require('clouds');
var cloudsController = require('clouds-controller');

var client = new clouds.Client({
  // 配置clouds-controller的connection
  connection: cloudsController.createConnection({
    port: 6480,
    host: '127.0.0.1'
  }),
  // 调用超时时间,如果服务器超过指定时间没有响应结果,则认为调用失败,单位:秒
  timeout: 2
});

var server = new clouds.Server({
  // 配置clouds-controller的connection
  connection: cloudsController.createConnection({
    port: 6480,
    host: '127.0.0.1'
  }),
  // 心跳周期,如果服务器端异常下线,超过指定时间将自动从服务器端删除,单位:秒
  heartbeat: 2
});
```

主要是在初始化客户端时传递一个`connection`参数来指定`clouds-controller`的连接,详细使用方法可参考`clouds`模块的文档。

### 2、启动`clouds-controller`服务器

可以编写以下代码来启动:

```javascript
var cloudsController = require('clouds-controller');

var server = cloudsController.createServer();
server.listen(6480, '127.0.0.1');
```

也可以通过安装`clouds-controller`命令来启动:

```bash
$ npm install clouds-controller -g
```

```bash
$ clouds-controller -h 127.0.0.1 -p 6480
```

## Coverage

```bash
$ ./run_coverage
```

91% coverage, 442 SLOC

## Tests

```bash
$ ./run_test
```

## License

```
The MIT License (MIT)

Copyright (c) 2015 Zongmin Lei <leizongmin@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```


text:
//////////////////////////////////////////////////////////////////////////////////
//  Managed UPnP
//	Written by Aaron Lee Murgatroyd (http://home.exetel.com.au/amurgshere/)
//	A CodePlex project (http://managedupnp.codeplex.com/)
//  Released under the Microsoft Public License (Ms-PL) .
//////////////////////////////////////////////////////////////////////////////////

#if !Exclude_Descriptions || !Exclude_CodeGen

using System;
using System.Text;
using System.Xml;

namespace ManagedUPnP.Descriptions
{
    /// <summary>
    /// Encapsulates the description for a list of allowed values.
    /// </summary>
    public class AllowedValuesDescription : DescriptionList<string>
    {
        #region Protected Constants

        /// <summary>
        /// Gets the element name for the allowed value list description.
        /// </summary>
        protected const string msElement = "allowedValueList";

        #endregion

        #region Public Static Methods

        /// <summary>
        /// Gets whether the current node for a reader marks the start of this description.
        /// </summary>
        /// <param name="reader">The XML text reader.</param>
        /// <returns>True or false.</returns>
        public static bool IsStartNodeFor(XmlTextReader reader)
        {
            return (reader.NodeType == XmlNodeType.Element && reader.Name == msElement);
        }

        /// <summary>
        /// Gets whether the current node for a reader marks the end of this description.
        /// </summary>
        /// <param name="reader">The XML text reader.</param>
        /// <returns>True or false.</returns>
        public static bool IsEndNodeFor(XmlTextReader reader)
        {
            return (reader.NodeType == XmlNodeType.EndElement && reader.Name == msElement);
        }

        #endregion

        #region Initialisation

        /// <summary>
        /// Creates a new allowed values description.
        /// </summary>
        public AllowedValuesDescription(Description parent)
            : base(parent)
        {
        }

        /// <summary>
        /// Creates a new allowed values description from a reader.
        /// </summary>
        /// <param name="parent">The parent description object, or null if root description.</param>
        /// <param name="reader">The XML reader to get the values from.</param>
        public AllowedValuesDescription(Description parent, XmlTextReader reader)
            : base(parent, reader)
        {
        }

        #endregion

        #region Protected Methods

        /// <summary>
        /// Uses an XML node for this description.
        /// </summary>
        /// <param name="reader">The XML reader to use the node from.</param>
        /// <param name="lastNodeName">The last node name.</param>
        /// <returns>True if the node was processed false otherwise.</returns>
        [UsesProperty("allowedValue")]
        protected override bool UseNode(XmlTextReader reader, string lastNodeName)
        {
            if (lastNodeName == "allowedValue")
            {
                if (reader.NodeType == XmlNodeType.Text)
                    mlList.Add(reader.Value);

                return true;
            }

            return false;
        }

        /// <summary>
        /// Gets whether the current node for a reader marks the start of this description.
        /// </summary>
        /// <param name="reader">The XML text reader.</param>
        /// <returns>True or false.</returns>
        protected override bool IsEndNode(XmlTextReader reader)
        {
            return IsEndNodeFor(reader);
        }

        /// <summary>
        /// Gets whether the current node for a reader marks the start of this description.
        /// </summary>
        /// <param name="reader">The XML text reader.</param>
        /// <returns>True or false.</returns>
        protected override bool IsStartNode(XmlTextReader reader)
        {
            return IsStartNodeFor(reader);
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Converts the description to a string.
        /// </summary>
        /// <param name="indent">The indent for the string.</param>
        /// <returns>The string representation for the description.</returns>
        public override string ToString(int indent)
        {
            if (this.Count > 0)
            {
                string lsIndent = Indent(indent);
                StringBuilder lsbBuilder = new StringBuilder();

                lsbBuilder.Append(lsIndent);
                lsbBuilder.Append("(Allowed:");

                bool lbFirst = true;
                foreach (String lsItem in this)
                {
                    if (!lbFirst) lsbBuilder.Append(", ");
                    lbFirst = false;

                    lsbBuilder.Append("'");
                    lsbBuilder.Append(lsItem.ToString());
                    lsbBuilder.Append("'");
                }

                lsbBuilder.Append(")");

                lsbBuilder.Append(base.ToString(indent).LineBefore());

                return lsbBuilder.ToString();
            }
            else
                return String.Empty;
        }

        #endregion
    }
}

#endif


text:
package com.eagerlogic.entitydb;

import java.util.Iterator;
import java.util.TreeMap;

/**
 *
 * @author dipacs
 */
final class DbFileStructure implements Iterable<DbFileStructure.Piece> {

	public static class Piece {

		private final long offset;
		private final long length;

		public Piece(long start, long length) {
			this.offset = start;
			this.length = length;
		}
	}
	private final TreeMap<Long, Piece> pieces = new TreeMap<>();
	private final long headerSize;

	DbFileStructure(long headerSize) {
		this.headerSize = headerSize;
	}

	public void addPiece(long offset, long length) {
		pieces.put(offset, new Piece(offset, length));
	}

	public void removePiece(long offset) {
		if (pieces.remove(offset) == null) {
			throw new RuntimeException("Internal error. Can't find piece with offset: " + offset);
		}
	}

	public Piece getPiece(long offset) {
		return pieces.get(offset);
	}

	public long[] getEmptySpace(long size) {
		long lastFreeByte = headerSize;
		long prevOffset = -1;
		long nextOffset = -1;
		for (Piece piece : pieces.values()) {
			if (piece.offset - lastFreeByte >= size) {
				nextOffset = piece.offset;
				break;
			}
			prevOffset = piece.offset;
			lastFreeByte = piece.offset + piece.length;
		}
		return new long[]{prevOffset, lastFreeByte, nextOffset};
	}

	public long[] getPieceSurround(long offset) {
		long prevOffset = -1;
		long exactOffset = -1;
		long nextOffset = -1;
		for (Piece piece : pieces.values()) {
			if (piece.offset < offset) {
				prevOffset = piece.offset;
			} else if (piece.offset > offset) {
				nextOffset = piece.offset;
				break;
			} else {
				exactOffset = piece.offset;
			}
		}

		if (exactOffset < 0) {
			throw new IllegalArgumentException("No piece can be found with the given offset: " + offset);
		}
		return new long[] {prevOffset, exactOffset, nextOffset};
	}

	public Iterator<Piece> iterator() {
		return pieces.values().iterator();
	}
}


text: export { default } from 'shared/mixins/store-tweaks';


text:
HeartCode
=========

Proposed Stack:
---------------

* NodeJS
* Express
* React
* SuperAgent
* LazyJS
*

Process:
--------

TDD

September 22nd: Proposals

Coding with love


text:
package advent.twelve;

public class JsonNumber implements JsonElement {

	@Override
	public JsonType getJsonType() {
		return JsonType.NUMBER;
	}

	public JsonNumber(long number) {
		this.number = number;
	}

	private final Long number;

	public Long getNumber() {
		return number;
	}

	@Override
	public String toString() {
		return number.toString();
	}
}


text:
import Controller from '@ember/controller';

/**
 * Defines the class for datasets/dataset/tab route controller
 * Provides access to application objects like the BannerService instance
 * to templates and components lower in the hierarchy
 * @export
 * @class DatasetTab
 * @extends {Controller}
 */
export default class DatasetTab extends Controller {
  /**
   * TODO META-10613: Create a util for extending controller/query param logic for bulk jit request
   * Defines the query parameters meaningful to this route
   */
  queryParams = ['request_jit_urns'];

  /**
   * A list of dataset urns to request for JIT ACL Access provided as a query param
   * The query param renders the request-access modal if there are urns provided
   * @type {Array<string>}
   */
  request_jit_urns: Array<string> = [];
}

declare module '@ember/controller' {
  // eslint-disable-next-line @typescript-eslint/interface-name-prefix
  interface Registry {
    'datasets/dataset/tab': DatasetTab;
  }
}


text:
function InventoryHostsStrings (BaseString) {
    BaseString.call(this, 'inventory-hosts');

    let t = this.t;
    let ns = this['inventory-hosts'];

    ns.deletegroup = {
        GROUP: count => t.p(count, 'group', 'groups'),
        HOST: count => t.p(count, 'host', 'hosts'),
        PROMOTE_GROUPS_AND_HOSTS: data => t.s('Promote {{ group }} and {{ host }}', {
            group: this.get('deletegroup.GROUP', data.groups),
            host: this.get('deletegroup.HOST', data.hosts)
        }),
        DELETE_GROUPS_AND_HOSTS: data => t.s('Delete {{ group }} and {{ host }}', {
            group: this.get('deletegroup.GROUP', data.groups),
            host: this.get('deletegroup.HOST', data.hosts)
        }),
        PROMOTE_GROUP: count => t.p(count, 'Promote group', 'Promote groups'),
        DELETE_GROUP: count => t.p(count, 'Delete group', 'Delete groups'),
        PROMOTE_HOST: count => t.p(count, 'Promote host', 'Promote hosts'),
        DELETE_HOST: count => t.p(count, 'Delete host', 'Delete hosts'),
    };

    ns.inventory = {
        EDIT_HOST: t.s('Edit host'),
        VIEW_HOST: t.s('View host'),
        VIEW_INSIGHTS: t.s('View Insights Data')
    };

    ns.hostList = {
        DISABLED_TOGGLE_TOOLTIP: () => t.s('{{ str1 }}

{{ str2 }}
', {
            str1: t.s('Indicates if a host is available and should be included in running jobs.'),
            str2: t.s('For hosts that are part of an external inventory, this may be reset by the inventory sync process.')
        })
    };

    ns.smartinventories = {
        hostfilter: {
            MISSING_ORG: t.s('Please select an organization before editing the host filter.'),
            INSTRUCTIONS: t.s('Please click the icon to edit the host filter.'),
            MISSING_PERMISSIONS: t.s('You do not have sufficient permissions to edit the host filter.'),
            OPEN: t.s('Open host filter')
        }
    };

    ns.smartinventorybutton = {
        DISABLED_INSTRUCTIONS: t.s("Please enter at least one search term to create a new Smart Inventory."),
        ENABLED_INSTRUCTIONS: t.s("Create a new Smart Inventory from search results.

Note: changing the organization of the Smart Inventory could change the hosts included in the Smart Inventory.")
    };

    ns.insights = {
        VIEW: t.s("View Insights")
    };
}

InventoryHostsStrings.$inject = ['BaseStringService'];

export default InventoryHostsStrings;


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="{{$setting['site_description']}}"/>
    <meta name="keywords" content="{{$setting['searchengine_keywords']}}" />
    <meta property="og:image" content="@yield('page_image')" />
    <meta property="og:description" content="@yield('page_description')" />
    <meta property="og:title" content="@yield('title')" />
    <link rel="stylesheet" href="{{ asset('/vendor/bishopm/css/bootstrap.css')}}">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin=""/>

    @yield('css')
    <title>@yield('title_prefix', $setting['site_name']) | @yield('title')</title>

      {!!$setting['site_logo']!!}
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

      </button>

        {!!$webmenu!!}

          @if(Auth::check())

                @if (Auth::user()->individual)
                  {{Auth::user()->individual->firstname}}
                @else
                  {{Auth::user()->name}}
                @endif

                @if (Auth::user()->can('view-backend'))
                   Backend
                @endif
                @if (Auth::user()->individual)
                  individual->slug}}"> My user profile
                @endif
                 My {{$setting['site_abbreviation'] or 'church'}}
                @if (Auth::user()->individual)
                   My details
                   User forum
                @endif
                @if (Auth::user()->can('view-worship'))
                   Worship
                @endif

                 Log Out
                <form id="logout-form" action="{{url('/')}}/logout" method="POST" style="display: none;"><input type="hidden" name="_token" value="{{csrf_token()}}"></form>

          @else

               Login / Register

          @endif

    @if ((isset($slideshow)) and ($slideshow->slideshow=="back"))
      @include('connexion::shared.carousel-back')
    @elseif ((isset($slideshow)) and ($slideshow->slideshow=="front"))
      @include('connexion::shared.errors')
      @include('connexion::shared.carousel-front')
    @endif
    @yield('content')

    @include('connexion::shared.login-modal')

      @foreach ($webfooter as $kk=>$wf)

{{$kk}}

            @foreach ($wf as $wi)

{!!$wi!!}

            @endforeach

      @endforeach

         {{$setting['church_phone']}} |  {{ HTML::mailto($setting['church_email']) }}

        {{$setting['church_address']}} |

        Service times: {{$setting['service_times'] ?? ''}}

@yield('js')
@include('connexion::shared.analytics')


text:
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace Iced.Intel {
	/// <summary>
	/// Extension methods
	/// </summary>
	public static class MnemonicUtils {
		/// <summary>
		/// Gets the mnemonic
		/// </summary>
		/// <param name="code">Code value</param>
		/// <returns></returns>
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Mnemonic Mnemonic(this Code code) {
			Debug.Assert((uint)code < (uint)MnemonicUtilsData.toMnemonic.Length);
			return (Mnemonic)MnemonicUtilsData.toMnemonic[(int)code];
		}
	}
}


text:
package system

import (
	"bufio"
	"bytes"
	"fmt"
	"runtime"

	"github.com/shirou/gopsutil/host"
	"github.com/shirou/gopsutil/load"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/plugins/inputs"
)

type SystemStats struct{}

func (_ *SystemStats) Description() string {
	return "Read metrics about system load & uptime"
}

func (_ *SystemStats) SampleConfig() string { return "" }

func (_ *SystemStats) Gather(acc telegraf.Accumulator) error {
	loadavg, err := load.Avg()
	if err != nil {
		return err
	}

	hostinfo, err := host.Info()
	if err != nil {
		return err
	}

	users, err := host.Users()
	if err != nil {
		return err
	}

	fields := map[string]interface{}{
		"load1":         loadavg.Load1,
		"load5":         loadavg.Load5,
		"load15":        loadavg.Load15,
		"uptime":        hostinfo.Uptime,
		"n_users":       len(users),
		"uptime_format": format_uptime(hostinfo.Uptime),
		"n_cpus":        runtime.NumCPU(),
	}
	acc.AddFields("system", fields, nil)

	return nil
}

func format_uptime(uptime uint64) string {
	buf := new(bytes.Buffer)
	w := bufio.NewWriter(buf)

	days := uptime / (60 * 60 * 24)

	if days != 0 {
		s := ""
		if days > 1 {
			s = "s"
		}
		fmt.Fprintf(w, "%d day%s, ", days, s)
	}

	minutes := uptime / 60
	hours := minutes / 60
	hours %= 24
	minutes %= 60

	fmt.Fprintf(w, "%2d:%02d", hours, minutes)

	w.Flush()
	return buf.String()
}

func init() {
	inputs.Add("system", func() telegraf.Input {
		return &SystemStats{}
	})
}


text:
using System;
using System.Collections.Generic;
using Umbraco.Core.Models;
using Umbraco.Web;
using System.Web;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using ConcreteContentTypes.Core.Models;
using ConcreteContentTypes.Core.Interfaces;
using Newtonsoft.Json;

using RJP.MultiUrlPicker.Models;
using System;
using GlobalManifesto.Products.Models.Media;
using Umbraco.Examine.Linq.Attributes;
using ConcreteContentTypes.Core.Extensions;

namespace GlobalManifesto.Products.Models.Content
{
	 [NodeTypeAlias("RelatedLinksBlock")]
 	public partial class RelatedLinksBlock : BlockBase
	{
		public override string ContentTypeAlias { get { return "RelatedLinksBlock"; } }

		[Field("relatedLinks")]
		public MultiUrls RelatedLinks { get; set; }

		[Field("title")]
		public string Title { get; set; }

		private IEnumerable<IPublishedContent> _children = null;
		[JsonIgnore]
		public IEnumerable<IPublishedContent> Children
		{
			get
			{
				if (_children == null && this.Content != null)
					_children = this.Content.Children;

				return _children;
			}
		}

		public RelatedLinksBlock()
			: base()
		{
		}

		public RelatedLinksBlock(string name, IConcreteModel parent)
			: this(name, parent.Id)
		{
		}

		public RelatedLinksBlock(string name, int parentId)
			: base()
		{
			this.Name = name;
			this.ParentId = parentId;
		}

		public RelatedLinksBlock(int contentId, bool getPropertiesRecursively = false)
			: base(contentId, getPropertiesRecursively)
		{
		}

		public RelatedLinksBlock(IPublishedContent content, bool getPropertiesRecursively = false)
			: base(content, getPropertiesRecursively)
		{
		}

		public override void Init(IPublishedContent content)
		{
			base.Init(content);

			this.RelatedLinks = Content.GetPropertyValue<MultiUrls>("relatedLinks", this.GetPropertiesRecursively);

			this.Title = Content.GetPropertyValue<string>("title", this.GetPropertiesRecursively);

		}

	}
}


text:
#include "SDL_config.h"

/* An implementation of mutexes using semaphores */

#include "SDL_thread.h"
#include "SDL_systhread_c.h"

#include <arch/spinlock.h>

struct SDL_mutex {
	int recursive;
	Uint32 owner;
	spinlock_t mutex;
};

/* Create a mutex */
SDL_mutex *SDL_CreateMutex(void)
{
	SDL_mutex *mutex;

	/* Allocate mutex memory */
	mutex = (SDL_mutex *)SDL_malloc(sizeof(*mutex));
	if ( mutex ) {
		spinlock_init(&mutex->mutex);
		mutex->recursive = 0;
		mutex->owner = 0;
	} else {
		SDL_OutOfMemory();
	}
	return mutex;
}

/* Free the mutex */
void SDL_DestroyMutex(SDL_mutex *mutex)
{
	if ( mutex ) {
		SDL_free(mutex);
	}
}

/* Lock the semaphore */
int SDL_mutexP(SDL_mutex *mutex)
{
#if SDL_THREADS_DISABLED
	return  SDL_arraysize(return ),0;
#else
	Uint32 this_thread;

	if ( mutex == NULL ) {
		SDL_SetError("Passed a NULL mutex");
		return -1;
	}

	this_thread = SDL_ThreadID();
	if ( mutex->owner == this_thread ) {
		++mutex->recursive;
	} else {
		/* The order of operations is important.
		   We set the locking thread id after we obtain the lock
		   so unlocks from other threads will fail.
		*/
		spinlock_lock(&mutex->mutex);
		mutex->owner = this_thread;
		mutex->recursive = 0;
	}

	return 0;
#endif /* SDL_THREADS_DISABLED */
}

/* Unlock the mutex */
int SDL_mutexV(SDL_mutex *mutex)
{
#if SDL_THREADS_DISABLED
	return 0;
#else
	if ( mutex == NULL ) {
		SDL_SetError("Passed a NULL mutex");
		return -1;
	}

	/* If we don't own the mutex, we can't unlock it */
	if ( SDL_ThreadID() != mutex->owner ) {
		SDL_SetError("mutex not owned by this thread");
		return -1;
	}

	if ( mutex->recursive ) {
		--mutex->recursive;
	} else {
		/* The order of operations is important.
		   First reset the owner so another thread doesn't lock
		   the mutex and set the ownership before we reset it,
		   then release the lock semaphore.
		 */
		mutex->owner = 0;
		spinlock_unlock(&mutex->mutex);
	}
	return 0;
#endif /* SDL_THREADS_DISABLED */
}


text:
package jelectrum;
import java.io.File;

public class FreeSpaceWatcher extends Thread
{
  File location;
  Jelectrum jelly;
  long min_space;

  public FreeSpaceWatcher(File location, Jelectrum jelly, long min_space)
  {
    setName("FreeSpaceWatcher@" + location);
    setDaemon(true);

    this.location = location;
    this.jelly = jelly;
    this.min_space = min_space;

  }

  public void run()
  {
    while(true)
    {
      try
      {
        long space = location.getUsableSpace();
        if (space < min_space)
        {
          jelly.getEventLog().alarm("FreeSpaceWacher: low on space in " + location);
          System.exit(10);

        }
        sleep(20000);

      }
      catch(Throwable t)
      {
        jelly.getEventLog().alarm("FreeSpaceWacher: " + t);
        t.printStackTrace();
      }

    }

  }
}


text:
using System;
using System.Collections.Concurrent;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core.Models;
using Umbraco.Core;
using Umbraco.Web.Security;

namespace Umbraco.Web.Mvc
{

    /// <summary>
    /// The base controller that all Presentation Add-in controllers should inherit from
    /// </summary>
    [MergeModelStateToChildAction]
    [MergeParentContextViewData]
    public abstract class SurfaceController : PluginController
    {

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="umbracoContext"></param>
        protected SurfaceController(UmbracoContext umbracoContext)
            : base(umbracoContext)
        {
            _membershipHelper = new MembershipHelper(umbracoContext);
        }

        /// <summary>
        /// Empty constructor, uses Singleton to resolve the UmbracoContext
        /// </summary>
        protected SurfaceController()
            : base(UmbracoContext.Current)
        {
            _membershipHelper = new MembershipHelper(UmbracoContext.Current);
        }

        private readonly MembershipHelper _membershipHelper;

        /// <summary>
        /// Returns the MemberHelper instance
        /// </summary>
        public MembershipHelper Members
        {
            get { return _membershipHelper; }
        }

        /// <summary>
        /// Redirects to the Umbraco page with the given id
        /// </summary>
        /// <param name="pageId"></param>
        /// <returns></returns>
        protected RedirectToUmbracoPageResult RedirectToUmbracoPage(int pageId)
        {
            return new RedirectToUmbracoPageResult(pageId, UmbracoContext);
        }

        /// <summary>
        /// Redirects to the Umbraco page with the given id
        /// </summary>
        /// <param name="publishedContent"></param>
        /// <returns></returns>
        protected RedirectToUmbracoPageResult RedirectToUmbracoPage(IPublishedContent publishedContent)
        {
            return new RedirectToUmbracoPageResult(publishedContent, UmbracoContext);
        }

        /// <summary>
        /// Redirects to the currently rendered Umbraco page
        /// </summary>
        /// <returns></returns>
        protected RedirectToUmbracoPageResult RedirectToCurrentUmbracoPage()
        {
            return new RedirectToUmbracoPageResult(CurrentPage, UmbracoContext);
        }

        /// <summary>
        /// Redirects to the currently rendered Umbraco URL
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// this is useful if you need to redirect
        /// to the current page but the current page is actually a rewritten URL normally done with something like
        /// Server.Transfer.
        /// </remarks>
        protected RedirectToUmbracoUrlResult RedirectToCurrentUmbracoUrl()
        {
            return new RedirectToUmbracoUrlResult(UmbracoContext);
        }

        /// <summary>
        /// Returns the currently rendered Umbraco page
        /// </summary>
        /// <returns></returns>
        protected UmbracoPageResult CurrentUmbracoPage()
        {
            return new UmbracoPageResult();
        }

        /// <summary>
        /// Gets the current page.
        /// </summary>
        protected IPublishedContent CurrentPage
        {
            get
            {
			    var routeDefAttempt = TryGetRouteDefinitionFromAncestorViewContexts();
                if (!routeDefAttempt.Success)
                {
                    throw routeDefAttempt.Exception;
                }

			    var routeDef = routeDefAttempt.Result;
                return routeDef.PublishedContentRequest.PublishedContent;
            }
        }

        /// <summary>
        /// we need to recursively find the route definition based on the parent view context
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// We may have Child Actions within Child actions so we need to recursively look this up.
        /// see: http://issues.umbraco.org/issue/U4-1844
        /// </remarks>
        private Attempt<RouteDefinition> TryGetRouteDefinitionFromAncestorViewContexts()
        {
            ControllerContext currentContext = ControllerContext;
            while (currentContext != null)
            {
                var currentRouteData = currentContext.RouteData;
                if (currentRouteData.DataTokens.ContainsKey("umbraco-route-def"))
                {
                    return Attempt.Succeed((RouteDefinition) currentRouteData.DataTokens["umbraco-route-def"]);
                }
                if (currentContext.IsChildAction)
                {
                    //assign current context to parent
                    currentContext = currentContext.ParentActionViewContext;
                }
                else
                {
                    //exit the loop
                    currentContext = null;
                }
            }
            return Attempt<RouteDefinition>.Fail(
                new InvalidOperationException("Cannot find the Umbraco route definition in the route values, the request must be made in the context of an Umbraco request"));
        }

    }
}


text:
> https://leetcode.com/problems/detect-capital/description/

Given a word, you need to judge whether the usage of capitals in it is right or not.

We define the usage of capitals in a word to be right when one of the following cases holds:

- All letters in this word are capitals, like "USA".
- All letters in this word are not capitals, like "leetcode".
- Only the first letter in this word is capital if it has more than one letter, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Example 1:
```
Input: "USA"
Output: True
```
Example 2:
```
Input: "FlaG"
Output: False
```
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.

- 判断一个字符串是不是正确地使用了大写字母
- 下面是正确地使用的情况
  - 第一个大写字母,后面的都是小写
  - 全部是大写
  - 全部是小写
- 解析上面的规则就是:
  - 长度0或者1的字符串肯定是的
  - 第一个字母不能比第二个字母小
  - 从第二个字母开始,所有字母必须一样

```go
func isLowwer(r rune) bool {
	return r >= 97 && r <= 122
}

func detectCapitalUse(word string) bool {
	if len(word) == 0 || len(word) == 1 {
		return true
	}

	f := isLowwer(rune(word[1]))

	if isLowwer(rune(word[0])) && !isLowwer(rune(word[1])) {
		return false
	}

	for k, v := range word {
		if k == 0 {
			continue
		}
		if isLowwer(v) != f {
			return false
		}
	}

	return true
}
```


text:
title: Find More Than the First Match
localeTitle: Encontre mais do que o primeiro jogo
---
## Encontre mais do que o primeiro jogo

Se você tiver várias ocorrências de sua regex dentro de uma string, você pode obter a função `match()` para detectar todas elas. Simplesmente marque a bandeira `g` no final do seu regex! Isso é o que você está fazendo neste desafio.

## Sugestão 1:

Altere o regex para que ele detecte a palavra "twinkle".

## Dica 2:

Você pode adicionar várias tags a uma regex! Por exemplo, um regex que detecta várias ocorrências e detecta, independentemente do caso, pode ser estruturado como `gi` ou `ig` .

## Alerta de Spoiler - Solução à frente!

## Solução

```javascript
let twinkleStar = "Twinkle, twinkle, little star";
 let starRegex = /twinkle/gi;
 let result = twinkleStar.match(starRegex);

```


text:
<?php
$engine_cfg = GetEngineConfig();

//CreateTopic("Тестовый топик");
?>

					<? Draw(Markup("social_sidebar")); ?>

Обсуждения

										<?php
										if(true /*$engine_cfg['logged']*/)
										{
											Draw("

");
										}
										?>

Создание темы

										<input id='new_topic_name' placeholder='Название темы (обязательно)' maxlength='50' value='' class='text_input big_input inner_center n_back3' style='width: 98%;'/>

										<textarea id='new_topic_text' class='text_input n_back3' placeholder='Текст сообщения' maxlength='20480' style='display: block; width: 98%; height: 100px;'></textarea>

Создать

								<?

								$topics = array();

								$query = SQL("SELECT * FROM `topics` WHERE `status`='0' AND `pinned` = '1' ORDER BY `rating` DESC");

								while($row = SQLFetchAssoc($query))
								{
									$topics[sizeof($topics)] = GetTopic($row['id'], $row);
								}

								$query = SQL("SELECT * FROM `topics` WHERE `status`='0' AND `pinned` = '0' ORDER BY `edited` DESC");

								while($row = SQLFetchAssoc($query))
								{
									$topics[sizeof($topics)] = GetTopic($row['id'], $row);
								}

								//

								if(sizeof($topics) > 0)
								{
									Draw("
Темы ".sizeof($topics)."
");

									Draw(GetTopicsMarkup($topics));
								}
								else
								{
									Draw("

Пока нет тем

									");
								}

								?>

	<?php Draw(Markup("big_footer_markup"));?>


text:
<?php

namespace Symfony\Component\Validator\Util;

use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * @internal to be removed in Symfony 5.0.
 */
class LegacyTranslatorProxy implements LegacyTranslatorInterface, TranslatorInterface
{
    private $translator;

    public function __construct(TranslatorInterface $translator)
    {
        if (!$translator instanceof LocaleAwareInterface) {
            throw new \InvalidArgumentException(sprintf('The translator passed to "%s()" must implement "%s".', __METHOD__, LocaleAwareInterface::class));
        }
        $this->translator = $translator;
    }

    public function getTranslator(): TranslatorInterface
    {
        return $this->translator;
    }

    /**
     * {@inheritdoc}
     */
    public function setLocale($locale)
    {
        $this->translator->setLocale($locale);
    }

    /**
     * {@inheritdoc}
     */
    public function getLocale()
    {
        return $this->translator->getLocale();
    }

    /**
     * {@inheritdoc}
     */
    public function trans($id, array $parameters = [], $domain = null, $locale = null)
    {
        return $this->translator->trans($id, $parameters, $domain, $locale);
    }

    /**
     * {@inheritdoc}
     */
    public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null)
    {
        return $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale);
    }
}


text:
"""Django's command-line utility for administrative tasks."""
import os
import sys

example_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(example_dir, '..'))

def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)

if __name__ == '__main__':
    main()


text:
module.exports = OpenResolutionSyntax;

var ResolutionSyntax = require('./resolutionSyntax'),
    inherits = require('../../util/inherits');

inherits(OpenResolutionSyntax, ResolutionSyntax);

var MultipleResolutionSyntax = require('./multipleResolutionSyntax'),
    LazyResolutionSyntax = require('./lazyResolutionSyntax');

function OpenResolutionSyntax(scope, params) {
    ResolutionSyntax.call(this, scope, params);
}

OpenResolutionSyntax.prototype.multiple = function () {
    this._params.multiple = true;
    return new MultipleResolutionSyntax(this._scope, this._params);
};

OpenResolutionSyntax.prototype.lazy = function () {
    this._params.lazy = true;
    return new LazyResolutionSyntax(this._scope, this._params);
};


text:
static constexpr float sq(float var) { return var * var; }

// converts Tait-Bryan 312 sequence of rotations from frame 1 to frame 2
// to the corresponding rotation matrix that rotates from frame 2 to frame 1
// rot312(0) - First rotation is a RH rotation about the Z axis (rad)
// rot312(1) - Second rotation is a RH rotation about the X axis (rad)
// rot312(2) - Third rotation is a RH rotation about the Y axis (rad)
// See http://www.atacolorado.com/eulersequences.doc
matrix::Dcmf taitBryan312ToRotMat(const matrix::Vector3f &rot312);

// Use Kahan summation algorithm to get the sum of "sum_previous" and "input".
// This function relies on the caller to be responsible for keeping a copy of
// "accumulator" and passing this value at the next iteration.
// Ref: https://en.wikipedia.org/wiki/Kahan_summation_algorithm
float kahanSummation(float sum_previous, float input, float &accumulator);

// calculate the inverse rotation matrix from a quaternion rotation
// this produces the inverse rotation to that produced by the math library quaternion to Dcmf operator
matrix::Dcmf quatToInverseRotMat(const matrix::Quatf &quat);

// We should use a 3-2-1 Tait-Bryan (yaw-pitch-roll) rotation sequence
// when there is more roll than pitch tilt and a 3-1-2 rotation sequence
// when there is more pitch than roll tilt to avoid gimbal lock.
bool shouldUse321RotationSequence(const matrix::Dcmf& R);

float getEuler321Yaw(const matrix::Quatf& q);
float getEuler321Yaw(const matrix::Dcmf& R);

float getEuler312Yaw(const matrix::Quatf& q);
float getEuler312Yaw(const matrix::Dcmf& R);

matrix::Dcmf updateEuler321YawInRotMat(float yaw, const matrix::Dcmf& rot_in);
matrix::Dcmf updateEuler312YawInRotMat(float yaw, const matrix::Dcmf& rot_in);

// Checks which euler rotation sequence to use and update yaw in rotation matrix
matrix::Dcmf updateYawInRotMat(float yaw, const matrix::Dcmf& rot_in);

namespace ecl{
	inline float powf(float x, int exp)
	{
		float ret;
		if (exp > 0) {
			ret = x;
			for (int count = 1; count < exp; count++) {
				ret *= x;
			}
			return ret;
		} else if (exp < 0) {
			return 1.0f / ecl::powf(x, -exp);
		}
		return 1.0f;
	}
}


text:
When /^I visit the gem page for "([^\"]*)"$/ do |gem_name|
  rubygem = Rubygem.find_by_name!(gem_name)
  visit rubygem_path(rubygem)
end

When /^I visit the gem page for "([^\"]*)" version "([^\"]*)"$/ do |gem_name, version_number|
  rubygem = Rubygem.find_by_name!(gem_name)
  visit rubygem_version_path(rubygem, version_number)
end

And /^I save and open the page$/ do
  save_and_open_page
end


text:
/*global $,angular*/
(function (angular) {
    'use strict';

    angular.module('panel-view-app', [])
        .directive('nbPanelView', ['$compile', '$animate', '$rootScope', '$timeout', function ($compile, $animate, $rootScope, $timeout) {
            var defaultHtml,
                viewList = [],
                newviewTemplate = '<ng-include class="PH_SRC-view" src="\'../partials/PH_SRC.html\'" />';

            return {
                restrict: 'AE',
                link: function (scope, element, attrs) {
                    scope.$watch(attrs.viewName, function (newView, oldView) {
                        function triggerViewChangeEvent() {
                            // 100 ms to allow DOM to render view
                            $timeout(function () {
                                $rootScope.$broadcast("view-changed", {displayed: newView, hidden: oldView});
                            }, 100);
                        }

                        if (newView === '') {
                            // cleanup all views
                            if (defaultHtml) {
                                element.html(defaultHtml);
                            } else {
                                defaultHtml = element.html();
                                element.empty();
                            }
                            viewList.length = 0;
                        } else if (newView && viewList.indexOf(newView) === -1) {
                            // first time loading
                            if (!viewList.length) {
                                // no view loaded
                                defaultHtml = defaultHtml || element.html();
                                element.empty();
                            }
                            viewList.push(newView);
                            var viewHtml = newviewTemplate.replace(/PH_SRC/g, newView);
                            var viewNode = $compile(angular.element(viewHtml))(scope);
                            $animate.enter(viewNode, element);
                        }
                        // side bar item
                        $('li[select-view]').removeClass('active');
                        $('li[select-view="' + newView + '"]').addClass('active');

                        // show existing view
                        element.find('ng-include.' + newView + '-view').show();
                        // hide old view if exists any
                        element.find('ng-include.' + oldView + '-view').hide();
                        triggerViewChangeEvent();
                    });
                }
            };
        }]);

}(angular));


text:
define([
], function (
) {
    'use strict';

    /**
	 * Preloader is in charge of loading all the game assets
	 * @class
     * @memberof Jellyfish
	 * @param game {Phaser.Game} game instance
	**/
    function Preloader(game) {
        this.preloadBar = null;
    }

    Preloader.prototype =
	{
        /**
	     * Load all the game assets
	    **/
        preload: function () {

			this.loadError = false;

            this.preloadBar = this.add.sprite(this.game.world.centerX - 490, this.game.height / 2, 'preloaderBar');
            this.load.setPreloadSprite(this.preloadBar);

            this.loadSpecificAssets();
            this.loadSharedAssets();
        },

        /**
         * Load game specific assets
         **/
        loadSpecificAssets: function () {
            if (!this.game.gameConfig.gameId) {
                //##console.error("Game Id equals " + this.game.gameConfig.gameId + ". No loading will be possible");
            }
            //Game specific Graphics
            this.load.image('background', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/background.png');

            this.game.load.atlasJSONHash('hole', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/hole/hole.png', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/hole/hole.json');
            this.game.load.atlasJSONHash('crab', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/crab/crab.png', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/crab/crab.json');

            //Game specific UI Graphics
            //##console.log('minigames/' + this.game.gameConfig.gameId + '/assets/images/ui/ScoreSuccess_TapeCrabe.png');
            this.load.image('uiScoreWrong', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/ui/ScoreWrong_TapeCrabe.png');
            this.load.image('uiScoreRight', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/ui/ScoreSuccess_TapeCrabe.png');
            this.load.image('uiScoreEmpty', 'minigames/' + this.game.gameConfig.gameId + '/assets/images/ui/ScoreEmpty_TapeCrabe.png');

            //Game Specific Audio
            var temp;
            for (var i = 0; i < 13 ; i++) {
                if ((i + 1) >= 10) temp = i +1;
                else temp = "0" + (i + 1);
                this.game.load.audio('rdm' + temp, 'minigames/' + this.game.gameConfig.gameId + '/assets/audio/sfx/ELAN_GAME_CRAB_Rdm_' + temp + '.ogg');
            }

            //Kalulu Game Specific audio
            this.game.load.audio('kaluluIntro', 'minigames/' + this.game.gameConfig.gameId + '/assets/audio/kalulu/kalulu_intro_' + this.game.gameConfig.gameId + '_' + this.game.rafiki.discipline + '.ogg');
            this.game.load.audio('kaluluHelp', 'minigames/' + this.game.gameConfig.gameId + '/assets/audio/kalulu/kalulu_help_' + this.game.gameConfig.gameId + '_' + this.game.rafiki.discipline + '.ogg');
            this.game.load.audio('kaluluGameOverWin', 'minigames/' + this.game.gameConfig.gameId + '/assets/audio/kalulu/kalulu_end_' + this.game.gameConfig.gameId + '_' + this.game.rafiki.discipline + '.ogg');
        },

        /**
         * Load all assets in sharedAssets
         **/
        loadSharedAssets: function () {

            //UI
            this.game.load.atlasJSONHash('ui', 'minigames/common/assets/images/ui/ui.png', 'minigames/common/assets/images/ui/ui.json');

            //FX
            this.game.load.atlasJSONHash('fx', 'minigames/common/assets/images/fx/fx.png', 'minigames/common/assets/images/fx/fx.json');
            this.load.image('wrong', 'minigames/common/assets/images/fx/wrong.png');

            var animPath = 'minigames/common/assets/images/kalulu_animations/';

            //KaluluGraphics
            this.game.load.atlasJSONHash('kaluluIntro'    , animPath + 'kaluluIntro.png', animPath + 'kaluluIntro.json');
            this.game.load.atlasJSONHash('kaluluOutro'    , animPath + 'kaluluOutro.png', animPath + 'kaluluOutro.json');
            this.game.load.atlasJSONHash('kaluluIdle1'    , animPath + 'kaluluIdle1.png', animPath + 'kaluluIdle1.json');
            this.game.load.atlasJSONHash('kaluluIdle2'    , animPath + 'kaluluIdle2.png', animPath + 'kaluluIdle2.json');
            this.game.load.atlasJSONHash('kaluluSpeaking1', animPath + 'kaluluSpeaking1.png', animPath + 'kaluluSpeaking1.json');
            this.game.load.atlasJSONHash('kaluluSpeaking2', animPath + 'kaluluSpeaking2.png', animPath + 'kaluluSpeaking2.json');

            var sfxPath = 'minigames/common/assets/audio/sfx/';

			this.game.load.onFileError.add(this.onFileError);

            //General Audio
            this.game.load.audio('menuNo'            , sfxPath + 'ButtonCancel.ogg');
            this.game.load.audio('menuYes'           , sfxPath + 'ButtonOK.ogg');

            this.game.load.audio('winGame'           , sfxPath + 'GameOverWin.ogg');
            this.game.load.audio('loseGame'          , sfxPath + 'GameOverLose.ogg');

            this.game.load.audio('kaluluOn'          , sfxPath + 'KaluluOn.ogg');
            this.game.load.audio('kaluluOff'         , sfxPath + 'KaluluOff.ogg');

            this.game.load.audio('menu'              , sfxPath + 'OpenPopin.ogg');

            this.game.load.audio('right'             , sfxPath + 'ResponseCorrect.ogg');
            this.game.load.audio('wrong'             , sfxPath + 'ResponseIncorrect.ogg');

            this.game.load.audio('kaluluGameOverLose', 'minigames/common/assets/audio/kalulu/kalulu_lose_minigame.ogg');
        },

		/**
		 * File loading error handler.
		 *
		 **/
		onFileError: function (fileKey, file) {
			this.loadError = true;
			//##console.log("onFileError called. Will restart preload");
		},

        /**
         * Starts next state: Preload or Setup whether Preload failed or not.
         * @private
         **/
        create: function () {

			this.game.load.onFileError.removeAll();

			//call next state, used to load the pedagogic data for a first game.
			if(this.loadError)
				this.state.start('Preload');
			else
				this.state.start('Setup');
        }
    };

    return Preloader;
});


text:
package org.opengis.cite.iso19139;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opengis.cite.iso19139.ETSAssert;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

@Ignore
public class VerifyETSAssert {

    private static final String WADL_NS = "http://wadl.dev.java.net/2009/02";
    private static DocumentBuilder docBuilder;
    private static SchemaFactory factory;
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    public VerifyETSAssert() {
    }

    @BeforeClass
    public static void setUpClass() throws ParserConfigurationException {
        factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        docBuilder = dbf.newDocumentBuilder();
    }

    @Test
    public void validateUsingSchemaHints_expect2Errors() throws SAXException {
        thrown.expect(AssertionError.class);
        thrown.expectMessage("2 schema validation error(s) detected");
        URL url = this.getClass().getResource("/Gamma.xml");
        Schema schema = factory.newSchema();
        Validator validator = schema.newValidator();
        ETSAssert
                .assertSchemaValid(validator, new StreamSource(url.toString()));
    }

    @Test
    public void assertXPathWithNamespaceBindings() throws SAXException,
            IOException {
        Document doc = docBuilder.parse(this.getClass().getResourceAsStream(
                "/capabilities-simple.xml"));
        Map<String, String> nsBindings = new HashMap<String, String>();
        nsBindings.put(WADL_NS, "ns1");
        String xpath = "//ns1:resources";
        ETSAssert.assertXPath(xpath, doc, nsBindings);
    }

    @Test
    public void assertXPath_expectFalse() throws SAXException, IOException {
        thrown.expect(AssertionError.class);
        thrown.expectMessage("Unexpected result evaluating XPath expression");
        Document doc = docBuilder.parse(this.getClass().getResourceAsStream(
                "/capabilities-simple.xml"));
        // using built-in namespace binding
        String xpath = "//ows:OperationsMetadata/ows:Constraint[@name='XMLEncoding']/ows:DefaultValue = 'TRUE'";
        ETSAssert.assertXPath(xpath, doc, null);
    }
}


text:
package com.opengamma.financial.comparison;

import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

import org.testng.annotations.Test;

import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.test.TestGroup;

/**
 * Test.
 */
@Test(groups = TestGroup.UNIT)
public class SecurityInfoTest extends AbstractTest {

  public void testRawSecurity() {
    final AbstractComparator comparator = new AbstractComparator(OpenGammaFudgeContext.getInstance()) {
    };
    final ComparisonContext context = comparator.createContext();
    final SecurityInfo raw1 = new SecurityInfo(context, createRawSecurity("Foo", 42));
    final SecurityInfo raw2 = new SecurityInfo(context, createRawSecurity("Foo", 0));
    final SecurityInfo raw3 = new SecurityInfo(context, createRawSecurity("Bar", 42));
    final SecurityInfo raw4 = new SecurityInfo(context, createRawSecurity("Foo", 42));
    assertTrue(raw1.equals(raw4));
    assertTrue(raw4.equals(raw1));
    assertFalse(raw1.equals(raw2));
    assertFalse(raw1.equals(raw3));
    assertFalse(raw2.equals(raw1));
    assertFalse(raw2.equals(raw3));
    assertFalse(raw3.equals(raw1));
    assertFalse(raw3.equals(raw2));
  }

}


text:
Naive Bayes
===========

This learning algorithm creates a `Naive Bayes`_ graph structure in which a single class variable points to all other variables. The probability tables are filled out using Expectation Maximization.

.. _`Naive Bayes`: https://dslpitt.org/genie/wiki/Reference_Manual:_DSL_bs

.. image:: https://raw.githubusercontent.com/sisl/Smile.jl/master/doc/naive_bayes.png

Parameters
----------

**classVariableId**: the variable id corresponding to the class variable

.. code-block:: julia

	LearnParams_NaiveBayes() = new("class")
	LearnParams_NaiveBayes(var::AbstractString) = new(var)

Examples
--------

.. code-block:: julia

	net = Network()
	learn!( net, dset, LearnParams_NaiveBayes())


text:
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Http;

namespace OAuth.AspNet.AuthServer
{

    /// <summary>
    /// Provides context information used when granting an OAuth refresh token.
    /// </summary>
    public class OAuthGrantRefreshTokenContext : BaseValidatingTicketContext<OAuthAuthorizationServerOptions>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthGrantRefreshTokenContext"/> class
        /// </summary>
        /// <param name="context"></param>
        /// <param name="options"></param>
        /// <param name="ticket"></param>
        /// <param name="clientId"></param>
        public OAuthGrantRefreshTokenContext(HttpContext context, OAuthAuthorizationServerOptions options, AuthenticationTicket ticket, string clientId) : base(context, options, ticket)
        {
            ClientId = clientId;
        }

        /// <summary>
        /// The OAuth client id.
        /// </summary>
        public string ClientId { get; private set; }
    }

}


text:
// ///////////////////////////////////////////////////////////////////////////////////////////
//  Description:     TagOption class.
//  Author:          Ben Moore
//  Created date:    21/08/2015
//  Copyright:       Donky Networks Ltd 2015
// ///////////////////////////////////////////////////////////////////////////////////////////

namespace Donky.Core.Services.Registration
{
	internal class TagOption
	{
		public string Value { get; set; }

		public bool IsSelected { get; set; }
	}
}


text:
<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "branch_lot".
 *
 * @property string $id
 * @property string $branch_id
 * @property string $lot_id
 *
 * @property Branch $branch
 * @property Lot $lot
 */
class BranchLot extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'branch_lot';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['branch_id', 'lot_id'], 'required'],
            [['branch_id', 'lot_id'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'branch_id' => 'Branch ID',
            'lot_id' => 'Lot ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBranch()
    {
        return $this->hasOne(Branch::className(), ['id' => 'branch_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLot()
    {
        return $this->hasOne(Lot::className(), ['id' => 'lot_id']);
    }
}


text:
package com.google.zxing.datamatrix.decoder;

/**
 *
Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into
 * multiple blocks, each of which is a unit of data and error-correction codewords. Each
 * is represented by an instance of this class.

 *
 * @author bbrown@google.com (Brian Brown)
 */
final class DataBlock {

  private final int numDataCodewords;
  private final byte[] codewords;

  private DataBlock(int numDataCodewords, byte[] codewords) {
    this.numDataCodewords = numDataCodewords;
    this.codewords = codewords;
  }

  /**
   *
When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them.
   * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This
   * method will separate the data into original blocks.

   *
   * @param rawCodewords bytes as read directly from the Data Matrix Code
   * @param version version of the Data Matrix Code
   * @return {@link DataBlock}s containing original bytes, "de-interleaved" from representation in the
   *         Data Matrix Code
   */
  static DataBlock[] getDataBlocks(byte[] rawCodewords,
                                   Version version) {
    // Figure out the number and size of data blocks used by this version
    Version.ECBlocks ecBlocks = version.getECBlocks();

    // First count the total number of data blocks
    int totalBlocks = 0;
    Version.ECB[] ecBlockArray = ecBlocks.getECBlocks();
    for (int i = 0; i < ecBlockArray.length; i++) {
      totalBlocks += ecBlockArray[i].getCount();
    }

    // Now establish DataBlocks of the appropriate size and number of data codewords
    DataBlock[] result = new DataBlock[totalBlocks];
    int numResultBlocks = 0;
    for (int j = 0; j < ecBlockArray.length; j++) {
      Version.ECB ecBlock = ecBlockArray[j];
      for (int i = 0; i < ecBlock.getCount(); i++) {
        int numDataCodewords = ecBlock.getDataCodewords();
        int numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords;
        result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]);
      }
    }

    // All blocks have the same amount of data, except that the last n
    // (where n may be 0) have 1 less byte. Figure out where these start.
    // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144
    int longerBlocksTotalCodewords = result[0].codewords.length;
    //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1;

    int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords();
    int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1;
    // The last elements of result may be 1 element shorter for 144 matrix
    // first fill out as many elements as all of them have minus 1
    int rawCodewordsOffset = 0;
    for (int i = 0; i < shorterBlocksNumDataCodewords; i++) {
      for (int j = 0; j < numResultBlocks; j++) {
        result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
      }
    }

    // Fill out the last data block in the longer ones
    boolean specialVersion = version.getVersionNumber() == 24;
    int numLongerBlocks = specialVersion ? 8 : numResultBlocks;
    for (int j = 0; j < numLongerBlocks; j++) {
      result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++];
    }

    // Now add in error correction blocks
    int max = result[0].codewords.length;
    for (int i = longerBlocksNumDataCodewords; i < max; i++) {
      for (int j = 0; j < numResultBlocks; j++) {
        int iOffset = (specialVersion && j > 7) ? i - 1 : i;
        result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
      }
    }

    if (rawCodewordsOffset != rawCodewords.length) {
      throw new IllegalArgumentException();
    }

    return result;
  }

  int getNumDataCodewords() {
    return numDataCodewords;
  }

  byte[] getCodewords() {
    return codewords;
  }

}


text:
import {
  bootstrapDiagram,
  inject
} from 'test/TestHelper';

import { assign } from 'min-dash';

import { createCanvasEvent as canvasEvent } from '../../../util/MockEvents';

import dragModule from 'lib/features/dragging';
import hoverFixModule from 'lib/features/hover-fix';

describe('features/hover-fix', function() {

  describe('element-level hover fix', function() {

    beforeEach(bootstrapDiagram({ modules: [ hoverFixModule ] }));

    var shape1,
        shape2;

    beforeEach(inject(function(canvas, elementFactory) {

      shape1 = elementFactory.createShape({
        id: 'shape1',
        x: 10,
        y: 10,
        width: 50,
        height: 50
      });

      canvas.addShape(shape1);

      shape2 = elementFactory.createShape({
        id: 'shape2',
        x: 100,
        y: 10,
        width: 50,
        height: 50
      });

      canvas.addShape(shape2);

    }));

    it('should ensure the correct events are fired in sequence', inject(function(canvas, eventBus) {

      // given
      var events = [];

      eventBus.on([ 'element.hover', 'element.out' ], function(event) {
        events.push({ type: event.type, element: event.element });
      });

      eventBus.fire('element.hover', { element: shape1, gfx: canvas.getGraphics(shape1) });

      // assume
      expect(events).to.eql([ { type: 'element.hover', element: shape1 } ]);

      // when
      eventBus.fire('element.hover', { element: shape2, gfx: canvas.getGraphics(shape2) });

      // then
      expect(events).to.eql([
        { type: 'element.hover', element: shape1 },
        { type: 'element.out', element: shape1 },
        { type: 'element.hover', element: shape2 }
      ]);
    }));

    it('should not interfere with the normal hovering process', inject(function(canvas, eventBus) {

      // given
      var events = [];

      eventBus.on([ 'element.hover', 'element.out' ], function(event) {
        events.push({ type: event.type, element: event.element });
      });

      eventBus.fire('element.hover', { element: shape1, gfx: canvas.getGraphics(shape1) });

      // assume
      expect(events).to.eql([ { type: 'element.hover', element: shape1 } ]);

      // when
      eventBus.fire('element.out', { element: shape1, gfx: canvas.getGraphics(shape2) });
      eventBus.fire('element.hover', { element: shape2, gfx: canvas.getGraphics(shape2) });

      // then
      expect(events).to.eql([
        { type: 'element.hover', element: shape1 },
        { type: 'element.out', element: shape1 },
        { type: 'element.hover', element: shape2 }
      ]);
    }));

  });

  describe('dragging-level hover', function() {

    beforeEach(bootstrapDiagram({ modules: [ dragModule ] }));

    var shape1,
        shape2;

    beforeEach(inject(function(canvas, elementFactory) {

      shape1 = elementFactory.createShape({
        id: 'shape1',
        x: 10,
        y: 10,
        width: 50,
        height: 50
      });

      canvas.addShape(shape1);

      shape2 = elementFactory.createShape({
        id: 'shape2',
        x: 100,
        y: 10,
        width: 50,
        height: 50
      });

      canvas.addShape(shape2);

    }));

    describe('in fix', function() {

      beforeEach(inject(function(dragging) {
        dragging.setOptions({ manual: true });
      }));

      it('should ensure hover', inject(
        function(eventBus, dragging, hoverFix, elementRegistry) {

          // given
          var gfx = elementRegistry.getGraphics(shape1);

          var listener = sinon.spy(function(event) {
            expect(event.hover).to.eql(shape1);
            expect(event.hoverGfx).to.eql(gfx);
          });

          eventBus.on('drag.hover', listener);

          hoverFix._findTargetGfx = function(event) {
            return gfx;
          };

          // when
          dragging.init(canvasEvent({ x: 10, y: 10 }), 'foo');
          dragging.move(canvasEvent({ x: 30, y: 20 }));

          // then
          expect(listener).to.have.been.calledOnce;
        }
      ));

      it('should trigger hover and then move', inject(
        function(eventBus, dragging, hoverFix, elementRegistry) {

          // given
          var shape1_gfx = elementRegistry.getGraphics(shape1);

          var recordedEvents = [];

          eventBus.on([
            'foo.hover',
            'foo.move'
          ], function(event) {
            recordedEvents.push([ event.type, event.hover ]);
          });

          hoverFix._findTargetGfx = function(event) {
            return shape1_gfx;
          };

          // when
          dragging.init(canvasEvent({ x: 10, y: 10 }), 'foo');
          dragging.move(canvasEvent({ x: 30, y: 20 }));

          // then
          // first hover and then fake move
          expect(recordedEvents).to.eql([
            [ 'foo.hover', shape1 ],
            [ 'foo.move', shape1 ]
          ]);
        }
      ));

    });

    describe('out fix', function() {

      it('should ensure out', inject(function(dragging, canvas, eventBus) {

        // given
        var listener = sinon.spy(function(event) {
          expect(event.hover).to.eql(shape1);
          expect(event.hoverGfx).to.eql(canvas.getGraphics(shape1));
        });

        eventBus.on('drag.out', listener);

        // when
        dragging.init(canvasEvent({ x: 10, y: 10 }), 'foo');
        eventBus.fire('element.hover', { element: shape1, gfx: canvas.getGraphics(shape1) });

        // (no out)
        eventBus.fire('element.hover', { element: shape2, gfx: canvas.getGraphics(shape2) });

        // then
        expect(listener).to.have.been.calledOnce;
      }));

      it('should keep event order', inject(function(dragging, canvas, eventBus) {

        // given
        var eventNames = [
              'drag.hover',
              'drag.out'
            ],
            events = recordEvents(eventNames, eventBus);

        // when
        dragging.init(canvasEvent({ x: 10, y: 10 }), 'foo');
        eventBus.fire('element.hover', { element: shape1, gfx: canvas.getGraphics(shape1) });

        // (no out)
        eventBus.fire('element.hover', { element: shape2, gfx: canvas.getGraphics(shape2) });

        // then
        expect(events).to.eql([
          { type: 'drag.hover', hover: shape1 },
          { type: 'drag.out', hover: shape1 },
          { type: 'drag.hover', hover: shape2 }
        ]);
      }));

      it('should prevent additional out', inject(function(dragging, canvas, eventBus) {

        // given
        var listener = sinon.spy(function(event) {
          expect(event.hover).to.eql(shape1);
          expect(event.hoverGfx).to.eql(canvas.getGraphics(shape1));
        });

        eventBus.on('drag.out', listener);

        // when
        dragging.init(canvasEvent({ x: 10, y: 10 }), 'foo');
        eventBus.fire('element.hover', { element: shape1, gfx: canvas.getGraphics(shape1) });
        eventBus.fire('element.out', { element: shape1, gfx: canvas.getGraphics(shape1) });
        eventBus.fire('element.hover', { element: shape2, gfx: canvas.getGraphics(shape2) });

        // then
        expect(listener).to.have.been.calledOnce;
      }));

    });

  });

});

// helpers /////////////////////

function recordEvents(eventNames, eventBus) {

  var events = [];

  eventNames.forEach(function(eventName) {
    eventBus.on(eventName, function(e) {
      events.push(assign({}, {
        type: e.type,
        hover: e.hover
      }));
    });
  });

  return events;
}


text:
// Copyright 2015 Rocky Bernstein
/*==============================================================
  Debugger info('return')' command
  =============================================================*/
var util  = require('util'),
    columnize = require('../../columnize');

function Init(name, subcmd) {
    return {
	help: "**info('return')**\n\
\n\
Information about a stack frame. This command only makes sense\n\
when stopped at a return.\n\
\n\
See also:\n\
---------\n\
`info('frame')`, `info('args')`, `info('locals')`",
      connection: true,
      run: function(intf) {
	intf.pause();
	intf.client.reqFrame(function(err, frame) {
	  if (err) {
	    intf.error(err);
	    intf.resume(true);
	  } else if (!frame.atReturn) {
	    intf.error("Not stopped at a return");
	    intf.resume(true);
	  } else {
	    // console.log(frame);
	    var ref = frame.returnValue.ref;
	    intf.client.reqLookup([ref], function(err, res) {
	      if (err) {
		intf.error(err);
		intf.resume(true);
		return;
	      } else {
		intf.print('type: ' + res[ref].type);
		intf.print('value: ' + res[ref].text);
		intf.resume(true);
	      }
	    });
	  };
	}, 0);
      }
    }
}

exports.Init = Init;


text:
use warnings;
use strict;
use JSON;

use ElectricCommander;
use ElectricCommander::PropMod qw(/myProject/modules);
use WebSphere::WebSphere;
use WebSphere::Util;

$| = 1;

# -------------------------------------------------------------------------
# Variables
# -------------------------------------------------------------------------

my $opts = {
    configname                       => '$[configname]',
    messagingSystemType              => '$[messagingSystemType]',
    activationSpecScope              => '$[activationSpecScope]',
    activationSpecAdministrativeName => '$[activationSpecAdministrativeName]',
};

my $ec = ElectricCommander->new();
$ec->abortOnError(0);
my $websphere = WebSphere::WebSphere->new($ec, $opts->{configname}, '');

my $wasApi = '_ActivationSpec';
if ($opts->{messagingSystemType} eq 'WMQ') {
    $wasApi = 'WMQ' . $wasApi;
}
elsif ($opts->{messagingSystemType} eq 'SIB') {
    $wasApi = 'SIB' . $wasApi;
}
else {
    $websphere->bail_out("Wrong Messaging System Type. Expected one of 'SIB', 'WMQ'. Got:$opts->{messagingSystemType}");
}

my $parsedActivationSpecScope = $websphere->parseScope($opts->{activationSpecScope});
$websphere->setTemplateProperties(
    wasApi     => $wasApi,
    activationSpecScope => $parsedActivationSpecScope,
);

my $logger = $websphere->log();
my $file = 'delete_jms_activation_spec.py';
my $script = $ec->getProperty("/myProject/wsadmin_scripts/$file")->getNodeText('//value');
$file = $websphere->write_jython_script(
    $file, {},
    augment_filename_with_random_numbers => 1
);

my $shellcmd = $websphere->_create_runfile($file, ());
my $escaped_shellcmd = $websphere->_mask_password($shellcmd);
$logger->info('WSAdmin command line: ', $escaped_shellcmd);

$logger->debug("WSAdmin script:");
$logger->debug('' . $script);
$logger->debug("== End of WSAdmin script ==");
my %props = ();

$props{DeleteJMSActivationSpecLine} = $escaped_shellcmd;
my $cmd_res = `$shellcmd 2>&1`;
$logger->info($cmd_res);

my $code = $? >> 8;

my $result_params = {
    outcome => {
        target => 'myCall',
        result => '',
    },
    procedure => {
        target => 'myCall',
        msg => ''
    },
    pipeline => {
        target => 'Delete JMS ActivationSpec Result:',
        msg => '',
    }
};

# success
my $operation_mode = 'deleting';
$operation_mode = $1 if $cmd_res =~ m/Operation\smode:\s(.*?)$/ms;
if ($code == SUCCESS) {
    my $message = sprintf 'Successfully deleted %s: %s for %s scope',
        $wasApi,
        $opts->{activationSpecAdministrativeName},
        $parsedActivationSpecScope;

    if ($cmd_res =~ m/Status:\sOK,\sMessage:\s(.*?)$/ms) {
        $message = $1;
        $message .= " for $parsedActivationSpecScope scope";
    }
    $result_params->{outcome}->{result} = 'success';
    $result_params->{procedure}->{msg} = $result_params->{pipeline}->{msg} = $message;
}
else {
    my $error = $websphere->extractWebSphereExceptions($cmd_res);
    if ($error) {
        $error = "Error occured during $operation_mode of $wasApi $opts->{activationSpecAdministrativeName}:\n$error";
    }
    else {
        $error = "Unexpected error occured.";
    }
    $result_params->{outcome}->{result} = 'error';
    $result_params->{procedure}->{msg} = $result_params->{pipeline}->{msg} = $error;
}

my $exit = $websphere->setResult(%$result_params);

$exit->();


text:
Options will only apply to the relevant files, so you don't need separate targets for png/jpg.

## optimizationLevel *(png)*

Type: `Number`
Default: `3`

Select optimization level between `0` and `7`.

> The optimization level 0 enables a set of optimization operations that require minimal effort. There will be no changes to image attributes like bit depth or color type, and no recompression of existing IDAT datastreams. The optimization level 1 enables a single IDAT compression trial. The trial chosen is what. OptiPNG thinks it's probably the most effective. The optimization levels 2 and higher enable multiple IDAT compression trials; the higher the level, the more trials.

Level and trials:

1. 1 trial
2. 8 trials
3. 16 trials
4. 24 trials
5. 48 trials
6. 120 trials
7. 240 trials

## progressive *(jpg)*

Type: `Boolean`
Default: `true`

Lossless conversion to progressive.

## interlaced *(gif)*

Type: `Boolean`
Default: `true`

Interlace gif for progressive rendering.

##### svgoPlugins *(svg)*

Type: `array`
Default: `[]`

Customize which SVGO plugins to use. [More here](https://github.com/sindresorhus/grunt-svgmin#available-optionsplugins).

## use

Type: `Array`
Default: `null`

Additional [plugins](https://www.npmjs.com/browse/keyword/imageminplugin) to use with imagemin.


text:
var fs = require('fs-extra');
var rimraf = require("rimraf");
var copydir = require('copy-dir');
const { spawn } = require( 'child_process' );

var profiles = JSON.parse(fs.readFileSync('config/profiles.json', 'utf-8'));
var credentials = JSON.parse(fs.readFileSync('build/build.json', 'utf-8'));

for (let j = 2; j < process.argv.length; j++) {
	var profile = process.argv[j];
	console.log('Processing '+ profile);
	console.log('------------------------------------');
	if (!credentials[profile]) {
		console.log('credentials not found');
		continue;
	}
	console.log('remove previous folder');
	rimraf.sync('../../riciclo_running/'+profile);
	console.log('remove previous folder done');
	console.log('copy mobile folder');
	copydir.sync("../mobile", "../../riciclo_running/"+profile+'');
	console.log('copy mobile folder done');
	fs.copy("config/instances/"+profile+"/www", "../../riciclo_running/"+profile+"/www");
	console.log('copy www folder done');
	fs.copy("config/instances/"+profile+"/resources", "../../riciclo_running/"+profile+"/resources");
	console.log('copy config resources done');
	console.log('start build script');
	var ex = spawn('build_android.bat', [profile, credentials[profile].password, credentials[profile].alias]);
	ex.stdout.on('data', function (data) {
		console.log('stdout: ' + data);
	});
	ex.stderr.on( 'data', data => {
		console.log( `${profile} stderr: ${data}` );
	});
	ex.on( 'close', code => {
		console.log( `${profile} child process exited with code ${code}` );
	});
}


text:
#ifndef utils_hpp
#define utils_hpp

#include <string>
#include <vector>
#include <sstream>
#include <regex>

namespace ext
{
	/**
	 Checks if string starts with provided prefix

	 @param[in] str string to check
	 @param[in] prefix prefix to test at the beginning of the str
	 @return true if str starts with prefix
	 */
	bool starts_with(const std::string &s, const std::string &prefix, bool case_sensitive = false);
	/**
	 Checks if string ends with provided suffix

	 @param[in] str string to check
	 @param[in] suffix suffix to test at the end of the str
	 @return true if str ends with suffix
	 */
	bool ends_with(const std::string &s, const std::string &suffix, bool case_sensitive = false);
	/**
	 Shortcut for the string's find method

	 @param str container string
	 @param pattern pattern to test
	 @return true if pattern occured in str
	 */
	bool find(const std::string &s, const std::string &pattern);
	/**
	 Split text into tokens

	 @param text text to split
	 @param sep separator
	 @return tokens
	 */
	std::vector<std::string> split(const std::string &text, std::string sep);

	std::string remove_first(const std::string &s, const std::string &substring);

	std::string remove_last(const std::string &s, const std::string &substring);

	void ltrim(std::string &s);

	void rtrim(std::string &s);

	void trim(std::string &s);

	std::string ltrimmed(std::string s);

	std::string rtrimmed(std::string s);

	std::string trimmed(std::string s);

	namespace internal
	{
		template<typename T>
		inline void unpack(std::vector<std::string> &vbuf, T t)
		{
			std::stringstream buf { t };
			vbuf.push_back(buf.str());
		}
		template<typename T, typename ...Args>
		inline void unpack(std::vector<std::string> &vbuf, T t, Args &&... args)
		{
			std::stringstream buf { t };
			vbuf.push_back(buf.str());
			unpack(vbuf, std::forward<Args>(args)...);
		}
	}

	/**
	    Python-like string formatting
	 */
	template<typename ... Args>
	inline std::string format(const std::string &fmt, Args ... args)
	{
		std::vector<std::string> vbuf;  // store arguments as strings
		std::string in(fmt), out;    // unformatted and formatted strings
		std::regex re_arg("\\{\\b\\d+\\b\\}");  // search for {0}, {1}, ...
		std::regex re_idx("\\b\\d+\\b");        // search for 0, 1, ...
		std::smatch m_arg, m_idx;               // store matches
		size_t idx = 0;                         // index of argument inside {...}
		// Unpack arguments and store them in vbuf
		internal::unpack(vbuf, std::forward<Args>(args)...);

		// Replace all {x} with vbuf[x]
		while(std::regex_search(in, m_arg, re_arg)) {
			out += m_arg.prefix();

			if(std::regex_search(m_arg[0].str(), m_idx, re_idx)) {
				idx = std::stoi(m_idx[0].str());
			}

			if(idx < vbuf.size()) {
				out += std::regex_replace(m_arg[0].str(), re_arg, vbuf[idx]);
			}

			in = m_arg.suffix();
		}

		out += in;
		return out;
	}
}

#endif /* utils_hpp */


text:
import Ember from 'ember';

export default Ember.Route.extend({
  setupController(controller) {
    controller.setProperties({
      lat: 32.75494243654723,
      lng: -86.8359375,
      zoom: 5,

      circles: Ember.A([
        {
          id: 'klaj32-flka2-adkj2-39',
          lat: 32.85494243654723,
          lng: -86.7359375,
          radius: 145000,
          fillOpacity: '0.4',
          fillColor: '#D43029',
          strokeColor: '#D43029',
          draggable: true,
          editable: true,
          dragstart: function() {
            controller.set('isCircleDragging', true);
          },
          dragend: function() {
            controller.set('isCircleDragging', false);
          },
          center_changed: function(circle) {
            if(!circle) { return false; }
            controller.set('circles.[].0.lat', circle.center.lat());
            controller.set('circles.[].0.lng', circle.center.lng());
          },
          radius_changed: function(circle) {
            if(!circle) { return false; }
            controller.set('circles.[].0.radius', Math.round(circle.radius));
          },
          mouseup: function(e, circle) {
            const lat = circle.center.lat();
            const lng = circle.center.lng();
            controller.setProperties({
              lat, lng,
              'circles.[].0.lat': lat,
              'circles.[].0.lng': lng,
              'circles.[].0.radius': Math.round(circle.radius)
            });
          }
        }
      ]),

      isCircleDragging: false,

      circle: Ember.computed.oneWay('circles.[].0')
    });
  }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
    xmlns:cxf-core="http://cxf.apache.org/blueprint/core"
    xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd    http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schema/blueprint/jaxrs.xsd     http://cxf.apache.org/blueprint/core http://cxf.apache.org/schema/blueprint/core.xsd     http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <!-- OSGI blueprint property placeholder -->
    <cm:property-placeholder id="beosbank.placeholder"
        persistent-id="com.beosbank.esb.wsproxy.env.cfg" update-strategy="reload">
        <cm:default-properties>
            <cm:property name="vdb.url" value="http://localhost:8080/odata"/>
            <cm:property name="vdb.user" value="teiidUser"/>
            <cm:property name="vdb.password" value=""/>
            <cm:property name="proxy.httpBaseUrl" value=""/>
        </cm:default-properties>
    </cm:property-placeholder>
    <camelContext id="beosbank-vdb-wsproxy" xmlns="http://camel.apache.org/schema/blueprint">
        <route customId="true" id="vdb-proxy-route">
            <from id="_from1" uri="jetty://{{proxy.httpBaseUrl}}/{{proxy.uri}}?matchOnUriPrefix=true"/>
            <log id="_log1" message="Request received ${headers} body=${body}"/>
            <to id="_to1" uri="cxfrs:bean:vdbRestBackEndServer"/>
        </route>
    </camelContext>
    <!-- HTTP Endpoints-->
    <cxf:rsClient address="${vdb.url}" id="vdbRestBackEndServer" loggingFeatureEnabled="true"/>
    <!-- VDB Security Credentials -->
    <conduit name="*.http-conduit"
        xmlns="http://cxf.apache.org/transports/http/configuration" xmlns:sec="http://cxf.apache.org/configuration/security">
        <authorization>
            <sec:UserName>${vdb.user}</sec:UserName>
            <sec:Password>${vdb.password}</sec:Password>
            <sec:AuthorizationType>Basic</sec:AuthorizationType>
        </authorization>
    </conduit>
</blueprint>


text:
package com.learn.designpattern.proxy;

/**
 * 经理助理,代理总经理事务
 *
 * @author chenrg
 * @date 2017年5月5日
 */
public class Assistant implements IManager {

	private IManager generalManager = new GeneralManager();

	/**
	 * 助理在代理总经理处理事务时,记录执行日志
	 *
	 * @author chenrg
	 * @date 2017年5月5日
	 */
	private void recordMessage() {
		System.out.println("记录事务执行日志");
	}

	public void approveProject(String projectName) {
		recordMessage();
		generalManager.approveProject(projectName);
	}

	public void allocatingResource(String[] employees, String[] tasks) {
		recordMessage();
		generalManager.allocatingResource(employees, tasks);
	}

}


text:
from Population.Population import Population

class Evolution(object):
    """docstring for Evolution"""

    def __init__(self, problemMap, population, selector, crosser, mutator):
        self.problemMap = problemMap
        self.population = population
        self.selector = selector
        self.crosser = crosser
        self.mutator = mutator

    def evolve(self):
        childrenPopulation = self.crosser.applyCrossing(self.problemMap, self.population, self.population.size, self.mutator)
        # childrenPopulation = self.mutator.applyMutation(self.problemMap, childrenPopulation)
        sumPopulation = Population(2 * self.population.size, self.population.units + childrenPopulation.units)
        return self.selector.applySelection(sumPopulation, self.population.size)

    def make(self, iterations):
        """
        :param iterations:
        :return:
        """
        for i in range(iterations):
            # evolve one generation
            newPopulation = self.evolve()

            # change options
            #self.mutator.changeParams()
            #self.selector.changeParams()

            # print results
            print("\nGeneration {0}: ".format(i+1))
            for i in range(len(newPopulation.units)):
                unit = newPopulation.units[i]
                print("{0}: {1}".format(i, unit.fitness))

            self.population = newPopulation
            input('Press enter for next generation...')

        return self.population