text:
var vows = require('vows');
var assert = require('assert');
var url = require('url');
var util = require('util');
var token = require('middleware/token');
var Server = require('server');

function MockRequest() {
}

function MockResponse() {
  this._headers = {};
  this._data = '';
}

MockResponse.prototype.setHeader = function(name, value) {
  this._headers[name] = value;
}

MockResponse.prototype.end = function(data, encoding) {
  this._data += data;
  if (this.done) { this.done(); }
}

vows.describe('token').addBatch({

  'middleware that issues an access token': {
    topic: function() {
      var server = new Server();
      server.exchange('authorization_code', function(req, res, next) {
        if (req.body.code == 'abc123') {
          var json = JSON.stringify({ token_type: 'bearer', access_token: 'aaa-111-ccc' });
          res.end(json);
        } else {
          return done(new Error('something is wrong'));
        }
      });

      return token(server);
    },

    'when handling a request': {
      topic: function(token) {
        var self = this;
        var req = new MockRequest();
        req.body = { grant_type: 'authorization_code', code: 'abc123' };

        var res = new MockResponse();
        res.done = function() {
          self.callback(null, req, res);
        }

        function next(err) {
          self.callback(new Error('should not be called'));
        }
        process.nextTick(function () {
          token(req, res, next)
        });
      },

      'should not call next' : function(err, req, res, e) {
        assert.isNull(err);
      },
      'should send response' : function(err, req, res) {
        assert.equal(res._data, '{"token_type":"bearer","access_token":"aaa-111-ccc"}');
      },
    },
  },

  'middleware that handles a request with an unsupported grant type': {
    topic: function() {
      var server = new Server();
      server.exchange('authorization_code', function(req, res, next) {
        var json = JSON.stringify({ token_type: 'bearer', access_token: 'aaa-111-ccc' });
        res.end(json);
      });

      return token(server);
    },

    'when handling a request': {
      topic: function(token) {
        var self = this;
        var req = new MockRequest();
        req.body = { grant_type: 'foo', code: 'abc123' };

        var res = new MockResponse();
        res.done = function() {
          self.callback(new Error('should not be called'));
        }

        function next(err) {
          self.callback(null, req, res, err);
        }
        process.nextTick(function () {
          token(req, res, next)
        });
      },

      'should not respond to request' : function(err, req, res) {
        assert.isNull(err);
      },
      'should next with error' : function(err, req, res, e) {
        assert.instanceOf(e, Error);
        assert.equal(e.constructor.name, 'AuthorizationError');
        assert.equal(e.code, 'unsupported_grant_type');
      },
    },
  },

  'middleware that errors while exhanging a grant': {
    topic: function() {
      var server = new Server();
      server.exchange('authorization_code', function(req, res, next) {
        next(new Error('something went wrong'));
      });

      return token(server);
    },

    'when handling a request': {
      topic: function(token) {
        var self = this;
        var req = new MockRequest();
        req.body = { grant_type: 'authorization_code', code: 'abc123' };

        var res = new MockResponse();
        res.done = function() {
          self.callback(new Error('should not be called'));
        }

        function next(err) {
          self.callback(null, req, res, err);
        }
        process.nextTick(function () {
          token(req, res, next)
        });
      },

      'should not respond to request' : function(err, req, res) {
        assert.isNull(err);
      },
      'should next with error' : function(err, req, res, e) {
        assert.instanceOf(e, Error);
      },
    },
  },

  'middleware constructed without a server instance': {
    'should throw an error': function () {
      assert.throws(function() { token() });
    },
  },

}).export(module);


text:
package co.unruly.control;

import co.unruly.control.pair.Pair;
import org.junit.Test;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static co.unruly.control.HigherOrderFunctions.withIndices;
import static co.unruly.control.HigherOrderFunctions.zip;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;

public class ZipTest {

    @Test
    public void zipsItemsTogether() {
        List<Pair<String, String>> pairs = zip(
            Stream.of("hello", "goodbye"),
            Stream.of("world", "cruel world"))
        .collect(Collectors.toList());

        assertThat(pairs, contains(Pair.of("hello", "world"), Pair.of("goodbye", "cruel world")));
    }

    @Test
    public void zipsItemsTogetherUsingFunction() {
        List<Integer> pairs = zip(
            Stream.of(1,2,3,4,5),
            Stream.of(1,10,100,1000,10000),
            (x, y) -> x * y)
        .collect(Collectors.toList());

        assertThat(pairs, contains(1, 20, 300, 4000, 50000));
    }

    @Test
    public void generatedStreamIsShorterOfInputStreams() {
        List<Integer> pairs = zip(
            Stream.of(1,2,3),
            Stream.of(1,10,100,1000,10000),
            (x, y) -> x * y)
        .collect(Collectors.toList());

        assertThat(pairs, contains(1, 20, 300));
    }

    @Test
    public void buildsIndexedList() {
        List<Pair<Integer, String>> indexed = withIndices(Stream.of("zero", "one", "two", "three"))
        .collect(Collectors.toList());

        assertThat(indexed, contains(Pair.of(0, "zero"), Pair.of(1, "one"), Pair.of(2, "two"), Pair.of(3, "three")));
    }
}

redpajama_set_name: RedPajamaGithub


text:
var Matrix4 = require('./math/matrix4') ;
var Vector3 = require('./math/vector3') ;
var Geometry = require('./geometry') ;
var Base = require('./base') ;

var Model = function(def, renderer) {
  Base.call(this, renderer) ;

  if (typeof renderer === 'undefined') {
    throw "Must define a renderer!" ;
  }

  this.transformedVerts = [] ;

  if (typeof def !== 'undefined') {
    this.loadDef (def) ;
  }
};

Model.prototype = Object.create(Base.prototype) ;
Model.prototype.constructor = Model ;

Model.prototype.loadDef = function (modelDef) {
  var initMaterials = {} ;
  var mats = Object.keys(modelDef.lines) ;

  for (var i = 0; i < mats.length; i++) {
    initMaterials[mats[i]] = {
      alpha: 1.0,
      color: 0xFFFFFF
      //color: Math.floor(Math.random()*16777215)
    };
  }

  this.def = modelDef ;
  this.materials = initMaterials ;
} ;

Model.prototype.update = function() {
  this.applyTransforms () ;
  this.transformedVerts = Geometry.generateTransformedVerts (
    this.renderer.projMatrix, this.modelMatrix, this.def.vertices) ;
} ;

Model.prototype.render = function(graphics) {
  this.renderer.renderModelToGraphics(this, graphics, this.lineThickness) ;
} ;

module.exports = Model ;


text:
import ReactiveElement from "../core/ReactiveElement.js";
import CalendarElementMixin from "./CalendarElementMixin.js";

export default class CalendarMonthYearHeader extends CalendarElementMixin(
  ReactiveElement
) {
  monthFormat: "numeric" | "2-digit" | "long" | "short" | "narrow";
  yearFormat: "numeric" | "2-digit";
}


text:
var name=xpath("//h1[@class='entry-title public']/strong/a/text()")
var readme=xpath("//div[@id='readme']/tidyText()")
var star=xpath("//ul[@class='pagehead-actions']/li[1]//a[@class='social-count js-social-count']/text()")
var fork=xpath("//ul[@class='pagehead-actions']/li[2]//a[@class='social-count']/text()")
var url=page.getUrl().toString()
if (name!=null){
    println(name)
    println(readme)
    println(star)
    println(url)
}

urls("(https://github\\.com/\\w+/\\w+)")
urls("(https://github\\.com/\\w+)")


text: Colocviu 1 PDSD


text:
namespace Lab3
{
	class MainWindow : public Window
	{
	public:
		MainWindow(HINSTANCE hInst, int nCmdShow, LPCWSTR appTitle, LPCWSTR mainWindowClassName,
					int x, int y, int width, int height);
		~MainWindow();

		Button *DrawButton, *ClearButton;
		bool DisplayPicture;

		bool AddWindowMessages() override;

		int Start();
		BOOL Show(int nCmdShow);

		LRESULT OnResize(WPARAM wParam, LPARAM lParam) override;
		LRESULT OnPaint(WPARAM wParam, LPARAM lParam) override;
		LRESULT OnCommand(WPARAM wParam, LPARAM lParam) override;
		LRESULT OnDrawItem(WPARAM wParam, LPARAM lParam);

		void ChangePictureState(bool display);
		void DrawPicture(HDC hdc);
	};
}


text:
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.bazel.repository;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.bazel.rules.workspace.MavenJarRule;
import com.google.devtools.build.lib.packages.AggregatingAttributeMapper;
import com.google.devtools.build.lib.packages.AttributeMap;
import com.google.devtools.build.lib.packages.PackageIdentifier.RepositoryName;
import com.google.devtools.build.lib.packages.Rule;
import com.google.devtools.build.lib.packages.Type;
import com.google.devtools.build.lib.skyframe.FileValue;
import com.google.devtools.build.lib.skyframe.RepositoryValue;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;

import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;

import java.io.IOException;
import java.util.List;

import javax.annotation.Nullable;

/**
 * Implementation of maven_jar.
 */
public class MavenJarFunction extends HttpArchiveFunction {

  @Override
  public SkyValue compute(SkyKey skyKey, Environment env) throws RepositoryFunctionException {
    RepositoryName repositoryName = (RepositoryName) skyKey.argument();
    Rule rule = RepositoryFunction.getRule(repositoryName, MavenJarRule.NAME, env);
    if (rule == null) {
      return null;
    }
    AggregatingAttributeMapper mapper = AggregatingAttributeMapper.of(rule);
    MavenDownloader downloader = createMavenDownloader(mapper);
    return createOutputTree(downloader, env);
  }

