text:
namespace blink {
namespace {

// Returns the error message to let the developer know about the reason of the unusual failures.
const String getMessageForResponseError(WebServiceWorkerResponseError error, const KURL& requestURL)
{
    String errorMessage = "The FetchEvent for \"" + requestURL.string() + "\" resulted in a network error response: ";
    switch (error) {
    case WebServiceWorkerResponseErrorPromiseRejected:
        errorMessage = errorMessage + "the promise was rejected.";
        break;
    case WebServiceWorkerResponseErrorDefaultPrevented:
        errorMessage = errorMessage + "preventDefault() was called without calling respondWith().";
        break;
    case WebServiceWorkerResponseErrorNoV8Instance:
        errorMessage = errorMessage + "an object that was not a Response was passed to respondWith().";
        break;
    case WebServiceWorkerResponseErrorResponseTypeError:
        errorMessage = errorMessage + "the promise was resolved with an error response object.";
        break;
    case WebServiceWorkerResponseErrorResponseTypeOpaque:
        errorMessage = errorMessage + "an \"opaque\" response was used for a request whose type is not no-cors";
        break;
    case WebServiceWorkerResponseErrorResponseTypeNotBasicOrDefault:
        ASSERT_NOT_REACHED();
        break;
    case WebServiceWorkerResponseErrorBodyUsed:
        errorMessage = errorMessage + "a Response whose \"bodyUsed\" is \"true\" cannot be used to respond to a request.";
        break;
    case WebServiceWorkerResponseErrorResponseTypeOpaqueForClientRequest:
        errorMessage = errorMessage + "an \"opaque\" response was used for a client request.";
        break;
    case WebServiceWorkerResponseErrorResponseTypeOpaqueRedirect:
        errorMessage = errorMessage + "an \"opaqueredirect\" type response was used for a request which is not a navigation request.";
        break;
    case WebServiceWorkerResponseErrorBodyLocked:
        errorMessage = errorMessage + "a Response whose \"body\" is locked cannot be used to respond to a request.";
        break;
    case WebServiceWorkerResponseErrorUnknown:
    default:
        errorMessage = errorMessage + "an unexpected error occurred.";
        break;
    }
    return errorMessage;
}

bool isNavigationRequest(WebURLRequest::FrameType frameType)
{
    return frameType != WebURLRequest::FrameTypeNone;
}

bool isClientRequest(WebURLRequest::FrameType frameType, WebURLRequest::RequestContext requestContext)
{
    return isNavigationRequest(frameType) || requestContext == WebURLRequest::RequestContextSharedWorker || requestContext == WebURLRequest::RequestContextWorker;
}

class NoopLoaderClient final : public GarbageCollectedFinalized<NoopLoaderClient>, public FetchDataLoader::Client {
    WTF_MAKE_NONCOPYABLE(NoopLoaderClient);
    USING_GARBAGE_COLLECTED_MIXIN(NoopLoaderClient);
public:
    NoopLoaderClient() = default;
    void didFetchDataLoadedStream() override {}
    void didFetchDataLoadFailed() override {}
    DEFINE_INLINE_TRACE() { FetchDataLoader::Client::trace(visitor); }
};

} // namespace

class RespondWithObserver::ThenFunction final : public ScriptFunction {
public:
    enum ResolveType {
        Fulfilled,
        Rejected,
    };

    static v8::Local<v8::Function> createFunction(ScriptState* scriptState, RespondWithObserver* observer, ResolveType type)
    {
        ThenFunction* self = new ThenFunction(scriptState, observer, type);
        return self->bindToV8Function();
    }

    DEFINE_INLINE_VIRTUAL_TRACE()
    {
        visitor->trace(m_observer);
        ScriptFunction::trace(visitor);
    }

private:
    ThenFunction(ScriptState* scriptState, RespondWithObserver* observer, ResolveType type)
        : ScriptFunction(scriptState)
        , m_observer(observer)
        , m_resolveType(type)
    {
    }

    ScriptValue call(ScriptValue value) override
    {
        ASSERT(m_observer);
        ASSERT(m_resolveType == Fulfilled || m_resolveType == Rejected);
        if (m_resolveType == Rejected) {
            m_observer->responseWasRejected(WebServiceWorkerResponseErrorPromiseRejected);
            value = ScriptPromise::reject(value.scriptState(), value).scriptValue();
        } else {
            m_observer->responseWasFulfilled(value);
        }
        m_observer = nullptr;
        return value;
    }

    Member<RespondWithObserver> m_observer;
    ResolveType m_resolveType;
};

RespondWithObserver* RespondWithObserver::create(ExecutionContext* context, int eventID, const KURL& requestURL, WebURLRequest::FetchRequestMode requestMode, WebURLRequest::FrameType frameType, WebURLRequest::RequestContext requestContext)
{
    return new RespondWithObserver(context, eventID, requestURL, requestMode, frameType, requestContext);
}

void RespondWithObserver::contextDestroyed()
{
    ContextLifecycleObserver::contextDestroyed();
    m_state = Done;
}

void RespondWithObserver::didDispatchEvent(bool defaultPrevented)
{
    ASSERT(executionContext());
    if (m_state != Initial)
        return;

    if (defaultPrevented) {
        responseWasRejected(WebServiceWorkerResponseErrorDefaultPrevented);
        return;
    }

    ServiceWorkerGlobalScopeClient::from(executionContext())->didHandleFetchEvent(m_eventID);
    m_state = Done;
}

void RespondWithObserver::respondWith(ScriptState* scriptState, ScriptPromise scriptPromise, ExceptionState& exceptionState)
{
    if (m_state != Initial) {
        exceptionState.throwDOMException(InvalidStateError, "The fetch event has already been responded to.");
        return;
    }

    m_state = Pending;
    scriptPromise.then(
        ThenFunction::createFunction(scriptState, this, ThenFunction::Fulfilled),
        ThenFunction::createFunction(scriptState, this, ThenFunction::Rejected));
}

void RespondWithObserver::responseWasRejected(WebServiceWorkerResponseError error)
{
    ASSERT(executionContext());
    executionContext()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, getMessageForResponseError(error, m_requestURL)));

    // The default value of WebServiceWorkerResponse's status is 0, which maps
    // to a network error.
    WebServiceWorkerResponse webResponse;
    webResponse.setError(error);
    ServiceWorkerGlobalScopeClient::from(executionContext())->didHandleFetchEvent(m_eventID, webResponse);
    m_state = Done;
}

void RespondWithObserver::responseWasFulfilled(const ScriptValue& value)
{
    ASSERT(executionContext());
    if (!V8Response::hasInstance(value.v8Value(), toIsolate(executionContext()))) {
        responseWasRejected(WebServiceWorkerResponseErrorNoV8Instance);
        return;
    }
    Response* response = V8Response::toImplWithTypeCheck(toIsolate(executionContext()), value.v8Value());
    // "If one of the following conditions is true, return a network error:
    //   - |response|'s type is |error|.
    //   - |request|'s mode is not |no-cors| and response's type is |opaque|.
    //   - |request| is a client request and |response|'s type is neither
    //     |basic| nor |default|."
    const FetchResponseData::Type responseType = response->response()->type();
    if (responseType == FetchResponseData::ErrorType) {
        responseWasRejected(WebServiceWorkerResponseErrorResponseTypeError);
        return;
    }
    if (responseType == FetchResponseData::OpaqueType) {
        if (m_requestMode != WebURLRequest::FetchRequestModeNoCORS) {
            responseWasRejected(WebServiceWorkerResponseErrorResponseTypeOpaque);
            return;
        }

        // The request mode of client requests should be "same-origin" but it is
        // not explicitly stated in the spec yet. So we need to check here.
        // FIXME: Set the request mode of client requests to "same-origin" and
        // remove this check when the spec will be updated.
        // Spec issue: https://github.com/whatwg/fetch/issues/101
        if (isClientRequest(m_frameType, m_requestContext)) {
            responseWasRejected(WebServiceWorkerResponseErrorResponseTypeOpaqueForClientRequest);
            return;
        }
    }
    if (!isNavigationRequest(m_frameType) && responseType == FetchResponseData::OpaqueRedirectType) {
        responseWasRejected(WebServiceWorkerResponseErrorResponseTypeOpaqueRedirect);
        return;
    }
    if (response->isBodyLocked()) {
        responseWasRejected(WebServiceWorkerResponseErrorBodyLocked);
        return;
    }
    if (response->bodyUsed()) {
        responseWasRejected(WebServiceWorkerResponseErrorBodyUsed);
        return;
    }

    WebServiceWorkerResponse webResponse;
    response->populateWebServiceWorkerResponse(webResponse);
    BodyStreamBuffer* buffer = response->internalBodyBuffer();
    if (buffer) {
        RefPtr<BlobDataHandle> blobDataHandle = buffer->drainAsBlobDataHandle(FetchDataConsumerHandle::Reader::AllowBlobWithInvalidSize);
        if (blobDataHandle) {
            webResponse.setBlobDataHandle(blobDataHandle);
        } else {
            Stream* outStream = Stream::create(executionContext(), "");
            webResponse.setStreamURL(outStream->url());
            buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsStream(outStream), new NoopLoaderClient);
        }
    }
    ServiceWorkerGlobalScopeClient::from(executionContext())->didHandleFetchEvent(m_eventID, webResponse);
    m_state = Done;
}

RespondWithObserver::RespondWithObserver(ExecutionContext* context, int eventID, const KURL& requestURL, WebURLRequest::FetchRequestMode requestMode, WebURLRequest::FrameType frameType, WebURLRequest::RequestContext requestContext)
    : ContextLifecycleObserver(context)
    , m_eventID(eventID)
    , m_requestURL(requestURL)
    , m_requestMode(requestMode)
    , m_frameType(frameType)
    , m_requestContext(requestContext)
    , m_state(Initial)
{
}

DEFINE_TRACE(RespondWithObserver)
{
    ContextLifecycleObserver::trace(visitor);
}

} // namespace blink


text:
<?php

class CM_Paging_ContentList_BadwordsTest extends CMTest_TestCase {

    /** @var CM_Paging_ContentList_Badwords */
    private $_paging;

    public function setUp() {
        $this->_paging = new CM_Paging_ContentList_Badwords();
        $this->_paging->add('bad.com');
        $this->_paging->add('superbad');
        $this->_paging->add('foo*bar');
        $this->_paging->add('|zoo|');
    }

    protected function tearDown() {
        $this->_paging->removeAll();
    }

