text:
Drill code makes extensive use of logging to provide the developer with in-depth information about Drill's internals. The logging is vital when tracking down a problem, but a distraction at other times. To control logging, you must understand the various forms of logging and logging control.

## Logback Classic

Drill uses [Logback Classic](http://logback.qos.ch) as its logger. In production mode, you control logging via the `$DRILL_HOME/conf/logback.xml` (or, alternatively, `$DRILL_SITE/logback.xml`) file. This configuration is _not_ used when testing, however.

When running tests, either in Maven or your IDE, Drill uses a different configuration file: the one in the `src/test/resources` folder for the Maven subproject that holds the test. For example, if you run tests in the `drill-common` project, Logback will find the configuration in `common/src/test/resources/logback.xml`.

Configure logging in this test file. For example, to set the debug log level:
```
  <logger name="org.apache.drill" additivity="false">
    <level value="debug" />
```

Under Maven, each module has visibility to is own test resources, but not the test resources from any other Maven module. To control test logging, therefore, we must have a copy of `logback-test.xml` in the `src/test/resources` folder of each Maven module.

Sometimes it is helpful to verify which configuration file Logback actually uses. As explained in [this Stack Overflow post](http://stackoverflow.com/questions/18922730/how-can-i-determine-what-log-configuration-source-logback-actually-used), you can find this information using a Logback property:
```
mvn surefire:test -Dtest=TestClassPathScanner \
       -Dlogback.statusListenerClass=ch.qos.logback.core.status.OnConsoleStatusListener
```

## Test Logging with Maven

Maven output is controlled by [Maven's logging mechanism](https://maven.apache.org/maven-logging.html) which seems to be [SLF4J Simple](http://www.slf4j.org/apidocs/org/slf4j/impl/SimpleLogger.html).

To "quiet" the amount of Maven output, you must modify the logging configuration file in your Maven installation. (There seems to be no way to modify logging in the POM file itself.)

```
$ cd `dirname \`which mvn\``/../conf/logging
$ pwd # Should print /some/path/apache-maven-3.x.y/conf/logging
$ vi simplelogger.properties
```
The following suppresses all but the most of Maven's "info" logging:
```
#org.slf4j.simpleLogger.defaultLogLevel=info
org.slf4j.simpleLogger.defaultLogLevel=warn
...

# Custom entries
# Display check style issues (shown at info log level)
org.slf4j.simpleLogger.log.org.apache.maven.plugin.checkstyle=info
```

Since the `maven-checkstyle-plugin` displays its errors to the log at the INFO log level, we have to allow it to display info-level messages (the last line in the example.)

Since this is a Maven configuration (not a POM file change), you must make it on each machine on which you run Maven.

As noted above, logging within Drill tests is controlled by Logback, not Maven.

## Logback Test Logging in Eclipse

[Logback](http://logback.qos.ch) really prefers to find a single `logback.xml` configuration file on the class path. There seems to be a subtle difference in how Eclipse and Maven build the class path used to run tests. Eclipse includes the test resources from all dependencies, whereas Surefire does not. This means that, if you run a test in `exec/java-exec`, such as `TestClassPathScanner`, the test resources from `common` will be on the class path if run from Eclipse, but not run from Surefire.

For the most part, having extra items on the class path in Eclipse is benign. Problems occur, however, when files of the same name appears multiple time on the class path. This is the situation with Logback.

When run under Maven Surefire, each project requires its own `logback.xml` (or, preferably `logback-test.xml`) in `src/test/resources`.

But, when run under Eclipse, the test program sees all the Logback config files on the path, causing Logback to print a bunch of log messages:

```
...WARN in ch.qos.logback.classic.LoggerContext[default] -
     Resource [logback.xml] occurs multiple times on the classpath.
...WARN in ch.qos.logback.classic.LoggerContext[default] -
     Resource [logback.xml] occurs at [file:/path/to/drill/exec/java-exec/target/test-classes/logback.xml]
...WARN in ch.qos.logback.classic.LoggerContext[default] -
     Resource [logback.xml] occurs at [file:/path/to/drill/common/target/test-classes/logback.xml]
```

To see this, add the following to any test from `java-exec`, such as `TestClassPathScanner`:
```
    System.out.println( "Class path: " + System.getProperty("java.class.path") );
```

When run in Eclipse:
```
Class path: /path/to/drill/exec/java-exec/target/test-classes:\
/path/to/drill/exec/java-exec/target/classes:...\
/path/to/drill/common/target/test-classes:...\
...INFO in ch.qos.logback.classic.LoggerContext[default] - \
Found resource [logback.xml] at [file:/path/to/drill/common/target/test-classes/logback.xml]
```
But, when run under Maven:
```
Class path: /path/to/drill/exec/java-exec/target/test-classes:\
/path/to/drill/exec/java-exec/target/classes:...\
/Users/me/.m2/repository/org/apache/drill/drill-common/1.9.0-SNAPSHOT/drill-common-1.9.0-SNAPSHOT.jar:...
...INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.xml]
```

The Eclipse behavior seems to be both [known and unlikely to change](http://stackoverflow.com/a/15723127).

Based on the [Logback Configuration](http://logback.qos.ch/manual/configuration.html) documentation, the solution seems to be to apply a "No-op" logger by default. In Eclipse -> Preferences -> Java -> Installed JREs, select your default JRE or JDK. Click Edit... Add the following as one of the Default VM arguments:
```
-Dlogback.statusListenerClass=ch.qos.logback.core.status.NopStatusListener
```
(Since this is a system property, it will be passed to every run or debug session. No harm if you happen to use a project that does not use Logback, the property will just be ignored by everything else.)

Then, if for some reason you want to see the Logback logging, add the following to your debug launch configuration:
```
-Dlogback.statusListenerClass=ch.qos.logback.core.status.OnConsoleStatusListener
```
The launch configuration option overrides (appears on the Java command line after) the global setting.

## Test Logging Configurations

### Default Test Log Levels

There is a global `logback-test.xml` configuration file in [common/src/test/resources/logback-test.xml](../../common/src/test/resources/logback-test.xml). This
logging configuration by default outputs error level logs to stdout.

Debug level logging to lilith can be turned on by adding `-Ddrill.lilith.enable=true` to the command used to run tests.

### Changing Test Log Levels

Often times it is most convenient to output logs to the console for debugging. This is best done programatically
by using the [LogFixture](../../exec/java-exec/src/test/java/org/apache/drill/test/LogFixture.java). The [LogFixture](../../exec/java-exec/src/test/java/org/apache/drill/test/LogFixture.java)
allows temporarily changing log levels for blocks of code programatically for debugging. An example of doing this is
the following.

```
    try(LogFixture logFixture = new LogFixture.LogFixtureBuilder()
      .logger(MyClass.class, Level.INFO)
      .toConsole() // This redirects output to stdout
      .build()) {
      // Code block with different log levels.
    }
```

More details on how to use the [LogFixture](../../exec/java-exec/src/test/java/org/apache/drill/test/LogFixture.java) can be found
int the javadocs for the class. Additionally, there are several methods that allow printing of query results to the console for debugging:

 * BaseTestQuery.printResult
 * QueryTestUtil.testRunAndPrint
 * QueryBuilder.print
 * ClusterTest.runAndPrint
 * ClientFixture.runQueriesAndPrint

**IMPORTANT NOTE:** The methods described above along with LogFixtureBuilder.toConsole() should only be used for debugging. Code
that uses these methods should not be committed, since it produces excess logging on our build servers.


text:
<!--
Description: iTunes channel keywords
Expect:      not bozo and feed['tags'][0]['term'] == 'Technology' and 'itunes_keywords' not in feed
-->
<rss xmlns:itunes="http://www.itunes.com/DTDs/Podcast-1.0.dtd">
<channel>
<itunes:keywords>Technology</itunes:keywords>
</channel>
</rss>

redpajama_set_name: RedPajamaGithub


text:
package org.assertj.core.api.charsequence;

import static org.assertj.core.util.Lists.newArrayList;
import static org.mockito.Mockito.verify;

import java.util.List;

import org.assertj.core.api.CharSequenceAssert;
import org.assertj.core.api.CharSequenceAssertBaseTest;
import org.junit.jupiter.api.BeforeAll;

/**
 * Tests for <code>{@link CharSequenceAssert#hasSameSizeAs(Iterable)}</code>.
 *
 * @author Nicolas François
 */
class CharSequenceAssert_hasSameSizeAs_with_Iterable_Test extends CharSequenceAssertBaseTest {

  private static List<String> other;

  @BeforeAll
  static void setUpOnce() {
    other = newArrayList("Luke");
  }

  @Override
  protected CharSequenceAssert invoke_api_method() {
    return assertions.hasSameSizeAs(other);
  }

  @Override
  protected void verify_internal_effects() {
    verify(strings).assertHasSameSizeAs(getInfo(assertions), getActual(assertions), other);
  }
}


text:
package api

import (
	"net/http/httptest"
	"testing"

	"github.com/ovh/cds/engine/api/application"
	"github.com/ovh/cds/engine/api/keys"
	"github.com/ovh/cds/engine/api/test/assets"
	"github.com/ovh/cds/sdk"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func Test_getApplicationExportHandler(t *testing.T) {
	api, db, _ := newTestAPI(t)

	u, pass := assets.InsertAdminUser(t, db)
	proj := assets.InsertTestProject(t, db, api.Cache, sdk.RandomString(10), sdk.RandomString(10))
	require.NotNil(t, proj)
	appName := sdk.RandomString(10)
	app := &sdk.Application{
		Name: appName,
	}
	require.NoError(t, application.Insert(db, *proj, app))

	v1 := sdk.ApplicationVariable{
		Name:  "var1",
		Value: "value 1",
		Type:  sdk.StringVariable,
	}

	require.NoError(t, application.InsertVariable(db, app.ID, &v1, u))

	v2 := sdk.ApplicationVariable{
		Name:  "var2",
		Value: "value 2",
		Type:  sdk.SecretVariable,
	}

	require.NoError(t, application.InsertVariable(db, app.ID, &v2, u))

	//Insert ssh and gpg keys
	k := &sdk.ApplicationKey{
		Name:          "mykey",
		Type:          sdk.KeyTypePGP,
		ApplicationID: app.ID,
	}
	kk, err := keys.GeneratePGPKeyPair(k.Name)
	require.NoError(t, err)

	k.Public = kk.Public
	k.Private = kk.Private
	k.KeyID = kk.KeyID
	require.NoError(t, application.InsertKey(db, k))

	k2 := &sdk.ApplicationKey{
		Name:          "mykey-ssh",
		Type:          sdk.KeyTypeSSH,
		ApplicationID: app.ID,
	}
	kssh, err := keys.GenerateSSHKey(k2.Name)
	require.NoError(t, err)

	k2.Public = kssh.Public
	k2.Private = kssh.Private
	k2.KeyID = kssh.KeyID
	require.NoError(t, application.InsertKey(db, k2))

	//Prepare request
	vars := map[string]string{
		"permProjectKey":  proj.Key,
		"applicationName": app.Name,
	}
	uri := api.Router.GetRoute("GET", api.getApplicationExportHandler, vars)
	require.NotEmpty(t, uri)
	req := assets.NewAuthentifiedRequest(t, u, pass, "GET", uri, nil)

	//Do the request
	rec := httptest.NewRecorder()
	api.Router.Mux.ServeHTTP(rec, req)
	assert.Equal(t, 200, rec.Code)

	//Check result
	t.Logf(">>%s", rec.Body.String())
}


text:
@interface SearchViewController ()<UISearchBarDelegate>
{
    NSString *_serachBarText;
    UISearchBar *_searchBar;
}
@end

@implementation SearchViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
}
- (void)viewWillDisappear:(BOOL)animated {
//    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    //视图消失前,,放弃第一响应
    [_searchBar resignFirstResponder];
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSearchBar];
    [self createBtn];
}
- (void)createSearchBar {
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    _searchBar.placeholder = @"请输入你想要的宝贝";
    _searchBar.delegate = self;
    //[_searchBar becomeFirstResponder];
    self.navigationItem.titleView = _searchBar;

    //设置rightItem
    NSMutableDictionary *textAttribute = [[NSMutableDictionary alloc]init];
    textAttribute[NSFontAttributeName] = [UIFont systemFontOfSize:14];
    textAttribute[NSForegroundColorAttributeName] = [UIColor blackColor];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:textAttribute forState:UIControlStateNormal];
}

#pragma mark -- rightItemClick
- (void)rightItemClick {

}

- (void)createBtn {
    CGSize size = self.view.frame.size;
    int i = 0;
    for (categaryModel *model  in _dataArr) {
        UIButton *button = [[UIButton alloc]init];
        button.frame = CGRectMake(10+(size.width/4)*(i%4), 64+(int)50 * (i / 4), 0, 0);
        [button sizeToFit];
        [button setTitle:model.title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        if (i== 3) {
            [button setTitle:@"我是你们" forState:UIControlStateNormal];
        }
        //自适应button的宽高。。。。。。
        [button sizeToFit];
        button.layer.borderWidth = 2;
        button.layer.cornerRadius = 10;
        button.layer.borderColor = [UIColor greenColor].CGColor;
        i++;
        [self.view addSubview:button];
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {

}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    _serachBarText = searchText;
   // NSLog(@"++++++++%@",_serachBarText);

}
//最后需要搜索的内容。。。。。。。。
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    _serachBarText = searchBar.text;
    NSLog(@"最后搜索的%@",_serachBarText);

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [_searchBar resignFirstResponder];
}

@end


text:
using Shouldly;
using System.Linq;
using Wall.Localization.Dictionaries.Json;
using Xunit;

namespace Wall.Tests.Localization.Json
{
    public class JsonEmbeddedFileLocalizationDictionaryProviderTests
    {
        private readonly JsonEmbeddedFileLocalizationDictionaryProvider _dictionaryProvider;

        public JsonEmbeddedFileLocalizationDictionaryProviderTests()
        {
            _dictionaryProvider = new JsonEmbeddedFileLocalizationDictionaryProvider(
                typeof(JsonEmbeddedFileLocalizationDictionaryProviderTests).GetAssembly(),
                "Wall.Tests.Localization.Json.JsonSources"
                );

            _dictionaryProvider.Initialize("Lang");
        }

        [Fact]
        public void Should_Get_Dictionaries()
        {
            var dictionaries = _dictionaryProvider.Dictionaries.Values.ToList();

            dictionaries.Count.ShouldBe(2);

            var enDict = dictionaries.FirstOrDefault(d => d.CultureInfo.Name == "en");
            enDict.ShouldNotBe(null);
            enDict["Apple"].ShouldBe("Apple");
            enDict["Banana"].ShouldBe("Banana");

            var zhCnDict = dictionaries.FirstOrDefault(d => d.CultureInfo.Name == "zh-CN");
            zhCnDict.ShouldNotBe(null);
            zhCnDict["Apple"].ShouldBe("苹果");
            zhCnDict["Banana"].ShouldBe("香蕉");
        }
    }
}


text:
Config Component
================

The Config component provides several classes to help you find, load, combine,
autofill and validate configuration values of any kind, whatever their source
may be (YAML, XML, INI files, or for instance a database).

Resources
---------

  * [Documentation](https://symfony.com/doc/current/components/config.html)
  * [Contributing](https://symfony.com/doc/current/contributing/index.html)
  * [Report issues](https://github.com/symfony/symfony/issues) and
    [send Pull Requests](https://github.com/symfony/symfony/pulls)
    in the [main Symfony repository](https://github.com/symfony/symfony)


text:
dashboard.js
============

An easy and intuitive dashboard framework built on backbone and inspired by [Dashing](http://dashing.io).

Check out the demo:
http://rawgit.com/thaddeusbort/dashboard.js/master/index.html

# Introduction
Dashboard.js is a backbone based framework for building a dashboard to display your important data.

#### Features:

 - No custom server required. All code is run on the frontend making it easy to test and quick to deploy.
 - Use some of our example widgets or easily build your own with html and javascript.
 - Drag & drop interface for re-arranging your widgets. [Powered by Gridster.js](https://github.com/ducksboard/gridster.js)

# Getting started
Download this project. To configure which widgets to display and their settings edit the `<widgets>` section of index.html.

### Widget Configuration
Widgets can have any number of configuration properties that are set using `data-` attributes on the widget tag.

Every widget must have an `id` and a `type` config attribute. The `id` is any unique id. The `type` attribute is
the type of widget. To see all the available widget types look in the widgets folder. The type will be the name of the folder:
 `text`, `weather`, `google_calendar`, ...

This example shows how the attributes `title` and `text` are set for the text widget:

```html
<widget data-id="text_widget_id" data-type="text" data-title="HELLO!" data-text="I'm a text widget"></widget>
```

The widget README should specify which attributes are available.

#### Size Attributes
All widgets support the `width` and `height` attributes. These can be used to make a widget take up more than a single space in the grid.

This example shows a map widget that will fit in a 2x2 grid section:

```html
<widget data-id="leaflet_widget_id" data-type="leaflet" data-width="2" data-height="2" data-jsonurl="http://api.tiles.mapbox.com/v3/examples.map-zr0njcqy/markers.geojson"></widget>
```

#### Frequency Attribute
A common attribute used by any widget that needs to be updated on a regular interval is the `frequency` attribute. The frequency attribute can be set in seconds, minutes, hours, or days by using the first letter of the unit type after the number.

```javascript
data-frequency="10s"   // 10 seconds
data-frequency="10m"   // 10 minutes
data-frequency="10h"   // 10 hours
data-frequency="10d"   // 10 days
data-frequency="100"   // 100 minutes
```
> If no unit type is specified, minutes will be used by default.

This example shows a weather widget that will be updated every 20 minutes:

```html
<widget data-id="weather_widget_id" data-type="weather" data-frequency="20m"></widget>
```

> Any frequency faster than 5 seconds will be set to 5 seconds.

### Widget Creation
To create a new widget type, create a folder in the widgets directory. The name of the folder will be the type name. Add a `widget.html` file that will be the html template and a `widget.js` file that will hold any logic for the widget. The `widget.js` file should contain a function name `WIDGET_TYPE_getdata`. Dashboard.js will call this function when the dashboard is first loaded as well as on an interval if a `data-frequency` attribute is set on the widget. The function is passed a reference to the configuration which includes all data- parameters from the widget tag as well as a callback function that can be used to pass data back from a long running operation. See the `google_calendar` example widget for an example of this.

You can also specify a `WIDGET_TYPE_init` function that will get called when the widget is first loaded. This can be helpful for loading dependencies like external javascript libraries. See the `google_calendar` example widget for an example of this.

# License
Distributed under the MIT license.


text:
require File.dirname(__FILE__) + '/../../spec_helper.rb'

module Spec
  module Mocks

    describe "an expectation set on nil" do

      it "should issue a warning with file and line number information" do
        expected_warning = "An expectation of :foo was set on nil. Called from #{__FILE__}:#{__LINE__+3}. Use allow_message_expectations_on_nil to disable warnings."
        Kernel.should_receive(:warn).with(expected_warning)

        nil.should_receive(:foo)
        nil.foo
      end

      it "should issue a warning when the expectation is negative" do
        Kernel.should_receive(:warn)

        nil.should_not_receive(:foo)
      end

      it "should not issue a warning when expectations are set to be allowed" do
        allow_message_expectations_on_nil
        Kernel.should_not_receive(:warn)

        nil.should_receive(:foo)
        nil.should_not_receive(:bar)
        nil.foo
      end

    end

    describe "#allow_message_expectations_on_nil" do

      it "should not effect subsequent examples" do
        example_group = Class.new(ExampleGroup)
        example_group.it("when called in one example that doesn't end up setting an expectation on nil") do
                        allow_message_expectations_on_nil
                      end
        example_group.it("should not effect the next exapmle ran") do
                        Kernel.should_receive(:warn)
                        nil.should_receive(:foo)
                        nil.foo
                      end

        example_group.run.should be_true

      end

    end

  end
end


text:
// This file is automatically generated.

package adila.db;

/*
 * LG OPTIMUS ZIP
 *
 * DEVICE: lgl75c
 * MODEL: LGL75C
 */
final class lgl75c {
    public static final String DATA = "LG|OPTIMUS ZIP|";
}


text:
<rootTag>
    <Common>
        <Version>1</Version>
        <SourceComponent>
            <ComponentName>demoApl</ComponentName>
        </SourceComponent>
        <DestComponent>
            <ComponentName>mlo</ComponentName>
        </DestComponent>
        <Operation>Request</Operation>
    </Common>
    <Slice>
        <SliceId>00000001</SliceId>
        <Flows>
            <Flow>
                <RequestType>add</RequestType>
                <FlowName>flow100</FlowName>
                <SourceCENodeName>tokyo123</SourceCENodeName>
                <SourceCEPortNo>00000001</SourceCEPortNo>
                <DestCENodeName>osaka999</DestCENodeName>
                <DestCEPortNo>00000002</DestCEPortNo>
                <RequestBandWidth>1000</RequestBandWidth>
                <RequestDelay>1</RequestDelay>
                <ProtectionLevel>0</ProtectionLevel>
            </Flow>
        </Flows>
    </Slice>
</rootTag>


text:
var App = function(router)
{
	this.router = router;
};

// Starts the application
App.prototype.start = function()
{
	this.router.listen(8181);
};

// Initializes handler routes
App.prototype.initialize = function()
{
	// 404
	this.router.app.use(function(request, response, next)
	{
		response.status(404);

		if (request.accepts('html'))
		{
			response.render('error/404');
			return;
		}

		if (request.accepts('json'))
		{
			response.send({ error: "Not found" });
			return;
		}

		response.type('text').send("Not found");
	});
};

App.$inject = [ "Router" ];
module.exports = App;


text:
package org.wso2.carbon.device.mgt.common;

import javax.xml.bind.annotation.XmlElement;
import java.io.Serializable;
import java.util.List;
import io.swagger.annotations.*;

@ApiModel(value = "Feature", description = "This class carries all information related to a devices enrollment" +
                                                 " status.")
public class Feature implements Serializable {

    @ApiModelProperty(name = "id", value = "Feature Id.", required = true )
    private int id;
    @ApiModelProperty(name = "code", value = "The code of the feature. For example the code to lock a device" +
                                             " is DEVICE_LOCK.", required = true )
    private String code;
    @ApiModelProperty(name = "name", value = "A name that describes a feature.", required = true )
    private String name;
    @ApiModelProperty(name = "description", value = "Provides a description of the features..", required = true )
    private String description;
    @ApiModelProperty(name = "deviceType", value = "Provide the device type for the respective feature. " +
                                                   "Features allow you to perform operations on any device type, " +
                                                   "such as android, iOS or windows..", required = true )
    private String deviceType;

    @ApiModelProperty(name = "metadataEntries", value = "Properties related to features.", required = true )
    private List<MetadataEntry> metadataEntries;

    @XmlElement
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @XmlElement
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @XmlElement
    public String getName() {
        return name;
    }

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

    public List<MetadataEntry> getMetadataEntries() {
        return metadataEntries;
    }

    public void setMetadataEntries(List<MetadataEntry> metadataEntries) {
        this.metadataEntries = metadataEntries;
    }

    @XmlElement
    public String getDeviceType() {
        return deviceType;
    }

    public void setDeviceType(String deviceType) {
        this.deviceType = deviceType;
    }

    @XmlElement
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public static class MetadataEntry implements Serializable {

        private int id;
        private Object value;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }
    }
}


text:
package org.elasticsearch.index.shard;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Streamable;
import org.elasticsearch.index.Index;

import java.io.IOException;
import java.io.Serializable;

/**
 * Allows for shard level components to be injected with the shard id.
 */
public class ShardId implements Serializable, Streamable {

    private Index index;

    private int shardId;

    private int hashCode;

    private ShardId() {

    }

    public ShardId(String index, int shardId) {
        this(new Index(index), shardId);
    }

    public ShardId(Index index, int shardId) {
        this.index = index;
        this.shardId = shardId;
        this.hashCode = computeHashCode();
    }

    public Index index() {
        return this.index;
    }

    public String getIndex() {
        return index().name();
    }

    public int id() {
        return this.shardId;
    }

    public int getId() {
        return id();
    }

    @Override
    public String toString() {
        return "[" + index.name() + "][" + shardId + "]";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        ShardId shardId1 = (ShardId) o;
        return shardId == shardId1.shardId && index.name().equals(shardId1.index.name());
    }

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

    private int computeHashCode() {
        int result = index != null ? index.hashCode() : 0;
        result = 31 * result + shardId;
        return result;
    }

    public static ShardId readShardId(StreamInput in) throws IOException {
        ShardId shardId = new ShardId();
        shardId.readFrom(in);
        return shardId;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        index = Index.readIndexName(in);
        shardId = in.readVInt();
        hashCode = computeHashCode();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        index.writeTo(out);
        out.writeVInt(shardId);
    }
}


text:
package wolfboyft.magicalmages.misc;

import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor.ArmorMaterial;

public enum EnumArmour {

	WITHER(ModItemHelper.addArmorMaterial("wither", 1000, new int[] { 4, 8, 6,
			4 }, 20), "wither", false, 75, Items.nether_star),

	NINJA(ModItemHelper.addArmorMaterial("ninja", 250,
			new int[] { 2, 4, 3, 2 }, 20), "ninja", false, 35, Blocks.wool);

	private ArmorMaterial armorMaterial;
	private String type;
	private boolean undamageable;
	private int damageReduction;
	private Item repairItem;

	private EnumArmour(ArmorMaterial armorMaterial, String type,
			boolean undamageable, int damageReduction, Item repair) {
		this.armorMaterial = armorMaterial;
		this.type = type;
		this.undamageable = undamageable;
		this.damageReduction = damageReduction;
		this.repairItem = repair;
	}

	private EnumArmour(ArmorMaterial armorMaterial, String type,
			boolean undamageable, int damageReduction, Block repair) {
		this.armorMaterial = armorMaterial;
		this.type = type;
		this.undamageable = undamageable;
		this.damageReduction = damageReduction;
		this.repairItem = ModItemHelper.toItem(repair);
	}

	public Item getRepairItem() {
		return repairItem;
	}

	public ArmorMaterial getArmorMaterial() {
		return armorMaterial;
	}

	public String getType() {
		return type;
	}

	public boolean isUndamageable() {
		return undamageable;
	}

	public int getDamageReduction() {
		return damageReduction;
	}
}


text:
function H = mrdivide(F,g)
%/   CHEBFUN2V right divide.
%
% F/c divides each component of a CHEBFUN2V by a scalar.
%
% Only allowed to divide by scalars.
%
% See also MLDIVIDE.

% Copyright 2015 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

if ( ( isempty(F) ) || ( isempty(g) ) )
   H = chebfun2v;
   return
end

if ( ~isa(g,'double') && ~isa(g,'chebfun2') )
    error('CHEBFUN:CHEBFUN2V:mrdivide:nonScalar', ...
        'Division must be scalar valued.');
end

% componentwise divide.
if ( isa(g,'double') )
    H = F;
    for j = 1 : F.nComponents
        H.components{j} = mrdivide(F.components{j}, g);
    end
else
    H = F;
    for j = 1 : F.nComponents
        H.components{j} = rdivide(F.components{j}, g);
    end
end

end


text:
A `String` in Java is an object that represents immutable text as a sequence of Unicode characters (letters, digits, punctuation, etc.). Double quotes are used to define a `String` instance:

```java
String fruit = "Apple";
```

Strings are manipulated by calling the string's methods. Once a string has been constructed, its value can never change. Any methods that appear to modify a string will actually return a new string.
The `String` class provides some _static_ methods to transform the strings.


text:
'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash');

/**
 * Extend user's controller
 */
module.exports = _.extend(
	require('./users/users.authentication.server.controller'),
	require('./users/users.authorization.server.controller'),
	require('./users/users.password.server.controller'),
	require('./users/users.profile.server.controller')
);

exports.requiresLogin = function(req, res, next) {
    if (!req.isAuthenticated()) {
        return res.status(410).send({
            message: 'Vous devez vous connecter pour utiliser cette application'
        });
    }

    next();
};


text:
@interface JDYMeViewController : UITableViewController

@end


text:
CREATE TABLE `affiliation10recent` (
	`Affiliation10RecentId` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
	`RawId` INT(11) UNSIGNED NOT NULL,
	`Position` INT(11) UNSIGNED NOT NULL,
	`Name` VARCHAR(50) NOT NULL,
	`Count` INT(11) UNSIGNED NOT NULL,
	PRIMARY KEY (`Affiliation10RecentId`),
	UNIQUE INDEX `Affiliation10RecentId` (`Affiliation10RecentId`),
	INDEX `RawId` (`RawId`)
)
ENGINE=InnoDB;


text:
package server

import (
	"net/http"
	"strings"

	"github.com/golang/glog"
	"github.com/emicklei/go-restful"

	genericmux "github.com/rantuttl/cloudops/apiserver/pkg/genericserver/server/mux"
)

type APIServerHandler struct {
	// FullHandlerChain is the one that is eventually served with.  It should include the full filter
	// chain and then call the Director.
	FullHandlerChain http.Handler
	// The registered APIs.  InstallAPIs uses this.  Other servers probably shouldn't access this directly.
	GoRestfulContainer *restful.Container
	NonGoRestfulMux *genericmux.PathRecorderMux
	Director http.Handler
}

// HandlerChainBuilderFn is used to wrap the GoRestfulContainer handler using the provided handler chain.
// It is normally used to apply filtering like authentication and authorization
type HandlerChainBuilderFn func(apiHandler http.Handler) http.Handler

func NewAPIServerHandler(name string, handlerChainBuilder HandlerChainBuilderFn, notFoundHandler http.Handler) *APIServerHandler {
	nonGoRestfulMux := genericmux.NewPathRecorderMux(name)
	if notFoundHandler != nil {
		nonGoRestfulMux.NotFoundHandler(notFoundHandler)
	}

	gorestfulContainer := restful.NewContainer()
	gorestfulContainer.ServeMux = http.NewServeMux()
	gorestfulContainer.Router(restful.CurlyRouter{})
	// FIXME (rantuttl): finish recovery handling (see ./staging/src/k8s.io/apiserver/pkg/server/handler.go)
	//gorestfulContainer.RecoverHandler(func(panicReason interface{}, ...

	//gorestfulContainer.ServiceErrorHandler(func(serviceErr restful.ServiceError, ...

	director := director{
		name:			name,
		goRestfulContainer:	gorestfulContainer,
		nonGoRestfulMux:	nonGoRestfulMux,
	}

	return &APIServerHandler{
		FullHandlerChain:	handlerChainBuilder(director),
		GoRestfulContainer:	gorestfulContainer,
		Director:		director,
	}
}

type director struct {
        name               string
        goRestfulContainer *restful.Container
        nonGoRestfulMux    *genericmux.PathRecorderMux
}

func (d director) ServeHTTP(w http.ResponseWriter, req *http.Request) {
        path := req.URL.Path

        // check to see if our webservices want to claim this path
        for _, ws := range d.goRestfulContainer.RegisteredWebServices() {
                switch {
                case strings.HasPrefix(path, ws.RootPath()):
                        // ensure an exact match or a path boundary match
                        if len(path) == len(ws.RootPath()) || path[len(ws.RootPath())] == '/' {
                                glog.V(5).Infof("%v: %v %q satisfied by gorestful with webservice %v", d.name, req.Method, path, ws.RootPath())
                                // don't use servemux here because gorestful servemuxes get messed up when removing webservices
                                // TODO fix gorestful, remove TPRs, or stop using gorestful
                                d.goRestfulContainer.Dispatch(w, req)
                                return
                        }
                }
        }

        // if we didn't find a match, then we just skip gorestful altogether
        glog.V(5).Infof("%v: %v %q satisfied by nonGoRestful", d.name, req.Method, path)
        d.nonGoRestfulMux.ServeHTTP(w, req)
}

// ServeHTTP makes it an http.Handler
// top-level entry point to the handler chain
func (a *APIServerHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        a.FullHandlerChain.ServeHTTP(w, r)
}


text:
class Hatchy::UserUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop.xsd">

  <bean id="eddie"
      class="com.springinaction.springidol.Instrumentalist">
    <property name="instrument">
      <bean class="com.springinaction.springidol.Guitar" />
    </property>
  </bean>

  <!-- <start id="audience_bean" /> -->
  <bean id="audience"
      class="com.springinaction.springidol.AroundAudience" />
  <!-- <end id="audience_bean" /> -->

  <!-- <start id="audience_aspect" /> -->
  <aop:config>
    <aop:aspect ref="audience">
      <aop:pointcut id="performance" expression=
          "execution(* com.springinaction.springidol.Performer.perform(..))"
          />

      <aop:around
          pointcut-ref="performance"
          method="watchPerformance" />
    </aop:aspect>
  </aop:config>
  <!-- <end id="audience_aspect" /> -->

</beans>


text:
<?php

/**
 * @file
 * Contains \Drupal\block\Event\BlockEvents.
 */

namespace Drupal\block\Event;

/**
 * Defines events for the Block module.
 */
final class BlockEvents {

  /**
   * Name of the event when gathering condition context for a block plugin.
   *
   * This event allows you to provide additional context that can be used by
   * a condition plugin in order to determine the visibility of a block. The
   * event listener method receives a \Drupal\block\Event\BlockContextEvent
   * instance. Generally any new context is paired with a new condition plugin
   * that interprets the provided context and allows the block system to
   * determine whether or not the block should be displayed.
   *
   * @Event
   *
   * @see \Drupal\Core\Block\BlockBase::getConditionContexts()
   * @see \Drupal\block\Event\BlockContextEvent
   * @see \Drupal\block\EventSubscriber\NodeRouteContext::onBlockActiveContext()
   * @see \Drupal\Core\Condition\ConditionInterface
   */
  const ACTIVE_CONTEXT = 'block.active_context';

  /**
   * Name of the event when gathering contexts for plugin configuration.
   *
   * This event allows you to provide information about your context to the
   * administration UI without having to provide a value for the context. For
   * example, during configuration there is no specific node to pass as context.
   * However, we still need to inform the system that a context named 'node' is
   * available and provide a definition so that blocks can be configured to use
   * it.
   *
   * The event listener method receives a \Drupal\block\Event\BlockContextEvent
   * instance.
   *
   * @Event
   *
   * @see \Drupal\block\BlockForm::form()
   * @see \Drupal\block\Event\BlockContextEvent
   * @see \Drupal\block\EventSubscriber\NodeRouteContext::onBlockAdministrativeContext()
   */
  const ADMINISTRATIVE_CONTEXT = 'block.administrative_context';

}


text:
@interface iPhoneNativeDriverSampleAppDelegate
    : NSObject<UIApplicationDelegate> {
 @private
  IBOutlet UIWindow *window_;
  IBOutlet UINavigationController *navigationController_;
}

@end


text:
__author__    = "Andre Merzky, Ole Weidner"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__   = "MIT"

import os
import sys
import saga

# ------------------------------------------------------------------------------
#
def test_deepcopy():
    """ Test deep copy """

    try:
        jd1 = saga.job.Description ()
        jd1.executable = '/bin/sleep'
        jd1.arguments  = ['1.3']
        jd2 = jd1.clone ()
        jd2.executable = '/bin/nanosleep'
        assert jd1.executable != jd2.executable, "%s != %s" % (jd1.executable, jd2.executable)
        assert jd1.arguments  == jd2.arguments

    except saga.SagaException as se:
        assert False, "Unexpected exception: %s" % se

def test_environment_list ():
    """ Test environment support for list type """

    jd = saga.job.Description ()
    jd.environment = ['A=a', 'B=b']
    assert (type(jd.environment) == list), "Expected list() type but got %s" % type(jd.environment)
    assert (jd.environment == ['A=a', 'B=b']), "'%s' == '%s'" % (jd.environment, ['A=a', 'B=b'])

def test_environment_dict ():
    """ Test environment support for dict type """

    jd = saga.job.Description ()
    jd.environment = {'A':'a', 'B':'b'}
    assert (type(jd.environment) == dict), "Expected dict() type but got %s" % type(jd.environment)
    assert (jd.environment == {'A':'a', 'B':'b'}), "'%s' == '%s'" % (jd.environment, {'A':'a', 'B':'b'})

def test_environment ():
    """ Test environment type exceptions """

    try :
        jd = saga.job.Description ()
        jd.environment = 1
        assert (False), "expected BadParameter exception, got none"
    except saga.BadParameter :
        assert (True)
    except saga.SagaException as se:
        assert (False), "expected BadParameter exception, got %s" % se


text:
Spree::StoreController.class_eval do

  private

  def load_best_sellers
    config = Spree::BestSellersConfiguration.new
    if ((config.has_preference?(:show_best_sellers) && config[:show_best_sellers]) || (config.has_preference?(:show_best_sellers_sidebar) && config[:show_best_sellers_sidebar]))
      @best_sellers = (Spree::Product.best_sellers rescue nil)
    end
  end

end


text:
package org.wso2.appserver.integration.common.artifacts.spring3.restful.webapp.classloading.controller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.wso2.appserver.integration.common.artifacts.spring3.restful.webapp.classloading.model.Status;
import org.wso2.appserver.integration.common.artifacts.spring3.restful.webapp.classloading.model.Student;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/student")
public class StudentController {

    private static final Log log = LogFactory.getLog(StudentController.class);
    private static final long deployedTime = System.currentTimeMillis();

    @Autowired
    @Qualifier("dbStudent")
    private DataSource dataSource;

    @RequestMapping(method = RequestMethod.GET, value = "/deployedtime")
    @ResponseBody
    public String getDeployedtime() {
        return "{\"deployedTime\":\"" + Objects.toString(deployedTime, "") + "\"}";
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<Student> getallStudent() {
        log.info("Retrieve all Student info");
        List<Student> students = new ArrayList<>();
        String query = "SELECT id, first_name, last_name, age from student";
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        List<Map<String, Object>> studentRows = jdbcTemplate.queryForList(query);
        for(Map<String, Object> studentRow : studentRows) {
            Student student = new Student();
            student.setId(Integer.parseInt(String.valueOf(studentRow.get("id"))));
            student.setFirstName(String.valueOf(studentRow.get("first_name")));
            student.setLastName(String.valueOf(studentRow.get("last_name")));
            student.setAge(Integer.parseInt(String.valueOf(studentRow.get("age"))));
            students.add(student);
        }
        return students;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    @ResponseBody
    public Student getStudent(@PathVariable("id") int id) {
        log.info("Retrieve Student Info");
        Student student = new Student();
        String query = "SELECT id, first_name, last_name, age FROM student WHERE id = ?";
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(query);
            statement.setInt(1, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                student.setId(resultSet.getInt("id"));
                student.setFirstName(resultSet.getString("first_name"));
                student.setLastName(resultSet.getString("last_name"));
                student.setAge(resultSet.getInt("age"));
            }
        } catch (SQLException e) {
            log.error("Error retrieving Student Info");
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("Closing Connection");
            }
        }
        return student;
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ResponseBody
    public Status insertStudent(@RequestBody Student student) {
        log.info("Insert Student Info");
        Status status = new Status();
        String query = "INSERT INTO student (id, first_name, last_name, age) VALUES (?, ?, ?, ?)";
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(query);
            statement.setInt(1, student.getId());
            statement.setString(2, student.getFirstName());
            statement.setString(3, student.getLastName());
            statement.setInt(4, student.getAge());
            statement.execute();
            status.setStatus(true);
        } catch (SQLException e) {
            log.error("Error in inserting Student Info");
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("Closing Connection");
            }
        }
        return status;
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Status updateStudent(@RequestBody Student student) {
        log.info("Update Student Info");
        Status status = new Status();
        String query = "UPDATE student SET first_name = ?, last_name = ?, age = ? WHERE id = ?";
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(query);
            statement.setString(1, student.getFirstName());
            statement.setString(2, student.getLastName());
            statement.setInt(3, student.getAge());
            statement.setInt(4, student.getId());
            statement.executeUpdate();
            status.setStatus(true);
        } catch (SQLException e) {
            log.error("Error in updating Student Info");
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("Closing Connection");
            }
        }
        return status;
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    @ResponseBody
    public Status deleteStudent(@PathVariable("id") int id) {
        log.info("Deleting Student Info");
        Status status = new Status();
        String query = "DELETE FROM student WHERE id = ?";
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = dataSource.getConnection();
            statement = connection.prepareStatement(query);
            statement.setInt(1, id);
            statement.executeUpdate();
            status.setStatus(true);
        } catch (SQLException e) {
            log.error("Error in deleting student");
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("Closing Connection");
            }
        }
        return status;
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe Pkgr::Distributions do
  it "raises an error if the distribution is unknown" do
    Facter.should_receive(:value).with('operatingsystem').ordered.and_return("Foo")
    Facter.should_receive(:value).with('operatingsystemrelease').ordered.and_return("bar")
    expect{ Pkgr::Distributions.current }.to raise_error(Pkgr::Errors::UnknownDistribution)
  end

  it "returns the correct ubuntu distribution" do
    Facter.should_receive(:value).with('operatingsystem').ordered.and_return("Ubuntu")
    Facter.should_receive(:value).with('operatingsystemrelease').ordered.and_return("12.04")
    current_distribution = Pkgr::Distributions.current
    expect(current_distribution).to be_a(Pkgr::Distributions::Ubuntu)
    expect(current_distribution.release).to eq("12.04")
    expect(current_distribution.runner.type).to eq("upstart")
  end

  it "forces a specific distribution" do
    distro = Pkgr::Distributions.current(double(:config, force_os: "debian-7.4"))
    expect(distro).to be_a(Pkgr::Distributions::Debian)
    expect(distro.release).to eq("7")
  end
end


text:
> ## **IMPORTANT**

> This module is no longer actively maintained, however, if you're interested in adopting it, please let us know!

SilverStripe Elastica Module
============================

Provides elastic search integration for SilverStripe DataObjects using Elastica.

Usage
-----

The first step is to configure the Elastic Search service. To do this, the configuration system
is used. The simplest default configuration is:

    Injector:
      Symbiote\Elastica\ElasticaService:
        constructor:
          - %$Elastica\Client
          - index-name-to-use

You can then use the `Symbiote\Elastica\Searchable` extension to add searching functionality
to your data objects. Elastic search can then be interacted with using the
`Symbiote\Elastica\ElasticService` class.


text:
/* MagicMirror²
 * Node Helper: Newsfeed - NewsfeedFetcher
 *
 * By Michael Teeuw https://michaelteeuw.nl
 * MIT Licensed.
 */
const Log = require("logger");
const FeedMe = require("feedme");
const NodeHelper = require("node_helper");
const fetch = require("fetch");
const iconv = require("iconv-lite");
const stream = require("stream");

/**
 * Responsible for requesting an update on the set interval and broadcasting the data.
 *
 * @param {string} url URL of the news feed.
 * @param {number} reloadInterval Reload interval in milliseconds.
 * @param {string} encoding Encoding of the feed.
 * @param {boolean} logFeedWarnings If true log warnings when there is an error parsing a news article.
 * @class
 */
const NewsfeedFetcher = function (url, reloadInterval, encoding, logFeedWarnings) {
	let reloadTimer = null;
	let items = [];

	let fetchFailedCallback = function () {};
	let itemsReceivedCallback = function () {};

	if (reloadInterval < 1000) {
		reloadInterval = 1000;
	}

	/* private methods */

	/**
	 * Request the new items.
	 */
	const fetchNews = () => {
		clearTimeout(reloadTimer);
		reloadTimer = null;
		items = [];

		const parser = new FeedMe();

		parser.on("item", (item) => {
			const title = item.title;
			let description = item.description || item.summary || item.content || "";
			const pubdate = item.pubdate || item.published || item.updated || item["dc:date"];
			const url = item.url || item.link || "";

			if (title && pubdate) {
				const regex = /(<([^>]+)>)/gi;
				description = description.toString().replace(regex, "");

				items.push({
					title: title,
					description: description,
					pubdate: pubdate,
					url: url
				});
			} else if (logFeedWarnings) {
				Log.warn("Can't parse feed item:");
				Log.warn(item);
				Log.warn("Title: " + title);
				Log.warn("Description: " + description);
				Log.warn("Pubdate: " + pubdate);
			}
		});

		parser.on("end", () => {
			this.broadcastItems();
			scheduleTimer();
		});

		parser.on("error", (error) => {
			fetchFailedCallback(this, error);
			scheduleTimer();
		});

		parser.on("ttl", (minutes) => {
			try {
				// 86400000 = 24 hours is mentioned in the docs as maximum value:
				const ttlms = Math.min(minutes * 60 * 1000, 86400000);
				if (ttlms > reloadInterval) {
					reloadInterval = ttlms;
					Log.info("Newsfeed-Fetcher: reloadInterval set to ttl=" + reloadInterval + " for url " + url);
				}
			} catch (error) {
				Log.warn("Newsfeed-Fetcher: feed ttl is no valid integer=" + minutes + " for url " + url);
			}
		});

		const nodeVersion = Number(process.version.match(/^v(\d+\.\d+)/)[1]);
		const headers = {
			"User-Agent": "Mozilla/5.0 (Node.js " + nodeVersion + ") MagicMirror/" + global.version,
			"Cache-Control": "max-age=0, no-cache, no-store, must-revalidate",
			Pragma: "no-cache"
		};

		fetch(url, { headers: headers })
			.then(NodeHelper.checkFetchStatus)
			.then((response) => {
				let nodeStream;
				if (response.body instanceof stream.Readable) {
					nodeStream = response.body;
				} else {
					nodeStream = stream.Readable.fromWeb(response.body);
				}
				nodeStream.pipe(iconv.decodeStream(encoding)).pipe(parser);
			})
			.catch((error) => {
				fetchFailedCallback(this, error);
				scheduleTimer();
			});
	};

	/**
	 * Schedule the timer for the next update.
	 */
	const scheduleTimer = function () {
		clearTimeout(reloadTimer);
		reloadTimer = setTimeout(function () {
			fetchNews();
		}, reloadInterval);
	};

	/* public methods */

	/**
	 * Update the reload interval, but only if we need to increase the speed.
	 *
	 * @param {number} interval Interval for the update in milliseconds.
	 */
	this.setReloadInterval = function (interval) {
		if (interval > 1000 && interval < reloadInterval) {
			reloadInterval = interval;
		}
	};

	/**
	 * Initiate fetchNews();
	 */
	this.startFetch = function () {
		fetchNews();
	};

	/**
	 * Broadcast the existing items.
	 */
	this.broadcastItems = function () {
		if (items.length <= 0) {
			Log.info("Newsfeed-Fetcher: No items to broadcast yet.");
			return;
		}
		Log.info("Newsfeed-Fetcher: Broadcasting " + items.length + " items.");
		itemsReceivedCallback(this);
	};

	this.onReceive = function (callback) {
		itemsReceivedCallback = callback;
	};

	this.onError = function (callback) {
		fetchFailedCallback = callback;
	};

	this.url = function () {
		return url;
	};

	this.items = function () {
		return items;
	};
};

module.exports = NewsfeedFetcher;


text:
require 'serverengine'

require 'json'
require 'optparse'

# This is a script to run ServerEngine and SocketManager as a real process.
# bundle exec ruby example/server.rb [-t TYPE] [-w NUM]
# available type of workers are: embedded(default), process, thread, spawn

foreground = false
supervisor = false
worker_type = nil
workers = 4
exit_with_code = nil
exit_at_seconds = 5
exit_at_random = false
stop_immediately_at_exit = false
unrecoverable_exit_codes = []

opt = OptionParser.new
opt.on('-f'){ foreground = true }
opt.on('-x'){ supervisor = true }
opt.on('-t TYPE'){|v| worker_type = v }
opt.on('-w NUM'){|v| workers = v.to_i }
opt.on('-e NUM'){|v| exit_with_code = v.to_i }
opt.on('-s NUM'){|v| exit_at_seconds = v.to_i }
opt.on('-r'){ exit_at_random = true }
opt.on('-i'){ stop_immediately_at_exit = true }
opt.on('-u NUM'){|v| unrecoverable_exit_codes << v.to_i }
opt.parse!(ARGV)

if exit_with_code
  ENV['EXIT_WITH_CODE'] = exit_with_code.to_s
  ENV['EXIT_AT_SECONDS'] = exit_at_seconds.to_s
  if exit_at_random
    ENV['EXIT_AT_RANDOM'] = 'true'
  end
end

module MyServer
  attr_reader :socket_manager_path

  def before_run
    @socket_manager_path = ServerEngine::SocketManager::Server.generate_path
    @socket_manager_server = ServerEngine::SocketManager::Server.open(@socket_manager_path)
  rescue Exception => e
    logger.error "unexpected error in server, class #{e.class}: #{e.message}"
    raise
  end

  def after_run
    logger.info "Server stopped."
    @socket_manager_server.close
  end
end

module MyWorker
  def initialize
    @stop = false
    @socket_manager = ServerEngine::SocketManager::Client.new(server.socket_manager_path)
    @exit_with_code = ENV.key?('EXIT_WITH_CODE') ? ENV['EXIT_WITH_CODE'].to_i : nil
    @exit_at_seconds = ENV.key?('EXIT_AT_SECONDS') ? ENV['EXIT_AT_SECONDS'].to_i : nil
    @exit_at_random = ENV.key?('EXIT_AT_RANDOM')
  end

  def main
    # test to listen the same port
    logger.info "Starting to run Worker."
    _listen_sock = @socket_manager.listen_tcp('0.0.0.0', 12345)
    stop_at = if @exit_with_code
                stop_seconds = @exit_at_random ? rand(@exit_at_seconds) : @exit_at_seconds
                logger.info "Stop #{stop_seconds} seconds later with code #{@exit_with_code}."
                Time.now + stop_seconds
              else
                nil
              end
    until @stop
      if stop_at && Time.now >= stop_at
        logger.info "Exitting with code #{@exit_with_code}"
        exit! @exit_with_code
      end
      logger.info "Awesome work!"
      sleep 1
    end
    logger.info "Exitting"
  rescue Exception => e
    logger.warn "unexpected error, class #{e.class}: #{e.message}"
    raise
  end

  def stop
    @stop = true
  end
end

module MySpawnWorker
  def spawn(process_manager)
    env = {
      'SERVER_ENGINE_CONFIG' => config.to_json,
      'SERVER_ENGINE_SOCKET_MANAGER_PATH' => server.socket_manager_path,
    }
    if ENV['EXIT_WITH_CODE']
      env['EXIT_WITH_CODE'] = ENV['EXIT_WITH_CODE']
      env['EXIT_AT_SECONDS'] = ENV['EXIT_AT_SECONDS']
      if ENV['EXIT_AT_RANDOM']
        env['EXIT_AT_RANDOM'] = 'true'
      end
    end
    process_manager.spawn(env, "ruby", File.expand_path("../spawn_worker_script.rb", __FILE__))
  rescue Exception => e
    logger.error "unexpected error, class #{e.class}: #{e.message}"
    raise
  end
end

opts = {
  daemonize: !foreground,
  daemon_process_name: 'mydaemon',
  supervisor: supervisor,
  log: 'myserver.log',
  pid_path: 'myserver.pid',
  worker_type: worker_type,
  workers: workers,
}
if stop_immediately_at_exit
  opts[:stop_immediately_at_unrecoverable_exit] = true
end
unless unrecoverable_exit_codes.empty?
  opts[:unrecoverable_exit_codes] = unrecoverable_exit_codes
end

worker_klass = MyWorker
if worker_type == 'spawn'
  worker_klass = MySpawnWorker
end
se = ServerEngine.create(MyServer, worker_klass, opts)

se.run


text:
@echo off

set /P ttiUsername="Username (DEFAULT: username): " || ^
set ttiUsername=username
set ttiPassword=password
set TTI_PLAYCOOKIE=%ttiUsername%
set TTI_GAMESERVER=127.0.0.1

rem Read the contents of PPYTHON_PATH into %PPYTHON_PATH%:
set /P PPYTHON_PATH=<PPYTHON_PATH

echo ===============================
echo Starting Toontown Infinite...
echo ppython: %PPYTHON_PATH%
echo Username: %ttiUsername%
echo Client Agent IP: %TTI_GAMESERVER%
echo ===============================

%PPYTHON_PATH% -m toontown.toonbase.ToontownStart
pause


text:
FactoryGirl.define do
  factory :ems_cluster_performance
end


text:
> Create a [JSFiddle](https://jsfiddle.net/) and reproduce your issue.

## Expected behaviour

I thought that by going to the page '...' and pressing the button '...' then '...' would happen.

## Actual behaviour

Instead of '...', what I saw was that '...' happened instead.

## Browsers affected

I tested on all major browsers and only '...' does not work.

## Steps to Reproduce

1.
2.
3.


text:
import clr
clr.AddReference('SIPSorcery.SIP.Core')
from SIPSorcery.SIP import *

m_registrarSocket = "udp:127.0.0.1:5001"
m_regAgentSocket = "udp:127.0.0.1:5002"
m_proxySocketInternal = "udp:127.0.0.1:5060"
m_appServerSocket = "udp:127.0.0.1:5065"

if isreq:

  #===== SIP Request Processing =====

  #sys.Log("req " + summary)
  req.Header.MaxForwards = req.Header.MaxForwards - 1

  if sipMethod == "REGISTER":
    if remoteEndPoint.ToString() == m_regAgentSocket:
      # A couple of registrars get confused with multiple Via headers in a REGISTER request.
      # To get around that use the branch from the reg agent as the branch in a request that only has one Via.
      branch = req.Header.Vias.PopTopViaHeader().Branch

      # The registration agent has indicated where it wants the REGISTER request sent to by adding a Route header.
      # Remove the header in case it confuses the SIP Registrar the REGISTER is being sent to.
      destRegistrar = req.Header.Routes.PopRoute().ToSIPEndPoint()
      src = sys.GetDefaultSIPEndPoint(destRegistrar.SIPProtocol)
      req.Header.Routes = None
      sys.SendTransparent(destRegistrar, req, branch, src, None, publicip)

    else:
      req.Header.ProxyReceivedOn = localEndPoint.ToString()
      req.Header.ProxyReceivedFrom = remoteEndPoint.ToString()
      sys.Send(m_registrarSocket, req, proxyBranch, m_proxySocketInternal)

  elif sipMethod == "SUBSCRIBE":
    sys.Respond(req, SIPResponseStatusCodesEnum.MethodNotAllowed, None)

  else:
    if remoteEndPoint.ToString().StartsWith("udp:127.0.0.1"):
      # Request from a SIP Application server for an external UA.
      dest = sys.Resolve(req)
      if dest == None:
        if sipMethod != "ACK":
          sys.Respond(req, SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "Host " + req.URI.Host + " unresolvable")
      else:
        contactURI = None
        if sipMethod == "INVITE":
          if not dest.SocketEndPoint.Address.ToString().StartsWith("10."):
            # Request is for an external UA, use public IP.
            contactURI = SIPURI(req.URI.Scheme, SIPEndPoint.ParseSIPEndPoint(publicip.ToString()))
          else:
            # Request is for same private network as the proxy, don't use external public IP.
            contactURI = SIPURI(req.URI.Scheme, sys.GetDefaultSIPEndPoint(dest.SIPProtocol))
        src = sys.GetDefaultSIPEndPoint(dest.SIPProtocol)
        branch = req.Header.Vias.PopTopViaHeader().Branch
        if not dest.SocketEndPoint.Address.ToString().StartsWith("10."):
          sys.SendTransparent(dest, req, branch, src, contactURI, publicip)
        else:
          sys.SendTransparent(dest, req, branch, src, contactURI, None)
    else:
      # Request from an external UA for a SIP Application Server
      req.Header.ProxyReceivedOn = localEndPoint.ToString()
      req.Header.ProxyReceivedFrom = remoteEndPoint.ToString()
      sys.Send(m_appServerSocket, req, proxyBranch, m_proxySocketInternal)

  #===== End SIP Request Processing =====

else:

  #===== SIP Response Processing =====

  #sys.Log("resp " + summary)

  if sipMethod == "REGISTER" and remoteEndPoint.ToString() == m_registrarSocket:
    # REGISTER response from SIP Registrar.
    resp.Header.ProxyReceivedOn = None
    resp.Header.ProxyReceivedFrom = None
    sys.Send(resp, outSocket)

  elif sipMethod == "REGISTER":
    # REGISTER response for SIP Registration Agent.
    resp.Header.Vias.PushViaHeader(SIPViaHeader(SIPEndPoint.ParseSIPEndPoint(m_regAgentSocket), topVia.Branch))
    sys.Send(resp, SIPEndPoint.ParseSIPEndPoint(m_proxySocketInternal))

  elif remoteEndPoint.ToString().StartsWith("udp:127.0.0.1"):
    # Responses from SIP Application Servers for external UAs.
    if sipMethod == "INVITE":
      if not outSocket.SocketEndPoint.Address.ToString().StartsWith("10."):
        # INVITE response from an SIP Application Server, need to set the Contact URI to the proxy socket for the protocol.
        contactURI = SIPURI(resp.Header.To.ToURI.Scheme, SIPEndPoint.ParseSIPEndPoint(publicip.ToString()))
      else:
        contactURI = SIPURI(resp.Header.To.ToURI.Scheme, sys.GetDefaultSIPEndPoint(resp.Header.Vias.TopViaHeader.Transport))
      sys.Send(resp, outSocket, contactURI)
    else:
      sys.Send(resp, outSocket)

  else:
    # Responses from external UAs for SIP Application Servers.
    resp.Header.ProxyReceivedOn = localEndPoint.ToString()
    resp.Header.ProxyReceivedFrom = remoteEndPoint.ToString()
    resp.Header.Vias.PushViaHeader(SIPViaHeader(SIPEndPoint.ParseSIPEndPoint(m_appServerSocket), topVia.Branch))
    sys.Send(resp, SIPEndPoint.ParseSIPEndPoint(m_proxySocketInternal))

  #===== End SIP Response Processing =====


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import { Animation } from '../../animations/animation';
import { Transition } from '../../transitions/transition';
/**
 * Animations for loading
 */
export var LoadingPopIn = (function (_super) {
    __extends(LoadingPopIn, _super);
    function LoadingPopIn() {
        _super.apply(this, arguments);
    }
    LoadingPopIn.prototype.init = function () {
        var ele = this.enteringView.pageRef().nativeElement;
        var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
        var wrapper = new Animation(this.plt, ele.querySelector('.loading-wrapper'));
        wrapper.fromTo('opacity', 0.01, 1).fromTo('scale', 1.1, 1);
        backdrop.fromTo('opacity', 0.01, 0.3);
        this
            .easing('ease-in-out')
            .duration(200)
            .add(backdrop)
            .add(wrapper);
    };
    return LoadingPopIn;
}(Transition));
export var LoadingPopOut = (function (_super) {
    __extends(LoadingPopOut, _super);
    function LoadingPopOut() {
        _super.apply(this, arguments);
    }
    LoadingPopOut.prototype.init = function () {
        var ele = this.leavingView.pageRef().nativeElement;
        var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
        var wrapper = new Animation(this.plt, ele.querySelector('.loading-wrapper'));
        wrapper.fromTo('opacity', 0.99, 0).fromTo('scale', 1, 0.9);
        backdrop.fromTo('opacity', 0.3, 0);
        this
            .easing('ease-in-out')
            .duration(200)
            .add(backdrop)
            .add(wrapper);
    };
    return LoadingPopOut;
}(Transition));
export var LoadingMdPopIn = (function (_super) {
    __extends(LoadingMdPopIn, _super);
    function LoadingMdPopIn() {
        _super.apply(this, arguments);
    }
    LoadingMdPopIn.prototype.init = function () {
        var ele = this.enteringView.pageRef().nativeElement;
        var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
        var wrapper = new Animation(this.plt, ele.querySelector('.loading-wrapper'));
        wrapper.fromTo('opacity', 0.01, 1).fromTo('scale', 1.1, 1);
        backdrop.fromTo('opacity', 0.01, 0.5);
        this
            .easing('ease-in-out')
            .duration(200)
            .add(backdrop)
            .add(wrapper);
    };
    return LoadingMdPopIn;
}(Transition));
export var LoadingMdPopOut = (function (_super) {
    __extends(LoadingMdPopOut, _super);
    function LoadingMdPopOut() {
        _super.apply(this, arguments);
    }
    LoadingMdPopOut.prototype.init = function () {
        var ele = this.leavingView.pageRef().nativeElement;
        var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
        var wrapper = new Animation(this.plt, ele.querySelector('.loading-wrapper'));
        wrapper.fromTo('opacity', 0.99, 0).fromTo('scale', 1, 0.9);
        backdrop.fromTo('opacity', 0.5, 0);
        this
            .easing('ease-in-out')
            .duration(200)
            .add(backdrop)
            .add(wrapper);
    };
    return LoadingMdPopOut;
}(Transition));
export var LoadingWpPopIn = (function (_super) {
    __extends(LoadingWpPopIn, _super);
    function LoadingWpPopIn() {
        _super.apply(this, arguments);
    }
    LoadingWpPopIn.prototype.init = function () {
        var ele = this.enteringView.pageRef().nativeElement;
        var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
        var wrapper = new Animation(this.plt, ele.querySelector('.loading-wrapper'));
        wrapper.fromTo('opacity', 0.01, 1).fromTo('scale', 1.3, 1);
        backdrop.fromTo('opacity', 0.01, 0.16);
        this
            .easing('cubic-bezier(0,0,0.05,1)')
            .duration(200)
            .add(backdrop)
            .add(wrapper);
    };
    return LoadingWpPopIn;
}(Transition));
export var LoadingWpPopOut = (function (_super) {
    __extends(LoadingWpPopOut, _super);
    function LoadingWpPopOut() {
        _super.apply(this, arguments);
    }
    LoadingWpPopOut.prototype.init = function () {
        var ele = this.leavingView.pageRef().nativeElement;
        var backdrop = new Animation(this.plt, ele.querySelector('ion-backdrop'));
        var wrapper = new Animation(this.plt, ele.querySelector('.loading-wrapper'));
        wrapper.fromTo('opacity', 0.99, 0).fromTo('scale', 1, 1.3);
        backdrop.fromTo('opacity', 0.16, 0);
        this
            .easing('ease-out')
            .duration(150)
            .add(backdrop)
            .add(wrapper);
    };
    return LoadingWpPopOut;
}(Transition));
//# sourceMappingURL=loading-transitions.js.map


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Common.Logging;
using ReMi.Api.Insfrastructure.Notifications.Filters;
using ReMi.Api.Insfrastructure.Security;
using ReMi.BusinessEntities.Auth;
using ReMi.BusinessLogic.Auth;
using ReMi.Common.Utils;
using ReMi.Contracts.Cqrs.Events;
using ReMi.Contracts.Cqrs.Queries;
using ReMi.Queries.Auth;

namespace ReMi.Api.Insfrastructure.Notifications
{
    public class SubscriptionManager : ISubscriptionManager
    {
        private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

        private static readonly ConcurrentDictionary<string, ClientRegistration> RegisteredClients = new ConcurrentDictionary<string, ClientRegistration>();

        public IAccountsBusinessLogic AccountsBusinessLogic { get; set; }
        public INotificationFilterApplying NotificationFilterApplying { get; set; }
        public ISerialization Serialization { get; set; }
        public IHandleQuery<GetAccountRequest, GetAccountResponse> GetAccountQuery { get; set; }

        public void Register(string connectionId, string token)
        {
            Logger.InfoFormat("Register ConnectionId={0}, Token={1}", connectionId, token);

            var parts = HttpTokenHelper.GetTokenParts(token);

            if (parts != null)
            {
                var registration = new ClientRegistration
                {
                    ConnectionId = connectionId,
                    Token = token,
                    SessionId = parts.SessionId,
                    UserName = parts.UserName,
                };

                if (RegisteredClients.TryAdd(token, registration))
                    Logger.DebugFormat("[ConnectionId={0}] Registered client {1}", registration.ConnectionId, registration);
                else
                    Logger.WarnFormat("[ConnectionId={0}] Failed to regsiter client {1}", registration.ConnectionId, registration);
            }
            else
            {
                Logger.WarnFormat("[ConnectionId={0}] Invalid token={1}", connectionId, token);
            }
        }

        public void Subscribe(string connectionId, string eventName, string filterJson)
        {
            Logger.DebugFormat("[connectionId={0}] Subscribe Event={1}, Filter={2}",
                connectionId, eventName, filterJson);

            var registration = FindByConnectionId(connectionId);
            if (registration == null)
            {
                Logger.WarnFormat("[connectionId={0}] Registration not found. Event={1}, Filter={2}",
                    connectionId, eventName, filterJson);
                return;
            }
            if (registration.Subscriptions == null)
            {
                Logger.WarnFormat("[connectionId={0}] Registration has no subscriptions. Event={1}, Filter={2}",
                    connectionId, eventName, filterJson);
                return;

            }

            var frontendFilters = ParseFrontendFilter(filterJson);

            var subscription = registration.Subscriptions.Find(o => o.EventName == eventName);
            if (subscription != null)
            {
                foreach (var frontendFilter in frontendFilters)
                {
                    if (!subscription.Filters.Contains(frontendFilter))
                    {
                        subscription.Filters.Add(frontendFilter);

                        Logger.DebugFormat("[connectionId={0}] Subscription Event={1}, Filter={2} added to existing {3}",
                            connectionId, eventName, filterJson, subscription);
                    }
                }
            }
            else
            {
                registration.Subscriptions.Add(new Subscription
                {
                    EventName = eventName,
                    Filters = frontendFilters
                });

                Logger.DebugFormat("[connectionId={0}] Subscription created for Event={1}, Filter={2}",
                    connectionId, eventName, filterJson);
            }
        }

        public void Unsubscribe(string connectionId, string eventName, string filterJson)
        {
            Logger.DebugFormat("[ConnectionId={0}] Unsubscribe from Event={1}, Filter={2}",
                connectionId, eventName, filterJson);

            var frontendFilter = new List<SubscriptionFilter>();
            if (!string.IsNullOrWhiteSpace(filterJson))
                frontendFilter = ParseFrontendFilter(filterJson);

            var registration = FindByConnectionId(connectionId);
            if (registration != null)
            {
                if (registration.Subscriptions == null)
                {
                    Logger.WarnFormat("[connectionId={0}] Registration has no subscriptions. Event={1}, Filter={2}",
                        connectionId, eventName, filterJson);
                }
                else
                {
                    if (!frontendFilter.Any())
                    {
                        registration.Subscriptions.RemoveAll(o => o.EventName == eventName);
                        Logger.DebugFormat("[ConnectionId={0}] Subscription removed Event={1}, Filter={2}",
                            connectionId, eventName, filterJson);
                    }
                    else
                    {
                        registration.Subscriptions.RemoveAll(
                            o => o.EventName == eventName && frontendFilter.SequenceEqual(o.Filters));

                        Logger.WarnFormat("[ConnectionId={0}] Filtered subscription removed Event={1}, Filter={2}",
                            connectionId, eventName, filterJson);
                    }
                }
            }

            Logger.DebugFormat("[ConnectionId={0}] Current subscriptions after removal. Registration={1}",
                connectionId, registration);
        }

        public void Unsubscribe(string connectionId, string eventName)
        {
            Unsubscribe(connectionId, eventName, null);
        }

        public void UnRegisterByToken(string token)
        {
            Logger.DebugFormat("[token={0}] UnRegisterByToken", token);

            var prevRegistration = FindByToken(token);
            if (prevRegistration != null)
            {
                RegisteredClients.TryRemove(token, out prevRegistration);

                Logger.DebugFormat("[ConnectionId={0}] Unregistered connection {1}",
                    prevRegistration.ConnectionId, prevRegistration);
            }
        }

        public void UnRegisterByConnectionId(string connectionId)
        {
            Logger.DebugFormat("[ConnectionId={0}] UnRegisterByConnectionId", connectionId);

            var registration = FindByConnectionId(connectionId);
            if (registration != null)
                UnRegisterByToken(registration.Token);

            Logger.DebugFormat("[ConnectionId={0}] Unregistered connection {1}", connectionId, registration);
        }

        public bool IsRegistered(string token)
        {
            var registration = FindByToken(token);
            return (registration != null);
        }

        public bool IsRegisteredConnectionId(string connectionId)
        {
            var registration = FindByConnectionId(connectionId);
            return (registration != null);
        }

        public string[] FilterSubscribers(IEvent evnt)
        {
            var registrations = RegisteredClients.ToArray();

            Logger.DebugFormat("Event {0} has subscriptions {1}", evnt.GetType().Name, registrations);

            return
                registrations
                    .Select(o => new { o.Value.ConnectionId, Account = GetAccountFromRegistration(o.Value.ConnectionId), o.Value.Subscriptions })
                    .Where(o => NotificationFilterApplying.Apply(evnt, o.Account, o.Subscriptions))
                    .Select(o => o.ConnectionId)
                    .ToArray();
        }

        #region Helpers

        private Account GetAccountFromRegistration(string connectionId)
        {
            var registration = FindByConnectionId(connectionId);
            if (registration == null)
                throw new Exception(string.Format("Request connection not registered. ConnectionId={0}", connectionId));

            var session = AccountsBusinessLogic.GetSession(registration.SessionId);
            if (session == null)
                throw new Exception(string.Format("Session not found. ConnectionId={0}, SessionId={1}", connectionId, registration.SessionId));

            var account = GetAccountQuery.Handle(new GetAccountRequest {AccountId = session.AccountId}).Account;
            if (account == null)
                throw new Exception(string.Format("Account not found. ConnectionId={0}, AccountId={1}", connectionId, session.ExternalId));

            return account;
        }

        private ClientRegistration FindByToken(string token)
        {
            ClientRegistration found;
            if (RegisteredClients.TryGetValue(token, out found))
                return found;

            return null;
        }

        private ClientRegistration FindByConnectionId(string connectionId)
        {
            var found = RegisteredClients.FirstOrDefault(o => o.Value.ConnectionId == connectionId);
            if (found.Value != null)
                return found.Value;

            return null;
        }

        private SubscriptionFilters ParseFrontendFilter(string filterJson)
        {
            var result = new SubscriptionFilters();

            var frontendFilters = Serialization.FromJson<FrontendFilter>(filterJson);
            if (frontendFilters != null)
            {
                result.AddRange(frontendFilters.Select(filter => new SubscriptionFilter
                {
                    Property = filter.Key,
                    Value = filter.Value
                }));
            }

            return result;
        }

        #endregion
    }

}


text:
// snowWhiteDbRestAPI.js

// BASE SETUP
// =============================================================================

// call the packages we need
var express = require('express'); 		// call express
var app = express(); 				// define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 2200; 		// set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); 				// get an instance of the express Router

// <-- route middleware and first route are here
router.use(function (req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});
// more routes for our API will happen here

//#################################################Setting##############################################
var Setting = require('./app/models/setting');
//--------------------------on routes that end in /settings---------------------------------------------
router.route('/settings')
// create a setting (accessed at POST http://localhost:2200/api/settings)
	.post(function (req, res) {

	    var setting = new Setting(); 		// create a new instance of the Setting model
	    setting.uploadPath = req.body.uploadPath;  // set the settings uploadPath (comes from the request)
	    setting.uploadTmpPath = req.body.uploadTmpPath;  // set the settings uploadTmpPath (comes from the request)
	    setting.maxPostSize = req.body.maxPostSize;  // set the settings maxPostSize (comes from the request)
	    setting.maxFileSize = req.body.maxFileSize;  // set the settings maxFileSize (comes from the request)
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            // save the setting and check for errors
	            setting.save(function (err) {
	                if (err)
	                    res.send(err);

	                res.json({ message: 'Setting Successfully created!' });
	                mongoose.disconnect();
	            });
	        }
	    });

	})
// get all the settings (accessed at GET http://localhost:2200/api/settings)
	.get(function (req, res) {
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            Setting.find(function (err, settings) {
	                if (err)
	                    res.send(err);

	                res.json(settings);
	                mongoose.disconnect();
	            });
	        }
	    });
	});
//--------------------------on routes that end in /settings/:setting_id---------------------------------
router.route('/settings/:setting_id')
// get the setting with that id (accessed at GET http://localhost:2200/api/settings/:setting_id)
	.get(function (req, res) {
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            Setting.findById(req.params.setting_id, function (err, setting) {
	                if (err)
	                    res.send(err);
	                res.json(setting);
	                mongoose.disconnect();
	            });
	        }
	    });
	})
// update the setting with this id (accessed at PUT http://localhost:2200/api/settings/:setting_id)
    .put(function (req, res) {
        mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
            if (err) {
                console.error('\x1b[31m', 'Could not connect to MongoDB!');
                console.log(err);
            } else {
                // use our setting model to find the setting we want
                Setting.findById(req.params.setting_id, function (err, setting) {

                    if (err)
                        res.send(err);
                    if (setting !== null) {
                        setting.uploadPath = req.body.uploadPath;  // set the settings uploadPath (comes from the request)
                        setting.uploadTmpPath = req.body.uploadTmpPath;  // set the settings uploadTmpPath (comes from the request)
                        setting.maxPostSize = req.body.maxPostSize;  // set the settings maxPostSize (comes from the request)
                        setting.maxFileSize = req.body.maxFileSize;  // set the settings maxFileSize (comes from the request)

                        // save the setting
                        setting.save(function (err) {
                            if (err)
                                res.send(err);

                            res.json({ message: 'Setting Successfully updated!' });
                            mongoose.disconnect();
                        });
                    }
                    else {
                        res.json({ message: 'Setting not found!' });
                        mongoose.disconnect();
                    }
                });
            }
        });
    })
// delete the setting with this id (accessed at DELETE http://localhost:2200/api/settings/:setting_id)
	.delete(function (req, res) {
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            Setting.remove({
	                _id: req.params.setting_id
	            }, function (err, setting) {
	                if (err)
	                    res.send(err);
	                if (setting == 1) {
	                    res.json({ message: 'Setting Successfully deleted' });
	                    mongoose.disconnect();
	                } else {
	                    res.json({ message: 'Setting not found!' });
	                    mongoose.disconnect();
	                }
	            });

	        }
	    });
	});
//######################################################################################################

//####################################################User##############################################
var User = require('./app/models/user');
//--------------------------on routes that end in /users------------------------------------------------
router.route('/users')
// create a user (accessed at POST http://localhost:2200/api/users)
	.post(function (req, res) {

	    var user = new User(); 		// create a new instance of the User model
	    user.uploadPath = req.body.uploadPath;  // set the users uploadPath (comes from the request)
	    user.uploadTmpPath = req.body.uploadTmpPath;  // set the users uploadTmpPath (comes from the request)
	    user.maxPostSize = req.body.maxPostSize;  // set the users maxPostSize (comes from the request)
	    user.maxFileSize = req.body.maxFileSize;  // set the users maxFileSize (comes from the request)
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            // save the user and check for errors
	            user.save(function (err) {
	                if (err)
	                    res.send(err);

	                res.json({ message: 'User Successfully created!' });
	                mongoose.disconnect();
	            });
	        }
	    });

	})
// get all the users (accessed at GET http://localhost:2200/api/users)
	.get(function (req, res) {
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            User.find(function (err, users) {
	                if (err)
	                    res.send(err);

	                res.json(users);
	                mongoose.disconnect();
	            });
	        }
	    });
	});
//--------------------------on routes that end in /users/:user_id---------------------------------------
router.route('/users/:user_id')
// get the user with that id (accessed at GET http://localhost:2200/api/users/:user_id)
	.get(function (req, res) {
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            User.findById(req.params.user_id, function (err, user) {
	                if (err)
	                    res.send(err);
	                res.json(user);
	                mongoose.disconnect();
	            });
	        }
	    });
	})
// update the user with this id (accessed at PUT http://localhost:2200/api/users/:user_id)
    .put(function (req, res) {
        mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
            if (err) {
                console.error('\x1b[31m', 'Could not connect to MongoDB!');
                console.log(err);
            } else {
                // use our user model to find the user we want
                User.findById(req.params.user_id, function (err, user) {

                    if (err)
                        res.send(err);
                    if (user !== null) {
                        user.uploadPath = req.body.uploadPath;  // set the users uploadPath (comes from the request)
                        user.uploadTmpPath = req.body.uploadTmpPath;  // set the users uploadTmpPath (comes from the request)
                        user.maxPostSize = req.body.maxPostSize;  // set the users maxPostSize (comes from the request)
                        user.maxFileSize = req.body.maxFileSize;  // set the users maxFileSize (comes from the request)

                        // save the user
                        user.save(function (err) {
                            if (err)
                                res.send(err);

                            res.json({ message: 'User Successfully updated!' });
                            mongoose.disconnect();
                        });
                    }
                    else {
                        res.json({ message: 'User not found!' });
                        mongoose.disconnect();
                    }
                });
            }
        });
    })
// delete the user with this id (accessed at DELETE http://localhost:2200/api/users/:user_id)
	.delete(function (req, res) {
	    mongoose.connect('mongodb://localhost:27017/snow_white', function (err) { // connect to our database
	        if (err) {
	            console.error('\x1b[31m', 'Could not connect to MongoDB!');
	            console.log(err);
	        } else {
	            User.remove({
	                _id: req.params.user_id
	            }, function (err, user) {
	                if (err)
	                    res.send(err);
	                if (user == 1) {
	                    res.json({ message: 'User Successfully deleted' });
	                    mongoose.disconnect();
	                } else {
	                    res.json({ message: 'User not found!' });
	                    mongoose.disconnect();
	                }
	            });

	        }
	    });
	});
//######################################################################################################

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/db', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Database REST API Server is running on port ' + port);


text:
package com.pmu.android.util;

import android.view.View;
import android.widget.EditText;

public class UIUtil {

	private static View view;

	public static void setView(View newView) {
		view = newView;
	}

	public static String getString(int id) {
		EditText edt = (EditText) view.findViewById(id);
		return edt.getText().toString();
	}

}


text:
<?php

namespace Concrete\Core\Board\Command;

use Concrete\Core\Foundation\Command\Command;

class AddContentToBoardInstanceCommand extends Command
{

    use BoardInstanceTrait;

}