  @VisibleForTesting
  MavenDownloader createMavenDownloader(AttributeMap mapper) {
    String name = mapper.getName();
    Path outputDirectory = getExternalRepositoryDirectory().getRelative(name);
    return new MavenDownloader(name, mapper, outputDirectory);
  }

  SkyValue createOutputTree(MavenDownloader downloader, Environment env)
      throws RepositoryFunctionException {
    FileValue outputDirectoryValue = createDirectory(downloader.getOutputDirectory(), env);
    if (outputDirectoryValue == null) {
      return null;
    }

    Path repositoryJar;
    try {
      repositoryJar = downloader.download();
    } catch (IOException e) {
      throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }

    // Add a WORKSPACE file & BUILD file to the Maven jar.
    DecompressorValue value;
    try {
      value = (DecompressorValue) env.getValueOrThrow(DecompressorValue.jarKey(
          MavenJarRule.NAME, downloader.getName(), repositoryJar,
          outputDirectoryValue.realRootedPath().asPath()), IOException.class);
      if (value == null) {
        return null;
      }
    } catch (IOException e) {
      throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }
    FileValue repositoryFileValue = getRepositoryDirectory(value.getDirectory(), env);
    if (repositoryFileValue == null) {
      return null;
    }
    return RepositoryValue.create(repositoryFileValue);
  }

  @Override
  public SkyFunctionName getSkyFunctionName() {
    return SkyFunctionName.create(Ascii.toUpperCase(MavenJarRule.NAME));
  }

  /**
   * @see RepositoryFunction#getRule(RepositoryName, String, Environment)
   */
  @Override
  public Class<? extends RuleDefinition> getRuleDefinition() {
    return MavenJarRule.class;
  }

  /**
   * This downloader creates a connection to one or more Maven repositories and downloads a jar.
   */
  static class MavenDownloader {
    private final String name;
    private final String artifact;
    private final Path outputDirectory;
    @Nullable
    private final String sha1;
    // TODO(kchodorow): change this to a single repository on 9/15.
    private final List<RemoteRepository> repositories;

    public MavenDownloader(String name, AttributeMap mapper, Path outputDirectory) {
      this.name = name;
      this.outputDirectory = outputDirectory;

      if (!mapper.get("artifact", Type.STRING).isEmpty()) {
        this.artifact = mapper.get("artifact", Type.STRING);
      } else {
        this.artifact = mapper.get("group_id", Type.STRING) + ":"
            + mapper.get("artifact_id", Type.STRING) + ":"
            + mapper.get("version", Type.STRING);
      }
      this.sha1 = (mapper.has("sha1", Type.STRING)) ? mapper.get("sha1", Type.STRING) : null;

      if (mapper.has("repository", Type.STRING)
          && !mapper.get("repository", Type.STRING).isEmpty()) {
        this.repositories = ImmutableList.of(new RemoteRepository.Builder(
            "user-defined repository", "default", mapper.get("repository", Type.STRING)).build());
      } else if (mapper.has("repositories", Type.STRING_LIST)
          && !mapper.get("repositories", Type.STRING_LIST).isEmpty()) {
        // TODO(kchodorow): remove after 9/15, uses deprecated list of repositories attribute.
        this.repositories = Lists.newArrayList();
        for (String repositoryUrl : mapper.get("repositories", Type.STRING_LIST)) {
          this.repositories.add(new RemoteRepository.Builder(
              "user-defined repository " + repositories.size(), "default", repositoryUrl).build());
        }
      } else {
        this.repositories = ImmutableList.of(MavenConnector.getMavenCentralRemote());
      }
    }

    /**
     * Returns the name for this artifact-fetching rule.
     */
    public String getName() {
      return name;
    }

    /**
     * Returns the directory that this artifact will be downloaded to.
     */
    public Path getOutputDirectory() {
      return outputDirectory;
    }

    /**
     * Download the Maven artifact to the output directory. Returns the path to the jar.
     */
    public Path download() throws IOException {
      MavenConnector connector = new MavenConnector(outputDirectory.getPathString());
      RepositorySystem system = connector.newRepositorySystem();
      RepositorySystemSession session = connector.newRepositorySystemSession(system);

      ArtifactRequest artifactRequest = new ArtifactRequest();
      Artifact artifact;
      try {
        artifact = new DefaultArtifact(this.artifact);
      } catch (IllegalArgumentException e) {
        throw new IOException(e.getMessage());
      }
      artifactRequest.setArtifact(artifact);
      artifactRequest.setRepositories(repositories);

      try {
        ArtifactResult artifactResult = system.resolveArtifact(session, artifactRequest);
        artifact = artifactResult.getArtifact();
      } catch (ArtifactResolutionException e) {
        throw new IOException("Failed to fetch Maven dependency: " + e.getMessage());
      }

      Path downloadPath = outputDirectory.getRelative(artifact.getFile().getAbsolutePath());
      // Verify checksum.
      if (!Strings.isNullOrEmpty(sha1)) {
        Hasher hasher = Hashing.sha1().newHasher();
        String downloadSha1 = HttpDownloader.getHash(hasher, downloadPath);
        if (!sha1.equals(downloadSha1)) {
          throw new IOException("Downloaded file at " + downloadPath + " has SHA-1 of "
              + downloadSha1 + ", does not match expected SHA-1 (" + sha1 + ")");
        }
      }
      return downloadPath;
    }
  }

}


text:
import {By} from '@angular/platform-browser';
import {Router} from '@angular/router';
import {NO_ERRORS_SCHEMA} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {async, inject, ComponentFixture, TestBed} from '@angular/core/testing';
import {Observable} from 'rxjs/Observable';
import {DashboardComponent} from './dashboard.component';
import {DashboardModule} from './dashboard.module';
import {FakeBotStatusDataService, SOME_FAKE_OBSERVABLE_BOTS} from '../model/bot-status/testing';
import {BotStatusHttpDataService} from '../model/bot-status';
import {addMatchers, click} from '../../../testing';
import {HttpClientTestingModule} from '@angular/common/http/testing';

class RouterStub {
    navigateByUrl(url: string) {
        return url;
    }
}

/**
 * Tests the behaviour of the Dashboard component is as expected.
 *
 * It uses the Angular TestBed and a stubbed FakeBotStatusDataService.
 *
 * I think I prefer the notestbed approach - less code and accessing just the model, i.e. no By.css stuff...
 * But, TestBed useful if you need to test the UI rendering?
 *
 * Based off the main Angular tutorial:
 * https://angular.io/resources/live-examples/testing/ts/app-specs.plnkr.html
 */
let dashboardComponent: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
const BITSTAMP_BOT = 0;

/**
 * Add our custom Jasmine matchers.
 */
beforeEach(addMatchers);

/**
 * Add TestBed providers, compile, and create DashboardComponent.
 */
function compileAndCreate() {

    // beforeEach(async(() => {
    //     TestBed.configureTestingModule({
    //         providers: [
    //             {provide: BotStatusHttpDataService, useClass: FakeBotStatusDataService},
    //             {provide: Router, useClass: RouterStub},
    //             {provide: HttpClient, useValue: {}} // need this because the FakeBotStatusDataService extends
    //                                                 // BotStatusHttpDataService
    //         ]
    //     }).compileComponents().then(() => {
    //         fixture = TestBed.createComponent(DashboardComponent);
    //         dashboardComponent = fixture.componentInstance;
    //     });
    // }));

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
                    providers: [
                        {provide: BotStatusHttpDataService, useClass: FakeBotStatusDataService},
                        {provide: Router, useClass: RouterStub},
                        {provide: HttpClient, useValue: {}} // need this because the FakeBotStatusDataService extends
                                                            // BotStatusHttpDataService
                    ]
        }).compileComponents().then(() => {
                fixture = TestBed.createComponent(DashboardComponent);
                dashboardComponent = fixture.componentInstance;
            });
    }));
}

/**
 * Test Dashboard by via the bx-dashboard-item directive.
 */
describe('DashboardComponent tests with TestBed (shallow)', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [DashboardComponent],
            schemas: [NO_ERRORS_SCHEMA]
        });
    });

    compileAndCreate();
    tests(clickForShallow);

    function clickForShallow() {
        const dashboardItemElement = fixture.debugElement.query(By.css('app-bxbot-ui-dashboard-item'));
        // Triggers event to select the first <bx-dashboard-item> DebugElement
        dashboardItemElement.triggerEventHandler('selected', SOME_FAKE_OBSERVABLE_BOTS[BITSTAMP_BOT]);
    }
});

/**
 * Test Dashboard by accessing the div item class directly.
 */
describe('DashboardComponent tests with TestBed (deep)', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [DashboardModule]
        });
    });

    compileAndCreate();
    tests(clickForDeep);

    function clickForDeep() {
        // clicks the first
 DebugElement
        const dashboardItem = fixture.debugElement.query(By.css('.item'));
        click(dashboardItem);
    }
});

/**
 * The (almost) same tests for both.
 * Only change: the way that the first Bot is clicked.
 */