    public function testIsMatch() {
        $this->assertTrue($this->_paging->isMatch('bad.com'));
        $this->assertTrue($this->_paging->isMatch('BAD.com'));
        $this->assertTrue($this->_paging->isMatch('sub.bad.com'));
        $this->assertTrue($this->_paging->isMatch('bad.com-foo.de'));
        $this->assertFalse($this->_paging->isMatch('evil.com'));
        $this->assertTrue($this->_paging->isMatch('foo-bar'));
        $this->assertTrue($this->_paging->isMatch('foo"bar'));
        $this->assertTrue($this->_paging->isMatch('test zoo test'));
        $this->assertFalse($this->_paging->isMatch('testzoo'));
        $this->assertFalse($this->_paging->isMatch('testzootest'));
        $this->assertFalse($this->_paging->isMatch('test zootest'));
        $this->assertFalse($this->_paging->isMatch('foo"bar'));

        $this->_paging->add('evil.com');
        $this->assertTrue($this->_paging->isMatch('evil.com'));
    }

    public function testGetMatch() {
        $this->assertSame('bad.com', $this->_paging->getMatch('bad.com'));
        $this->assertSame('bad.com', $this->_paging->getMatch('BAD.com'));
        $this->assertSame('bad.com', $this->_paging->getMatch('sub.bad.com'));
        $this->assertSame('bad.com', $this->_paging->getMatch('bad.com-foo.de'));
        $this->assertFalse($this->_paging->getMatch('evil.com'));
        $this->assertSame('foobar', $this->_paging->getMatch('foo-bar'));
        $this->assertSame('foobar', $this->_paging->getMatch('hallo foo-bar world.'));
        $this->assertSame('zoo', $this->_paging->getMatch('test zoo test'));
        $this->assertFalse($this->_paging->getMatch('testzoo'));
        $this->assertFalse($this->_paging->getMatch('testzootest'));
        $this->assertFalse($this->_paging->getMatch('test zootest'));

        $this->_paging->add('evil.com');
        $this->assertSame('evil.com', $this->_paging->getMatch('evil.com'));
    }

    public function testReplaceMatch() {
        $this->assertSame('hallo … world.', $this->_paging->replaceMatch('hallo foo-bar world.', '…'));
        $this->assertSame('hallo $1 \1 world.', $this->_paging->replaceMatch('hallo foo-bar world.', '$1 \1'));
        $this->assertSame('Hello … world.', $this->_paging->replaceMatch('Hello zoo world.', '…'));
        $this->assertSame('Hello … world.', $this->_paging->replaceMatch('Hello sub.zoo.com world.', '…'));
    }
}

redpajama_set_name: RedPajamaGithub


text:
DataBucket - WebSocket Client
=============================
DataBucket is a template for an application that can load, analyze, and visualize data that is targeted at normal humans and not require the skills of data scientists.

The `websocket-client` NodeJS package that resides in this repository provides a JavaScript API that communicates with the DataBucket server.

Build
-----
To build the client, install all the dependent packages using `npm`:

    % npm install

Example Usage
-------------
*TBD*

Run CLI
-------
For quick testing and interactive discovery, there is a client CLI (command line interface) that can be used to interact with a running DataBucket server.
The CLI was built using the [Vorpal](https://github.com/dthree/vorpal) package.

    % node lib/cli.js

To get a list of commands, use the `help` command:

    > help


text:
/**
 * app00
 *
 * Created by tarso on 23/10/18
 */

const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://10.15.20.117:8545"));

var lastBlock = -1;

console.log('Current block:', web3.eth.blockNumber);

web3.eth.getBlock('latest', function (error, result) {
  if (!error) {
    console.log(result.number);
    for (var nSx1 = 0; nSx1 <= result.number; nSx1++) {
      web3.eth.getBlock(nSx1, function (error, result) {
        if (!error) {
          console.log('Block      :', result.number);
          console.log('Parent hash:', result.parentHash);
          console.log('Hash       :', result.hash);
          console.log('------------');
        } else {
          console.log(error);
        }
      });
    }
  } else {
    console.log(error);
  }
});

web3.eth.getBlockNumber(function (error, result) {
  if (!error) {
    console.log('Current block:', result);
  } else {
    console.log(error);
  }
});


text:
/*
||
|| @file FastFader.cpp
|| @version 1.0
|| @author Danne Stayskal
|| @contact danne@stayskal.com
||
|| @description
|| | Provides a fast, cross-fading pixelbuffer to the FastLED library
|| #
||
|| @changelog
|| | 1.0 2014-05-29 - Danne Stayskal : Initial Release
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
|| #
==========================================
*/

#include "FastFader.h"

/*
==========================================
= FastFader::FastFader()
= Class constructor
=
= Takes:
=  * leds, a reference to an array of FastLED.h CRGB triples
==========================================
*/
FastFader::FastFader(){}

/*
==========================================
= FastFader::bind
= Bind the pixel buffer and fader to the LED interface
=
= Takes: nothing
= Returns: this, the current FastFader object
==========================================
*/
FastFader& FastFader::bind(int (*pixel_buffer)[3], CRGB *leds, int num_leds, CFastLED& fast_led){
	LEDs = leds;
	NumLEDs = num_leds;
	FLED = fast_led;
	PixelBuffer = pixel_buffer;

  for (int i = 0; i < NumLEDs; i++) {
    LEDs[i] = CRGB(0,0,0);
    PixelBuffer[i][0] = 0;
    PixelBuffer[i][1] = 0;
    PixelBuffer[i][2] = 0;
  }

	return *this;
}

/*
==========================================
= FastFader::clear
= Empties the current pixelbuffer
=
= Takes: nothing
= Returns: this, the current FastFader object
==========================================
*/
FastFader& FastFader::clear(){
  for (int i = 0; i < NumLEDs; i++) {
    for (int channel = 0; channel < 3; channel++) {
      FastFader::PixelBuffer[i][channel] = 0;
    }
  }
	return *this;
}

/*
==========================================
= FastFader::set_pixel
= Sets an individual pixel in the pixel buffer
=
= Takes:
=  * pos, the integer position being set (0..NumLEDs-1)
=  * value, (optional, default 255) the luminosity value to set (0..255).
=    * If passed an integer, this will apply to all channels.
=    * If passed an array[3], this will be mapped to RGB on this pixel.
=  * channel, (optional, default all channels) which channel to set.
=    * -1 will set all channels.
=    * 0..2 will set Red, Green, or Blue, respectively
=    * >2 will set all channels.
=
= Returns: this, the current FastFader object
==========================================
*/
FastFader& FastFader::set_pixel(int pos, int value, int channel){

  // Clip pos to the range 0..NumLEDs - 1, inclusive
  if (pos < 0) {
    pos = 0;
  }
  if (pos > NumLEDs) {
    pos = NumLEDs;
  }

  // Clip value to the range 0..255, inclusive
  if (value > 255) {
    value = 255;
  }
  if (value < 0) {
    value = 0;
  }

  // Set the pixel in the buffer
  if (channel < 0 || channel > 2) {
    for (int c = 0; c < 3; c++) {
      PixelBuffer[pos][c] = value;
    }
  } else {
    PixelBuffer[pos][channel] = value;
  }

	return *this;
}

FastFader& FastFader::set_pixel(int pos, int value[3]){
  for (int c = 0; c < 3; c++) {
		set_pixel(pos, value[c], c);
	}
	return *this;
}

FastFader& FastFader::set_pixel(int pos, int value){
  for (int c = 0; c < 3; c++) {
		set_pixel(pos, value, c);
	}
	return *this;
}

FastFader& FastFader::set_pixel(int pos){
	return set_pixel(pos, 255, -1);
}

/*
==========================================
= FastFader::get_pixel
= Gets an individual pixel from the pixel buffer
=
= Takes:
=  * pos, the integer position being set (0..NumLEDs-1)
=
= Returns:
=  * pixel, an arrray reference to an [R,G,B] pixel.
==========================================
*/
int* FastFader::get_pixel(int pos){

  return PixelBuffer[pos];

}

/*
==========================================
= FastFader::set_frame
= Sets an entire frame of data into the pixel buffer
=
= Takes:
=  * frame, a reference to a two-dimensional frame array:
=    * Dimension 0: position (0..NumLEDs)
=    * Dimension 1: array of values ([int red, int green, int blue)])
=
= Returns: this, the current FastFader object
==========================================
*/
FastFader& FastFader::set_frame(int (*frame)[3]){
  for (int i = 0; i < NumLEDs; i++) {
  	for (int channel = 0; channel < 3; channel++) {
  		set_pixel(i, frame[i][channel], channel);
  	}
  }
	return *this;
}

/*
==========================================
= FastFader::push
= Pushes the present pixelbuffer to the LED array
=
= Takes:
= * fader_delay (optional, default 100), an integer value of how many miliseconds to take when fading in this frame
= * fader_steps (optional, default 10), an integer value of how many steps to take when fading
= * decay_type (optional), determining which weighting decay function to map over the fade:
=   * NO_DECAY is the fastest, and will not actually fade the pixels in. It's good for slow boards.
=   * LINEAR_DECAY will decay the cross-fade linearly
=   * LOGARITHMIC_DECAY (default) will decay the cross-fade logarithmically. It's more expensive, but prettier.
=
= Returns: this, the current FastFader object
==========================================
*/
FastFader& FastFader::push(int fader_delay, int fader_steps, int decay_type){

  // Clone the present LED interface into a fader array
  int fader_cache[NumLEDs][3];
  for (int i = 0; i < NumLEDs; i++) {
    for (int channel = 0; channel < 3; channel++) {
      fader_cache[i][channel] = LEDs[i][channel];
    }
  }

  // Fade from the previous frame to the next one
  int step_delay = int(fader_delay / fader_steps);
  double log_base = log(fader_steps);
  for (int current_step = 1; current_step <= fader_steps; current_step++) {

    double previous_weight;
    double current_weight;
    double fader_weight;

    if (decay_type < -1 || decay_type > 1) {
    	decay_type = LOGARITHMIC_DECAY;
    }

  	if (decay_type == NO_DECAY) {
      previous_weight = 0;
      current_weight = 1;
      fader_weight = 1;
    }

    if (decay_type == LINEAR_DECAY) {
      // Calculate linear frame weighs for this step

      previous_weight = 100 * (fader_steps - current_step);
      current_weight = 100 * (current_step - 1);
      fader_weight = 100 * (fader_steps - 1);
    }

    if (decay_type == LOGARITHMIC_DECAY) {
      // Logarithmically weight the fade-in, since human perception of luminosity
      // is logarithmic, not linear. This is log_n(current_step) where n = fader_steps

      current_weight = 100 - (100 * (log(fader_steps - current_step + 1) / log_base));
      previous_weight = 100 - (100 * (log(current_step) / log_base));
      fader_weight = current_weight + previous_weight;
    }

    // Send this fader step to the LED interface
    for (int i = 0; i < NumLEDs; i++) {
      LEDs[i] = CRGB(
        int(((PixelBuffer[i][0] * current_weight) + (fader_cache[i][0] * previous_weight)) / fader_weight),
        int(((PixelBuffer[i][1] * current_weight) + (fader_cache[i][1] * previous_weight)) / fader_weight),
        int(((PixelBuffer[i][2] * current_weight) + (fader_cache[i][2] * previous_weight)) / fader_weight)
      );
    }
    FLED.show();

    // Pause for a fraction of a moment
    delay(step_delay);
  }

	return *this;
}

FastFader& FastFader::push(int fader_delay, int fader_steps) {
	return push(fader_delay, fader_steps, LOGARITHMIC_DECAY);
}

FastFader& FastFader::push(int fader_delay) {
	return push(fader_delay, 10, LOGARITHMIC_DECAY);
}

FastFader& FastFader::push() {
	return push(100, 10, LOGARITHMIC_DECAY);
}


text:
package org.springframework.boot.autoconfigure.data.mongo;

import java.util.Set;

import com.mongodb.reactivestreams.client.MongoClient;
import org.junit.After;
import org.junit.Test;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.TestAutoConfigurationPackage;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.data.alt.mongo.CityMongoDbRepository;
import org.springframework.boot.autoconfigure.data.alt.mongo.ReactiveCityMongoDbRepository;
import org.springframework.boot.autoconfigure.data.empty.EmptyDataPackage;
import org.springframework.boot.autoconfigure.data.mongo.city.City;
import org.springframework.boot.autoconfigure.data.mongo.city.ReactiveCityRepository;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link MongoReactiveRepositoriesAutoConfiguration}.
 *
 * @author Mark Paluch
 */
