text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.github.yas99en.it</groupId>
  <artifactId>javascript-it</artifactId>
  <version>1.0-SNAPSHOT</version>

  <description>A simple IT verifying the basic use case.</description>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>@project.groupId@</groupId>
        <artifactId>@project.artifactId@</artifactId>
        <version>@project.version@</version>
        <configuration>
          <engine>javascript</engine>
          <script>
          log.info("hello from pom");
          log.info(project.name);
          log.info(project.version);
          log.info(project.basedir);
          log.info(project.build.finalName);
          log.info(project.build.directory);
          log.info(project.build.outputDirectory);
          log.info(settings.localRepository);
          log.info(mvn.session.executionRootDirectory);
          mvn.log.info("hello mvn.log.info");
          log.info(mvn.project.name);
//          mvn.fail("test fail");
          log.info(mvn.arguments);
          </script>
          <arguments>
            <argument>aaa</argument>
            <argument>xyz</argument>
          </arguments>
        </configuration>
        <executions>
          <execution>
            <id>hello</id>
            <phase>validate</phase>
            <goals>
              <goal>execute</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
import os
import unittest

import six

from conans.model.profile import Profile
from conans.paths import CONANFILE
from conans.test.utils.tools import  TestClient
from conans.util.files import save

conanfile_scope_env = """
from conans import ConanFile

class AConan(ConanFile):
    settings = "os"
    requires = "Hello/0.1@lasote/testing"

    def build(self):
        self.run("SET" if self.settings.os=="Windows" else "env")
"""

conanfile_dep = """
from conans import ConanFile

class AConan(ConanFile):
    name = "Hello"
    version = "0.1"

    def package_info(self):
        self.env_info.PATH=["/path/to/my/folder"]
"""

class ProfilesEnvironmentTest(unittest.TestCase):

    def setUp(self):
        self.client = TestClient()

    def test_build_with_profile(self):
        self._create_profile("scopes_env", {},
                             {"CXX": "/path/tomy/g++_build", "CC": "/path/tomy/gcc_build"})

        self.client.save({CONANFILE: conanfile_dep})
        self.client.run("export . lasote/testing")

        self.client.save({CONANFILE: conanfile_scope_env}, clean_first=True)
        self.client.run("install . --build=missing -pr scopes_env")
        self.client.run("build .")
        six.assertRegex(self, str(self.client.out), "PATH=['\"]*/path/to/my/folder")
        self._assert_env_variable_printed("CC", "/path/tomy/gcc_build")
        self._assert_env_variable_printed("CXX", "/path/tomy/g++_build")

    def _assert_env_variable_printed(self, name, value):
        self.assertIn("%s=%s" % (name, value), self.client.out)

    def _create_profile(self, name, settings, env=None):
        env = env or {}
        profile = Profile()
        profile._settings = settings or {}
        for varname, value in env.items():
            profile.env_values.add(varname, value)
        save(os.path.join(self.client.cache.profiles_path, name), "include(default)\n" + profile.dumps())

redpajama_set_name: RedPajamaGithub


text:
var ValueTransformer = function () {

    this.displayName = "Number Calculations";
    this.shortDescription = "Perform basic calculations.";
    this.isEditingDisabled = true;
    this.infoUrl = "https://github.com/SmartJSONEditor/PublicDocuments/wiki/ValueTransformer-NumberCalculations";

    this.parameters = function () {
        var popupDefaultValue = [
            { displayName: "Add +", value: "add" },
            { displayName: "Subtract -", value: "subtract" },
            { displayName: "Multiply *", value: "multiply" },
            { displayName: "Divide /", value: "divide" },
            { displayName: "Remainder", value: "remainder" },
        ];

        var popupUIParam = {
            name: "type",
            type: "Popup",
            displayName: "Modification Type",
            description: "Select function type",
            defaultValue: popupDefaultValue
        };

        var numberUIParam = {
            type: "Number",
            name: "number",
            displayName: "By Number",
            description: "Calculations by number.",
            defaultValue: "0"
        };

        return [popupUIParam, numberUIParam];
    }

    this.transform = function (inputValue, jsonValue, arrayIndex, parameters, info) {

        var value = Number(inputValue);
		var type = (Array.isArray(parameters.type) == true) ? "add" : parameters.type;
		var number = Number(parameters.number);

		if (type == "add") {
			value = (value + number);
		}
		if (type == "subtract") {
			value = (value - number);
		}
		if (type == "multiply") {
            value = (value * number);
		}
		if (type == "divide") {
            if (number == 0) {
                number = 1
            }
			value = (value / number);
		}
        if (type == "remainder") {
			value = value % number;
		}

        return value;
    };
}

function sjeClass() {
    return new ValueTransformer();
}


text:
<?xml version="1.0"?>
<config>
    <modules>
        <Algolia_Algoliasearch>
            <active>true</active>
            <codePool>community</codePool>
            <version>1.10.0</version>
        </Algolia_Algoliasearch>
    </modules>
</config>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.red5.io.flv.meta.IMetaData (Red5 :: IO 1.0.7-SNAPSHOT API)</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../../../../../javadoc.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.red5.io.flv.meta.IMetaData

Packages that use IMetaData

Package
Description

org.red5.io.flv

org.red5.io.flv.impl

org.red5.io.flv.meta

org.red5.io.mp4

org.red5.io.mp4.impl

Uses of IMetaData in org.red5.io.flv

Methods in org.red5.io.flv that return IMetaData

Modifier and Type
Method and Description

IMetaData
IFLV.getMetaData()

Returns a map of the metadata

Methods in org.red5.io.flv with parameters of type IMetaData

Modifier and Type
Method and Description

void
IFLV.setMetaData(IMetaData metadata)

Sets the metadata

Uses of IMetaData in org.red5.io.flv.impl

Methods in org.red5.io.flv.impl that return IMetaData

Modifier and Type
Method and Description

IMetaData
FLV.getMetaData()

Returns a map of the metadata

Methods in org.red5.io.flv.impl with parameters of type IMetaData

Modifier and Type
Method and Description

void
FLV.setMetaData(IMetaData meta)

Sets the metadata

Uses of IMetaData in org.red5.io.flv.meta

Classes in org.red5.io.flv.meta that implement IMetaData

Modifier and Type
Class and Description

class
MetaData<K,V>

MetaData Implementation

Methods in org.red5.io.flv.meta with parameters of type IMetaData

Modifier and Type
Method and Description

static IMeta
MetaService.mergeMeta(IMetaData<?,?> metaData1,
         IMetaData<?,?> metaData2)

Merges the two Meta objects

static IMeta
MetaService.mergeMeta(IMetaData<?,?> metaData1,
         IMetaData<?,?> metaData2)

Merges the two Meta objects

void
IMetaService.write(IMetaData<?,?> meta)

Initiates writing of the MetaData

void
MetaService.write(IMetaData<?,?> meta)

Initiates writing of the MetaData

void
IMetaService.writeMetaData(IMetaData<?,?> metaData)

Writes the MetaData

void
MetaService.writeMetaData(IMetaData<?,?> metaData)

Writes the MetaData

Uses of IMetaData in org.red5.io.mp4

Methods in org.red5.io.mp4 that return IMetaData

Modifier and Type
Method and Description

IMetaData<?,?>
IMP4.getMetaData()

Returns a map of the metadata

Methods in org.red5.io.mp4 with parameters of type IMetaData

Modifier and Type
Method and Description

void
IMP4.setMetaData(IMetaData<?,?> metadata)

Sets the metadata

Uses of IMetaData in org.red5.io.mp4.impl

Methods in org.red5.io.mp4.impl that return IMetaData

Modifier and Type
Method and Description

IMetaData<?,?>
MP4.getMetaData()

Returns a map of the metadata

Methods in org.red5.io.mp4.impl with parameters of type IMetaData

Modifier and Type
Method and Description

void
MP4.setMetaData(IMetaData<?,?> meta)

Sets the metadata

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2005–2016 Red5. All rights reserved.


text:
package com.parrot.arsdk.ardatatransfer;

/**
 * ARDataTransfer Downloader ProgressListener
 * @author david.flattin.ext@parrot.com
 * @date 09/06/2014
 */

public interface ARDataTransferDownloaderProgressListener
{
    /**
     * Gives the ARDataTransferDownloader download progress
     * @param arg Object progress Listener arg
     * @param percent percent of progress
     * @return void
     */
    void didDownloadProgress(Object arg, float percent);
}


text:
import { context, describe, it, before, afterEach, after } from '@ephox/bedrock-client';
import { Arr } from '@ephox/katamari';
import { Insert, Remove, Selectors, SugarBody, SugarElement } from '@ephox/sugar';
import { assert } from 'chai';