function tests(botClick: Function) {

    it('should NOT have Bot items before ngOnInit', () => {
        expect(dashboardComponent.bots).not.toBeDefined('should not have Bots items before ngOnInit called');
    });

    describe('After BotStatusDataService getAllBotStatus() Observable is subscribed to', () => {

        /*
         * Hack to prevent runtime test error:
         *
         * Failed: Cannot use setInterval from within an async zone test.
         * Error: Cannot use setInterval from within an async zone test.
         *
         * See: https://github.com/angular/angular/issues/10127
         */
        beforeAll(() => {
            // Monkey-patch Observable.debounceTime() since it is using
            // setInterval() internally which not allowed within async zone
            Observable.prototype.debounceTime = function () { return this; };
        });

        // Trigger component so it gets bots and binds to them the UI bits
        beforeEach(async(() => {
            fixture.detectChanges(); // runs ngOnInit + ngAfterViewInit -> getAllBotStatus()
            fixture.whenStable().then(() => fixture.detectChanges()); // bind to bots
        }));

        it('should have fetched 3 Bot items', (done) => {
            dashboardComponent.ngOnInit();
            dashboardComponent.bots.do((bots) => {

                expect(bots.length).toBe(3, 'should have 3 Bot items after ngAfterViewInit');

                // paranoia!
                expect(bots[0].id).toBe('bitstamp-1');
                expect(bots[1].id).toBe('gdax-2');
                expect(bots[2].id).toBe('gemini-3');

                done();
            }).toPromise(); // MUST have this for test to work!
            dashboardComponent.ngAfterViewInit();
        });

        it('should display 3 Bot items', () => {
            // Find and examine the displayed bots
            // Look for them in the DOM by css class
            const bots = fixture.debugElement.queryAll(By.css('app-bxbot-ui-dashboard-item'));
            expect(bots.length).toBe(3, 'should display 3 Bot items');
        });

        it('should tell Router to navigate when Bot item selected',

            // inject our stubbed Router
            inject([Router], (router: Router) => {

                const spy = spyOn(router, 'navigateByUrl');

                // callback: trigger click on first inner
 OR bx-dashboard-item triggerEventHandler
                botClick();

                // args passed to router.navigateByUrl()
                const navArgs = spy.calls.first().args[0];

                // expecting to navigate to id of the component's first Bot
                expect(navArgs).toBe('/bot/' + SOME_FAKE_OBSERVABLE_BOTS[BITSTAMP_BOT].id,
                    'should nav to BotDetailsComponent for first Bot');
            })
        );
    });
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
T. L. Mitchell, J. exped. trop. Australia 385. 1848

#### Original name
null

### Remarks
null


text:
console.log('Problem 11');
var format,
    personAge;

function stringFormat() {
    var argumentsArray,
        currentPlaceholder,
        formattedString,
        i;

    argumentsArray = arguments;
    formattedString = argumentsArray[0];
    for (i = 1; i < argumentsArray.length; i += 1) {
        currentPlaceholder = '{' + (i - 1) + '}';
        formattedString = formattedString.replace(currentPlaceholder, argumentsArray[i]);
    }

    return formattedString;
}

personAge = 30;
format = '{0} {1} age is {3}, male:{2}';
console.log(stringFormat(format, 'John', 'Doe', true, personAge));


text:
<?php

namespace JigTest\PlaceHolder;

class ChildDependency {

    const output = "This is a child dependency.";

    function render()
    {
        return ChildDependency::output;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?><resources>
<!--
 Copyright 2022 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

  <string name="horologist_pause_button_content_description">താൽക്കാലികമായി നിർത്തുക</string>
  <string name="horologist_play_button_content_description">പ്ലേ ചെയ്യുക</string>
  <string name="horologist_seek_to_next_button_content_description">അടുത്തത്</string>
  <string name="horologist_seek_to_previous_button_content_description">മുമ്പത്തേത്</string>
  <string name="horologist_seek_forward_button_content_description">മുന്നോട്ട് നീക്കുക</string>
  <string name="horologist_seek_forward_button_seconds_content_description">%s സെക്കൻഡ് മുന്നോട്ട് നീക്കുക</string>
  <string name="horologist_seek_back_button_content_description">പിന്നോട്ട് നീക്കുക</string>
  <string name="horologist_seek_back_button_seconds_content_description">%s സെക്കൻഡ് പിന്നോട്ട് നീക്കുക</string>
  <string name="horologist_shuffle_button_off_content_description">ഇടകലർത്തൽ മോഡ് ഓഫാണ്</string>
  <string name="horologist_shuffle_button_on_content_description">ഇടകലർത്തൽ മോഡ് ഓണാണ്</string>
  <string name="horologist_nothing_playing">ഒന്നും പ്ലേചെയ്യുന്നില്ല</string>
  <string name="horologist_browse_downloads_title">ഡൗൺലോഡുകൾ</string>
  <string name="horologist_browse_downloads_empty">കേട്ട് തുടങ്ങാൻ സംഗീതം ഡൗൺലോഡ് ചെയ്യുക</string>
  <string name="horologist_browse_library_title">ലൈബ്രറി</string>
  <string name="horologist_browse_library_playlists">പ്ലേലിസ്റ്റുകൾ</string>
  <string name="horologist_browse_library_playlists_button">പ്ലേലിസ്റ്റുകൾ</string>
  <string name="horologist_browse_library_settings_button">ക്രമീകരണം</string>
  <string name="horologist_browse_playlist_title">പ്ലേലിസ്റ്റുകൾ</string>
  <string name="horologist_playlist_download_button_download">വാച്ചിൽ ഡൗൺലോഡ് ചെയ്യൂ</string>
  <string name="horologist_playlist_download_button_cancel">റദ്ദാക്കുക</string>
  <string name="horologist_playlist_download_button_download_content_description">ഡൗൺലോഡ് ചെയ്യാനാകും</string>
  <string name="horologist_playlist_download_progress_button_cancel_content_description">ഡൗൺലോഡ് പുരോഗതിയിലാണ്</string>
  <string name="horologist_playlist_download_progress_button_cancel_action_label">റദ്ദാക്കുക</string>
  <string name="horologist_playlist_download_button_download_done_content_description">ഡൗൺലോഡ് ചെയ്‌തു</string>
  <string name="horologist_playlist_download_button_remove_download_action_label">ഡൗൺലോഡ് നീക്കം ചെയ്യുക</string>
  <string name="horologist_playlist_download_button_shuffle_content_description">ഇടകലർത്തുക</string>
  <string name="horologist_playlist_download_button_play_content_description">പ്ലേ ചെയ്യുക</string>
  <string name="horologist_playlist_download_media_chip_download_content_description">%s ഡൗൺലോഡ് പുരോഗതിയിലാണ്</string>
  <string name="horologist_playlist_download_download_progress_known_size">%2$s-ൽ %1$.0f%%</string>
  <string name="horologist_playlist_download_download_progress_waiting">കാക്കുന്നു…</string>
</resources>


text:
package com.cyberlightning.webserver.interfaces;

import com.cyberlightning.webserver.entities.MessageObject;

public interface IMessageEvent {
	public void onMessageReceived(MessageObject _msg);
}


text:
declare -a log_path
#log_path=("/data/applog/nginx/mas/" "/data/applog/nginx/mainaccess/")
log_path[0]="/data/applog/nginx/mas/"
log_path[1]="/data/applog/nginx/mainaccess/"
log_path[2]="/data/applog/nginx/3m/"

for daily_log_path in ${log_path[@]} ; do
    rt_log_path=${daily_log_path}
    echo ${rt_log_path}
    mv ${rt_log_path}access.log ${daily_log_path}access_$(date -d "yesterday" +%Y%m%d).log
done

nginx_pid=`ps aux |grep -E 'nginx: master process'|grep -v 'grep'|awk '{print $2}'`
kill -USR1 $nginx_pid

service nginx reload


text:
//
//  NSString+NERChainable.h
//  NerdyUI
//
//  Created by nerdycat on 10/2/16.
//  Copyright © 2016 nerdycat. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "NERDefs.h"
#import "NERTypeConverter.h"

/**
 * Create a NSString.
 * Str argument can be:
   1) C string
   2) any primitive type
   3) any object
   4) CGRect, CGPoint, CGSize, NSRange, UIEdgeInsets
   5) Selector
   6) Class
   7) Format String

 * Usages: Str(100), Str(3.14), Str(@0.618), Str([UIView class]), Str(_cmd), Str(view.frame),
           Str("Hello"), Str(@"World"), Str(@"%d+%d=%d", 1, 1, 1 + 1)
 */
#define Str(...)                ({NER_CHECK_IS_STRING(__VA_ARGS__)? \
                                    NER_STRING_FORMAT(__VA_ARGS__):\
                                    NER_STRING_VALUE(__VA_ARGS__);})

/**
 * Logging a single value or Logging with format string.
 * Log use Str() internally, so it can take any kind of arguments that Str() supported.
 * Usages: Log(view.height), Log(view.frame), Log(view), Log(_cmd),
           Log("Hello"), Log(@"World"), Log(@"%d+%d=%d", 1, 1, 1 + 1)
 */
#ifndef __OPTIMIZE__
#define Log(...)                ({id _prefix_ = NER_LOG_PREFIX(__VA_ARGS__); \
                                    id _str_ = Str(__VA_ARGS__);\
                                    NSLog(@"%@%@", _prefix_, _str_);})
#else
#define Log(...)
#endif

/**
 * Create an NSURL from URL string.
 */
#define Url(s)                  [NSURL URLWithString:s]

@interface NSString (NERChainable)

/**
 * Appending string.
 * a use Str() internally, so it can take any kind of arguments that Str() supported.
 * Usages: @"1".a(@"2").a(3).a(nil).a(4.0f).a(@5).a(@"%d", 6);      //@"123456"
 */
NER_STRING_PROP(Object)         a;

/**
 * Appending path component.
 * ap use Str() internally, so it can take any kind of arguments that Str() supported.
 * Usages: @"dir1".ap(222).ap(@"dir3").ap(@"cat.png")               //@"dir1/222/dir3/cat.png"
 */
NER_STRING_PROP(Object)         ap;

/**
 * Substring from index or from substring.
 * Usages:
   @"hello".subFrom(2);             //@"llo"
   @"hello".subFrom(@"el");         //@"ello"
 */
NER_STRING_PROP(IntOrObject)    subFrom;

/**
 * Substring to index or to substring.
 * Usages:
   @"hello".subTo(2);               //@"he"
   @"hello".subTo(@"el");           //@"h"
   @"hello".subFrom(1).subTo(@"o"); //@"ell"
 */