public class MongoReactiveRepositoriesAutoConfigurationTests {

	private AnnotationConfigApplicationContext context;

	@After
	public void close() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void testDefaultRepositoryConfiguration() throws Exception {
		prepareApplicationContext(TestConfiguration.class);
		assertThat(this.context.getBean(ReactiveCityRepository.class)).isNotNull();
		MongoClient client = this.context.getBean(MongoClient.class);
		assertThat(client).isInstanceOf(MongoClient.class);
		MongoMappingContext mappingContext = this.context
				.getBean(MongoMappingContext.class);
		@SuppressWarnings("unchecked")
		Set<? extends Class<?>> entities = (Set<? extends Class<?>>) ReflectionTestUtils
				.getField(mappingContext, "initialEntitySet");
		assertThat(entities).hasSize(1);
	}

	@Test
	public void testNoRepositoryConfiguration() throws Exception {
		prepareApplicationContext(EmptyConfiguration.class);
		MongoClient client = this.context.getBean(MongoClient.class);
		assertThat(client).isInstanceOf(MongoClient.class);
	}

	@Test
	public void doesNotTriggerDefaultRepositoryDetectionIfCustomized() {
		prepareApplicationContext(CustomizedConfiguration.class);
		assertThat(this.context.getBeansOfType(ReactiveCityMongoDbRepository.class))
				.isEmpty();
	}

	@Test(expected = NoSuchBeanDefinitionException.class)
	public void autoConfigurationShouldNotKickInEvenIfManualConfigDidNotCreateAnyRepositories() {
		prepareApplicationContext(SortOfInvalidCustomConfiguration.class);
		this.context.getBean(ReactiveCityRepository.class);
	}

	private void prepareApplicationContext(Class<?>... configurationClasses) {
		this.context = new AnnotationConfigApplicationContext();
		this.context.register(configurationClasses);
		this.context.register(MongoAutoConfiguration.class,
				MongoDataAutoConfiguration.class, MongoReactiveAutoConfiguration.class,
				MongoReactiveDataAutoConfiguration.class,
				MongoReactiveRepositoriesAutoConfiguration.class,
				PropertyPlaceholderAutoConfiguration.class);
		this.context.refresh();
	}

	@Configuration
	@TestAutoConfigurationPackage(City.class)
	protected static class TestConfiguration {

	}

	@Configuration
	@TestAutoConfigurationPackage(EmptyDataPackage.class)
	protected static class EmptyConfiguration {

	}

	@Configuration
	@TestAutoConfigurationPackage(MongoReactiveRepositoriesAutoConfigurationTests.class)
	@EnableMongoRepositories(basePackageClasses = CityMongoDbRepository.class)
	protected static class CustomizedConfiguration {

	}

	@Configuration
	// To not find any repositories
	@EnableReactiveMongoRepositories("foo.bar")
	@TestAutoConfigurationPackage(MongoReactiveRepositoriesAutoConfigurationTests.class)
	protected static class SortOfInvalidCustomConfiguration {

	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starters</artifactId>
		<version>2.0.0.BUILD-SNAPSHOT</version>
	</parent>
	<artifactId>spring-boot-starter-batch</artifactId>
	<name>Spring Boot Batch Starter</name>
	<description>Starter for using Spring Batch</description>
	<url>http://projects.spring.io/spring-boot/</url>
	<organization>
		<name>Pivotal Software, Inc.</name>
		<url>http://www.spring.io</url>
	</organization>
	<properties>
		<main.basedir>${basedir}/../..</main.basedir>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.batch</groupId>
			<artifactId>spring-batch-core</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.basepom.maven</groupId>
				<artifactId>duplicate-finder-maven-plugin</artifactId>
				<executions>
					<execution>
						<id>duplicate-dependencies</id>
						<phase>validate</phase>
						<goals>
							<goal>check</goal>
						</goals>
						<configuration>
							<exceptions>
								<exception>
									<conflictingDependencies>
										<dependency>
											<groupId>xpp3</groupId>
											<artifactId>xpp3_min</artifactId>
										</dependency>
										<dependency>
											<groupId>xmlpull</groupId>
											<artifactId>xmlpull</artifactId>
										</dependency>
									</conflictingDependencies>
								</exception>
							</exceptions>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
using SheepAspect.Framework;
using SheepAspect.Runtime;
using SheepAspect.Runtime.Lifecycles;

namespace SheepAspect.Core
{
    [SingletonAspect]
    public class PerThisLifecycleAspect<TAspect>
    {
         public object Bind(IJointPoint jp)
         {
             PerThisAspectLifecycle.Bind(jp, typeof(TAspect));
             return jp.Execute();
         }
    }
}


text:
/* //////////////////////////////////////////////////////////////////////////////////////
 * includes
 */
#include "find.h"
#include "find_if.h"

/* //////////////////////////////////////////////////////////////////////////////////////
 * implementation
 */
tb_size_t tb_find(tb_iterator_ref_t iterator, tb_size_t head, tb_size_t tail, tb_cpointer_t value)
{
    return tb_find_if(iterator, head, tail, tb_predicate_eq, value);
}
tb_size_t tb_find_all(tb_iterator_ref_t iterator, tb_cpointer_t value)
{
    return tb_find_all_if(iterator, tb_predicate_eq, value);
}


text:
"""
An initializer is just a PyTorch function.
Here we implement a proxy class that allows us
to register them and supply any additional function arguments
(for example, the `mean` and `std` of a normal initializer)
as named arguments to the constructor.

The available initialization functions are

* ["normal"](https://pytorch.org/docs/master/nn.init.html?highlight=uniform#torch.nn.init.normal_)
* ["uniform"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.uniform_)
* ["constant"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.constant_)
* ["eye"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.eye_)
* ["dirac"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.dirac_)
* ["xavier_uniform"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.xavier_uniform_)
* ["xavier_normal"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.xavier_normal_)
* ["kaiming_uniform"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.kaiming_uniform_)
* ["kaiming_normal"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.kaiming_normal_)
* ["orthogonal"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.orthogonal_)
* ["sparse"](https://pytorch.org/docs/master/nn.init.html?highlight=orthogonal#torch.nn.init.sparse_)
* ["block_orthogonal"](./initializers.md#block_orthogonal)
* ["uniform_unit_scaling"](./initializers.md#uniform_unit_scaling)
* ["pretrained"](./initializers.md#pretrainedmodelinitializer)
"""  # noqa: E501
import logging
import re
import math
from typing import Callable, List, Tuple, Dict
import itertools

import tarfile

import torch
import torch.nn.init

from allennlp.common import FromParams, Registrable
from allennlp.common.checks import ConfigurationError

logger = logging.getLogger(__name__)

class Initializer(Registrable):
    """
    An initializer is really just a bare pytorch function. This class
    is a proxy that allows us to implement `Registrable` for those functions.
    """

    default_implementation = "normal"

    def __call__(self, tensor: torch.Tensor, **kwargs) -> None:
        """
        This function is here just to make mypy happy.  We expect initialization functions to
        follow this API; the builtin pytorch initialization functions follow this just fine, even
        though they don't subclass `Initialization`.  We're just making it explicit here, so mypy
        knows that initializers are callable like this.
        """
        raise NotImplementedError

def uniform_unit_scaling(tensor: torch.Tensor, nonlinearity: str = "linear"):
    """
    An initaliser which preserves output variance for approximately gaussian
    distributed inputs. This boils down to initialising layers using a uniform
    distribution in the range `(-sqrt(3/dim[0]) * scale, sqrt(3 / dim[0]) * scale)`, where
    `dim[0]` is equal to the input dimension of the parameter and the `scale`
    is a constant scaling factor which depends on the non-linearity used.

    See `Random Walk Initialisation for Training Very Deep Feedforward Networks
    <https://www.semanticscholar.org/paper/Random-Walk-Initialization-for-Training-Very-Deep-Sussillo-Abbott/be9728a0728b6acf7a485225b1e41592176eda0b>`_
    for more information.

    # Parameters

    tensor : `torch.Tensor`, required.
        The tensor to initialise.
    nonlinearity : `str`, optional (default = `"linear"`)
        The non-linearity which is performed after the projection that this
        tensor is involved in. This must be the name of a function contained
        in the `torch.nn.functional` package.

    # Returns

    The initialised tensor.
    """
    size = 1.0
    # Estimate the input size. This won't work perfectly,
    # but it covers almost all use cases where this initialiser
    # would be expected to be useful, i.e in large linear and
    # convolutional layers, as the last dimension will almost
    # always be the output size.
    for dimension in list(tensor.size())[:-1]:
        size *= dimension

    activation_scaling = torch.nn.init.calculate_gain(nonlinearity, tensor)
    max_value = math.sqrt(3 / size) * activation_scaling