import 'tinymce';
import Editor from 'tinymce/core/api/Editor';
import EditorManager from 'tinymce/core/api/EditorManager';
import { RawEditorOptions } from 'tinymce/core/api/OptionTypes';

describe('browser.tinymce.core.EditorAutoFocusTest', () => {
  before(() => {
    Insert.append(SugarBody.body(), SugarElement.fromHtml(`

Editor_0

Editor_1

Editor_2

`));
  });

  after(() => {
    Selectors.one('#abc').each(Remove.remove);
  });

  afterEach(() => {
    EditorManager.remove();
  });

  const restOfWindowHeight = () =>
    window.innerHeight - SugarBody.body().dom.getBoundingClientRect().height;

  const isInViewport = (editor: Editor) => {
    const { top } = editor.getContainer().getBoundingClientRect();
    return top > 0 && top + 50 < window.innerHeight;
  };

  const pSetupEditorAutoFocus = (id: string, options: RawEditorOptions) => {
    const height = restOfWindowHeight();
    return new Promise((resolve) => {
      EditorManager.init({
        selector: 'div.tinymce',
        base_url: '/project/tinymce/js/tinymce/',
        menubar: false,
        statusbar: false,
        height,
        auto_focus: id,
        init_instance_callback: (editor: Editor) => {
          editor.on('focus', resolve);
        },
        ...options
      });
    });
  };

  const pTestEditorAutoFocus = async (id: string, options: RawEditorOptions) => {
    await pSetupEditorAutoFocus(id, options);
    const editor = EditorManager.get(id) as Editor;
    assert.isTrue(editor.hasFocus());
    assert.isTrue(isInViewport(editor));
  };

  Arr.each([
    { label: 'Iframe Editor', settings: {}},
    { label: 'Inline Editor', settings: { inline: true }},
  ], (tester) => {
    context(tester.label, () => {
      it('TINY-8785: should autofocus the first editor and skip scrolling', async () => {
        await pTestEditorAutoFocus('mce_0', tester.settings);
        assert.equal(window.scrollY, 0);
      });

      it('TINY-8785: should autofocus the second editor', async () => {
        await pTestEditorAutoFocus('mce_1', tester.settings);
      });

      it('TINY-8785: should autofocus the third editor', async () => {
        await pTestEditorAutoFocus('mce_2', tester.settings);
      });
    });
  });
});


text:
require 'spec_helper'

RSpec.describe Numo::Linalg do
  describe 'svdvals' do
    let(:m) { 5 }
    let(:n) { 3 }
    let(:mat_a) { rand_rect_real_mat(m, n) }
    let(:mat_b) { rand_rect_complex_mat(m, n) }

    it 'raises ArgumentError given a invalid driver option' do
      expect { described_class.svdvals(mat_a, driver: 'foo') }.to raise_error(ArgumentError)
    end

    it 'calculates the singular values of a rectangular real matrix' do
      s1, = described_class.svd(mat_a, driver: 'svd', job: 'N')
      s2 = described_class.svdvals(mat_a, driver: 'svd')
      expect((s1 - s2).abs.max).to be < ERR_TOL
    end

    it 'calculates the singular values of a rectangular complex matrix' do
      s1, = described_class.svd(mat_b, driver: 'svd', job: 'N')
      s2 = described_class.svdvals(mat_b, driver: 'svd')
      expect((s1 - s2).abs.max).to be < ERR_TOL
    end

    it 'calculates the singular values of a rectangular real matrix with divide and conquer algorithm' do
      s1, = described_class.svd(mat_a, driver: 'sdd', job: 'N')
      s2 = described_class.svdvals(mat_a, driver: 'sdd')
      expect((s1 - s2).abs.max).to be < ERR_TOL
    end

    it 'calculates the singular values of a rectangular complex matrix with divide and conquer algorithm' do
      s1, = described_class.svd(mat_b, driver: 'sdd', job: 'N')
      s2 = described_class.svdvals(mat_b, driver: 'sdd')
      expect((s1 - s2).abs.max).to be < ERR_TOL
    end
  end
end


text:
@interface MobFoodListViewController ()

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger totalPage;
@property (nonatomic, assign) NSInteger loadMoreCount;
@property (nonatomic, strong) NSString *pageFilePath;

@end

@implementation MobFoodListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerNib:[UINib nibWithNibName:@"MobFoodListCell" bundle:nil] forCellReuseIdentifier:@"listCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 97;

    self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.indicatorView.center = self.view.center;
    self.indicatorView.color = [UIColor grayColor];
    [self.view addSubview:self.indicatorView];
    [self.indicatorView startAnimating];

    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"pageCaches"];
    [[NSFileManager defaultManager] createDirectoryAtPath:docDir withIntermediateDirectories:YES attributes:nil error:nil];
    self.pageFilePath = [docDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", self.cid]];
    NSNumber *page = [NSArray arrayWithContentsOfFile:self.pageFilePath].firstObject;

    self.page = page ? page.integerValue : 1;
    self.totalPage = 10000;
    [self loadMoreData:[[MJRefreshFooter alloc] init]];
}

- (void)loadMoreData:(id)sender
{
    BOOL loadMore;
    if ([sender isKindOfClass:[MJRefreshFooter class]]) {
        loadMore = YES;
    } else {
        loadMore = NO;
    }
    [self fetchDataWithLoadMore:loadMore];
}

- (void)fetchDataWithLoadMore:(BOOL)loadMore
{
    NSInteger page;
    if (loadMore) {
        if (self.totalPage != 10000) {
            self.loadMoreCount++;
        }
        page = (self.page + self.loadMoreCount) > self.totalPage ? (self.page + self.loadMoreCount) - self.totalPage : (self.page + self.loadMoreCount);
    } else {
        self.loadMoreCount = 0;
        page = self.page == 1 ? self.totalPage : self.page - 1;
        self.page = page;

        [@[@(page)] writeToFile:self.pageFilePath atomically:YES];
    }
    if (self.cid) {
        [MobAPI sendRequestWithInterface:@"/v1/cook/menu/search" param:@{@"key" : APPKey, @"cid" : self.cid , @"page" : @(page)} onResult:^(MOBAResponse *response) {
            [self updateIndicatorView];
            if (response.error) {
                [FAFProgressHUD showError:@"数据加载失败" icon:nil color:nil];
            } else {
                NSInteger totalCount = ((NSNumber *)response.responder[@"total"]).integerValue;
                self.totalPage = (totalCount / 20) + (totalCount % 20 != 0 ? 1 : 0);
                [MobFoodClassModel faf_setupObjectClassInArray:^NSDictionary *{
                    return @{@"list" : @"MobFoodClassItemModel"};
                }];
                [MobFoodClassItemModel faf_setupObjectClassInArray:^NSDictionary *{
                    return @{@"recipe" : @"MobFoodClassItemRecipeModel"};
                }];
                [MobFoodClassItemRecipeModel faf_setupObjectClassInArray:^NSDictionary *{
                    return @{@"method" : @"MobFoodClassItemMethodModel"};
                }];
                MobFoodClassModel *model = [MobFoodClassModel faf_objectWithKeyValues:response.responder];
                if (loadMore) {
                    [self.dataArray addObjectsFromArray:model.list];
                } else {
                    self.dataArray = [NSMutableArray arrayWithArray:model.list];
                }
                [self.tableView reloadData];
            }
        }];
    } else {
        [MobAPI sendRequestWithInterface:@"/wx/article/search" param:@{@"key" : APPKey, @"cid" : @(27), @"page" : @(page)} onResult:^(MOBAResponse *response) {
            [self updateIndicatorView];
            if (response.error) {
                [FAFProgressHUD showError:@"数据加载失败" icon:nil color:nil];
            } else {
                NSInteger totalCount = ((NSNumber *)response.responder[@"result"][@"total"]).integerValue;
                self.totalPage = (totalCount / 20) + (totalCount % 20 != 0 ? 1 : 0);
                [MobCarefulSelectionModel faf_setupReplacedKeyFromPropertyName:^NSDictionary *{
                    return @{@"currentId" : @"id"};
                }];
                NSArray *objectArray = [MobCarefulSelectionModel faf_objectArrayWithKeyValuesArray:response.responder[@"result"][@"list"]];
                if (loadMore) {
                    [self.dataArray addObjectsFromArray:objectArray];
                } else {
                    self.dataArray = [NSMutableArray arrayWithArray:objectArray];
                }
                [self.tableView reloadData];
            }
        }];
    }
}