NER_STRING_PROP(IntOrObject)    subTo;

/**
 * Return first substring that match the regular expression.
 * It support two kind of argument:
   1) NSRegularExpression
   2) NSString that represent regular expression pattern.
 * Usages: @"pi: 3.14".subMatch(@"[0-9.]+")         //@"3.14"
 */
NER_STRING_PROP(Object)         subMatch;

/**
 * Returns a new string containing matching regular expressions replaced with the template string.
 * Inside template string, $0 being replaced by the contents of the matched range,
   $1 by the contents of the first capture group, and so on.
 * Usages:
   @"hello world".subReplace(@"world", @"WORLD")                //@"hello WORLD"
   @"hello world".subReplace(@"(\\w+) (\\w+)", @"$2 $1")        //@"world hello"
 */
NER_STRING_PROP(TwoObject)      subReplace;

#define a(...)                  a(Str(__VA_ARGS__))
#define ap(...)                 ap(Str(__VA_ARGS__))
#define subFrom(x)              subFrom(NER_CONVERT_VALUE_TO_NUMBER(x))
#define subTo(x)                subTo(NER_CONVERT_VALUE_TO_NUMBER(x))

/**
 * Prepend document/caches/tmp directory path to current string.
 * Usages: @"abc.db".inCaches, @"images".ap("cat.png").inDocument
 */
- (NSString *)inDocument;
- (NSString *)inCaches;
- (NSString *)inTmp;

@end


text:
import Helper from './_helper';
import { module, test } from 'qunit';

module('Integration | ORM | Belongs To | Named Reflexive | instantiating', {
  beforeEach() {
    this.helper = new Helper();
    this.schema = this.helper.schema;
  }
});

test('the child accepts a saved parent id', function(assert) {
  let friend = this.helper.savedParent();
  let user = this.schema.users.new({ bestFriendId: friend.id });

  assert.equal(user.bestFriendId, friend.id);
  assert.deepEqual(user.bestFriend.attrs, friend.attrs);
  assert.deepEqual(user.attrs, { bestFriendId: friend.id });
});

test('the child errors if the parent id doesnt exist', function(assert) {
  assert.throws(function() {
    this.schema.users.new({ bestFriendId: 2 });
  }, /You're instantiating a user that has a bestFriendId of 2, but that record doesn't exist in the database/);
});

test('the child accepts a null parent id', function(assert) {
  let user = this.schema.users.new({ bestFriendId: null });

  assert.equal(user.bestFriendId, null);
  assert.equal(user.bestFriend, null);
  assert.deepEqual(user.attrs, { bestFriendId: null });
});

test('the child accepts a saved parent model', function(assert) {
  let friend = this.helper.savedParent();
  let user = this.schema.users.new({ bestFriend: friend });

  assert.equal(user.bestFriendId, 1);
  assert.deepEqual(user.bestFriend.attrs, friend.attrs);
  assert.deepEqual(user.attrs, { bestFriendId: null }); // this would update when saved
});

test('the child accepts a new parent model', function(assert) {
  let zelda = this.schema.users.new({ name: 'Zelda' });
  let user = this.schema.users.new({ bestFriend: zelda });

  assert.equal(user.bestFriendId, null);
  assert.deepEqual(user.bestFriend, zelda);
  assert.deepEqual(user.attrs, { bestFriendId: null });
});

test('the child accepts a null parent model', function(assert) {
  let user = this.schema.users.new({ bestFriend: null });

  assert.equal(user.bestFriendId, null);
  assert.deepEqual(user.bestFriend, null);
  assert.deepEqual(user.attrs, { bestFriendId: null });
});

test('the child accepts a parent model and id', function(assert) {
  let friend = this.helper.savedParent();
  let user = this.schema.users.new({ bestFriend: friend, bestFriendId: friend.id });

  assert.equal(user.bestFriendId, '1');
  assert.deepEqual(user.bestFriend, friend);
  assert.deepEqual(user.attrs, { bestFriendId: friend.id });
});

test('the child accepts no reference to a parent id or model as empty obj', function(assert) {
  let user = this.schema.users.new({});

  assert.equal(user.bestFriendId, null);
  assert.deepEqual(user.bestFriend, null);
  assert.deepEqual(user.attrs, { bestFriendId: null });
});

test('the child accepts no reference to a parent id or model', function(assert) {
  let user = this.schema.users.new();

  assert.equal(user.bestFriendId, null);
  assert.deepEqual(user.bestFriend, null);
  assert.deepEqual(user.attrs, { bestFriendId: null });
});


text:
package com.flurdy.conductor

import akka.actor.{Actor,ActorRef,PoisonPill,Props}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import com.flurdy.sander.actor.{ActorFactory,WithActorFactory}

case class ServiceDetails(name: String)

object Service {
   case class StartService(servicesToStart: Seq[String], initiator: ActorRef)
   case class StopService(services: Map[String, ActorRef], initiator: ActorRef)
   def props(details: ServiceDetails, serviceRegistry: ActorRef,
             gantryRegistry: ActorRef)(implicit actorFactory: ActorFactory) =
         Props(classOf[Service], details, serviceRegistry, gantryRegistry, actorFactory)
}

class Service(val details: ServiceDetails,
              val serviceRegistry: ActorRef,
              val gantryRegistry: ActorRef)
              (implicit val actorFactory: ActorFactory) extends ServiceActor

trait ServiceActor extends Actor with WithLogging with WithActorFactory{
   import Service._
   import ServiceRegistry._
   import GantryRegistry._
   import Gantry._

   def details: ServiceDetails
   def serviceRegistry: ActorRef
   def gantryRegistry: ActorRef
   var gantry:    Option[ActorRef] = None
   var initiator: Option[ActorRef] = None

   override def receive = normal

   def normal: Receive = {

      case StartService(servicesToStart, initiator) =>
         log.debug(s"Start ${details.name}")
         this.initiator = Some(initiator)
         gantryRegistry ! FindGantry(details)

      case FoundGantry(gantry) =>
         this.gantry = Some(gantry)
         context.become(startingGantry)
         gantry ! RunImage

      case StopService(services, initiator) =>
         log.warning(s"Service already stopped: ${details.name}")

      case GantryNotFound(details) =>
         log.warning(s"Gantry not found ${details.name}")
   }

   def startingGantry: Receive = {

      case StartService(_, _) =>
         log.warning(s"Service already starting: ${details.name}")

      case ImageRunning(image) =>
         log.debug("Image running")
         context.become(runningGantry)
         initiator.fold{
            log.error("Intitiator not set")
         }{ initiatorFound =>
            serviceRegistry ! ServiceStarted(details.name, Seq.empty, initiatorFound)
         }

      case StopService(services, initiator) =>
         log.debug("Stop starting image in the future")
         context.system.scheduler.scheduleOnce(200 milliseconds, self, StopService(services, initiator))
   }

   def runningGantry: Receive = {

      case StartService(_, _) =>
         log.warning(s"Service already running: ${details.name}")

      case StopService(services, initiator) =>
         log.debug(s"Stop ${details.name}")
         gantry.fold {
            log.warning(s"No gantry found ${details.name}")
         }{ gantry =>
            context.become(stoppingGantry)

            gantry ! StopImage
         }
   }

   def stoppingGantry: Receive = {
      case StartService(_, _) =>
         log.warning(s"Service stopping: ${details.name}")

      case ImageStopped(image) =>
         log.debug("Image stopped")
         context.become(normal)
         initiator.fold{
            log.error("Intitiator not set")
         }{ initiatorFound =>
            serviceRegistry ! ServiceStopped(details.name, self, Map.empty, initiatorFound)
         }

      case StopService(services, initiator) =>
         log.warning(s"Service stopping: ${details.name}")

   }
}


text:
/* global describe, it, require */
'use strict';