    return tensor.data.uniform_(-max_value, max_value)

def block_orthogonal(tensor: torch.Tensor, split_sizes: List[int], gain: float = 1.0) -> None:
    """
    An initializer which allows initializing model parameters in "blocks". This is helpful
    in the case of recurrent models which use multiple gates applied to linear projections,
    which can be computed efficiently if they are concatenated together. However, they are
    separate parameters which should be initialized independently.

    # Parameters

    tensor : `torch.Tensor`, required.
        A tensor to initialize.
    split_sizes : `List[int]`, required.
        A list of length `tensor.ndim()` specifying the size of the
        blocks along that particular dimension. E.g. `[10, 20]` would
        result in the tensor being split into chunks of size 10 along the
        first dimension and 20 along the second.
    gain : `float`, optional (default = `1.0`)
        The gain (scaling) applied to the orthogonal initialization.
    """
    data = tensor.data
    sizes = list(tensor.size())
    if any(a % b != 0 for a, b in zip(sizes, split_sizes)):
        raise ConfigurationError(
            "tensor dimensions must be divisible by their respective "
            "split_sizes. Found size: {} and split_sizes: {}".format(sizes, split_sizes)
        )
    indexes = [list(range(0, max_size, split)) for max_size, split in zip(sizes, split_sizes)]
    # Iterate over all possible blocks within the tensor.
    for block_start_indices in itertools.product(*indexes):
        # A list of tuples containing the index to start at for this block
        # and the appropriate step size (i.e split_size[i] for dimension i).
        index_and_step_tuples = zip(block_start_indices, split_sizes)
        # This is a tuple of slices corresponding to:
        # tensor[index: index + step_size, ...]. This is
        # required because we could have an arbitrary number
        # of dimensions. The actual slices we need are the
        # start_index: start_index + step for each dimension in the tensor.
        block_slice = tuple(
            slice(start_index, start_index + step) for start_index, step in index_and_step_tuples
        )
        data[block_slice] = torch.nn.init.orthogonal_(tensor[block_slice].contiguous(), gain=gain)

def zero(tensor: torch.Tensor) -> None:
    return tensor.data.zero_()

def lstm_hidden_bias(tensor: torch.Tensor) -> None:
    """
    Initialize the biases of the forget gate to 1, and all other gates to 0,
    following Jozefowicz et al., An Empirical Exploration of Recurrent Network Architectures
    """
    # gates are (b_hi|b_hf|b_hg|b_ho) of shape (4*hidden_size)
    tensor.data.zero_()
    hidden_size = tensor.shape[0] // 4
    tensor.data[hidden_size : (2 * hidden_size)] = 1.0

class _InitializerWrapper(Initializer):
    def __init__(self, init_function: Callable[..., None], **kwargs):
        self._init_function = init_function
        self._kwargs = kwargs

    def __call__(self, tensor: torch.Tensor, **kwargs) -> None:
        self._init_function(tensor, **self._kwargs)

    def __repr__(self):
        return "Init: %s, with params: %s" % (self._init_function, self._kwargs)

@Initializer.register("normal")
class NormalInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "normal".
    """

    def __init__(self, mean: float = 0.0, std: float = 0.1):
        super().__init__(init_function=torch.nn.init.normal_, mean=mean, std=std)

@Initializer.register("orthogonal")
class OrthogonalInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "orthogonal".
    """

    def __init__(self, gain: float = 1.0):
        super().__init__(init_function=torch.nn.init.orthogonal_, gain=gain)

@Initializer.register("uniform")
class UniformInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "uniform".
    """

    def __init__(self, a: float = 0.0, b: float = 1.0):
        super().__init__(init_function=torch.nn.init.uniform_, a=a, b=b)

@Initializer.register("constant")
class ConstantInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "constant".
    """

    def __init__(self, val: float):
        super().__init__(init_function=torch.nn.init.constant_, val=val)

@Initializer.register("dirac")
class DiracInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "dirac".
    """

    def __init__(self):
        super().__init__(init_function=torch.nn.init.dirac_)

@Initializer.register("xavier_uniform")
class XavierUniformInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "xavir_uniform".
    """

    def __init__(self, gain: float = 1.0):
        super().__init__(init_function=torch.nn.init.xavier_uniform_, gain=gain)

@Initializer.register("xavier_normal")
class XavierNormalInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "xavier_normal".
    """

    def __init__(self, gain: float = 1.0):
        super().__init__(init_function=torch.nn.init.xavier_normal_, gain=gain)

@Initializer.register("kaiming_uniform")
class KaimingUniformInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "kaiming_uniform".
    """

    def __init__(self, a: float = 0.0, mode: str = "fan_in", nonlinearity: str = "leaky_relu"):
        super().__init__(
            init_function=torch.nn.init.kaiming_uniform_, a=a, mode=mode, nonlinearity=nonlinearity
        )

@Initializer.register("kaiming_normal")
class KaimingNormalInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "kaiming_normal".
    """

    def __init__(self, a: float = 0.0, mode: str = "fan_in", nonlinearity: str = "leaky_relu"):
        super().__init__(
            init_function=torch.nn.init.kaiming_normal_, a=a, mode=mode, nonlinearity=nonlinearity
        )

@Initializer.register("sparse")
class SparseInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "sparse".
    """

    def __init__(self, sparsity: float, std: float = 0.01):
        super().__init__(init_function=torch.nn.init.sparse_, sparsity=sparsity, std=std)

@Initializer.register("eye")
class EyeInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "eye".
    """

    def __init__(self):
        super().__init__(init_function=torch.nn.init.eye_)

@Initializer.register("block_orthogonal")
class BlockOrthogonalInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "block_orthogonal".
    """

    def __init__(self, split_sizes: List[int], gain: float = 1.0):
        super().__init__(init_function=block_orthogonal, split_sizes=split_sizes, gain=gain)

@Initializer.register("uniform_unit_scaling")
class UniformUnitScalingInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "uniform_unit_scaling".
    """

    def __init__(self, nonlinearity: str = "linear"):
        super().__init__(init_function=uniform_unit_scaling, nonlinearity=nonlinearity)

@Initializer.register("zero")
class ZeroInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "zero".
    """

    def __init__(self):
        super().__init__(init_function=zero)

@Initializer.register("lstm_hidden_bias")
class LstmHiddenBiasInitializer(_InitializerWrapper):
    """
    Registered as an `Initializer` with name "lstm_hidden_bias".
    """

    def __init__(self):
        super().__init__(init_function=lstm_hidden_bias)

@Initializer.register("pretrained")
class PretrainedModelInitializer(Initializer):
    """
    An initializer which allows initializing parameters using a pretrained model. The
    initializer will load all of the weights from the `weights_file_path` and use the
    name of the new parameters to index into the pretrained parameters. Therefore,
    by default, the names of the new and pretrained parameters must be the same.
    However, this behavior can be overridden using the `parameter_name_overrides`,
    which remaps the name of the new parameter to the key which should be used
    to index into the pretrained parameters.

    The initializer will load all of the weights from the `weights_file_path`
    regardless of which parameters will actually be used to initialize the new model.
    So, if you need to initialize several parameters using a pretrained model, the most
    memory-efficient way to do this is to use one `PretrainedModelInitializer` per
    weights file and use a regex to match all of the new parameters which need to be
    initialized.

    If you are using a configuration file to instantiate this object, the below entry
    in the `InitializerApplicator` parameters will initialize `linear_1.weight` and
    `linear_2.weight` using a pretrained model.  `linear_1.weight` will be initialized
    to the pretrained parameters called `linear_1.weight`, but `linear_2.weight` will
    be initialized to the pretrained parameters called `linear_3.weight`::

    ```
       ["linear_1.weight|linear_2.weight",
           {
               "type": "pretrained",
               "weights_file_path": "best.th",
               "parameter_name_overrides": {
                   "linear_2.weight": "linear_3.weight"
               }
           }
       ]
    ```

    To initialize weights for all the parameters from a pretrained model (assuming their names
    remain unchanged), use the following instead:

    ```
            [".*",
                {
                    "type": "pretrained",
                    "weights_file_path": "best.th",
                    "parameter_name_overrides": {}
                }
            ]
    ```

    Registered as an `Initializer` with name "pretrained".

    # Parameters

    weights_file_path : `str`, required
        The path to the weights file which has the pretrained model parameters.
    parameter_name_overrides : `Dict[str, str]`, optional (default = `None`)
        The mapping from the new parameter name to the name which should be used
        to index into the pretrained model parameters. If a parameter name is not
        specified, the initializer will use the parameter's default name as the key.
    """

    def __init__(
        self, weights_file_path: str, parameter_name_overrides: Dict[str, str] = None
    ) -> None:
        from allennlp.models.archival import (
            extracted_archive,
            get_weights_path,
        )  # import here to avoid circular imports

        self.weights: Dict[str, torch.Tensor]
        if tarfile.is_tarfile(weights_file_path):
            with extracted_archive(weights_file_path) as extraction_path:
                self.weights = torch.load(get_weights_path(extraction_path), map_location="cpu")
        else:
            self.weights = torch.load(weights_file_path, map_location="cpu")

        self.parameter_name_overrides = parameter_name_overrides or {}

    def __call__(self, tensor: torch.Tensor, parameter_name: str, **kwargs) -> None:  # type: ignore
        # Select the new parameter name if it's being overridden
        if parameter_name in self.parameter_name_overrides:
            parameter_name = self.parameter_name_overrides[parameter_name]

        # If the size of the source and destination tensors are not the
        # same, then we need to raise an error
        source_weights = self.weights[parameter_name]
        if tensor.data.size() != source_weights.size():
            raise ConfigurationError(
                "Incompatible sizes found for parameter %s. "
                "Found %s and %s" % (parameter_name, tensor.data.size(), source_weights.size())
            )

        # Copy the parameters from the source to the destination
        tensor.data.copy_(source_weights.data)

class InitializerApplicator(FromParams):
    """
    Applies initializers to the parameters of a Module based on regex matches.  Any parameter not
    explicitly matching a regex will not be initialized, instead using whatever the default
    initialization was in the module's code.

    If you are instantiating this object from a config file, an example configuration is as
    follows:

    ```json
    {
        "regexes": [
            ["parameter_regex_match1",
                {
                    "type": "normal"
                    "mean": 0.01
                    "std": 0.1
                }
            ],
            ["parameter_regex_match2", "uniform"]
        ],
        "prevent_regexes": ["prevent_init_regex"]
    }
    ```

    where the first item in each tuple under the `regexes` parameters is the regex that matches to
    parameters, and the second item specifies an `Initializer.` These values can either be strings,
    in which case they correspond to the names of initializers, or dictionaries, in which case they
    must contain the "type" key, corresponding to the name of an initializer.  In addition, they may
    contain auxiliary named parameters which will be fed to the initializer itself. To determine
    valid auxiliary parameters, please refer to the torch.nn.init documentation.

    # Parameters

    regexes : `List[Tuple[str, Initializer]]`, optional (default = `[]`)
        A list mapping parameter regexes to initializers.  We will check each parameter against
        each regex in turn, and apply the initializer paired with the first matching regex, if
        any.

    prevent_regexes: `List[str]`, optional (default=`None`)
        Any parameter name matching one of these regexes will not be initialized, regardless of
        whether it matches one of the regexes passed in the `regexes` parameter.
    """