- (void)updateIndicatorView
{
    if (self.tableView.mj_header == nil) {
        self.tableView.mj_header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData:)];
    }
    if (self.tableView.mj_footer == nil) {
        self.tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData:)];
    }
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if (self.indicatorView) {
        [self.indicatorView stopAnimating];
        [self.indicatorView removeFromSuperview];
        self.indicatorView = nil;
    }
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MobFoodListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell"];
    if (cell == nil) {
        cell = [MobFoodListCell mobFoodListCell];
    }

    [cell setupData:self.dataArray[indexPath.row]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
    if (self.cid) {
        MobFoodDetailViewController *vc = [[MobFoodDetailViewController alloc] init];
        MobFoodClassItemModel *model = self.dataArray[indexPath.row];
        vc.model = model;
        vc.title = model.name;
        vc.cid = model.menuId;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        MobAdViewController *vc = [[MobAdViewController alloc] init];
        MobCarefulSelectionModel *cModel = self.dataArray[indexPath.row];
        MobAdvertiseModel *model = [[MobAdvertiseModel alloc] init];
        model.link = cModel.sourceUrl;
        model.title = cModel.title;
        model.type = AdvertisementType_OtherWeb;
        model.imgUrl = cModel.thumbnails;
        vc.adModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end


text:
Contributing
============

## Setup the development environment for this bundle (Linux/Ubuntu)

1) Clone the bundle
```bash
cd /path/to/your/projects
git clone https://github.com/formapro/JsFormValidatorBundle.git
```
2) Install vendors
```bash
cd JsFormValidatorBundle
php composer.phar install --dev
```
3) Install assests
```bash
Tests/app/console assets:install Tests/app
```
4) Fix permissions
```bash
sudo chmod -R 0777 Tests/app/cache Tests/app/logs Resources/public/js/fp_js_validator.js
```
5) Create a new virtual host and set the ```Tests/app``` directory as a root
6) Restart apache
```bash
sudo service apache2 restart
```
7) Copy the ```Tests/app/Resources/local_config.php.tpl``` file as local_config.php
8) Open this file and change the host name to your own
9) Run selenium. If you do not have it yet:
```bash
curl http://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar > selenium.jar
java -jar selenium.jar
```
10) Run tests
```bash
phpunit
```

## Tests

Basically the bundle covered by functional selenium tests
The main test case is placed in ```Tests/Functional/MainFunctionalTest.php```
It calls pages which are defined in ```Tests/TestBundles/DefaultTestBundle```

The main idea of most tests is:
1) create an action ```mytestAction``` in ```Tests/TestBundles/DefaultTestBundle/Controller/FunctionalTestsController.php``` with a form that has specified list of validation rules
1.1) use a general route to call this action ```test/{controller}/{type}/{js}```
1.2) so, in your action you can get the ```$type``` and ```$js``` parameters
1.3) ```type``` variable can be used to check if the form should be filled out with valid or invalid data (1/0)
1.4) ```js``` variable - to check if JS should be enabled or disabled (1/0)
2) bind valid values to the form (call with ```type = 1```)
3) call this form with disabled JS (native Symfony validation) and get the list of errors ```test/mytest/1/0``` (1 - form is valid, 0 - js is disabled)
4) call the form with enabled JS (here works our bundle) and get list of errors ```test/mytest/1/1``` (1 - form is valid, 1- js is enabled)
5) compare errors from #3 and #4 steps - they should be equal
6) bind invalid values to the form  (call with ```type = 0```)
7) repeat steps #3, #4, #5 (```test/mytest/0/0``` and ```test/mytest/0/0```)

[How to run tests on a real project](Resources/doc/4.md)

## Javascripts

All the javascripts placed in the ```Resources/pulic/js``` folder
All of them are merged and included by assetic bundle for the dev/test environments.
The ```/Resources/public/js/fp_js_validator.js``` file is a merged library that uses as main included file.
Thera no reason to edit this file becauset it is updated automatically each time when you run dev/test


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*

 */

#include "common.h"

namespace
{
//  some helper functions
//

template < typename T >
void init_array( T * arr, size_t size )
{
    ::ZeroMemory( arr, size * sizeof( T ) );
}

//  locals
//

const char * const fixupNames[] =
{
    "Class Handle",
    "Field Handle",
    "Method Handle",
    "Function Call/Pointer",
    "Sync",
    "Pinvoke",
    "Profiling Handle",
    "Interface Table",
    "Module Handle",
    "Module Domain ID",
    "Class Domain ID",
    "Field Address",
    "Varargs Handle",
    "String",
    "Init Class",
    "Load Class",
    "Stub Dispatch",
    "Active Dependency"
};

const char * const callReasons[] =
{
    "Unknown",
    "Exotic (Not IL or ECall)",
    "PInvoke",
    "Has Generic Instantiation",
    "No code generated yet",
    "Method has fixups",
    "Prestub may produce stub",
    "Remoting interception",
    "Contains Cer root",
    "Restore method (Generics)",
    "Restore first call",
    "Restore value type",
    "Restore",
    "Can't patch",
    "Profiling",
    "Other loader module",
};

static_assert_no_msg((sizeof(callReasons)/sizeof(callReasons[0])) == CORINFO_INDIRECT_CALL_COUNT);

}

ZapperStats::ZapperStats()
    : m_methods( 0 )
    , m_failedMethods( 0 )
    , m_ilCodeSize( 0 )
    , m_nativeCodeSize( 0 )
    , m_nativeColdCodeSize( 0 )
    , m_nativeRODataSize( 0 )
    , m_gcInfoSize( 0 )
#ifdef WIN64EXCEPTIONS
    , m_unwindInfoSize( 0 )
#endif // WIN64EXCEPTIONS
    , m_NumHotAllocations( 0 )
    , m_NumHotColdAllocations( 0 )
    , m_NumMediumHeaders( 0 )
    , m_nativeCodeSizeInSplitMethods( 0 )
    , m_nativeColdCodeSizeInSplitMethods( 0 )
    , m_nativeCodeSizeInSplitProfiledMethods( 0 )
    , m_nativeColdCodeSizeInSplitProfiledMethods( 0 )
    , m_nativeCodeSizeInProfiledMethods( 0 )
    , m_nativeColdCodeSizeInProfiledMethods( 0 )
    , m_totalCodeSizeInProfiledMethods( 0 )
    , m_totalColdCodeSizeInProfiledMethods( 0 )
    , m_inputFileSize( 0 )
    , m_outputFileSize( 0 )
    , m_metadataSize( 0 )
    , m_preloadImageSize( 0 )
    , m_hotCodeMgrSize( 0 )
    , m_unprofiledCodeMgrSize( 0 )
    , m_coldCodeMgrSize( 0 )
    , m_eeInfoTableSize( 0 )
    , m_helperTableSize( 0 )
    , m_dynamicInfoTableSize( 0 )
    , m_dynamicInfoDelayListSize( 0 )
    , m_importTableSize( 0 )
    , m_debuggingTableSize( 0 )
    , m_headerSectionSize( 0 )
    , m_codeSectionSize( 0 )
    , m_coldCodeSectionSize( 0 )
    , m_exceptionSectionSize( 0 )
    , m_readOnlyDataSectionSize( 0 )
    , m_relocSectionSize( 0 )
    , m_ILMetadataSize( 0 )
    , m_externalMethodThunkSize( 0 )
    , m_externalMethodDataSize( 0 )
    , m_prestubMethods( 0 )
    , m_directMethods( 0 )
{
    init_array( m_indirectMethodReasons, CORINFO_INDIRECT_CALL_COUNT );
}