// MODULES //

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	partial = require( './../lib/partial.js' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'number pdf', function tests() {

	var lambda = 1;

	it( 'should export a function', function test() {
		expect( partial ).to.be.a( 'function' );
	});

	it( 'should partially apply the Poisson pdf for given parameter values', function test() {
		var pdf;
		pdf = partial( lambda);
		expect( pdf ).to.be.a( 'function' );
	});

});


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Structure;
using Microsoft.CodeAnalysis.CSharp.Structure.MetadataAsSource;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource
{
    public class EventFieldDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<EventFieldDeclarationSyntax>
    {
        protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource;
        internal override AbstractSyntaxStructureProvider CreateProvider() => new MetadataEventFieldDeclarationStructureProvider();

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task NoCommentsOrAttributes()
        {
            const string code = @"
class Foo
{
    public event EventArgs $$foo
}";

            await VerifyNoBlockSpansAsync(code);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task WithAttributes()
        {
            const string code = @"
class Foo
{
    {|hint:{|textspan:[Foo]
    |}event EventArgs $$foo|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task WithCommentsAndAttributes()
        {
            const string code = @"
class Foo
{
    {|hint:{|textspan:// Summary:
    //     This is a summary.
    [Foo]
    |}event EventArgs $$foo|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
        public async Task WithCommentsAttributesAndModifiers()
        {
            const string code = @"
class Foo
{
    {|hint:{|textspan:// Summary:
    //     This is a summary.
    [Foo]
    |}public event EventArgs $$foo|}
}";

            await VerifyBlockSpansAsync(code,
                Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true));
        }
    }
}


text:
package org.greencheek.spray.cache.memcached.hostparsing.dnslookup

import scala.concurrent.duration.Duration
import java.net.{InetAddress, InetSocketAddress}
import org.greencheek.dns.lookup.LookupService
import java.util.concurrent.{TimeoutException, TimeUnit}
import org.slf4j.{Logger, LoggerFactory}

/**
 * Created by dominictootell on 06/06/2014.
 */
object AddressByNameHostResolver extends HostResolver {
  private val logger : Logger = LoggerFactory.getLogger(classOf[HostResolver])

  override def returnSocketAddressesForHostNames(nodes: List[(String, Int)], dnsLookupTimeout: Duration): List[InetSocketAddress] = {
    val addressLookupService = LookupService.create()

    var workingNodes: List[InetSocketAddress] = Nil
    for (hostAndPort <- nodes) {
      var future: java.util.concurrent.Future[InetAddress] = null
      val host = hostAndPort._1
      val port = hostAndPort._2
      try {
        future = addressLookupService.getByName(host)
        var ia: InetAddress = future.get(dnsLookupTimeout.toSeconds, TimeUnit.SECONDS)
        if (ia == null) {
          logger.error("Unable to resolve dns entry for the host: {}", host)
        }
        else
        {
          try {
            workingNodes = new InetSocketAddress(ia,port ) :: workingNodes
          }
          catch {
            case e: IllegalArgumentException => {
              logger.error("Invalid port number has been provided for the memcached node: host({}),port({})", host, port)
            }
          }
        }
      }
      catch {
        case e: TimeoutException => {
          logger.error("Problem resolving host name ({}) to an ip address in fixed number of seconds: {}", host, dnsLookupTimeout, e)
        }
        case e: Exception => {
          logger.error("Problem resolving host name to ip address: {}", host)
        }
      }
      finally {
        if (future != null) future.cancel(true)
      }
    }
    addressLookupService.shutdown()

    workingNodes
  }

}


text:
package cn.nec.nlc.example.xmlpullparsertest01;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView tv = (TextView) findViewById(R.id.textview1);

		XmlPullParserFactory factory;
		try {
			factory = XmlPullParserFactory.newInstance();
			// set the features to be set (true) when XML Pull Parser is created by
			// this factory
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			// setInput(Reader in): Set the input source for parser to the
			// given reader and resets the parser.
			// StringReader: specialized Reader that reads characters from a
			// String in a sequential manner
			xpp.setInput(new StringReader("<foo>Hello World ~~</foo>"));
			StringBuffer tvOutput = new StringBuffer();
			// Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.)
			int eventType = xpp.getEventType();
	        while (eventType != XmlPullParser.END_DOCUMENT) {
	        	if(eventType == XmlPullParser.START_DOCUMENT) {  	// = 0
	        		// display in LogCat, Level Info (I)
	        		System.out.println("Start document");
	        		tvOutput.append("Start document\n");
	        	} else if(eventType == XmlPullParser.END_DOCUMENT) {
	        		System.out.println("End document");
	        		tvOutput.append("End document\n");
	        	} else if(eventType == XmlPullParser.START_TAG) { 	// = 2
	        		System.out.println("Start tag "+xpp.getName());
	        		tvOutput.append("Start tag "+xpp.getName() + "\n");
	        	} else if(eventType == XmlPullParser.END_TAG) {
	        		System.out.println("End tag "+xpp.getName()); 	// = 3
	        		tvOutput.append("End tag "+xpp.getName() + "\n");
	        	} else if(eventType == XmlPullParser.TEXT) { 		// = 4
	        		System.out.println("Text "+xpp.getText());
	        		tvOutput.append("Text "+xpp.getText() + "\n");
	        	}
	        	// get next parsing event
	        	eventType = xpp.next();
	        }
	        tv.setText(tvOutput);
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


text:
VERSION=$1
SCALA_VERSION=$2

#define the template.
cat  << EOF
name := "ntypes"
organization := "com.github.piotrkowalczuk"
version := "$VERSION"
scalaVersion := "$SCALA_VERSION"
description := "Set of types that helps to build complex protobuf messages that contains optional properties."
homepage := Some(url("https://github.com/piotrkowalczuk/ntypes"))

scmInfo := Some(
  ScmInfo(
    browseUrl = url("https://github.com/piotrkowalczuk/ntypes"),
    connection = "git@github.com:piotrkowalczuk/ntypes.git")
)

developers := List(
  Developer(
    id = "piotrkowalczuk",
    name = "Piotr Kowalczuk",
    email = "p.kowalczuk.priv@gmail.com",
    url = url("https://github.com/piotrkowalczuk")
  ),
  Developer(
    id = "fpopic",
    name = "Filip Popic",
    email = "filip.popic@gmail.com",
    url = url("https://github.com/fpopic")
  )
)

PB.targets in Compile := Seq(
  scalapb.gen(asciiFormatToString = true) -> (sourceManaged in Compile).value
)

resolvers += Resolver.bintrayRepo("piotrkowalczuk", "maven")

licenses += ("MIT", url("https://github.com/piotrkowalczuk/ntypes/blob/master/LICENSE.txt"))

credentials += Credentials(Path.userHome / ".bintray" / ".credentials")

publishMavenStyle := true

bintrayVcsUrl := Some("git@github.com:piotrkowalczuk/ntypes.git")

EOF


text:
package io.jooby.internal.handler.reactive;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

public class ReactiveSubscriber implements Subscriber<Object> {

  private final ChunkedSubscriber subscriber;

  public ReactiveSubscriber(ChunkedSubscriber subscriber) {
    this.subscriber = subscriber;
  }

  @Override
  public void onSubscribe(Subscription s) {
    subscriber.onSubscribe(new ReactiveSubscription(s));
  }

  @Override
  public void onNext(Object item) {
    subscriber.onNext(item);
  }

  @Override
  public void onError(Throwable x) {
    subscriber.onError(x);
  }

  @Override
  public void onComplete() {
    subscriber.onComplete();
  }
}


text:
<?php
namespace Disque\Test\Command;

use PHPUnit_Framework_TestCase;
use Disque\Command\Argument\InvalidCommandArgumentException;
use Disque\Command\CommandInterface;
use Disque\Command\AckJob;
use Disque\Command\Response\InvalidResponseException;

class AckJobTest extends PHPUnit_Framework_TestCase
{
    public function testInstance()
    {
        $c = new AckJob();
        $this->assertInstanceOf(CommandInterface::class, $c);
    }

    public function testGetCommand()
    {
        $c = new AckJob();
        $result = $c->getCommand();
        $this->assertSame('ACKJOB', $result);
    }

    public function testIsBlocking()
    {
        $c = new AckJob();
        $result = $c->isBlocking();
        $this->assertFalse($result);
    }

    public function testBuildInvalidArgumentsEmpty()
    {
        $this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: []');
        $c = new AckJob();
        $c->setArguments([]);
    }

    public function testBuildInvalidArgumentsNonStringArray()
    {
        $this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: [["test","stuff"]]');
        $c = new AckJob();
        $c->setArguments([['test','stuff']]);
    }

    public function testBuildInvalidArgumentsNonStringNumeric()
    {
        $this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: [128]');
        $c = new AckJob();
        $c->setArguments([128]);
    }

    public function testBuildInvalidArgumentsEmptyValue()
    {
        $this->setExpectedException(InvalidCommandArgumentException::class, 'Invalid command arguments. Arguments for command Disque\\Command\\AckJob: [""]');
        $c = new AckJob();
        $c->setArguments([""]);
    }

    public function testBuild()
    {
        $c = new AckJob();
        $c->setArguments(['id']);
        $result = $c->getArguments();
        $this->assertSame(['id'], $result);
    }

    public function testBuildSeveral()
    {
        $c = new AckJob();
        $c->setArguments(['id', 'id2']);
        $result = $c->getArguments();
        $this->assertSame(['id', 'id2'], $result);
    }

    public function testParseInvalidNonNumericArray()
    {
        $this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\AckJob got: ["test"]');
        $c = new AckJob();
        $c->parse(['test']);
    }

    public function testParseInvalidNonNumericString()
    {
        $this->setExpectedException(InvalidResponseException::class, 'Invalid command response. Command Disque\\Command\\AckJob got: "test"');
        $c = new AckJob();
        $c->parse('test');
    }

    public function testParse()
    {
        $c = new AckJob();
        $result = $c->parse('128');
        $this->assertSame(128, $result);
    }
}


text:
package io.fabric8.commands;

import io.fabric8.api.FabricService;
import io.fabric8.api.Profiles;
import io.fabric8.api.Version;
import io.fabric8.api.ProfileService;
import io.fabric8.utils.FabricValidations;

import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.CompleterValues;
import org.apache.felix.gogo.commands.Option;
import org.apache.karaf.shell.console.AbstractAction;

@Command(name = ProfileRename.FUNCTION_VALUE, scope = ProfileRename.SCOPE_VALUE, description = ProfileRename.DESCRIPTION)
public class ProfileRenameAction extends AbstractAction {

    @Option(name = "--version", description = "The profile version to rename.")
    private String versionId;

    @Option(name = "-f", aliases = "--force", description = "Flag to allow replacing the target profile (if exists).")
    private boolean force;

    @Argument(index = 0, required = true, name = "profile name", description = "Name of the profile.")
    @CompleterValues(index = 0)
    private String profileName;

    @Argument(index = 1, required = true, name = "new profile name", description = "New name of the profile.")
    @CompleterValues(index = 1)
    private String newName;

    private final ProfileService profileService;
    private final FabricService fabricService;

    ProfileRenameAction(FabricService fabricService) {
        this.profileService = fabricService.adapt(ProfileService.class);
        this.fabricService = fabricService;
    }

    @Override
    protected Object doExecute() throws Exception {
        // do not validate the old name in case a profile was created somehow with invalid name
        // but validate the new name
        try {
            FabricValidations.validateProfileName(newName);
        } catch (IllegalArgumentException e) {
            // we do not want exception in the server log, so print the error message to the console
            System.out.println(e.getMessage());
            return null;
        }

        Version version;
        if (versionId != null) {
            version = profileService.getRequiredVersion(versionId);
        } else {
            version = fabricService.getDefaultVersion();
        }
        if (!version.hasProfile(profileName)) {
            System.out.println("Profile " + profileName + " not found.");
            return null;
        } else if (version.hasProfile(newName)) {
            if (!force) {
                System.out.println("New name " + newName + " already exists. Use --force if you want to overwrite.");
                return null;
            }
        }
        try {
            Profiles.renameProfile(fabricService, versionId, profileName, newName, force);
        } catch (Exception ex) {
            System.err.println("Profile rename failed: " + ex.getMessage());
            log.error("Profile rename failed: ", ex);
        }
        return null;
    }

}


text:
package org.springframework.context.annotation;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.parsing.Location;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.beans.factory.parsing.ProblemReporter;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase;
import org.springframework.core.NestedIOException;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

/**
 * Parses a {@link Configuration} class definition, populating a collection of
 * {@link ConfigurationClass} objects (parsing a single Configuration class may result in
 * any number of ConfigurationClass objects because one Configuration class may import
 * another using the {@link Import} annotation).
 *
 *
This class helps separate the concern of parsing the structure of a Configuration
 * class from the concern of registering BeanDefinition objects based on the
 * content of that model (with the exception of {@code @ComponentScan} annotations which
 * need to be registered immediately).
 *
 *
This ASM-based implementation avoids reflection and eager class loading in order to
 * interoperate effectively with lazy class loading in a Spring ApplicationContext.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @author Phillip Webb
 * @author Sam Brannen
 * @since 3.0
 * @see ConfigurationClassBeanDefinitionReader
 */
class ConfigurationClassParser {

	private static final PropertySourceFactory DEFAULT_PROPERTY_SOURCE_FACTORY = new DefaultPropertySourceFactory();

	private static final Comparator<DeferredImportSelectorHolder> DEFERRED_IMPORT_COMPARATOR =
			new Comparator<ConfigurationClassParser.DeferredImportSelectorHolder>() {
				@Override
				public int compare(DeferredImportSelectorHolder o1, DeferredImportSelectorHolder o2) {
					return AnnotationAwareOrderComparator.INSTANCE.compare(o1.getImportSelector(), o2.getImportSelector());
				}
			};

	private final Log logger = LogFactory.getLog(getClass());

	private final MetadataReaderFactory metadataReaderFactory;

	private final ProblemReporter problemReporter;

	private final Environment environment;

	private final ResourceLoader resourceLoader;

	private final BeanDefinitionRegistry registry;

	private final ComponentScanAnnotationParser componentScanParser;

	private final ConditionEvaluator conditionEvaluator;

	private final Map<ConfigurationClass, ConfigurationClass> configurationClasses =
			new LinkedHashMap<ConfigurationClass, ConfigurationClass>();

	private final Map<String, ConfigurationClass> knownSuperclasses = new HashMap<String, ConfigurationClass>();

	private final List<String> propertySourceNames = new ArrayList<String>();

	private final ImportStack importStack = new ImportStack();

	private List<DeferredImportSelectorHolder> deferredImportSelectors;

	/**
	 * Create a new {@link ConfigurationClassParser} instance that will be used
	 * to populate the set of configuration classes.
	 */
	public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
			ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
			BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

		this.metadataReaderFactory = metadataReaderFactory;
		this.problemReporter = problemReporter;
		this.environment = environment;
		this.resourceLoader = resourceLoader;
		this.registry = registry;
		this.componentScanParser = new ComponentScanAnnotationParser(
				resourceLoader, environment, componentScanBeanNameGenerator, registry);
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
	}

	public void parse(Set<BeanDefinitionHolder> configCandidates) {
		this.deferredImportSelectors = new LinkedList<DeferredImportSelectorHolder>();

		for (BeanDefinitionHolder holder : configCandidates) {
			BeanDefinition bd = holder.getBeanDefinition();
			try {
				if (bd instanceof AnnotatedBeanDefinition) {
					parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
				}
				else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
					parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
				}
				else {
					parse(bd.getBeanClassName(), holder.getBeanName());
				}
			}
			catch (BeanDefinitionStoreException ex) {
				throw ex;
			}
			catch (Exception ex) {
				throw new BeanDefinitionStoreException(
						"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
			}
		}

		processDeferredImportSelectors();
	}

	protected final void parse(String className, String beanName) throws IOException {
		MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
		processConfigurationClass(new ConfigurationClass(reader, beanName));
	}

	protected final void parse(Class<?> clazz, String beanName) throws IOException {
		processConfigurationClass(new ConfigurationClass(clazz, beanName));
	}

	protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
		processConfigurationClass(new ConfigurationClass(metadata, beanName));
	}

	protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
			return;
		}

		ConfigurationClass existingClass = this.configurationClasses.get(configClass);
		if (existingClass != null) {
			if (configClass.isImported()) {
				if (existingClass.isImported()) {
					existingClass.mergeImportedBy(configClass);
				}
				// Otherwise ignore new imported config class; existing non-imported class overrides it.
				return;
			}
			else {
				// Explicit bean definition found, probably replacing an import.
				// Let's remove the old one and go with the new one.
				this.configurationClasses.remove(configClass);
				for (Iterator<ConfigurationClass> it = this.knownSuperclasses.values().iterator(); it.hasNext(); ) {
					if (configClass.equals(it.next())) {
						it.remove();
					}
				}
			}
		}

		// Recursively process the configuration class and its superclass hierarchy.
		SourceClass sourceClass = asSourceClass(configClass);
		do {
			sourceClass = doProcessConfigurationClass(configClass, sourceClass);
		}
		while (sourceClass != null);

		this.configurationClasses.put(configClass, configClass);
	}

	/**
	 * Apply processing and build a complete {@link ConfigurationClass} by reading the
	 * annotations, members and methods from the source class. This method can be called
	 * multiple times as relevant sources are discovered.
	 * @param configClass the configuration class being build
	 * @param sourceClass a source class
	 * @return the superclass, or {@code null} if none found or previously processed
	 */
	protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		// Recursively process any member (nested) classes first
		processMemberClasses(configClass, sourceClass);

		// Process any @PropertySource annotations
		for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) {
			if (this.environment instanceof ConfigurableEnvironment) {
				processPropertySource(propertySource);
			}
			else {
				logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
						"]. Reason: Environment must implement ConfigurableEnvironment");
			}
		}

		// Process any @ComponentScan annotations
		Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
		if (!componentScans.isEmpty() && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
			for (AnnotationAttributes componentScan : componentScans) {
				// The config class is annotated with @ComponentScan -> perform the scan immediately
				Set<BeanDefinitionHolder> scannedBeanDefinitions =
						this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
				// Check the set of scanned definitions for any further config classes and parse recursively if necessary
				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), this.metadataReaderFactory)) {
						parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		// Process any @Import annotations
		processImports(configClass, sourceClass, getImports(sourceClass), true);

		// Process any @ImportResource annotations
		if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
			AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
			String[] resources = importResource.getAliasedStringArray("locations", ImportResource.class, sourceClass);
			Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
			for (String resource : resources) {
				String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
				configClass.addImportedResource(resolvedResource, readerClass);
			}
		}

		// Process individual @Bean methods
		Set<MethodMetadata> beanMethods = sourceClass.getMetadata().getAnnotatedMethods(Bean.class.getName());
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}

		// Process default methods on interfaces
		processInterfaces(configClass, sourceClass);

		// Process superclass, if any
		if (sourceClass.getMetadata().hasSuperClass()) {
			String superclass = sourceClass.getMetadata().getSuperClassName();
			if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
				this.knownSuperclasses.put(superclass, configClass);
				// Superclass found, return its annotation metadata and recurse
				return sourceClass.getSuperClass();
			}
		}

		// No superclass -> processing is complete
		return null;
	}

	/**
	 * Register member (nested) classes that happen to be configuration classes themselves.
	 */
	private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		for (SourceClass memberClass : sourceClass.getMemberClasses()) {
			if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
					!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
				if (this.importStack.contains(configClass)) {
					this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
				}
				else {
					this.importStack.push(configClass);
					try {
						processConfigurationClass(memberClass.asConfigClass(configClass));
					}
					finally {
						this.importStack.pop();
					}
				}
			}
		}
	}

	/**
	 * Register default methods on interfaces implemented by the configuration class.
	 */
	private void processInterfaces(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		for (SourceClass ifc : sourceClass.getInterfaces()) {
			Set<MethodMetadata> beanMethods = ifc.getMetadata().getAnnotatedMethods(Bean.class.getName());
			for (MethodMetadata methodMetadata : beanMethods) {
				if (!methodMetadata.isAbstract()) {
					// A default method or other concrete method on a Java 8+ interface...
					configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
				}
			}
			processInterfaces(configClass, ifc);
		}
	}

	/**
	 * Process the given @PropertySource annotation metadata.
	 * @param propertySource metadata for the @PropertySource annotation found
	 * @throws IOException if loading a property source failed
	 */
	private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
		String name = propertySource.getString("name");
		if (!StringUtils.hasLength(name)) {
			name = null;
		}
		String encoding = propertySource.getString("encoding");
		if (!StringUtils.hasLength(encoding)) {
			encoding = null;
		}
		String[] locations = propertySource.getStringArray("value");
		Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
		boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

		Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
		PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
				DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiate(factoryClass));

		for (String location : locations) {
			try {
				String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
				Resource resource = this.resourceLoader.getResource(resolvedLocation);
				addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
			}
			catch (IllegalArgumentException ex) {
				// from resolveRequiredPlaceholders
				if (!ignoreResourceNotFound) {
					throw ex;
				}
			}
			catch (FileNotFoundException ex) {
				// from ResourcePropertySource constructor
				if (!ignoreResourceNotFound) {
					throw ex;
				}
			}
		}
	}

	private void addPropertySource(PropertySource<?> propertySource) {
		String name = propertySource.getName();
		MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();
		if (propertySources.contains(name) && this.propertySourceNames.contains(name)) {
			// We've already added a version, we need to extend it
			PropertySource<?> existing = propertySources.get(name);
			PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
					((ResourcePropertySource) propertySource).withResourceName() : propertySource);
			if (existing instanceof CompositePropertySource) {
				((CompositePropertySource) existing).addFirstPropertySource(newSource);
			}
			else {
				if (existing instanceof ResourcePropertySource) {
					existing = ((ResourcePropertySource) existing).withResourceName();
				}
				CompositePropertySource composite = new CompositePropertySource(name);
				composite.addPropertySource(newSource);
				composite.addPropertySource(existing);
				propertySources.replace(name, composite);
			}
		}
		else {
			if (this.propertySourceNames.isEmpty()) {
				propertySources.addLast(propertySource);
			}
			else {
				String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
				propertySources.addBefore(firstProcessed, propertySource);
			}
		}
		this.propertySourceNames.add(name);
	}

	/**
	 * Returns {@code @Import} class, considering all meta-annotations.
	 */
	private Set<SourceClass> getImports(SourceClass sourceClass) throws IOException {
		Set<SourceClass> imports = new LinkedHashSet<SourceClass>();
		Set<SourceClass> visited = new LinkedHashSet<SourceClass>();
		collectImports(sourceClass, imports, visited);
		return imports;
	}

	/**
	 * Recursively collect all declared {@code @Import} values. Unlike most
	 * meta-annotations it is valid to have several {@code @Import}s declared with
	 * different values; the usual process of returning values from the first
	 * meta-annotation on a class is not sufficient.
	 *
For example, it is common for a {@code @Configuration} class to declare direct
	 * {@code @Import}s in addition to meta-imports originating from an {@code @Enable}
	 * annotation.
	 * @param sourceClass the class to search
	 * @param imports the imports collected so far
	 * @param visited used to track visited classes to prevent infinite recursion
	 * @throws IOException if there is any problem reading metadata from the named class
	 */
	private void collectImports(SourceClass sourceClass, Set<SourceClass> imports, Set<SourceClass> visited) throws IOException {
		if (visited.add(sourceClass)) {
			for (SourceClass annotation : sourceClass.getAnnotations()) {
				String annName = annotation.getMetadata().getClassName();
				if (!annName.startsWith("java") && !annName.equals(Import.class.getName())) {
					collectImports(annotation, imports, visited);
				}
			}
			imports.addAll(sourceClass.getAnnotationAttributes(Import.class.getName(), "value"));
		}
	}

	private void processDeferredImportSelectors() {
		List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
		this.deferredImportSelectors = null;
		Collections.sort(deferredImports, DEFERRED_IMPORT_COMPARATOR);

		for (DeferredImportSelectorHolder deferredImport : deferredImports) {
			ConfigurationClass configClass = deferredImport.getConfigurationClass();
			try {
				String[] imports = deferredImport.getImportSelector().selectImports(configClass.getMetadata());
				processImports(configClass, asSourceClass(configClass), asSourceClasses(imports), false);
			}
			catch (BeanDefinitionStoreException ex) {
				throw ex;
			}
			catch (Exception ex) {
				throw new BeanDefinitionStoreException("Failed to process import candidates for configuration class [" +
						configClass.getMetadata().getClassName() + "]", ex);
			}
		}
	}

	private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
			Collection<SourceClass> importCandidates, boolean checkForCircularImports) throws IOException {

		if (importCandidates.isEmpty()) {
			return;
		}

		if (checkForCircularImports && this.importStack.contains(configClass)) {
			this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
		}
		else {
			this.importStack.push(configClass);
			try {
				for (SourceClass candidate : importCandidates) {
					if (candidate.isAssignable(ImportSelector.class)) {
						// Candidate class is an ImportSelector -> delegate to it to determine imports
						Class<?> candidateClass = candidate.loadClass();
						ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
						invokeAwareMethods(selector);
						if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) {
							this.deferredImportSelectors.add(
									new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector));
						}
						else {
							String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
							Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
							processImports(configClass, currentSourceClass, importSourceClasses, false);
						}
					}
					else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
						// Candidate class is an ImportBeanDefinitionRegistrar ->
						// delegate to it to register additional bean definitions
						Class<?> candidateClass = candidate.loadClass();
						ImportBeanDefinitionRegistrar registrar =
								BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
						invokeAwareMethods(registrar);
						configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
					}
					else {
						// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
						// process it as an @Configuration class
						this.importStack.registerImport(
								currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
						processConfigurationClass(candidate.asConfigClass(configClass));
					}
				}
			}
			catch (BeanDefinitionStoreException ex) {
				throw ex;
			}
			catch (Exception ex) {
				throw new BeanDefinitionStoreException("Failed to process import candidates for configuration class [" +
						configClass.getMetadata().getClassName() + "]", ex);
			}
			finally {
				this.importStack.pop();
			}
		}
	}

	/**
	 * Invoke {@link ResourceLoaderAware}, {@link BeanClassLoaderAware} and
	 * {@link BeanFactoryAware} contracts if implemented by the given {@code bean}.
	 */
	private void invokeAwareMethods(Object importStrategyBean) {
		if (importStrategyBean instanceof Aware) {
			if (importStrategyBean instanceof EnvironmentAware) {
				((EnvironmentAware) importStrategyBean).setEnvironment(this.environment);
			}
			if (importStrategyBean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) importStrategyBean).setResourceLoader(this.resourceLoader);
			}
			if (importStrategyBean instanceof BeanClassLoaderAware) {
				ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ?
						((ConfigurableBeanFactory) this.registry).getBeanClassLoader() :
						this.resourceLoader.getClassLoader());
				((BeanClassLoaderAware) importStrategyBean).setBeanClassLoader(classLoader);
			}
			if (importStrategyBean instanceof BeanFactoryAware && this.registry instanceof BeanFactory) {
				((BeanFactoryAware) importStrategyBean).setBeanFactory((BeanFactory) this.registry);
			}
		}
	}

	/**
	 * Validate each {@link ConfigurationClass} object.
	 * @see ConfigurationClass#validate
	 */
	public void validate() {
		for (ConfigurationClass configClass : this.configurationClasses.keySet()) {
			configClass.validate(this.problemReporter);
		}
	}

	public Set<ConfigurationClass> getConfigurationClasses() {
		return this.configurationClasses.keySet();
	}

	ImportRegistry getImportRegistry() {
		return this.importStack;
	}

	/**
	 * Factory method to obtain a {@link SourceClass} from a {@link ConfigurationClass}.
	 */
	public SourceClass asSourceClass(ConfigurationClass configurationClass) throws IOException {
		AnnotationMetadata metadata = configurationClass.getMetadata();
		if (metadata instanceof StandardAnnotationMetadata) {
			return asSourceClass(((StandardAnnotationMetadata) metadata).getIntrospectedClass());
		}
		return asSourceClass(configurationClass.getMetadata().getClassName());
	}

	/**
	 * Factory method to obtain a {@link SourceClass} from a {@link Class}.
	 */
	public SourceClass asSourceClass(Class<?> classType) throws IOException {
		try {
			// Sanity test that we can read annotations, if not fall back to ASM
			classType.getAnnotations();
			return new SourceClass(classType);
		}
		catch (Throwable ex) {
			// Enforce ASM via class name resolution
			return asSourceClass(classType.getName());
		}
	}

	/**
	 * Factory method to obtain {@link SourceClass}s from class names.
	 */
	public Collection<SourceClass> asSourceClasses(String[] classNames) throws IOException {
		List<SourceClass> annotatedClasses = new ArrayList<SourceClass>();
		for (String className : classNames) {
			annotatedClasses.add(asSourceClass(className));
		}
		return annotatedClasses;
	}

	/**
	 * Factory method to obtain a {@link SourceClass} from a class name.
	 */
	public SourceClass asSourceClass(String className) throws IOException {
		if (className.startsWith("java")) {
			// Never use ASM for core java types
			try {
				return new SourceClass(this.resourceLoader.getClassLoader().loadClass(className));
			}
			catch (ClassNotFoundException ex) {
				throw new NestedIOException("Failed to load class [" + className + "]", ex);
			}
		}
		return new SourceClass(this.metadataReaderFactory.getMetadataReader(className));
	}

	@SuppressWarnings("serial")
	private static class ImportStack extends ArrayDeque<ConfigurationClass> implements ImportRegistry {

		private final MultiValueMap<String, AnnotationMetadata> imports = new LinkedMultiValueMap<String, AnnotationMetadata>();

		public void registerImport(AnnotationMetadata importingClass, String importedClass) {
			this.imports.add(importedClass, importingClass);
		}

		@Override
		public void removeImportingClassFor(String importedClass) {
			for (List<AnnotationMetadata> list : this.imports.values()) {
				for (Iterator<AnnotationMetadata> iterator = list.iterator(); iterator.hasNext();) {
					if (iterator.next().getClassName().equals(importedClass)) {
						iterator.remove();
					}
				}
			}
		}

		@Override
		public AnnotationMetadata getImportingClassFor(String importedClass) {
			List<AnnotationMetadata> list = this.imports.get(importedClass);
			return (!CollectionUtils.isEmpty(list) ? list.get(list.size() - 1) : null);
		}

		/**
		 * Given a stack containing (in order)
		 *

		 *
com.acme.Foo

		 *
com.acme.Bar

		 *
com.acme.Baz

		 *

		 * return "[Foo->Bar->Baz]".
		 */
		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder("[");
			Iterator<ConfigurationClass> iterator = iterator();
			while (iterator.hasNext()) {
				builder.append(iterator.next().getSimpleName());
				if (iterator.hasNext()) {
					builder.append("->");
				}
			}
			return builder.append(']').toString();
		}
	}

	private static class DeferredImportSelectorHolder {

		private final ConfigurationClass configurationClass;

		private final DeferredImportSelector importSelector;

		public DeferredImportSelectorHolder(ConfigurationClass configurationClass, DeferredImportSelector importSelector) {
			this.configurationClass = configurationClass;
			this.importSelector = importSelector;
		}

		public ConfigurationClass getConfigurationClass() {
			return this.configurationClass;
		}

		public DeferredImportSelector getImportSelector() {
			return this.importSelector;
		}
	}

	/**
	 * Simple wrapper that allows annotated source classes to be dealt with
	 * in a uniform manner, regardless of how they are loaded.
	 */
	private class SourceClass {

		private final Object source;  // Class or MetadataReader

		private final AnnotationMetadata metadata;

		public SourceClass(Object source) {
			this.source = source;
			if (source instanceof Class<?>) {
				this.metadata = new StandardAnnotationMetadata((Class<?>) source, true);
			}
			else {
				this.metadata = ((MetadataReader) source).getAnnotationMetadata();
			}
		}

		public final AnnotationMetadata getMetadata() {
			return this.metadata;
		}

		public Class<?> loadClass() throws ClassNotFoundException {
			if (this.source instanceof Class<?>) {
				return (Class<?>) this.source;
			}
			String className = ((MetadataReader) this.source).getClassMetadata().getClassName();
			return resourceLoader.getClassLoader().loadClass(className);
		}

		public boolean isAssignable(Class<?> clazz) throws IOException {
			if (this.source instanceof Class) {
				return clazz.isAssignableFrom((Class<?>) this.source);
			}
			return new AssignableTypeFilter(clazz).match((MetadataReader) this.source, metadataReaderFactory);
		}

		public ConfigurationClass asConfigClass(ConfigurationClass importedBy) throws IOException {
			if (this.source instanceof Class<?>) {
				return new ConfigurationClass((Class<?>) this.source, importedBy);
			}
			return new ConfigurationClass((MetadataReader) this.source, importedBy);
		}

		public Collection<SourceClass> getMemberClasses() throws IOException {
			Object sourceToProcess = this.source;
			if (sourceToProcess instanceof Class<?>) {
				Class<?> sourceClass = (Class<?>) sourceToProcess;
				try {
					Class<?>[] declaredClasses = sourceClass.getDeclaredClasses();
					List<SourceClass> members = new ArrayList<SourceClass>(declaredClasses.length);
					for (Class<?> declaredClass : declaredClasses) {
						members.add(asSourceClass(declaredClass));
					}
					return members;
				}
				catch (NoClassDefFoundError err) {
					// getDeclaredClasses() failed because of non-resolvable dependencies
					// -> fall back to ASM below
					sourceToProcess = metadataReaderFactory.getMetadataReader(sourceClass.getName());
				}
			}

			// ASM-based resolution - safe for non-resolvable classes as well
			MetadataReader sourceReader = (MetadataReader) sourceToProcess;
			String[] memberClassNames = sourceReader.getClassMetadata().getMemberClassNames();
			List<SourceClass> members = new ArrayList<SourceClass>(memberClassNames.length);
			for (String memberClassName : memberClassNames) {
				try {
					members.add(asSourceClass(memberClassName));
				}
				catch (IOException ex) {
					// Let's skip it if it's not resolvable - we're just looking for candidates
					if (logger.isDebugEnabled()) {
						logger.debug("Failed to resolve member class [" + memberClassName +
								"] - not considering it as a configuration class candidate");
					}
				}
			}
			return members;
		}

		public SourceClass getSuperClass() throws IOException {
			if (this.source instanceof Class<?>) {
				return asSourceClass(((Class<?>) this.source).getSuperclass());
			}
			return asSourceClass(((MetadataReader) this.source).getClassMetadata().getSuperClassName());
		}

		public Set<SourceClass> getInterfaces() throws IOException {
			Set<SourceClass> result = new LinkedHashSet<SourceClass>();
			if (this.source instanceof Class<?>) {
				Class<?> sourceClass = (Class<?>) this.source;
				for (Class<?> ifcClass : sourceClass.getInterfaces()) {
					result.add(asSourceClass(ifcClass));
				}
			}
			else {
				for (String className : this.metadata.getInterfaceNames()) {
					result.add(asSourceClass(className));
				}
			}
			return result;
		}

		public Set<SourceClass> getAnnotations() throws IOException {
			Set<SourceClass> result = new LinkedHashSet<SourceClass>();
			for (String className : this.metadata.getAnnotationTypes()) {
				try {
					result.add(getRelated(className));
				}
				catch (Throwable ex) {
					// An annotation not present on the classpath is being ignored
					// by the JVM's class loading -> ignore here as well.
				}
			}
			return result;
		}

		public Collection<SourceClass> getAnnotationAttributes(String annotationType, String attribute) throws IOException {
			Map<String, Object> annotationAttributes = this.metadata.getAnnotationAttributes(annotationType, true);
			if (annotationAttributes == null || !annotationAttributes.containsKey(attribute)) {
				return Collections.emptySet();
			}
			String[] classNames = (String[]) annotationAttributes.get(attribute);
			Set<SourceClass> result = new LinkedHashSet<SourceClass>();
			for (String className : classNames) {
				result.add(getRelated(className));
			}
			return result;
		}

		private SourceClass getRelated(String className) throws IOException {
			if (this.source instanceof Class<?>) {
				try {
					Class<?> clazz = resourceLoader.getClassLoader().loadClass(className);
					return asSourceClass(clazz);
				}
				catch (ClassNotFoundException ex) {
					// Ignore -> fall back to ASM next, except for core java types.
					if (className.startsWith("java")) {
						throw new NestedIOException("Failed to load class [" + className + "]", ex);
					}
					return new SourceClass(metadataReaderFactory.getMetadataReader(className));
				}
			}
			return asSourceClass(className);
		}

		@Override
		public boolean equals(Object other) {
			return (this == other || (other instanceof SourceClass &&
					this.metadata.getClassName().equals(((SourceClass) other).metadata.getClassName())));
		}

		@Override
		public int hashCode() {
			return this.metadata.getClassName().hashCode();
		}

		@Override
		public String toString() {
			return this.metadata.getClassName();
		}
	}

	/**
	 * {@link Problem} registered upon detection of a circular {@link Import}.
	 */
	private static class CircularImportProblem extends Problem {

		public CircularImportProblem(ConfigurationClass attemptedImport, Deque<ConfigurationClass> importStack) {
			super(String.format("A circular @Import has been detected: " +
					"Illegal attempt by @Configuration class '%s' to import class '%s' as '%s' is " +
					"already present in the current import stack %s", importStack.peek().getSimpleName(),
					attemptedImport.getSimpleName(), attemptedImport.getSimpleName(), importStack),
					new Location(importStack.peek().getResource(), attemptedImport.getMetadata()));
		}
	}

}