    def __init__(
        self, regexes: List[Tuple[str, Initializer]] = None, prevent_regexes: List[str] = None
    ) -> None:
        self._initializers = regexes or []
        self._prevent_regex = None
        if prevent_regexes:
            self._prevent_regex = "(" + ")|(".join(prevent_regexes) + ")"

    def __call__(self, module: torch.nn.Module) -> None:
        """
        Applies an initializer to all parameters in a module that match one of the regexes we were
        given in this object's constructor.  Does nothing to parameters that do not match.

        # Parameters

        module : `torch.nn.Module`, required.
            The Pytorch module to apply the initializers to.
        """
        logger.info("Initializing parameters")
        unused_regexes = {initializer[0] for initializer in self._initializers}
        uninitialized_parameters = set()
        # Store which initializers were applied to which parameters.
        for name, parameter in module.named_parameters():
            for initializer_regex, initializer in self._initializers:
                allow = self._prevent_regex is None or not bool(
                    re.search(self._prevent_regex, name)
                )
                if allow and re.search(initializer_regex, name):
                    logger.info("Initializing %s using %s initializer", name, initializer_regex)
                    initializer(parameter, parameter_name=name)
                    unused_regexes.discard(initializer_regex)
                    break
            else:  # no break
                uninitialized_parameters.add(name)
        for regex in unused_regexes:
            logger.warning("Did not use initialization regex that was passed: %s", regex)
        logger.info(
            "Done initializing parameters; the following parameters are using their "
            "default initialization from their code"
        )
        uninitialized_parameter_list = list(uninitialized_parameters)
        uninitialized_parameter_list.sort()
        for name in uninitialized_parameter_list:
            logger.info("   %s", name)


text:
class PagesController < ApplicationController
  def index
    routes = {
      buildpacks_path: buildpacks_path,
      buildpack_path: buildpack_path('<%= id %>'),
    }
    gon.push(routes: routes)
  end
end


text:
import collections

##__________________________________________________________________||
TaskPackage = collections.namedtuple('TaskPackage', 'task args kwargs')

##__________________________________________________________________||


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Render\Element\SystemCompactLink.
 */

namespace Drupal\Core\Render\Element;

use Drupal\Core\Url as BaseUrl;
use Drupal\Component\Utility\NestedArray;

/**
 * Provides a link to show or hide help text on administration pages.
 *
 * Usage example:
 * @code
 * $form['system_compact_link'] = [
 *   '#type' => 'system_compact_link',
 * ];
 * @endcode
 *
 * @RenderElement("system_compact_link")
 */
class SystemCompactLink extends Link {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return array(
      '#pre_render' => array(
        array($class, 'preRenderCompactLink'),
        array($class, 'preRenderLink'),
      ),
      '#theme_wrappers' => array(
        'container' => array(
          '#attributes' => array('class' => array('compact-link')),
        ),
      ),
    );
  }

  /**
   * Pre-render callback: Renders a link into #markup.
   *
   * Doing so during pre_render gives modules a chance to alter the link parts.
   *
   * @param array $element
   *   A structured array whose keys form the arguments to Drupal::l():
   *   - #title: The link text to pass as argument to Drupal::l().
   *   - One of the following:
   *     - #route_name and (optionally) a #route_parameters array; The route
   *       name and route parameters which will be passed into the link
   *       generator.
   *     - #href: The system path or URL to pass as argument to Drupal::l().
   *   - #options: (optional) An array of options to pass to Drupal::l() or the
   *     link generator.
   *
   * @return array
   *   The passed-in element containing the system compact link default values.
   */
  public static function preRenderCompactLink($element) {
    // By default, link options to pass to l() are normally set in #options.
    $element += array('#options' => array());

    if (system_admin_compact_mode()) {
      $element['#title'] = t('Show descriptions');
      $element['#url'] = BaseUrl::fromRoute('system.admin_compact_page', array('mode' => 'off'));
      $element['#options'] = array(
        'attributes' => array('title' => t('Expand layout to include descriptions.')),
        'query' => \Drupal::destination()->getAsArray()
      );
    }
    else {
      $element['#title'] = t('Hide descriptions');
      $element['#url'] = BaseUrl::fromRoute('system.admin_compact_page', array('mode' => 'on'));
      $element['#options'] = array(
        'attributes' => array('title' => t('Compress layout by hiding descriptions.')),
        'query' => \Drupal::destination()->getAsArray(),
      );
    }

    $options = NestedArray::mergeDeep($element['#url']->getOptions(), $element['#options']);
    $element['#markup'] = \Drupal::l($element['#title'], $element['#url']->setOptions($options));

    return $element;
  }

}


text:
import tempfile
import os
import os.path
import subprocess

from marty.commands import Command
from marty.operations.fs import MartyFS

class Mount(Command):

    """ Mount a backup or a tree into a directory.
    """

    help = 'Mount a backup or a tree into a directory'

    def prepare(self):
        self._aparser.add_argument('remote', nargs='?')
        self._aparser.add_argument('name')
        self._aparser.add_argument('mountpoint')

    def run(self, args, config, storage, remotes):
        mountpoint = os.path.abspath(os.path.expanduser(args.mountpoint))
        if not os.path.exists(mountpoint):
            raise RuntimeError('Given mountpoint (%s) does not exist' % mountpoint)

        name = '%s/%s' % (args.remote, args.name) if args.remote else args.name
        tree = storage.get_tree(name)
        MartyFS(storage, tree, mountpoint).mount()

class Explore(Command):

    """ Explore a backup or tree by mounting it into a temporary directory.
    """

    help = 'Explore a backup or tree'

    def prepare(self):
        self._aparser.add_argument('remote', nargs='?')
        self._aparser.add_argument('name')

    def run(self, args, config, storage, remotes):
        name = '%s/%s' % (args.remote, args.name) if args.remote else args.name
        tree = storage.get_tree(name)

        with tempfile.TemporaryDirectory() as fullname:
            fs = MartyFS(storage, tree, fullname)
            fs.mount()
            shell = os.environ.get('SHELL', '/bin/sh')
            pshell = subprocess.Popen([shell], cwd=fullname)
            pshell.wait()
            fs.umount()


text:
from django.http import Http404
from django.utils.translation import gettext_lazy, pgettext_lazy
from cradmin_legacy import crapp
from cradmin_legacy.viewhelpers import listbuilderview
from cradmin_legacy.viewhelpers.listbuilder.itemvalue import TitleDescription

from devilry.apps.core.group_user_lookup import GroupUserLookup
from devilry.devilry_cradmin.devilry_listbuilder.feedbackfeed_timeline import StudentGroupCommentItemValueMinimal, \
    ExaminerGroupCommentItemValueMinimal, AdminGroupCommentItemValueMinimal
from devilry.devilry_group import models as group_models

class GroupCommentEditHistoryValue(TitleDescription):
    template_name = 'devilry_group/group_comment_history/history_item_value.django.html'
    valuealias = 'groupcomment_edit_history'

    def get_title(self):
        return self.groupcomment_edit_history.edited_datetime

    def get_visibility_text(self):
        visibility = self.groupcomment_edit_history.visibility
        if visibility == group_models.GroupComment.VISIBILITY_PRIVATE:
            return pgettext_lazy('comment edit history item', 'Only visible to you')
        if visibility == group_models.GroupComment.VISIBILITY_VISIBLE_TO_EXAMINER_AND_ADMINS:
            return pgettext_lazy('comment edit history item', 'Only visible to examiners and admins')
        return pgettext_lazy('comment edit history item', 'Visible to everyone')

    def get_extra_css_classes_list(self):
        extra_css_classes_list = super(GroupCommentEditHistoryValue, self).get_extra_css_classes_list()
        extra_css_classes_list.append('devilry-comment-edit-history-item')
        return extra_css_classes_list

class CommentHistoryView(listbuilderview.View):
    template_name = 'devilry_group/group_comment_history/comment_history.django.html'
    value_renderer_class = GroupCommentEditHistoryValue

    def get_pagetitle(self):
        return gettext_lazy('Comment edit history')

    def get_pageheading(self):
        return gettext_lazy('Comment edit history')

    def dispatch(self, request, *args, **kwargs):
        if 'group_comment_id' not in kwargs:
            raise Http404()
        try:
            self.group_comment = group_models.GroupComment.objects.get(id=kwargs['group_comment_id'])
        except group_models.GroupComment.DoesNotExist:
            raise Http404()

        # If the comment is private, only the user that created the comment can access the history view.
        if self.group_comment.visibility == group_models.GroupComment.VISIBILITY_PRIVATE \
                and self.group_comment.user != request.user:
            raise Http404()
        return super(CommentHistoryView, self).dispatch(request, *args, **kwargs)

    def get_no_items_message(self):
        return gettext_lazy('No items')

    def get_queryset_for_role(self, role):
        raise NotImplementedError()

    def get_current_group_comment_value_item_class(self):
        """
        Get the item value class for rendering the current group comment.
        """
        if self.group_comment.user_role == group_models.GroupComment.USER_ROLE_STUDENT:
            return StudentGroupCommentItemValueMinimal
        elif self.group_comment.user_role == group_models.GroupComment.USER_ROLE_EXAMINER:
            return ExaminerGroupCommentItemValueMinimal
        elif self.group_comment.user_role == group_models.GroupComment.USER_ROLE_ADMIN:
            return AdminGroupCommentItemValueMinimal
        raise ValueError('Unknown comment user role: {}'.format(self.group_comment.user_role))

    def get_current_group_comment_renderable(self):
        group = self.request.cradmin_role
        assignment = self.request.cradmin_role.parentnode
        devilry_viewrole = self.request.cradmin_instance.get_devilryrole_for_requestuser()
        group_user_lookup = GroupUserLookup(
            group=group,
            assignment=assignment,
            requestuser=self.request.user,
            requestuser_devilryrole=devilry_viewrole)
        group_comment_value_item_class = self.get_current_group_comment_value_item_class()
        return self.get_frame_renderer_class()(
            inneritem=group_comment_value_item_class(
                value=self.group_comment,
                devilry_viewrole=devilry_viewrole,
                assignment=assignment,
                requestuser=self.request.user,
                group_user_lookup=group_user_lookup
            )
        )

    def should_edit_history_be_rendered(self):
        return len(self.get_queryset()) != 0