#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:21000) // Suppress PREFast warning about overly large function
#endif
void ZapperStats::PrintStats()
{
    if (m_outputFileSize > 0) {

        GetSvcLogger()->Printf( "-------------------------------------------------------\n");
        GetSvcLogger()->Printf( "Input file size:            %8d\n",         m_inputFileSize);
        GetSvcLogger()->Printf( "Output file size:           %8d\n", m_outputFileSize);
        GetSvcLogger()->Printf( "Input file size/Output file size ratio:\t%8.2fx\n", double( m_outputFileSize ) / m_inputFileSize);
        GetSvcLogger()->Printf( "\n");
        GetSvcLogger()->Printf( "Metadata:                   %8d\t%8.2f%%\n", m_metadataSize, (double)m_metadataSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Debugging maps:             %8d\t%8.2f%%\n", m_debuggingTableSize, (double)m_debuggingTableSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Hot Code manager:           %8d\t%8.2f%%\n", m_hotCodeMgrSize, (double)m_hotCodeMgrSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Unprofiled Code manager:    %8d\t%8.2f%%\n", m_unprofiledCodeMgrSize, (double)m_unprofiledCodeMgrSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Cold Code manager:          %8d\t%8.2f%%\n", m_coldCodeMgrSize, (double)m_coldCodeMgrSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "GC info:                    %8d\t%8.2f%%\n", m_headerSectionSize, (double)m_headerSectionSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Native code & r/o data:     %8d\t%8.2f%%\n", m_codeSectionSize, (double)m_codeSectionSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Cold code:                  %8d\t%8.2f%%\n", m_coldCodeSectionSize, (double)m_coldCodeSectionSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Exception tables:           %8d\t%8.2f%%\n", m_exceptionSectionSize, (double)m_exceptionSectionSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Relocs:                     %8d\t%8.2f%%\n", m_relocSectionSize, (double)m_relocSectionSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "IL metadata:                %8d\t%8.2f%%\n", m_ILMetadataSize, (double)m_ILMetadataSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "External Method Thunks:     %8d\t%8.2f%%\n", m_externalMethodThunkSize, (double)m_externalMethodThunkSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "External Method Data:       %8d\t%8.2f%%\n", m_externalMethodDataSize, (double)m_externalMethodDataSize/m_outputFileSize*100);
        GetSvcLogger()->Printf( "Image of EE structures:     %8d\t%8.2f%%\n", m_preloadImageSize, (double)m_preloadImageSize/m_outputFileSize*100);

        unsigned totalIndirections =
          m_dynamicInfoDelayListSize +
          m_eeInfoTableSize +
          m_helperTableSize +
          m_dynamicInfoTableSize +
          m_importTableSize;

        GetSvcLogger()->Printf( "Indirections:               %8d\t%8.2f%%\n",
                totalIndirections, (double)totalIndirections/m_outputFileSize*100);
        GetSvcLogger()->Printf( "       ----- Breakdown of Indirections ----\n");

        GetSvcLogger()->Printf( "       Delay load lists:           %8d\t%8.2f%%\n",
                m_dynamicInfoDelayListSize, (double)m_dynamicInfoDelayListSize/totalIndirections*100);
        GetSvcLogger()->Printf( "       Tables:                     %8d\t%8.2f%%\n",
                m_dynamicInfoTableSize, (double)m_dynamicInfoTableSize/totalIndirections*100);
        GetSvcLogger()->Printf( "       EE Values:                  %8d\t%8.2f%%\n",
                m_eeInfoTableSize, (double)m_eeInfoTableSize/totalIndirections*100);
        GetSvcLogger()->Printf( "       Helper functions:           %8d\t%8.2f%%\n",
                m_helperTableSize, (double)m_helperTableSize/totalIndirections*100);
    }

    GetSvcLogger()->Printf( "       Direct method descs:\t%5d/%5d %8.2f%%\n",
            m_directMethods, m_prestubMethods+m_directMethods,
            (double)m_directMethods/(m_directMethods+m_prestubMethods)*100);
    GetSvcLogger()->Printf( "       Indirect method descs:\t%5d/%5d %8.2f%%\n",
            m_prestubMethods, m_prestubMethods+m_directMethods,
            (double)m_prestubMethods/(m_directMethods+m_prestubMethods)*100);

    for (int i=0; i < CORINFO_INDIRECT_CALL_COUNT; i++)
        GetSvcLogger()->Printf( "               %-30s  %5d %8.2f%%\n",
                callReasons[i],
                m_indirectMethodReasons[i],
                double(m_indirectMethodReasons[i])/(m_directMethods+m_prestubMethods)*100);

    GetSvcLogger()->Printf( "-------------------------------------------------------\n");
    GetSvcLogger()->Printf( "Total Methods: \t\t\t\t%8d\n", m_methods);
    GetSvcLogger()->Printf( "Total Hot Only: \t\t\t%8d\n", m_NumHotAllocations);
    GetSvcLogger()->Printf( "Total Split (Hot/Cold): \t\t%8d\n", m_NumHotColdAllocations);
    GetSvcLogger()->Printf( "Total Medium Headers: \t\t\t%8d\n", m_NumMediumHeaders);
    GetSvcLogger()->Printf( "Split Methods: Hot Code \t\t%8d\n", m_nativeCodeSizeInSplitMethods);
    GetSvcLogger()->Printf( "Split Methods: Cold Code \t\t%8d\n", m_nativeColdCodeSizeInSplitMethods);
    GetSvcLogger()->Printf( "Split Profiled Methods: Hot Code \t%8d\n", m_nativeCodeSizeInSplitProfiledMethods);
    GetSvcLogger()->Printf( "Split Profiled Methods: Cold Code \t%8d\n", m_nativeColdCodeSizeInSplitProfiledMethods);
    GetSvcLogger()->Printf( "Profiled Methods: Hot Code \t\t%8d\n", m_nativeCodeSizeInProfiledMethods);
    GetSvcLogger()->Printf( "Profiled Methods: Cold Code \t\t%8d\n", m_nativeColdCodeSizeInProfiledMethods);
    GetSvcLogger()->Printf( "Profiled Methods: Total Hot Code+Headers %7d\n", m_totalCodeSizeInProfiledMethods);
    GetSvcLogger()->Printf( "Profiled Methods: Total Cold Code+Headers %6d\n", m_totalColdCodeSizeInProfiledMethods);
    GetSvcLogger()->Printf( "All Methods: Total Hot+Unprofiled Code \t\t%8d\n",  m_nativeCodeSize);
    GetSvcLogger()->Printf( "All Methods: Total Cold Code \t\t%8d\n", m_nativeColdCodeSize);
    GetSvcLogger()->Printf( "All Methods: Total Hot Code+Headers \t%8d\n",  m_totalHotCodeSize);
    GetSvcLogger()->Printf( "All Methods: Total Unprofiled Code+Headers \t%8d\n", m_totalUnprofiledCodeSize);
    GetSvcLogger()->Printf( "All Methods: Total Cold Code+Headers \t%8d\n", m_totalColdCodeSize);

    GetSvcLogger()->Printf( "-------------------------------------------------------\n");
    GetSvcLogger()->Printf( "Total IL Code:          %8d\n", m_ilCodeSize);
    GetSvcLogger()->Printf( "Total Native Code:      %8d\n", m_nativeCodeSize + m_nativeColdCodeSize);
    GetSvcLogger()->Printf( "Total Code+Headers:     %8d\n", m_totalHotCodeSize + m_totalUnprofiledCodeSize + m_totalColdCodeSize);

    GetSvcLogger()->Printf( "Total Native RO Data:   %8d\n", m_nativeRODataSize);
    GetSvcLogger()->Printf( "Total Native GC Info:   %8d\n", m_gcInfoSize);
    size_t nativeTotal = m_nativeCodeSize + m_nativeRODataSize + m_gcInfoSize;
#ifdef WIN64EXCEPTIONS
    GetSvcLogger()->Printf( "Total Native UnwindInfo:%8d\n", m_unwindInfoSize);
    nativeTotal += m_unwindInfoSize;
#endif // WIN64EXCEPTIONS
    GetSvcLogger()->Printf( "Total Native Total :    %8d\n", nativeTotal);

    if (m_methods > 0) {
        GetSvcLogger()->Printf( "\n");
        GetSvcLogger()->Printf( "Average IL Code:            %8.2f\n", double(m_ilCodeSize) / m_methods);
        GetSvcLogger()->Printf( "Average NativeCode:         %8.2f\n", double(m_nativeCodeSize) / m_methods);
        GetSvcLogger()->Printf( "Average Native RO Data:     %8.2f\n", double(m_nativeRODataSize) / m_methods);
        GetSvcLogger()->Printf( "Average Native GC Info:     %8.2f\n", double(m_gcInfoSize) / m_methods);
#ifdef WIN64EXCEPTIONS
        GetSvcLogger()->Printf( "Average Native UnwindInfo:  %8.2f\n", double(m_unwindInfoSize) / m_methods);
#endif // WIN64EXCEPTIONS
        GetSvcLogger()->Printf( "Average Native:             %8.2f\n", double(nativeTotal) / m_methods);
        GetSvcLogger()->Printf( "\n");
        GetSvcLogger()->Printf( "NativeGC / Native:      %8.2f\n", double(m_gcInfoSize) / nativeTotal);
        GetSvcLogger()->Printf( "Native / IL:            %8.2f\n", double(nativeTotal) / m_ilCodeSize);
    }

    if (m_failedMethods > 0)
        GetSvcLogger()->Printf( "Methods which did not compile: %d\n", m_failedMethods);
    if (m_failedILStubs > 0)
        GetSvcLogger()->Printf( "IL STUBS which did not compile: %d\n", m_failedILStubs);
}
#ifdef _PREFAST_
#pragma warning(pop)
#endif

char const * GetCallReasonString( CorInfoIndirectCallReason reason )
{
    return callReasons[ reason ];
}