text:
<?php

namespace Krystal\Application\Component;

use Krystal\Http\Response\HttpResponse as Component;
use Krystal\Http\HeaderBag;
use Krystal\Application\InputInterface;
use Krystal\InstanceManager\DependencyInjectionContainerInterface;

final class Response implements ComponentInterface
{
    /**
     * {@inheritDoc}
     */
    public function getInstance(DependencyInjectionContainerInterface $container, array $config, InputInterface $input)
    {
        return new Component(new HeaderBag(), $input->getServer());
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'response';
    }
}


text:
@interface SMAnnotationView ()

@property (nonatomic) UILabel *countLabel;

@end

@implementation SMAnnotationView
//@synthesize image;

-(instancetype)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    if (self) {
        [self setUpLabel];
        [self setCount:1];
    }
    return self;
}

- (void)setUpLabel
{
    _countLabel = [[UILabel alloc] initWithFrame:self.bounds];
    _countLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _countLabel.textAlignment = NSTextAlignmentCenter;
    _countLabel.backgroundColor = [UIColor clearColor];
    _countLabel.textColor = [UIColor whiteColor];
    _countLabel.textAlignment = NSTextAlignmentCenter;
    _countLabel.adjustsFontSizeToFitWidth = YES;
    _countLabel.minimumScaleFactor = 2;
    _countLabel.numberOfLines = 1;
    _countLabel.font = [UIFont boldSystemFontOfSize:12];
    _countLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;

    [self addSubview:_countLabel];
}

-(void)setCount:(NSUInteger)count
{
    _count = count;
    [self layoutSubviews];
}

- (void)layoutSubviews
{
    if(self.image == nil)
        self.image = [UIImage imageNamed:@"map_yellow_pin"];

    self.countLabel.text = [self suffixNumber:[NSNumber numberWithInteger:self.count]];
    CGRect rect = self.bounds;

    rect.origin.y -= 7;
    self.countLabel.frame = rect;

}

-(NSString*) suffixNumber:(NSNumber*)number
{
    if (!number)
        return @"...";

    long long num = [number longLongValue];

    int s = ( (num < 0) ? -1 : (num > 0) ? 1 : 0 );
    NSString* sign = (s == -1 ? @"-" : @"" );

    num = llabs(num);

    if (num < 1000)
        return [NSString stringWithFormat:@"%@%lld",sign,num];

    int exp = (int) (log(num) / log(1000));

    NSArray* units = @[@"K",@"M",@"G",@"T",@"P",@"E"];

    return [NSString stringWithFormat:@"%@%.0f%@",sign, (num / pow(1000, exp)), [units objectAtIndex:(exp-1)]];
}

- (void)drawRect:(CGRect)rect
{

}
@end