    def get_context_data(self, **kwargs):
        context = super(CommentHistoryView, self).get_context_data(**kwargs)
        context['group_comment_renderable'] = self.get_current_group_comment_renderable()
        context['history_available'] = self.should_edit_history_be_rendered()
        return context


text:
title: Böhmermann über die Frauenkirche
date: 12:37 12/09/2014
taxonomy:
    category: blog
    tag: [dresden,frauenkirch,böhmermann]
continue_link: false
---

Echt pures Gold der Typ.

Böhmermann über die Frauenkirche:

Post by Jan Böhmermann.


text:
package at.linuxtage.companion.activities;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.*;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.nfc.NdefRecord;
import android.os.Build;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import at.linuxtage.companion.BuildConfig;
import at.linuxtage.companion.R;
import at.linuxtage.companion.api.GLTApi;
import at.linuxtage.companion.api.GLTApi;
import at.linuxtage.companion.api.GLTUrls;
import at.linuxtage.companion.db.AppDatabase;
import at.linuxtage.companion.fragments.*;
import at.linuxtage.companion.livedata.SingleEvent;
import at.linuxtage.companion.model.DownloadScheduleResult;
import at.linuxtage.companion.utils.NfcUtils;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

/**
 * Main entry point of the application. Allows to switch between section fragments and update the database.
 *
 * @author Christophe Beyls
 */
public class MainActivity extends AppCompatActivity implements NfcUtils.CreateNfcAppDataCallback {

	public static final String ACTION_SHORTCUT_BOOKMARKS = BuildConfig.APPLICATION_ID + ".intent.action.SHORTCUT_BOOKMARKS";
	public static final String ACTION_SHORTCUT_LIVE = BuildConfig.APPLICATION_ID + ".intent.action.SHORTCUT_LIVE";

	private enum Section {
		TRACKS(R.id.menu_tracks, true, true) {
			@Override
			public Fragment createFragment() {
				return new TracksFragment();
			}
		},
		BOOKMARKS(R.id.menu_bookmarks, false, false) {
			@Override
			public Fragment createFragment() {
				return new BookmarksListFragment();
			}
		},
		LIVE(R.id.menu_live, true, false) {
			@Override
			public Fragment createFragment() {
				return new LiveFragment();
			}
		},
		SPEAKERS(R.id.menu_speakers, false, false) {
			@Override
			public Fragment createFragment() {
				return new PersonsListFragment();
			}
		},
		MAP(R.id.menu_map, false, false) {
			@Override
			public Fragment createFragment() {
				return new MapFragment();
			}
		};

		private final int menuItemId;
		private final boolean extendsAppBar;
		private final boolean keep;

		Section(@IdRes int menuItemId, boolean extendsAppBar, boolean keep) {
			this.menuItemId = menuItemId;
			this.extendsAppBar = extendsAppBar;
			this.keep = keep;
		}

		@IdRes
		public int getMenuItemId() {
			return menuItemId;
		}

		public abstract Fragment createFragment();

		public boolean extendsAppBar() {
			return extendsAppBar;
		}

		public boolean shouldKeep() {
			return keep;
		}

		@Nullable
		public static Section fromMenuItemId(@IdRes int menuItemId) {
			for (Section section : Section.values()) {
				if (section.menuItemId == menuItemId) {
					return section;
				}
			}
			return null;
		}
	}

	private static final long DATABASE_VALIDITY_DURATION = DateUtils.DAY_IN_MILLIS;
	private static final long DOWNLOAD_REMINDER_SNOOZE_DURATION = DateUtils.DAY_IN_MILLIS;
	private static final String PREF_LAST_DOWNLOAD_REMINDER_TIME = "last_download_reminder_time";

	private static final String LAST_UPDATE_DATE_FORMAT = "d MMM yyyy kk:mm:ss";

	private Toolbar toolbar;

	// Main menu
	Section currentSection;
	MenuItem pendingNavigationMenuItem = null;
	DrawerLayout drawerLayout;
	private ActionBarDrawerToggle drawerToggle;
	View mainMenu;
	private NavigationView navigationView;
	private TextView lastUpdateTextView;

	private MenuItem searchMenuItem;

	private final Observer<SingleEvent<DownloadScheduleResult>> scheduleDownloadResultObserver = new Observer<SingleEvent<DownloadScheduleResult>>() {

		@Override
		public void onChanged(SingleEvent<DownloadScheduleResult> singleEvent) {
			final DownloadScheduleResult result = singleEvent.consume();
			if (result == null) {
				return;
			}
			String message;
			if (result.isError()) {
				message = getString(R.string.schedule_loading_error);
			} else if (result.isUpToDate()) {
				message = getString(R.string.events_download_up_to_date);
			} else {
				int eventsCount = result.getEventsCount();
				if (eventsCount == 0) {
					message = getString(R.string.events_download_empty);
				} else {
					message = getResources().getQuantityString(R.plurals.events_download_completed, eventsCount, eventsCount);
				}
			}
			Snackbar.make(findViewById(R.id.content), message, Snackbar.LENGTH_LONG).show();
		}
	};

	public static class DownloadScheduleReminderDialogFragment extends DialogFragment {

		@NonNull
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			return new AlertDialog.Builder(getContext())
					.setTitle(R.string.download_reminder_title)
					.setMessage(R.string.download_reminder_message)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							GLTApi.downloadSchedule(getContext());
						}

					}).setNegativeButton(android.R.string.cancel, null)
					.create();
		}
	}

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

		toolbar = findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);

		// Progress bar setup
		final ProgressBar progressBar = findViewById(R.id.progress);
		GLTApi.getDownloadScheduleProgress().observe(this, new Observer<Integer>() {

			@Override
			public void onChanged(Integer progressInteger) {
				int progress = progressInteger;
				if (progress != 100) {
					// Visible
					if (progressBar.getVisibility() == View.GONE) {
						progressBar.clearAnimation();
						progressBar.setVisibility(View.VISIBLE);
					}
					if (progress == -1) {
						progressBar.setIndeterminate(true);
					} else {
						progressBar.setIndeterminate(false);
						progressBar.setProgress(progress);
					}
				} else {
					// Invisible
					if (progressBar.getVisibility() == View.VISIBLE) {
						// Hide the progress bar with a fill and fade out animation
						progressBar.setIndeterminate(false);
						progressBar.setProgress(100);
						progressBar.animate()
								.alpha(0f)
								.withLayer()
								.setListener(new AnimatorListenerAdapter() {
									@Override
									public void onAnimationEnd(Animator animation) {
										progressBar.setVisibility(View.GONE);
										progressBar.setAlpha(1f);
									}
								});
					}
				}
			}
		});

		// Monitor the schedule download result
		GLTApi.getDownloadScheduleResult().observe(this, scheduleDownloadResultObserver);

		// Setup drawer layout
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		drawerLayout = findViewById(R.id.drawer_layout);
		drawerLayout.setDrawerShadow(ContextCompat.getDrawable(this, R.drawable.drawer_shadow_start), GravityCompat.START);
		drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.main_menu, R.string.close_menu) {

			@Override
			public void onDrawerStateChanged(int newState) {
				super.onDrawerStateChanged(newState);
				if (newState == DrawerLayout.STATE_DRAGGING) {
					pendingNavigationMenuItem = null;
				}
			}

			@Override
			public void onDrawerOpened(View drawerView) {
				super.onDrawerOpened(drawerView);
				// Make keypad navigation easier
				mainMenu.requestFocus();
			}

			@Override
			public void onDrawerClosed(View drawerView) {
				super.onDrawerClosed(drawerView);
				if (pendingNavigationMenuItem != null) {
					handleNavigationMenuItem(pendingNavigationMenuItem);
					pendingNavigationMenuItem = null;
				}
			}
		};
		drawerToggle.setDrawerIndicatorEnabled(true);
		drawerLayout.addDrawerListener(drawerToggle);
		// Disable drawerLayout focus to allow trackball navigation.
		// We handle the drawer closing on back press ourselves.
		drawerLayout.setFocusable(false);

		// Setup Main menu
		mainMenu = findViewById(R.id.main_menu);
		// Forward window insets to NavigationView
		ViewCompat.setOnApplyWindowInsetsListener(mainMenu, new OnApplyWindowInsetsListener() {
			@Override
			public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
				return insets;
			}
		});
		navigationView = findViewById(R.id.nav_view);
		navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
			@Override
			public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
				pendingNavigationMenuItem = menuItem;
				drawerLayout.closeDrawer(mainMenu);
				return true;
			}
		});

		// Last update date, below the list
		lastUpdateTextView = mainMenu.findViewById(R.id.last_update);
		AppDatabase.getInstance(this).getScheduleDao().getLastUpdateTime()
				.observe(this, lastUpdateTimeObserver);

		if (savedInstanceState == null) {
			// Select initial section
			currentSection = Section.TRACKS;
			String action = getIntent().getAction();
			if (action != null) {
				switch (action) {
					case ACTION_SHORTCUT_BOOKMARKS:
						currentSection = Section.BOOKMARKS;
						break;
					case ACTION_SHORTCUT_LIVE:
						currentSection = Section.LIVE;
						break;
				}
			}
			navigationView.setCheckedItem(currentSection.getMenuItemId());

			getSupportFragmentManager().beginTransaction()
					.add(R.id.content, currentSection.createFragment(), currentSection.name())
					.commit();
		}

		NfcUtils.setAppDataPushMessageCallbackIfAvailable(this, this);
	}

	private void updateActionBar(@NonNull Section section, @NonNull MenuItem menuItem) {
		setTitle(menuItem.getTitle());
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			toolbar.setElevation(section.extendsAppBar()
					? 0f : getResources().getDimension(R.dimen.toolbar_elevation));
		}
	}

	private final Observer<Long> lastUpdateTimeObserver = new Observer<Long>() {
		@Override
		public void onChanged(Long lastUpdateTime) {
			lastUpdateTextView.setText(getString(R.string.last_update,
					(lastUpdateTime == -1L)
							? getString(R.string.never)
							: android.text.format.DateFormat.format(LAST_UPDATE_DATE_FORMAT, lastUpdateTime)));
		}
	};

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		drawerToggle.syncState();

		// Restore current section from NavigationView
		final MenuItem menuItem = navigationView.getCheckedItem();
		if (menuItem != null) {
			if (currentSection == null) {
				currentSection = Section.fromMenuItemId(menuItem.getItemId());
			}
			if (currentSection != null) {
				updateActionBar(currentSection, menuItem);
			}
		}
	}

	@Override
	public void onBackPressed() {
		if (drawerLayout.isDrawerOpen(mainMenu)) {
			drawerLayout.closeDrawer(mainMenu);
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// Ensure no fragment transaction attempt will occur after onSaveInstanceState()
		if (pendingNavigationMenuItem != null) {
			pendingNavigationMenuItem = null;
			if (currentSection != null) {
				navigationView.setCheckedItem(currentSection.getMenuItemId());
			}
		}
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onStart() {
		super.onStart();

		// Download reminder
		long now = System.currentTimeMillis();
		Long timeValue = AppDatabase.getInstance(this).getScheduleDao().getLastUpdateTime().getValue();
		long time = (timeValue == null) ? -1L : timeValue;
		if ((time == -1L) || (time < (now - DATABASE_VALIDITY_DURATION))) {
			SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
			time = prefs.getLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, -1L);
			if ((time == -1L) || (time < (now - DOWNLOAD_REMINDER_SNOOZE_DURATION))) {
				prefs.edit()
						.putLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, now)
						.apply();

				FragmentManager fm = getSupportFragmentManager();
				if (fm.findFragmentByTag("download_reminder") == null) {
					new DownloadScheduleReminderDialogFragment().show(fm, "download_reminder");
				}
			}
		}
	}

	@Override
	protected void onStop() {
		if ((searchMenuItem != null) && searchMenuItem.isActionViewExpanded()) {
			searchMenuItem.collapseActionView();
		}

		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);

		MenuItem searchMenuItem = menu.findItem(R.id.search);
		this.searchMenuItem = searchMenuItem;
		// Associate searchable configuration with the SearchView
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) searchMenuItem.getActionView();
		searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Will close the drawer if the home button is pressed
		if (drawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		switch (item.getItemId()) {
			case R.id.refresh:
				Drawable icon = item.getIcon();
				if (icon instanceof Animatable) {
					// Hack: reset the icon to make sure the MenuItem will redraw itself properly
					item.setIcon(icon);
					((Animatable) icon).start();
				}
				GLTApi.downloadSchedule(this);
				return true;
		}
		return false;
	}

	// MAIN MENU

	void handleNavigationMenuItem(@NonNull MenuItem menuItem) {
		final int menuItemId = menuItem.getItemId();
		final Section section = Section.fromMenuItemId(menuItemId);
		if (section != null) {
			selectMenuSection(section, menuItem);
		} else {
			switch (menuItemId) {
				case R.id.menu_settings:
					startActivity(new Intent(MainActivity.this, SettingsActivity.class));
					overridePendingTransition(R.anim.slide_in_right, R.anim.partial_zoom_out);
					break;
				case R.id.menu_volunteer:
					try {
						new CustomTabsIntent.Builder()
								.setToolbarColor(ContextCompat.getColor(this, R.color.color_primary))
								.setShowTitle(true)
								.build()
								.launchUrl(this, Uri.parse(GLTUrls.getVolunteer()));
					} catch (ActivityNotFoundException ignore) {
					}
					break;
			}
		}
	}

	void selectMenuSection(@NonNull Section section, @NonNull MenuItem menuItem) {
		if (section != currentSection) {
			// Switch to new section
			FragmentManager fm = getSupportFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			Fragment f = fm.findFragmentById(R.id.content);
			if (f != null) {
				if (currentSection.shouldKeep()) {
					ft.detach(f);
				} else {
					ft.remove(f);
				}
			}
			if (section.shouldKeep() && ((f = fm.findFragmentByTag(section.name())) != null)) {
				ft.attach(f);
			} else {
				ft.add(R.id.content, section.createFragment(), section.name());
			}
			ft.commit();

			currentSection = section;
			updateActionBar(section, menuItem);
		}
	}

	@Nullable
	@Override
	public NdefRecord createNfcAppData() {
		// Delegate to the currently displayed fragment if it provides NFC data
		Fragment f = getSupportFragmentManager().findFragmentById(R.id.content);
		if (f instanceof NfcUtils.CreateNfcAppDataCallback) {
			return ((NfcUtils.CreateNfcAppDataCallback) f).createNfcAppData();
		}
		return null;
	}
}