text:
package info.neet_ai.machi_kiku;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class PlaylistAct extends AppCompatActivity {

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


text:
class Browser;
class PermissionRequestManager;
class PermissionRequest;

// This class is the platform-independent interface through which the permission
// request managers (which are one per tab) communicate to the UI surface.
// When the visible tab changes, the UI code must provide an object of this type
// to the manager for the visible tab.
class PermissionPrompt {
 public:
  // The delegate will receive events caused by user action which need to
  // be persisted in the per-tab UI state.
  class Delegate {
   public:
    virtual ~Delegate() {}

    virtual void ToggleAccept(int index, bool new_value) = 0;
    virtual void Accept() = 0;
    virtual void Deny() = 0;
    virtual void Closing() = 0;
  };

  typedef base::Callback<std::unique_ptr<PermissionPrompt>(Browser*)> Factory;

  // Create a platform specific instance.
  static std::unique_ptr<PermissionPrompt> Create(Browser* browser);
  virtual ~PermissionPrompt() {}

  // Sets the delegate which will receive UI events forwarded from the prompt.
  virtual void SetDelegate(Delegate* delegate) = 0;

  // Causes the request UI to show up with the given contents. This method may
  // be called with mostly-identical contents to the existing contents. This can
  // happen, for instance, if a new permission is requested and
  // CanAcceptRequestUpdate() is true.
  // Important: the view must not store any of the request objects it receives
  // in this call.
  virtual void Show(const std::vector<PermissionRequest*>& requests,
                    const std::vector<bool>& accept_state) = 0;

  // Returns true if the view can accept a new Show() command to coalesce
  // requests. Currently the policy is that this should return true if the view
  // is being shown and the mouse is not over the view area (!IsMouseHovered).
  virtual bool CanAcceptRequestUpdate() = 0;

  // Hides the permission prompt.
  virtual void Hide() = 0;

  // Returns true if there is a prompt currently showing.
  virtual bool IsVisible() = 0;

  // Updates where the prompt should be anchored. ex: fullscreen toggle.
  virtual void UpdateAnchorPosition() = 0;

  // Returns a reference to this prompt's native window.
  // TODO(hcarmona): Remove this as part of the bubble API work.
  virtual gfx::NativeWindow GetNativeWindow() = 0;
};

#endif  // CHROME_BROWSER_UI_WEBSITE_SETTINGS_PERMISSION_PROMPT_H_


text:
package org.apache.accumulo.gc;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.gc.thrift.GCStatus;
import org.apache.accumulo.core.gc.thrift.GcCycleStats;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.Ample.DataLevel;
import org.apache.accumulo.core.metadata.schema.MetadataSchema;
import org.apache.accumulo.core.replication.ReplicationSchema.StatusSection;
import org.apache.accumulo.core.replication.ReplicationTable;
import org.apache.accumulo.core.replication.ReplicationTableOfflineException;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.util.Pair;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.ServerContext;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.server.log.WalStateManager;
import org.apache.accumulo.server.log.WalStateManager.WalMarkerException;
import org.apache.accumulo.server.log.WalStateManager.WalState;
import org.apache.accumulo.server.master.LiveTServerSet;
import org.apache.accumulo.server.master.state.TServerInstance;
import org.apache.accumulo.server.master.state.TabletLocationState;
import org.apache.accumulo.server.master.state.TabletState;
import org.apache.accumulo.server.master.state.TabletStateStore;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.htrace.Trace;
import org.apache.htrace.TraceScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterators;

public class GarbageCollectWriteAheadLogs {
  private static final Logger log = LoggerFactory.getLogger(GarbageCollectWriteAheadLogs.class);

  private final ServerContext context;
  private final VolumeManager fs;
  private final boolean useTrash;
  private final LiveTServerSet liveServers;
  private final WalStateManager walMarker;
  private final Iterable<TabletLocationState> store;

  /**
   * Creates a new GC WAL object.
   *
   * @param context
   *          the collection server's context
   * @param fs
   *          volume manager to use
   * @param useTrash
   *          true to move files to trash rather than delete them
   */
  GarbageCollectWriteAheadLogs(final ServerContext context, final VolumeManager fs,
      final LiveTServerSet liveServers, boolean useTrash) {
    this.context = context;
    this.fs = fs;
    this.useTrash = useTrash;
    this.liveServers = liveServers;
    this.walMarker = new WalStateManager(context);
    this.store = () -> Iterators.concat(
        TabletStateStore.getStoreForLevel(DataLevel.ROOT, context).iterator(),
        TabletStateStore.getStoreForLevel(DataLevel.METADATA, context).iterator(),
        TabletStateStore.getStoreForLevel(DataLevel.USER, context).iterator());
  }

  /**
   * Creates a new GC WAL object. Meant for testing -- allows mocked objects.
   *
   * @param context
   *          the collection server's context
   * @param fs
   *          volume manager to use
   * @param useTrash
   *          true to move files to trash rather than delete them
   * @param liveTServerSet
   *          a started LiveTServerSet instance
   */
  @VisibleForTesting
  GarbageCollectWriteAheadLogs(ServerContext context, VolumeManager fs, boolean useTrash,
      LiveTServerSet liveTServerSet, WalStateManager walMarker,
      Iterable<TabletLocationState> store) {
    this.context = context;
    this.fs = fs;
    this.useTrash = useTrash;
    this.liveServers = liveTServerSet;
    this.walMarker = walMarker;
    this.store = store;
  }

  public void collect(GCStatus status) {
    try {
      long count;
      long fileScanStop;
      Map<TServerInstance,Set<UUID>> logsByServer;
      Map<UUID,Pair<WalState,Path>> logsState;
      Map<UUID,Path> recoveryLogs;
      try (TraceScope span = Trace.startSpan("getCandidates")) {
        status.currentLog.started = System.currentTimeMillis();

        recoveryLogs = getSortedWALogs();

        logsByServer = new HashMap<>();
        logsState = new HashMap<>();
        // Scan for log file info first: the order is important
        // Consider:
        // * get live servers
        // * new server gets a lock, creates a log
        // * get logs
        // * the log appears to belong to a dead server
        count = getCurrent(logsByServer, logsState);
        fileScanStop = System.currentTimeMillis();

        log.info(String.format("Fetched %d files for %d servers in %.2f seconds", count,
            logsByServer.size(), (fileScanStop - status.currentLog.started) / 1000.));
        status.currentLog.candidates = count;
      }

      // now it's safe to get the liveServers
      liveServers.scanServers();
      Set<TServerInstance> currentServers = liveServers.getCurrentServers();

      Map<UUID,TServerInstance> uuidToTServer;
      try (TraceScope span = Trace.startSpan("removeEntriesInUse")) {
        uuidToTServer = removeEntriesInUse(logsByServer, currentServers, logsState, recoveryLogs);
        count = uuidToTServer.size();
      } catch (Exception ex) {
        log.error("Unable to scan metadata table", ex);
        return;
      }

      long logEntryScanStop = System.currentTimeMillis();
      log.info(String.format("%d log entries scanned in %.2f seconds", count,
          (logEntryScanStop - fileScanStop) / 1000.));

      try (TraceScope span = Trace.startSpan("removeReplicationEntries")) {
        count = removeReplicationEntries(uuidToTServer);
      } catch (Exception ex) {
        log.error("Unable to scan replication table", ex);
        return;
      }

      long replicationEntryScanStop = System.currentTimeMillis();
      log.info(String.format("%d replication entries scanned in %.2f seconds", count,
          (replicationEntryScanStop - logEntryScanStop) / 1000.));

      long removeStop;
      try (TraceScope span = Trace.startSpan("removeFiles")) {

        logsState.keySet().retainAll(uuidToTServer.keySet());
        count = removeFiles(logsState.values(), status);

        removeStop = System.currentTimeMillis();
        log.info(String.format("%d total logs removed from %d servers in %.2f seconds", count,
            logsByServer.size(), (removeStop - logEntryScanStop) / 1000.));

        count = removeFiles(recoveryLogs.values());
        log.info("{} recovery logs removed", count);
      }

      try (TraceScope span = Trace.startSpan("removeMarkers")) {
        count = removeTabletServerMarkers(uuidToTServer, logsByServer, currentServers);
        long removeMarkersStop = System.currentTimeMillis();
        log.info(String.format("%d markers removed in %.2f seconds", count,
            (removeMarkersStop - removeStop) / 1000.));
      }

      status.currentLog.finished = removeStop;
      status.lastLog = status.currentLog;
      status.currentLog = new GcCycleStats();

    } catch (Exception e) {
      log.error("exception occured while garbage collecting write ahead logs", e);
    }
  }

  private long removeTabletServerMarkers(Map<UUID,TServerInstance> uidMap,
      Map<TServerInstance,Set<UUID>> candidates, Set<TServerInstance> liveServers) {
    long result = 0;
    // remove markers for files removed
    try {
      for (Entry<UUID,TServerInstance> entry : uidMap.entrySet()) {
        walMarker.removeWalMarker(entry.getValue(), entry.getKey());
      }
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
    // remove parent znode for dead tablet servers
    for (Entry<TServerInstance,Set<UUID>> entry : candidates.entrySet()) {
      if (!liveServers.contains(entry.getKey())) {
        log.info("Removing znode for " + entry.getKey());
        try {
          walMarker.forget(entry.getKey());
        } catch (WalMarkerException ex) {
          log.info("Error removing znode for " + entry.getKey() + " " + ex);
        }
      }
    }
    return result;
  }

  private long removeFile(Path path) {
    try {
      if (!useTrash || !fs.moveToTrash(path)) {
        fs.deleteRecursively(path);
      }
      return 1;
    } catch (FileNotFoundException ex) {
      // ignored
    } catch (IOException ex) {
      log.error("Unable to delete wal {}", path, ex);
    }

    return 0;
  }

  private long removeFiles(Collection<Pair<WalState,Path>> collection, final GCStatus status) {
    for (Pair<WalState,Path> stateFile : collection) {
      Path path = stateFile.getSecond();
      log.debug("Removing {} WAL {}", stateFile.getFirst(), path);
      status.currentLog.deleted += removeFile(path);
    }
    return status.currentLog.deleted;
  }

  private long removeFiles(Collection<Path> values) {
    long count = 0;
    for (Path path : values) {
      log.debug("Removing recovery log {}", path);
      count += removeFile(path);
    }
    return count;
  }

  private UUID path2uuid(Path path) {
    return UUID.fromString(path.getName());
  }

  private Map<UUID,TServerInstance> removeEntriesInUse(Map<TServerInstance,Set<UUID>> candidates,
      Set<TServerInstance> liveServers, Map<UUID,Pair<WalState,Path>> logsState,
      Map<UUID,Path> recoveryLogs) {

    Map<UUID,TServerInstance> result = new HashMap<>();
    for (Entry<TServerInstance,Set<UUID>> entry : candidates.entrySet()) {
      for (UUID id : entry.getValue()) {
        if (result.put(id, entry.getKey()) != null) {
          throw new IllegalArgumentException("WAL " + id + " owned by multiple tservers");
        }
      }
    }

    // remove any entries if there's a log reference (recovery hasn't finished)
    for (TabletLocationState state : store) {
      // Tablet is still assigned to a dead server. Master has moved markers and reassigned it
      // Easiest to just ignore all the WALs for the dead server.
      if (state.getState(liveServers) == TabletState.ASSIGNED_TO_DEAD_SERVER) {
        Set<UUID> idsToIgnore = candidates.remove(state.current);
        if (idsToIgnore != null) {
          result.keySet().removeAll(idsToIgnore);
          recoveryLogs.keySet().removeAll(idsToIgnore);
        }
      }
      // Tablet is being recovered and has WAL references, remove all the WALs for the dead server
      // that made the WALs.
      for (Collection<String> wals : state.walogs) {
        for (String wal : wals) {
          UUID walUUID = path2uuid(new Path(wal));
          TServerInstance dead = result.get(walUUID);
          // There's a reference to a log file, so skip that server's logs
          Set<UUID> idsToIgnore = candidates.remove(dead);
          if (idsToIgnore != null) {
            result.keySet().removeAll(idsToIgnore);
            recoveryLogs.keySet().removeAll(idsToIgnore);
          }
        }
      }
    }

    // Remove OPEN and CLOSED logs for live servers: they are still in use
    for (TServerInstance liveServer : liveServers) {
      Set<UUID> idsForServer = candidates.get(liveServer);
      // Server may not have any logs yet
      if (idsForServer != null) {
        for (UUID id : idsForServer) {
          Pair<WalState,Path> stateFile = logsState.get(id);
          if (stateFile.getFirst() != WalState.UNREFERENCED) {
            result.remove(id);
          }
        }

        recoveryLogs.keySet().removeAll(idsForServer);
      }
    }
    return result;
  }

  protected int removeReplicationEntries(Map<UUID,TServerInstance> candidates) {
    try {
      try {
        final Scanner s = ReplicationTable.getScanner(context);
        StatusSection.limit(s);
        for (Entry<Key,Value> entry : s) {
          UUID id = path2uuid(new Path(entry.getKey().getRow().toString()));
          candidates.remove(id);
          log.info("Ignore closed log " + id + " because it is being replicated");
        }
      } catch (ReplicationTableOfflineException ex) {
        return candidates.size();
      }

      final Scanner scanner = context.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
      scanner.fetchColumnFamily(MetadataSchema.ReplicationSection.COLF);
      scanner.setRange(MetadataSchema.ReplicationSection.getRange());
      for (Entry<Key,Value> entry : scanner) {
        Text file = new Text();
        MetadataSchema.ReplicationSection.getFile(entry.getKey(), file);
        UUID id = path2uuid(new Path(file.toString()));
        candidates.remove(id);
        log.info("Ignore closed log " + id + " because it is being replicated");
      }

      return candidates.size();
    } catch (TableNotFoundException e) {
      log.error("Failed to scan metadata table", e);
      throw new IllegalArgumentException(e);
    }
  }

  /**
   * Scans log markers. The map passed in is populated with the log ids.
   *
   * @param logsByServer
   *          map of dead server to log file entries
   * @return total number of log files
   */
  private long getCurrent(Map<TServerInstance,Set<UUID>> logsByServer,
      Map<UUID,Pair<WalState,Path>> logState) throws Exception {

    // get all the unused WALs in zookeeper
    long result = 0;
    Map<TServerInstance,List<UUID>> markers = walMarker.getAllMarkers();
    for (Entry<TServerInstance,List<UUID>> entry : markers.entrySet()) {
      HashSet<UUID> ids = new HashSet<>(entry.getValue().size());
      for (UUID id : entry.getValue()) {
        ids.add(id);
        logState.put(id, walMarker.state(entry.getKey(), id));
        result++;
      }
      logsByServer.put(entry.getKey(), ids);
    }
    return result;
  }

  /**
   * Looks for write-ahead logs in recovery directories.
   *
   * @return map of log uuids to paths
   */
  protected Map<UUID,Path> getSortedWALogs() throws IOException {
    Map<UUID,Path> result = new HashMap<>();

    for (String dir : ServerConstants.getRecoveryDirs(context)) {
      Path recoveryDir = new Path(dir);
      if (fs.exists(recoveryDir)) {
        for (FileStatus status : fs.listStatus(recoveryDir)) {
          try {
            UUID logId = path2uuid(status.getPath());
            result.put(logId, status.getPath());
          } catch (IllegalArgumentException iae) {
            log.debug("Ignoring file " + status.getPath() + " because it doesn't look like a uuid");
          }

        }
      }
    }
    return result;
  }
}


text:
package com.hippo.ehviewer.client;

import android.content.Context;

import com.hippo.network.CookieRepository;

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

import okhttp3.Cookie;
import okhttp3.HttpUrl;

public class EhCookieStore extends CookieRepository {

    public static final String KEY_IPD_MEMBER_ID = "ipb_member_id";
    public static final String KEY_IPD_PASS_HASH = "ipb_pass_hash";
    public static final String KEY_IGNEOUS = "igneous";

    public static final Cookie sTipsCookie =
            new Cookie.Builder()
                    .name(EhConfig.KEY_CONTENT_WARNING)
                    .value(EhConfig.CONTENT_WARNING_NOT_SHOW)
                    .domain(EhUrl.DOMAIN_E)
                    .path("/")
                    .expiresAt(Long.MAX_VALUE)
                    .build();

    public EhCookieStore(Context context) {
        super(context, "okhttp3-cookie.db");
    }

    public void signOut() {
        clear();
    }

    public boolean hasSignedIn() {
        HttpUrl url = HttpUrl.parse(EhUrl.HOST_E);
        return contains(url, KEY_IPD_MEMBER_ID) &&
                contains(url, KEY_IPD_PASS_HASH);
    }

    public static Cookie newCookie(Cookie cookie, String newDomain, boolean forcePersistent,
            boolean forceLongLive, boolean forceNotHostOnly) {
        Cookie.Builder builder = new Cookie.Builder();
        builder.name(cookie.name());
        builder.value(cookie.value());

        if (forceLongLive) {
            builder.expiresAt(Long.MAX_VALUE);
        } else if (cookie.persistent()) {
            builder.expiresAt(cookie.expiresAt());
        } else if (forcePersistent) {
            builder.expiresAt(Long.MAX_VALUE);
        }
        if (cookie.hostOnly() && !forceNotHostOnly) {
            builder.hostOnlyDomain(newDomain);
        } else {
            builder.domain(newDomain);
        }
        builder.path(cookie.path());
        if (cookie.secure()) {
            builder.secure();
        }
        if (cookie.httpOnly()) {
            builder.httpOnly();
        }
        return builder.build();
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = super.loadForRequest(url);

        boolean checkTips = domainMatch(url, EhUrl.DOMAIN_E);

        if (checkTips) {
            List<Cookie> result = new ArrayList<>(cookies.size() + 1);
            // Add all but skip some
            for (Cookie cookie: cookies) {
                String name = cookie.name();
                if (EhConfig.KEY_CONTENT_WARNING.equals(name)) {
                    continue;
                }
                if (EhConfig.KEY_UCONFIG.equals(name)) {
                    continue;
                }
                result.add(cookie);
            }
            // Add some
            result.add(sTipsCookie);
            return Collections.unmodifiableList(result);
        } else {
            return cookies;
        }
    }
}


text:
/*	$NetBSD: npf_conn.h,v 1.6.2.2 2014/12/22 02:10:30 msaitoh Exp $	*/

/*-
 * Copyright (c) 2009-2014 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This material is based upon work partially supported by The
 * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _NPF_CONN_H_
#define _NPF_CONN_H_

#if !defined(_KERNEL)
#error "kernel-level header only"
#endif

#include <sys/types.h>

#include "npf_impl.h"

typedef struct npf_connkey npf_connkey_t;

#if defined(__NPF_CONN_PRIVATE)

#include <sys/rbtree.h>

/*
 * See npf_conn_conkey() function for the key layout description.
 */
#define	NPF_CONN_NKEYWORDS	(2 + ((sizeof(npf_addr_t) * 2) >> 2))
#define	NPF_CONN_MAXKEYLEN	(NPF_CONN_NKEYWORDS * sizeof(uint32_t))
#define	NPF_CONN_GETALEN(key)	((key)->ck_key[0] & 0xffff)
#define	NPF_CONN_KEYLEN(key)	(8 + (2 * NPF_CONN_GETALEN(key)))

struct npf_connkey {
	/* Entry node and back-pointer to the actual connection. */
	rb_node_t		ck_rbnode;
	uint32_t		ck_key[NPF_CONN_NKEYWORDS];
	npf_conn_t *		ck_backptr;
};

/*
 * The main connection tracking structure.
 */

struct npf_conn {
	/*
	 * Connection "forwards" and "backwards" entries, plus the
	 * interface ID (if zero, then the state is global).
	 */
	npf_connkey_t		c_forw_entry;
	npf_connkey_t		c_back_entry;
	u_int			c_proto;
	u_int			c_ifid;

	/* Flags and entry in the connection database or G/C list. */
	u_int			c_flags;
	npf_conn_t *		c_next;

	/* Associated rule procedure or NAT (if any). */
	npf_rproc_t *		c_rproc;
	npf_nat_t *		c_nat;

	/*
	 * The protocol state, reference count and the last activity
	 * time (used to calculate expiration time).
	 */
	kmutex_t		c_lock;
	npf_state_t		c_state;
	u_int			c_refcnt;
	struct timespec		c_atime;
};

#endif

/*
 * Connection tracking interface.
 */
void		npf_conn_sysinit(void);
void		npf_conn_sysfini(void);
void		npf_conn_tracking(bool);
void		npf_conn_load(npf_conndb_t *, bool);

unsigned	npf_conn_conkey(const npf_cache_t *, npf_connkey_t *, bool);
npf_conn_t *	npf_conn_lookup(const npf_cache_t *, const int, bool *);
npf_conn_t *	npf_conn_inspect(npf_cache_t *, const int, int *);
npf_conn_t *	npf_conn_establish(npf_cache_t *, int, bool);
void		npf_conn_release(npf_conn_t *);
void		npf_conn_expire(npf_conn_t *);
bool		npf_conn_pass(const npf_conn_t *, npf_rproc_t **);
void		npf_conn_setpass(npf_conn_t *, npf_rproc_t *);
int		npf_conn_setnat(const npf_cache_t *, npf_conn_t *,
		    npf_nat_t *, u_int);
npf_nat_t *	npf_conn_getnat(npf_conn_t *, const int, bool *);
void		npf_conn_gc(npf_conndb_t *, bool, bool);
int		npf_conn_import(npf_conndb_t *, prop_dictionary_t,
		    npf_ruleset_t *);
prop_dictionary_t npf_conn_export(const npf_conn_t *);
void		npf_conn_print(const npf_conn_t *);

/*
 * Connection database (aka state table) interface.
 */
npf_conndb_t *	npf_conndb_create(void);
void		npf_conndb_destroy(npf_conndb_t *);

npf_conn_t *	npf_conndb_lookup(npf_conndb_t *, const npf_connkey_t *,
		    bool *);
bool		npf_conndb_insert(npf_conndb_t *, npf_connkey_t *,
		    npf_conn_t *);
npf_conn_t *	npf_conndb_remove(npf_conndb_t *, const npf_connkey_t *);

void		npf_conndb_enqueue(npf_conndb_t *, npf_conn_t *);
void		npf_conndb_dequeue(npf_conndb_t *, npf_conn_t *,
		    npf_conn_t *);
npf_conn_t *	npf_conndb_getlist(npf_conndb_t *);
void		npf_conndb_settail(npf_conndb_t *, npf_conn_t *);
int		npf_conndb_export(prop_array_t);

#endif	/* _NPF_CONN_H_ */


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE400_Resource_Exhaustion__fgets_sleep_07.c
Label Definition File: CWE400_Resource_Exhaustion.label.xml
Template File: sources-sinks-07.tmpl.c
*/
/*
 * @description
 * CWE: 400 Resource Exhaustion
 * BadSource: fgets Read data from the console using fgets()
 * GoodSource: Assign count to be a relatively small number
 * Sinks: sleep
 *    GoodSink: Validate count before using it as a parameter in sleep function
 *    BadSink : Use count as the parameter for sleep withhout checking it's size first
 * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
 *
 * */

#include "std_testcase.h"

#define CHAR_ARRAY_SIZE (3 * sizeof(count) + 2)

#ifdef _WIN32
#include <windows.h>
#define SLEEP Sleep
#else
#include <unistd.h>
#define SLEEP usleep
#endif

/* The variable below is not declared "const", but is never assigned
   any other value so a tool should be able to identify that reads of
   this will always give its initialized value. */
static int staticFive = 5;

#ifndef OMITBAD

void CWE400_Resource_Exhaustion__fgets_sleep_07_bad()
{
    int count;
    /* Initialize count */
    count = -1;
    if(staticFive==5)
    {
        {
            char inputBuffer[CHAR_ARRAY_SIZE] = "";
            /* POTENTIAL FLAW: Read count from the console using fgets() */
            if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
            {
                /* Convert to int */
                count = atoi(inputBuffer);
            }
            else
            {
                printLine("fgets() failed.");
            }
        }
    }
    if(staticFive==5)
    {
        /* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
        SLEEP(count);
        printLine("Sleep time possibly too long");
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */
static void goodB2G1()
{
    int count;
    /* Initialize count */
    count = -1;
    if(staticFive==5)
    {
        {
            char inputBuffer[CHAR_ARRAY_SIZE] = "";
            /* POTENTIAL FLAW: Read count from the console using fgets() */
            if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
            {
                /* Convert to int */
                count = atoi(inputBuffer);
            }
            else
            {
                printLine("fgets() failed.");
            }
        }
    }
    if(staticFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Validate count before using it as a parameter in the sleep function */
        if (count > 0 && count <= 2000)
        {
            SLEEP(count);
            printLine("Sleep time OK");
        }
        else
        {
            printLine("Sleep time too long");
        }
    }
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
    int count;
    /* Initialize count */
    count = -1;
    if(staticFive==5)
    {
        {
            char inputBuffer[CHAR_ARRAY_SIZE] = "";
            /* POTENTIAL FLAW: Read count from the console using fgets() */
            if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
            {
                /* Convert to int */
                count = atoi(inputBuffer);
            }
            else
            {
                printLine("fgets() failed.");
            }
        }
    }
    if(staticFive==5)
    {
        /* FIX: Validate count before using it as a parameter in the sleep function */
        if (count > 0 && count <= 2000)
        {
            SLEEP(count);
            printLine("Sleep time OK");
        }
        else
        {
            printLine("Sleep time too long");
        }
    }
}

/* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
    int count;
    /* Initialize count */
    count = -1;
    if(staticFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Use a relatively small number */
        count = 20;
    }
    if(staticFive==5)
    {
        /* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
        SLEEP(count);
        printLine("Sleep time possibly too long");
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
    int count;
    /* Initialize count */
    count = -1;
    if(staticFive==5)
    {
        /* FIX: Use a relatively small number */
        count = 20;
    }
    if(staticFive==5)
    {
        /* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
        SLEEP(count);
        printLine("Sleep time possibly too long");
    }
}

void CWE400_Resource_Exhaustion__fgets_sleep_07_good()
{
    goodB2G1();
    goodB2G2();
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE400_Resource_Exhaustion__fgets_sleep_07_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE400_Resource_Exhaustion__fgets_sleep_07_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
from django.conf import settings
from django.conf.urls import include, patterns, url
from django.contrib.auth.signals import user_logged_in
from django.test import TestCase
from django.test.utils import override_settings
from rest_framework.test import APITestCase

urlpatterns = patterns('',
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)

class TestLogin(TestCase):
    urls = __name__ # Work around a Django bug: https://code.djangoproject.com/ticket/21766

    def setUp(self):
        from .util import get_user_model
        self.username = 'frodo'
        self.password = 'shire1234'
        user = get_user_model().objects.create_user(
            username=self.username,
            password=self.password
        )

    def test_login_view_does_not_set_upload_prefix_cookie_by_default(self):
        data = {
            'username': self.username,
            'password': self.password,
        }
        resp = self.client.post('/api-auth/login/', data)
        self.assertNotIn('upload_prefix', resp.cookies)

    @override_settings(
        MIDDLEWARE_CLASSES=settings.MIDDLEWARE_CLASSES + ('drf_to_s3.middleware.UploadPrefixMiddleware',)
    )
    def test_login_view_sets_upload_prefix_cookie(self):
        data = {
            'username': self.username,
            'password': self.password,
        }
        resp = self.client.post('/api-auth/login/', data)
        self.assertEquals(resp.cookies['upload_prefix'].value, self.username)

    @override_settings(
        MIDDLEWARE_CLASSES=settings.MIDDLEWARE_CLASSES + ('drf_to_s3.middleware.UploadPrefixMiddleware',),
        UPLOAD_PREFIX_COOKIE_NAME='my-app-prefix-cookie',
    )
    def test_login_view_honors_cookie_name_setting(self):
        data = {
            'username': self.username,
            'password': self.password,
        }
        resp = self.client.post('/api-auth/login/', data)
        self.assertNotIn('upload_prefix', resp.cookies)
        self.assertEquals(resp.cookies['my-app-prefix-cookie'].value, self.username)


text:
<!DOCTYPE HTML>

<title>Uses of Class io.constructor.client.models.Result (constructorio-client 5.21.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-11-21">
<meta name="description" content="use: package: io.constructor.client.models, class: Result">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Index

Help

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Uses of Class
io.constructor.client.models.Result

Packages that use Result

Package

Description

io.constructor.client.models

Uses of Result in io.constructor.client.models

Methods in io.constructor.client.models that return types with arguments of type Result

Modifier and Type

Method

Description

List<Result>

BrowseResponseInner.getResults()

List<Result>

RecommendationsResponseInner.getResults()

List<Result>

SearchResponseInner.getResults()

Map<String,<wbr>List<Result>>

AutocompleteResponse.getSections()

List<Result>

Result.getVariations()

Copyright © 2022. All rights reserved.


text:
package pl.rest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import pl.rest.model.Team;
import pl.rest.repozytoria.TeamRepository;

@RestController("football")
public class FootballService {

	@Autowired
	TeamRepository teamRepository;

	@RequestMapping
	public Iterable<Team> hello(@RequestParam(value="name", defaultValue="World") String name){
		return teamRepository.findAll();

	}
}


text:
class CreateContactReminders < ActiveRecord::Migration
  def up
    execute <<-EOSQL
        CREATE TABLE contact_reminders (
          id bigint(11) NOT NULL AUTO_INCREMENT,
          contact_id bigint(11) NOT NULL,
          content varchar(200) NOT NULL,
          color varchar(20),
          time TIMESTAMP,
          created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    EOSQL
  end

  def down
    execute <<-EOSQL
      DROP TABLE contact_reminders
    EOSQL
  end
end


text:
package org.smartdata.integration.util;

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.apache.commons.lang.StringUtils;
import org.smartdata.agent.SmartAgent;
import org.smartdata.integration.rest.RestApiBase;
import org.smartdata.server.SmartDaemon;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static io.restassured.path.json.JsonPath.with;

public class Util {

  public static void waitSlaveServerAvailable() throws InterruptedException {
    Util.retryUntil(new RetryTask() {
      @Override
      public boolean retry() {
        Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/servers");
        List<String> ids = with(response.asString()).get("body.id");
        return ids.size() > 0;
      }
    }, 15);
  }

  public static void waitSlaveServersDown() throws InterruptedException {
    Util.retryUntil(new RetryTask() {
      @Override
      public boolean retry() {
        Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/servers");
        List<String> ids = with(response.asString()).get("body.id");
        return ids.size() == 0;
      }
    }, 15);
  }

  public static void waitAgentAvailable() throws InterruptedException {
    Util.retryUntil(new RetryTask() {
      @Override
      public boolean retry() {
        Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/agents");
        List<String> ids = with(response.asString()).get("body.id");
        return ids.size() > 0;
      }
    }, 15);
  }

  public static void waitAgentsDown() throws InterruptedException {
    Util.retryUntil(new RetryTask() {
      @Override
      public boolean retry() {
        Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/agents");
        List<String> ids = with(response.asString()).get("body.id");
        return ids.size() == 0;
      }
    }, 15);
  }

  public static void retryUntil(RetryTask retryTask, int maxRetries) throws InterruptedException {
    retryUntil(retryTask, maxRetries, 1000);
  }

  public static void retryUntil(RetryTask retryTask, int maxRetries, long interval)
      throws InterruptedException {
    boolean met = false;
    int retries = 0;

    while (!met && retries < maxRetries) {
      met = retryTask.retry();
      retries += 1;
      if (!met) {
        Thread.sleep(interval);
      }
    }

    if (!met) {
      throw new RuntimeException("Failed after retry " + maxRetries + "times.");
    }
  }

  public static Process startNewServer() throws IOException {
    return Util.buildProcess(
        System.getProperty("java.class.path").split(java.io.File.pathSeparator),
        SmartDaemon.class.getCanonicalName(),
        new String[0]);
  }

  public static Process startNewAgent() throws IOException {
    return Util.buildProcess(
        System.getProperty("java.class.path").split(java.io.File.pathSeparator),
        SmartAgent.class.getCanonicalName(),
        new String[0]);
  }

  public static Process buildProcess(
      String[] options, String[] classPath, String mainClass, String[] arguments)
      throws IOException {
    String java = System.getProperty("java.home") + "/bin/java";
    List<String> commands = new ArrayList<>();
    commands.add(java);
    commands.addAll(Arrays.asList(options));
    commands.add("-cp");
    commands.add(StringUtils.join(classPath, File.pathSeparator));
    commands.add(mainClass);
    commands.addAll(Arrays.asList(arguments));
    return new ProcessBuilder(commands).start();
  }

  public static Process buildProcess(String mainClass, String[] arguments) throws IOException {
    return buildProcess(new String[0], mainClass, arguments);
  }

  public static Process buildProcess(String[] classPath, String mainClass, String[] arguments)
      throws IOException {
    return buildProcess(new String[0], classPath, mainClass, arguments);
  }
}


text:
package com.iluwatar;

/**
 *
 * Oliphaunts are expensive to create
 *
 */
public class Oliphaunt {

	private static int counter = 1;

	private final int id;

	public Oliphaunt() {
		id = counter++;
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public int getId() {
		return id;
	}

	@Override
	public String toString() {
		return String.format("Oliphaunt id=%d", id);
	}
}


text:
describe RuboCop::Cop::Lint::Obscure do
  let(:config) { RuboCop::Config.new }
  subject(:cop) { described_class.new(config) }

  it 'registers an offense when using flipflop' do
    expect_offense(<<~RUBY)
      puts 'foo' if 'a'..'b'
                    ^^^^^^^^ Do not use the flipflop operator
    RUBY
  end

  it 'registers an offense when using eflipflop' do
    expect_offense(<<~RUBY)
      puts 'foo' if 'a'...'b'
                    ^^^^^^^^^ Do not use the flipflop operator
    RUBY
  end

  it 'registers an offense when using String#%' do
    expect_offense(<<~RUBY)
      puts 'foo' % 'bar'
           ^^^^^^^^^^^^^ Do not use String#%
    RUBY
  end

  it 'does not register an offense when using incluse Range `..`' do
    expect_no_offenses(<<~RUBY)
      1..2
    RUBY
  end

  it 'does not register an offense when using exclusive Range `...`' do
    expect_no_offenses(<<~RUBY)
      1...2
    RUBY
  end
end