text:
from gensim.models.doc2vec import Doc2Vec
import argparse
import pprint
import sys
import util

def process_arguments(args):
    parser = argparse.ArgumentParser(description='configure Doc2Vec model building')
    parser.add_argument('--model_path', action='store', help='the path to the model')
    params = vars(parser.parse_args(args))
    return params

if __name__ == '__main__':
    params = process_arguments(sys.argv[1:])
    input_path = params['model_path']

    util.enable_verbose_training(sys.argv[0])

    try:
        model = Doc2Vec.load_word2vec_format(input_path, binary=True)
        # this raises an exception if the model type is different..
    except Exception:
        # just use the other mothod of loading..
        model = Doc2Vec.load(input_path)
    print(len(model.vocab))

    pprint.pprint(model.most_similar('computers are cool'))
    pprint.pprint(model.most_similar('computers are stupid'))


text:
. ~/.bash_profile
. ~/.bashrc
loggerX=`date >> ~/Dropbox/logger.txt`
echo $loggerX
#dirStill="/mnt/Post_Ready/Retouch_Still/"
#dirFashion="/mnt/Post_Ready/Retouch_Fashion/"
#filesStill7=`find /mnt/Post_Ready/Retouch_Still/ -type f -mtime -7 -iname \*.jpg`
#filesFashion7=`find /mnt/Post_Ready/Retouch_Fashion/ -type f -mtime -7 -iname \*.jpg`
#importArgs="$@"
#for f in "$@"
importDir=/mnt/Post_Ready/zAlfresco_Primary/Alfresco_Batch_Import/
importDirFiles=`find $importDir -type f -iname \*.jpg`
tmpImportDirInPrg=/mnt/Post_Ready/zAlfresco_Primary/tmp_Alfresco_Batch_Import_Drop
tmpImportDirComplete=/mnt/Post_Ready/zAlfresco_Primary/tmp_Alfresco_Batch_Import_Complete
exifXmlFmt=$LIBSRV/exifFormatFile_XML_AlfAltered.txt

for f in $importDirFiles
do
outName=`basename "$f" | sed s/.jpg//g`
xmlOutImport="$tmpImportDirInPrg/$outName.jpg.metadata.properties.xml"
#exiftool -X -E -f -m -l -listItem 0 -struct -p $exifXmlFmt $f > $xmlOutImport
exiftool -d +%D-%b-%y -ee -m -f -p $exifXmlFmt $f > $xmlOutImport
mv $f $tmpImportDirInPrg
done;

###    #   <-------copy of file and xmlShadow sent to sort. jpg is rezed down to 600x720
   #   Sort to dir hashs
cd $tmpImportDirInPrg
for f in `find $tmpImportDirInPrg -type f -maxdepth 1 -iname \*.*`
do
outNameFull=`basename "$f"`
exiftool -'directory'=$tmpImportDirInPrg/%4f/ $tmpImportDirInPrg/$outNameFull
#exiftool -f -'directory'=$importDir/%4f/ $xmlOutImport
#mv $f $tmpImportDirComplete
#cd $tmpImportDirComplete
#exiftool -'directory'=$tmpImportDirComplete/%4f/ $tmpImportDirComplete/$outName.jpg
done;
echo $loggerX
exit;


text:
bool deps_entry_t::to_path(const pal::string_t& base, bool look_in_base, pal::string_t* str) const
{
    pal::string_t& candidate = *str;

    candidate.clear();

    // Base directory must be present to obtain full path
    if (base.empty())
    {
        return false;
    }

    // Entry relative path contains '/' separator, sanitize it to use
    // platform separator. Perf: avoid extra copy if it matters.
    pal::string_t pal_relative_path = relative_path;
    if (_X('/') != DIR_SEPARATOR)
    {
        replace_char(&pal_relative_path, _X('/'), DIR_SEPARATOR);
    }

    // Reserve space for the path below
    candidate.reserve(base.length() +
        pal_relative_path.length() + 3);

    candidate.assign(base);
    pal::string_t sub_path = look_in_base ? get_filename(pal_relative_path) : pal_relative_path;
    append_path(&candidate, sub_path.c_str());

    bool exists = pal::file_exists(candidate);
    const pal::char_t* query_type = look_in_base ? _X("Local") : _X("Relative");
    if (!exists)
    {
        trace::verbose(_X("    %s path query did not exist %s"), query_type, candidate.c_str());
        candidate.clear();
    }
    else
    {
        trace::verbose(_X("    %s path query exists %s"), query_type, candidate.c_str());
    }
    return exists;
}

// -----------------------------------------------------------------------------
// Given a "base" directory, yield the local path of this file
//
// Parameters:
//    base - The base directory to look for the relative path of this entry
//    str  - If the method returns true, contains the file path for this deps
//           entry relative to the "base" directory
//
// Returns:
//    If the file exists in the path relative to the "base" directory.
//
bool deps_entry_t::to_dir_path(const pal::string_t& base, pal::string_t* str) const
{
    return to_path(base, true, str);
}
// -----------------------------------------------------------------------------
// Given a "base" directory, yield the relative path of this file in the package
// layout.
//
// Parameters:
//    base - The base directory to look for the relative path of this entry
//    str  - If the method returns true, contains the file path for this deps
//           entry relative to the "base" directory
//
// Returns:
//    If the file exists in the path relative to the "base" directory.
//
bool deps_entry_t::to_rel_path(const pal::string_t& base, pal::string_t* str) const
{
    return to_path(base, false, str);
}

// -----------------------------------------------------------------------------
// Given a "base" directory, yield the relative path of this file in the package
// layout.
//
// Parameters:
//    base - The base directory to look for the relative path of this entry
//    str  - If the method returns true, contains the file path for this deps
//           entry relative to the "base" directory
//
// Returns:
//    If the file exists in the path relative to the "base" directory.
//
bool deps_entry_t::to_full_path(const pal::string_t& base, pal::string_t* str) const
{
    str->clear();

    // Base directory must be present to obtain full path
    if (base.empty())
    {
        return false;
    }

    pal::string_t new_base = base;
    append_path(&new_base, library_name.c_str());
    append_path(&new_base, library_version.c_str());

    return to_rel_path(new_base, str);
}

// -----------------------------------------------------------------------------
// Given a "base" directory, yield the relative path of this file in the package
// layout if the entry hash matches the hash file in the "base" directory
//
// Parameters:
//    base - The base directory to look for the relative path of this entry and
//           the hash file.
//    str  - If the method returns true, contains the file path for this deps
//           entry relative to the "base" directory
//
// Description:
//    Looks for a file named "{PackageName}.{PackageVersion}.nupkg.{HashAlgorithm}"
//    If the deps entry's {HashAlgorithm}-{HashValue} matches the contents then
//    yields the relative path of this entry in the "base" dir.
//
// Returns:
//    If the file exists in the path relative to the "base" directory and there
//    was hash file match with this deps entry.
//
// See: to_full_path(base, str)
//
bool deps_entry_t::to_hash_matched_path(const pal::string_t& base, pal::string_t* str) const
{
    pal::string_t& candidate = *str;

    candidate.clear();

    // Base directory must be present to perform hash lookup.
    if (base.empty())
    {
        return false;
    }

    // First detect position of hyphen in [Algorithm]-[Hash] in the string.
    size_t pos = library_hash.find(_X("-"));
    if (pos == 0 || pos == pal::string_t::npos)
    {
        trace::verbose(_X("Invalid hash %s value for deps file entry: %s"), library_hash.c_str(), library_name.c_str());
        return false;
    }

    // Build the nupkg file name. Just reserve approx 8 char_t's for the algorithm name.
    pal::string_t nupkg_filename;
    nupkg_filename.reserve(library_name.length() + 1 + library_version.length() + 16);
    nupkg_filename.append(library_name);
    nupkg_filename.append(_X("."));
    nupkg_filename.append(library_version);
    nupkg_filename.append(_X(".nupkg."));
    nupkg_filename.append(library_hash.substr(0, pos));

    // Build the hash file path str.
    pal::string_t hash_file;
    hash_file.reserve(base.length() + library_name.length() + library_version.length() + nupkg_filename.length() + 3);
    hash_file.assign(base);
    append_path(&hash_file, library_name.c_str());
    append_path(&hash_file, library_version.c_str());
    append_path(&hash_file, nupkg_filename.c_str());

    // Read the contents of the hash file.
    pal::ifstream_t fstream(hash_file);
    if (!fstream.good())
    {
        trace::verbose(_X("The hash file is invalid [%s]"), hash_file.c_str());
        return false;
    }

    // Obtain the hash from the file.
    std::string hash;
    hash.assign(pal::istreambuf_iterator_t(fstream),
        pal::istreambuf_iterator_t());
    pal::string_t pal_hash;
    pal::to_palstring(hash.c_str(), &pal_hash);

    // Check if contents match deps entry.
    pal::string_t entry_hash = library_hash.substr(pos + 1);
    if (entry_hash != pal_hash)
    {
        trace::verbose(_X("The file hash [%s][%d] did not match entry hash [%s][%d]"),
            pal_hash.c_str(), pal_hash.length(), entry_hash.c_str(), entry_hash.length());
        return false;
    }

    // All good, just append the relative dir to base.
    return to_full_path(base, &candidate);
}


text:
layout: single
property_name: border-top-left-radius
---

    {% include section-nav.html property_name="border-top-left-radius" %}

      #border-top-left-radius

定义左上角的圆角半径。

            默认

          border-top-left-radius: 0;

去掉左上角的圆角。

Hello world

          border-top-left-radius: 20px;

可以使用像素值。

Hello world

          border-top-left-radius: 50%;

也可以使用百分比值。在这个例子中,圆角从上边框的中间开始,到左边框的中间结束。

Hello world

          border-top-left-radius: 20px 50%;

如果设置了两个值,第一个值设置的是上边框的圆角半径,第二个值设置的是左边框的圆角半径。

Hello world


text:
FROM debian:stretch

MAINTAINER Björn Dahlgren <bjodah@gmail.com>

ENV LANG C.UTF-8

# This dockerfile is designed to run on binder (mybinder.org)
RUN apt-get update && \
    apt-get --quiet --assume-yes install curl git g++-6 libgmp-dev binutils-dev bzip2 make cmake sudo \
    python-dev python-pip liblapack-dev && \
    apt-get clean && \
    curl -LOs http://computation.llnl.gov/projects/sundials/download/sundials-2.7.0.tar.gz && \
    tar xzf sundials-2.7.0.tar.gz && mkdir build/ && cd build/ && \
    cmake -DCMAKE_PREFIX_PATH=/usr/local -DCMAKE_INSTALL_PREFIX=/usr/local -DCMAKE_BUILD_TYPE=Release \
    -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=OFF -DEXAMPLES_ENABLE=OFF -DEXAMPLES_INSTALL=OFF -DLAPACK_ENABLE=ON \
    ../sundials*/ && make install && cd - && rm -r build/ sundials* && \
    python -m pip install --upgrade pip

# At this point the system should be able to pip-install the pakcage and all of its dependencies. We'll do so
# when running the image using the ``host-jupyter-using-docker.sh`` script. Installed packages are cached.


text:
layout: post
title: LeetCode | Unique Binary Search Trees II in Python
categories: LeetCode
tags: Python

---
<!-- import js for mathjax -->
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=default"></script>

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
jax: ["input/TeX","output/HTML-CSS"],
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]},
extensions: ["tex2jax.js","MathMenu.js","MathZoom.js"],
TeX: { equationNumbers: { autoNumber: "AMS" }, extensions: ["AMSmath.js", "AMSsymbols.js","noErrors.js","noUndefined.js"]}
});
</script>

<script type="text/javascript"
    src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML">
</script>

<pre>
'''
Question:
    Given n, generate all structurally unique BST\'s (binary search trees) that store values 1...n.

Algorithm:
    recursion
'''

class Solution:
    # @return a list of tree node
    def generateTrees(self, n):
        return self.generateTrees_rec(1, n)

    def generateTrees_rec(self, s, e):
        if s > e:
            return [None]
        res = []
        for i in xrange(s, e+1):
            left_arr, right_arr = self.generateTrees_rec(s, i-1), self.generateTrees_rec(i+1, e)
            for left in left_arr:
                for right in right_arr:
                    root, root.left, root.right = TreeNode(i), left, right
                    res.append(root)
        return res
</pre>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: grid_board.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: grid_board.js

var inherits = require('util').inherits;
var Board = require("./board.js");

/**
 * Grid Board (i.e. Checkers)
 * @constructor
 * @extends {Board}
 * @param {int} width - width of the board
 * @param {int} height - height of the board
*/
function GridBoard(width, height) {
  Board.call(this);
  for (var i = 0; i < width; i++) {
    this.tiles[i] = Array(this.height);
  }

  this.width = width;
  this.height = height;
};

inherits(GridBoard, Board);

/**
 * Get a Tile from the board
 * @param {int} x - x coordinate of the tile
 * @param {int} y - y coordinate of the tile
 * @returns {Tile}
*/
GridBoard.prototype.getTile = function(x, y) {
  return this.tiles[x][y];
};

/**
 * Get the position of a Tile
 * @param {Tile} tile - The tile to find position of
 * @returns {Dictionary|int} {x: a, y: b}
*/
GridBoard.prototype.getTilePosition = function(tile) {

  for (var x = 0; x < this.width; x++) {
    for (var y = 0; y < this.height; y++) {
      if (this.tiles[x][y] == tile) {
        return {x: x, y: y};
      }
    }
  }

  return null;
};

module.exports = GridBoard;

Home

Classes

ArrayBoard

Board

Card

Component

Deck

EdgeTile

Game

GridBoard

Player

Tile

Token

Trade

VertexTile

View

    Documentation generated by JSDoc 3.3.3 on Thu Jan 21 2016 20:55:21 GMT-0500 (EST)


text:
import React, {Component} from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import { css } from 'aphrodite'
import { styles } from './styles.css'
import { Button } from 'react-bootstrap';
//import img1 from './Inbound.svg'

var avgs = [{
      num: 2144567891,
      csp: "XYZ",
      averageT:"1 Days",
      reason:"Pricing"
  },
  {
      num: 2144567892,
      csp: "XYZ",
      averageT:"1 Days",
      reason:"Pricing"
  },
  {
      num: 12144567893,
      csp: "XYZ",
      averageT:"2 Days",
      reason:"Service Quality"
  },
  {
      num: 2144567894,
      csp: "XYZ",
      averageT:"2 Days",
      reason:"Service Quality"
  }
  ]
class graphs extends Component{

    render() {
        return(

                        <BootstrapTable data={ avgs } striped hover condensed>
                            <TableHeaderColumn dataField='num' isKey>Number</TableHeaderColumn>
                            <TableHeaderColumn dataField='csp'>Current CSP</TableHeaderColumn>
                            <TableHeaderColumn dataField='averageT'>Average Time</TableHeaderColumn>
                            <TableHeaderColumn dataField='reason'>Reason</TableHeaderColumn>
                        </BootstrapTable>

        );
    }

}

export default graphs;


text:
import { expect } from "chai";
import sinon from "sinon";
import { FileSystemWatcher, OutputChannel, workspace } from "vscode";

import { CoverageService } from "../../src/coverage-system/coverageservice";
import { StatusBarToggler } from "../../src/extension/statusbartoggler";

const mockOutputChannel = {appendLine: (x) => {}} as OutputChannel;
const mockFileWatcher = {
    dispose: () => {},
    onDidChange: (fn: any) => {},
    onDidCreate: (fn: any) => {},
    onDidDelete: (fn: any) => {},
};
const mockStatusBarToggler = {setLoading: () => {}} as StatusBarToggler;

suite("CoverageService Tests", function() {
    teardown(() => sinon.restore());

    test("Should listen for all paths specified in manualCoverageFilePaths @unit", () => {
        const config: any = {
            manualCoverageFilePaths: [
                "/path1",
                "/path2",
            ],
        };
        const service = new CoverageService(config, mockOutputChannel, mockStatusBarToggler);

        const stubCreateFileSystemWatcher = sinon.stub(workspace, "createFileSystemWatcher")
            .returns(mockFileWatcher as FileSystemWatcher);

        (service as any).listenToFileSystem();

        expect(stubCreateFileSystemWatcher.calledWith("{/path1,/path2}"));
    });

    test("Should listen for coverage file names in workspace @unit", () => {
        const config: any = {
            coverageBaseDir: "custom/path/*",
            coverageFileNames: [
                "coverage.xml",
                "custom-lcov.info",
            ],
            manualCoverageFilePaths: [],
        };
        const service = new CoverageService(config, mockOutputChannel, mockStatusBarToggler);

        const stubCreateFileSystemWatcher = sinon.stub(workspace, "createFileSystemWatcher")
            .returns(mockFileWatcher as FileSystemWatcher);

        (service as any).listenToFileSystem();

        let prefix = config.coverageBaseDir;
        if (workspace.workspaceFolders) {
            const workspaceFolders = workspace.workspaceFolders.map((wf) => wf.uri.fsPath);
            prefix = `{${workspaceFolders}}/${prefix}`;
        }
        expect(stubCreateFileSystemWatcher.calledWith(`${prefix}/{coverage.xml,custom-lcov.info}`));
    });
});


text:
<?php
/**
 *
 *
 * PHP version 5
 *
 * @package
 * @author  Andrey Filippov <afi.work@gmail.com>
 */

use Solo\Logger\Logger;

require_once "../vendor/autoload.php";

$settings = [

	// This is a list of loggers
	"loggers" => [

		// this is a name of logger. You can get the logger by name calling Logger::get("logger_name")
		"test-logger" => [
			"writers" => ["default"],
			"format" => "{date-time} {log-name} [{log-level}]: {log-message}\nContext: {log-context}\n\n"
		]
	],
];

Logger::init($settings);

// write to default logger
Logger::get()->debug("Some message");

// write to custom logger
Logger::get("test-logger")->debug("Test message");


text:
                     0 ?
                                (environment.ignoreFailure? deployView.statuses.IGNORE : deployView.statuses.FAIL) : deployView.statuses.PASS}}"
                            dash-status-fail-text="{{environment.failedComponents}}"
                            dash-status-ignore-text="{{environment.failedComponents}}">

                    {{environment.name}}

                    {{environment.lastUpdated | date:'MMM d, yyyy'}}

                 0}">
                    {{environment.serverUpCount}}

                 0}">
                    {{environment.serverDownCount}}