text:
#include "core/fetch/ResourceFetcher.h"

#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/FetchInitiatorTypeNames.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ImageResource.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/MockFetchContext.h"
#include "core/fetch/MockResourceClients.h"
#include "core/fetch/RawResource.h"
#include "core/fetch/ResourceLoader.h"
#include "platform/WebTaskRunner.h"
#include "platform/exported/WrappedResourceResponse.h"
#include "platform/heap/Handle.h"
#include "platform/heap/HeapAllocator.h"
#include "platform/heap/Member.h"
#include "platform/network/ResourceRequest.h"
#include "platform/network/ResourceTimingInfo.h"
#include "platform/scheduler/test/fake_web_task_runner.h"
#include "platform/testing/URLTestHelpers.h"
#include "platform/testing/weburl_loader_mock.h"
#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
#include "public/platform/WebURLLoaderMockFactory.h"
#include "public/platform/WebURLResponse.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "wtf/Allocator.h"
#include "wtf/PtrUtil.h"
#include "wtf/Vector.h"
#include <memory>

namespace blink {

namespace {
const char testImageFilename[] = "white-1x1.png";
const int testImageSize = 103;  // size of web/tests/data/white-1x1.png
}

class ResourceFetcherTest : public ::testing::Test {};

TEST_F(ResourceFetcherTest, StartLoadAfterFrameDetach) {
  KURL secureURL(ParsedURLString, "https://secureorigin.test/image.png");
  // Try to request a url. The request should fail, and a resource in an error
  // state should be returned, and no resource should be present in the cache.
  ResourceFetcher* fetcher = ResourceFetcher::create(nullptr);
  ResourceRequest resourceRequest(secureURL);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Resource* resource = RawResource::fetch(fetchRequest, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->errorOccurred());
  EXPECT_TRUE(resource->resourceError().isAccessCheck());
  EXPECT_FALSE(memoryCache()->resourceForURL(secureURL));

  // Start by calling startLoad() directly, rather than via requestResource().
  // This shouldn't crash.
  fetcher->startLoad(RawResource::create(secureURL, Resource::Raw));
}

TEST_F(ResourceFetcherTest, UseExistingResource) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  URLTestHelpers::registerMockedURLLoadWithCustomResponse(
      url, testImageFilename, WebString::fromUTF8(""),
      WrappedResourceResponse(response));

  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* resource = ImageResource::fetch(fetchRequest, fetcher);
  ASSERT_TRUE(resource);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(resource->isLoaded());
  EXPECT_TRUE(memoryCache()->contains(resource));

  Resource* newResource = ImageResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);
  memoryCache()->remove(resource);
}

TEST_F(ResourceFetcherTest, Vary) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  Resource* resource = RawResource::create(url, Resource::Raw);
  memoryCache()->add(resource);
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::Vary, "*");
  resource->responseReceived(response, nullptr);
  resource->finish();
  ASSERT_TRUE(resource->hasVaryHeader());

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Platform::current()->getURLLoaderMockFactory()->registerURL(
      url, WebURLResponse(), "");
  Resource* newResource = RawResource::fetch(fetchRequest, fetcher);
  EXPECT_NE(resource, newResource);
  newResource->loader()->cancel();
  memoryCache()->remove(newResource);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);

  memoryCache()->remove(resource);
}

TEST_F(ResourceFetcherTest, VaryOnBack) {
  MockFetchContext* context =
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource);
  context->setCachePolicy(CachePolicyHistoryBuffer);
  ResourceFetcher* fetcher = ResourceFetcher::create(context);

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  Resource* resource = RawResource::create(url, Resource::Raw);
  memoryCache()->add(resource);
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::Vary, "*");
  resource->responseReceived(response, nullptr);
  resource->finish();
  ASSERT_TRUE(resource->hasVaryHeader());

  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Resource* newResource = RawResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);

  memoryCache()->remove(newResource);
}

TEST_F(ResourceFetcherTest, VaryImage) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::Vary, "*");
  URLTestHelpers::registerMockedURLLoadWithCustomResponse(
      url, testImageFilename, WebString::fromUTF8(""),
      WrappedResourceResponse(response));

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  Resource* resource = ImageResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  ASSERT_TRUE(resource->hasVaryHeader());

  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = ImageResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);

  memoryCache()->remove(newResource);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}

class RequestSameResourceOnComplete
    : public GarbageCollectedFinalized<RequestSameResourceOnComplete>,
      public RawResourceClient {
  USING_GARBAGE_COLLECTED_MIXIN(RequestSameResourceOnComplete);

 public:
  explicit RequestSameResourceOnComplete(Resource* resource)
      : m_resource(resource), m_notifyFinishedCalled(false) {}

  void notifyFinished(Resource* resource) override {
    EXPECT_EQ(m_resource, resource);
    MockFetchContext* context =
        MockFetchContext::create(MockFetchContext::kShouldLoadNewResource);
    context->setCachePolicy(CachePolicyRevalidate);
    ResourceFetcher* fetcher2 = ResourceFetcher::create(context);
    FetchRequest fetchRequest2(m_resource->url(), FetchInitiatorInfo());
    Resource* resource2 = ImageResource::fetch(fetchRequest2, fetcher2);
    EXPECT_EQ(m_resource, resource2);
    m_notifyFinishedCalled = true;
  }
  bool notifyFinishedCalled() const { return m_notifyFinishedCalled; }

  DEFINE_INLINE_TRACE() {
    visitor->trace(m_resource);
    RawResourceClient::trace(visitor);
  }

  String debugName() const override { return "RequestSameResourceOnComplete"; }

 private:
  Member<Resource> m_resource;
  bool m_notifyFinishedCalled;
};

TEST_F(ResourceFetcherTest, RevalidateWhileFinishingLoading) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(200);
  response.setHTTPHeaderField(HTTPNames::Cache_Control, "max-age=3600");
  response.setHTTPHeaderField(HTTPNames::ETag, "1234567890");
  URLTestHelpers::registerMockedURLLoadWithCustomResponse(
      url, testImageFilename, WebString::fromUTF8(""),
      WrappedResourceResponse(response));
  ResourceFetcher* fetcher1 = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest request1(url);
  request1.setHTTPHeaderField(HTTPNames::Cache_Control, "no-cache");
  FetchRequest fetchRequest1 = FetchRequest(request1, FetchInitiatorInfo());
  Resource* resource1 = ImageResource::fetch(fetchRequest1, fetcher1);
  Persistent<RequestSameResourceOnComplete> client =
      new RequestSameResourceOnComplete(resource1);
  resource1->addClient(client);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(client->notifyFinishedCalled());
  resource1->removeClient(client);
  memoryCache()->remove(resource1);
}

TEST_F(ResourceFetcherTest, DontReuseMediaDataUrl) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest request(KURL(ParsedURLString, "data:text/html,foo"));
  request.setRequestContext(WebURLRequest::RequestContextVideo);
  ResourceLoaderOptions options;
  options.dataBufferingPolicy = DoNotBufferData;
  FetchRequest fetchRequest =
      FetchRequest(request, FetchInitiatorTypeNames::internal, options);
  Resource* resource1 = RawResource::fetchMedia(fetchRequest, fetcher);
  Resource* resource2 = RawResource::fetchMedia(fetchRequest, fetcher);
  EXPECT_NE(resource1, resource2);
  memoryCache()->remove(resource2);
}

class ServeRequestsOnCompleteClient final
    : public GarbageCollectedFinalized<ServeRequestsOnCompleteClient>,
      public RawResourceClient {
  USING_GARBAGE_COLLECTED_MIXIN(ServeRequestsOnCompleteClient);

 public:
  void notifyFinished(Resource*) override {
    Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  }

  // No callbacks should be received except for the notifyFinished() triggered
  // by ResourceLoader::cancel().
  void dataSent(Resource*, unsigned long long, unsigned long long) override {
    ASSERT_TRUE(false);
  }
  void responseReceived(Resource*,
                        const ResourceResponse&,
                        std::unique_ptr<WebDataConsumerHandle>) override {
    ASSERT_TRUE(false);
  }
  void setSerializedCachedMetadata(Resource*, const char*, size_t) override {
    ASSERT_TRUE(false);
  }
  void dataReceived(Resource*, const char*, size_t) override {
    ASSERT_TRUE(false);
  }
  bool redirectReceived(Resource*,
                        const ResourceRequest&,
                        const ResourceResponse&) override {
    ADD_FAILURE();
    return true;
  }
  void dataDownloaded(Resource*, int) override { ASSERT_TRUE(false); }
  void didReceiveResourceTiming(Resource*, const ResourceTimingInfo&) override {
    ASSERT_TRUE(false);
  }

  DEFINE_INLINE_TRACE() { RawResourceClient::trace(visitor); }

  String debugName() const override { return "ServeRequestsOnCompleteClient"; }
};

// Regression test for http://crbug.com/594072.
// This emulates a modal dialog triggering a nested run loop inside
// ResourceLoader::cancel(). If the ResourceLoader doesn't promptly cancel its
// WebURLLoader before notifying its clients, a nested run loop  may send a
// network response, leading to an invalid state transition in ResourceLoader.
TEST_F(ResourceFetcherTest, ResponseOnCancel) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, testImageFilename, "image/png");

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Resource* resource = RawResource::fetch(fetchRequest, fetcher);
  Persistent<ServeRequestsOnCompleteClient> client =
      new ServeRequestsOnCompleteClient();
  resource->addClient(client);
  resource->loader()->cancel();
  resource->removeClient(client);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
}

class ScopedMockRedirectRequester {
  STACK_ALLOCATED();
  WTF_MAKE_NONCOPYABLE(ScopedMockRedirectRequester);

 public:
  ScopedMockRedirectRequester() : m_context(nullptr) {}

  ~ScopedMockRedirectRequester() { cleanUp(); }

  void registerRedirect(const WebString& fromURL, const WebString& toURL) {
    KURL redirectURL(ParsedURLString, fromURL);
    WebURLResponse redirectResponse;
    redirectResponse.setURL(redirectURL);
    redirectResponse.setHTTPStatusCode(301);
    redirectResponse.setHTTPHeaderField(HTTPNames::Location, toURL);
    redirectResponse.setEncodedDataLength(kRedirectResponseOverheadBytes);
    Platform::current()->getURLLoaderMockFactory()->registerURL(
        redirectURL, redirectResponse, "");
  }

  void registerFinalResource(const WebString& url) {
    KURL finalURL(ParsedURLString, url);
    URLTestHelpers::registerMockedURLLoad(finalURL, testImageFilename);
  }

  void request(const WebString& url) {
    DCHECK(!m_context);
    m_context =
        MockFetchContext::create(MockFetchContext::kShouldLoadNewResource);
    ResourceFetcher* fetcher = ResourceFetcher::create(m_context);
    ResourceRequest resourceRequest(url);
    resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
    FetchRequest fetchRequest =
        FetchRequest(resourceRequest, FetchInitiatorInfo());
    RawResource::fetch(fetchRequest, fetcher);
    Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  }

  void cleanUp() {
    Platform::current()->getURLLoaderMockFactory()->unregisterAllURLs();
    memoryCache()->evictResources();
  }

  MockFetchContext* context() const { return m_context; }

 private:
  Member<MockFetchContext> m_context;
};

TEST_F(ResourceFetcherTest, SameOriginRedirect) {
  const char redirectURL[] = "http://127.0.0.1:8000/redirect.html";
  const char finalURL[] = "http://127.0.0.1:8000/final.html";
  ScopedMockRedirectRequester requester;
  requester.registerRedirect(redirectURL, finalURL);
  requester.registerFinalResource(finalURL);
  requester.request(redirectURL);

  EXPECT_EQ(kRedirectResponseOverheadBytes + testImageSize,
            requester.context()->getTransferSize());
}

TEST_F(ResourceFetcherTest, CrossOriginRedirect) {
  const char redirectURL[] = "http://otherorigin.test/redirect.html";
  const char finalURL[] = "http://127.0.0.1:8000/final.html";
  ScopedMockRedirectRequester requester;
  requester.registerRedirect(redirectURL, finalURL);
  requester.registerFinalResource(finalURL);
  requester.request(redirectURL);

  EXPECT_EQ(testImageSize, requester.context()->getTransferSize());
}

TEST_F(ResourceFetcherTest, ComplexCrossOriginRedirect) {
  const char redirectURL1[] = "http://127.0.0.1:8000/redirect1.html";
  const char redirectURL2[] = "http://otherorigin.test/redirect2.html";
  const char redirectURL3[] = "http://127.0.0.1:8000/redirect3.html";
  const char finalURL[] = "http://127.0.0.1:8000/final.html";
  ScopedMockRedirectRequester requester;
  requester.registerRedirect(redirectURL1, redirectURL2);
  requester.registerRedirect(redirectURL2, redirectURL3);
  requester.registerRedirect(redirectURL3, finalURL);
  requester.registerFinalResource(finalURL);
  requester.request(redirectURL1);

  EXPECT_EQ(testImageSize, requester.context()->getTransferSize());
}

TEST_F(ResourceFetcherTest, SynchronousRequest) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, testImageFilename, "image/png");

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest(resourceRequest, FetchInitiatorInfo());
  fetchRequest.makeSynchronous();
  Resource* resource = RawResource::fetch(fetchRequest, fetcher);
  EXPECT_TRUE(resource->isLoaded());
  EXPECT_EQ(ResourceLoadPriorityHighest,
            resource->resourceRequest().priority());

  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  memoryCache()->remove(resource);
}

TEST_F(ResourceFetcherTest, PreloadImageTwice) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, testImageFilename, "image/png");

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  Resource* resource = ImageResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher->preloadStarted(resource);

  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = ImageResource::fetch(fetchRequest, fetcher);
  EXPECT_EQ(resource, newResource);
  fetcher->preloadStarted(resource);

  fetcher->clearPreloads(ResourceFetcher::ClearAllPreloads);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_FALSE(memoryCache()->contains(resource));
  EXPECT_FALSE(resource->isPreloaded());
}

TEST_F(ResourceFetcherTest, LinkPreloadImageAndUse) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, testImageFilename, "image/png");

  // Link preload preload scanner
  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestOriginal.setLinkPreload(true);
  Resource* resource = ImageResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->isLinkPreload());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher->preloadStarted(resource);

  // Image preload scanner
  FetchRequest fetchRequestPreloadScanner =
      FetchRequest(url, FetchInitiatorInfo());
  Resource* imgPreloadScannerResource =
      ImageResource::fetch(fetchRequestPreloadScanner, fetcher);
  EXPECT_EQ(resource, imgPreloadScannerResource);
  EXPECT_FALSE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Image created by parser
  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = ImageResource::fetch(fetchRequest, fetcher);
  Persistent<MockResourceClient> client = new MockResourceClient(newResource);
  EXPECT_EQ(resource, newResource);
  EXPECT_FALSE(resource->isLinkPreload());

  // DCL reached
  fetcher->clearPreloads(ResourceFetcher::ClearSpeculativeMarkupPreloads);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(memoryCache()->contains(resource));
  EXPECT_FALSE(resource->isPreloaded());
}

TEST_F(ResourceFetcherTest, LinkPreloadImageMultipleFetchersAndUse) {
  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceFetcher* fetcher2 = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));

  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.png");
  URLTestHelpers::registerMockedURLLoad(url, testImageFilename, "image/png");

  FetchRequest fetchRequestOriginal = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestOriginal.setLinkPreload(true);
  Resource* resource = ImageResource::fetch(fetchRequestOriginal, fetcher);
  ASSERT_TRUE(resource);
  EXPECT_TRUE(resource->isLinkPreload());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher->preloadStarted(resource);

  FetchRequest fetchRequestSecond = FetchRequest(url, FetchInitiatorInfo());
  fetchRequestSecond.setLinkPreload(true);
  Resource* secondResource = ImageResource::fetch(fetchRequestSecond, fetcher2);
  ASSERT_TRUE(secondResource);
  EXPECT_TRUE(secondResource->isLinkPreload());
  Platform::current()->getURLLoaderMockFactory()->serveAsynchronousRequests();
  fetcher2->preloadStarted(secondResource);

  // Link rel preload scanner
  FetchRequest fetchRequestLinkPreloadScanner =
      FetchRequest(url, FetchInitiatorInfo());
  fetchRequestLinkPreloadScanner.setLinkPreload(true);
  Resource* linkPreloadScannerResource =
      ImageResource::fetch(fetchRequestLinkPreloadScanner, fetcher);
  EXPECT_EQ(resource, linkPreloadScannerResource);
  EXPECT_TRUE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Image preload scanner
  FetchRequest fetchRequestPreloadScanner =
      FetchRequest(url, FetchInitiatorInfo());
  Resource* imgPreloadScannerResource =
      ImageResource::fetch(fetchRequestPreloadScanner, fetcher);
  EXPECT_EQ(resource, imgPreloadScannerResource);
  EXPECT_FALSE(resource->isLinkPreload());
  fetcher->preloadStarted(resource);

  // Image preload scanner on the second fetcher
  FetchRequest fetchRequestPreloadScanner2 =
      FetchRequest(url, FetchInitiatorInfo());
  Resource* imgPreloadScannerResource2 =
      ImageResource::fetch(fetchRequestPreloadScanner2, fetcher2);
  EXPECT_EQ(resource, imgPreloadScannerResource2);
  EXPECT_FALSE(resource->isLinkPreload());
  fetcher2->preloadStarted(resource);

  // Image created by parser
  FetchRequest fetchRequest = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource = ImageResource::fetch(fetchRequest, fetcher);
  Persistent<MockResourceClient> client = new MockResourceClient(newResource);
  EXPECT_EQ(resource, newResource);
  EXPECT_FALSE(resource->isLinkPreload());

  // Image created by parser on the second fetcher
  FetchRequest fetchRequest2 = FetchRequest(url, FetchInitiatorInfo());
  Resource* newResource2 = ImageResource::fetch(fetchRequest, fetcher2);
  Persistent<MockResourceClient> client2 = new MockResourceClient(newResource2);
  EXPECT_EQ(resource, newResource2);
  EXPECT_FALSE(resource->isLinkPreload());
  // DCL reached on first fetcher
  EXPECT_TRUE(resource->isPreloaded());
  fetcher->clearPreloads(ResourceFetcher::ClearSpeculativeMarkupPreloads);
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);
  EXPECT_TRUE(memoryCache()->contains(resource));
  EXPECT_TRUE(resource->isPreloaded());

  // DCL reached on second fetcher
  fetcher2->clearPreloads(ResourceFetcher::ClearSpeculativeMarkupPreloads);
  EXPECT_TRUE(memoryCache()->contains(resource));
  EXPECT_FALSE(resource->isPreloaded());
}

TEST_F(ResourceFetcherTest, Revalidate304) {
  KURL url(ParsedURLString, "http://127.0.0.1:8000/foo.html");
  Resource* resource = RawResource::create(url, Resource::Raw);
  memoryCache()->add(resource);
  ResourceResponse response;
  response.setURL(url);
  response.setHTTPStatusCode(304);
  response.setHTTPHeaderField("etag", "1234567890");
  resource->responseReceived(response, nullptr);
  resource->finish();

  ResourceFetcher* fetcher = ResourceFetcher::create(
      MockFetchContext::create(MockFetchContext::kShouldLoadNewResource));
  ResourceRequest resourceRequest(url);
  resourceRequest.setRequestContext(WebURLRequest::RequestContextInternal);
  FetchRequest fetchRequest =
      FetchRequest(resourceRequest, FetchInitiatorInfo());
  Platform::current()->getURLLoaderMockFactory()->registerURL(
      url, WebURLResponse(), "");
  Resource* newResource = RawResource::fetch(fetchRequest, fetcher);
  fetcher->stopFetching();
  Platform::current()->getURLLoaderMockFactory()->unregisterURL(url);

  EXPECT_NE(resource, newResource);
}

}  // namespace blink


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="UserMapper">

	<resultMap id="UserResult" type="User">
		<result property="id" column="id" />
		<result property="nickname" column="nickname" />
		<result property="pic" column="pic"/>
		<result property="content" column="content"/>
	</resultMap>

	<sql id="user_columns">
		user_user.id,
		user_user.nickname,
		user_user.pic,
		user_user.content
	</sql>

	<sql id="user_properties">
		#{id},
		#{nickname},
		#{pic},
		#{content}
	</sql>

	<!-- 添加user -->
	<insert id="createUser" parameterType="User" keyColumn="id"
		keyProperty="id" useGeneratedKeys="true">
		insert into user_user (<include refid="user_columns" />)
		values (<include refid="user_properties" />)
	</insert>

	<!-- 删除user -->
	<delete id="deleteUserById" parameterType="String">
		delete from user_user
		where
		id in(${value})
	</delete>

	<!-- 修改user -->
	<update id="updateUser" parameterType="User">
		update
		user_user SET
		nickname = #{nickname},
		pic=#{pic},
		content=#{content}
		where
		id =#{id}
	</update>

	<!-- 根据id查询user -->
	<select id="getUserById" resultMap="UserResult" parameterType="Long">
		select
		<include refid="user_columns" />
		from user_user
		where
		id = #{value}
	</select>

	<!-- 根据条件查询用户列表 -->
	<select id="getUserList" parameterType="QueryUser" resultMap="UserResult">
		select <include refid="user_columns"/>
		from user_user
		where 1=1
		<if test="nickname!=null and nickname!=''">
			and nickname like concat('%',#{nickname},'%')
		</if>
		order by id desc
	</select>

	<!-- 根据条件查询用户列表 -->
	<select id="getUserListByIds" parameterType="String" resultMap="UserResult">
		select <include refid="user_columns"/>
		from user_user
		where id in (${value})
	</select>

	<!-- 分页查询用户 -->
	<select id="queryUserPage" parameterType="java.util.Map" resultMap="UserResult">
		select <include refid="user_columns"/>
		from user_user
		where 1=1
		<if test="e.nickname!=null and e.nickname!=''">
			and nickname like concat('%',#{e.nickname},'%')
		</if>
		order by id desc
		<include refid="publicMapper.pageEnd"/>
	</select>
	<select id="queryUserPageCount" parameterType="java.util.Map" resultType="int">
		select count(1)
		from user_user
		where 1=1
		<if test="e.nickname!=null and e.nickname!=''">
			and nickname like concat('%',#{e.nickname},'%')
		</if>
	</select>
</mapper>

redpajama_set_name: RedPajamaGithub


text:
<ion-header>
  <ion-navbar>
    <ion-title>Über Uns</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  Wir sind Ihr Lieferdienst, wenn es um PIZZA* geht! Dafür stehen wir mit unserem Namen.
</ion-content>

<ion-footer>
  <ion-toolbar>
    <small>*ohne Ananas!</small>
  </ion-toolbar>
</ion-footer>


text:
Geocoder maps address to a point

Uses callback approach

<tt>GClientGeocoder.getLatLng</tt>

<tt>GLatLng</tt> point if successfull

<tt>null</tt> if could not resolve the address

<tt>GClientGeocoder.getLocations</tt>

<tt>Status.code</tt> holds request status

Multiple locations in <tt>Placemark</tt>

Formatted address in xAL

Geocoder dont's

Don't create multiple geocoders

Don't repeatedly geocode same address


text:
package se.devscout.scoutapi.dao;

import com.google.common.collect.Lists;
import io.dropwizard.hibernate.AbstractDAO;
import org.hibernate.SessionFactory;
import se.devscout.scoutapi.model.IdentityType;
import se.devscout.scoutapi.model.User;

import java.util.HashSet;
import java.util.List;

public class UserDao extends AbstractDAO<User> {
    public UserDao(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    public List<User> all() {
        return Lists.newArrayList(new HashSet<>(list(namedQuery("User.all"))));
    }

    public List<User> byName(String name) {
        return list(namedQuery("User.byName").setText("name", "%" + name + "%"));
    }

    public User readUser(long id) {
        return get(id);
    }

    public User readUserByIdentity(IdentityType type, String value) {
        List list = namedQuery("User.byIdentity").setParameter("type", type).setString("value", value).list();
        if (!list.isEmpty()) {
            User user = (User) list.get(0);
            return user;
        } else {
            return null;
        }
    }

    public User create(User user) {
        return persist(user);
    }

    public User update(User user) {
        return persist(user);
    }

    public void delete(User user) {
        currentSession().delete(user);
    }

}


text:
A small app that analyses color data from a library of images shared between my and my girlfriend who lives abroad.

[Demo](https://juniorxsound.github.io/ICM-Fall-2016/5_Tones_of_Emotion/)

![Screenshot](https://github.com/juniorxsound/ICM-Fall-2016/blob/master/5_Tones_of_Emotion/assets/header.gif "5 Tones of Emotion")

Libraries used:

1. [p5.js](https://github.com/processing/p5.js) - a JS client-side library for creating graphic and interactive experiences
2. [jQuery](https://github.com/jquery/jquery)
3. [Vibrant.js](https://github.com/jariz/vibrant.js) - Extract prominent colors from an image. JS port of Android's Palette.

> Built as a part of ICM class @ ITP, NYU lectured by Daniel Shiffman.

Written by Or Fleisher.


text:
alter table project_versions add column approved_at timestamp;

# --- !Downs

alter table project_versions drop column approved_at;


text: knowledgecommissionreport works!


text:
CVE-2021-29530

### Impact
An attacker can trigger a null pointer dereference by providing an invalid
`permutation` to `tf.raw_ops.SparseMatrixSparseCholesky`:

```python
import tensorflow as tf
import numpy as np
from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops

indices_array = np.array([[0, 0]])
value_array = np.array([-10.0], dtype=np.float32)
dense_shape = [1, 1]
st = tf.SparseTensor(indices_array, value_array, dense_shape)

input = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
       st.indices, st.values, st.dense_shape)

permutation = tf.constant([], shape=[1, 0], dtype=tf.int32)

tf.raw_ops.SparseMatrixSparseCholesky(input=input, permutation=permutation, type=tf.float32)
```

This is because the
[implementation](https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/kernels/sparse/sparse_cholesky_op.cc#L85-L86) fails to properly validate the input arguments:

```cc
void Compute(OpKernelContext* ctx) final {
  ...
  const Tensor& input_permutation_indices = ctx->input(1);
  ...
  ValidateInputs(ctx, *input_matrix, input_permutation_indices, &batch_size, &num_rows);
  ...
}

void ValidateInputs(OpKernelContext* ctx,
    const CSRSparseMatrix& sparse_matrix,
    const Tensor& permutation_indices, int* batch_size,
    int64* num_rows) {
  OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum<T>::value, ...)
  ...
}
```

Although `ValidateInputs` is called and there are checks in the body of this
function, the code proceeds to the next line in `ValidateInputs` since
[`OP_REQUIRES`](https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/framework/op_requires.h#L41-L48)
is a macro that only exits the current function.

```cc
#define OP_REQUIRES(CTX, EXP, STATUS)                     \
  do {                                                    \
    if (!TF_PREDICT_TRUE(EXP)) {                          \
      CheckNotInComputeAsync((CTX), "OP_REQUIRES_ASYNC"); \
      (CTX)->CtxFailure(__FILE__, __LINE__, (STATUS));    \
      return;                                             \
    }                                                     \
  } while (0)
```

Thus, the first validation condition that fails in `ValidateInputs` will cause
an early return from that function. However, the caller will continue execution
from the next line. The fix is to either explicitly check `context->status()`
or to convert `ValidateInputs` to return a `Status`.

### Patches
We have patched the issue in GitHub commit
[e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd](https://github.com/tensorflow/tensorflow/commit/e6a7c7cc18c3aaad1ae0872cb0a959f5c923d2bd).

The fix will be included in TensorFlow 2.5.0. We will also cherrypick this
commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow
2.1.4, as these are also affected and still in supported range.

### For more information
Please consult [our security
guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for
more information regarding the security model and how to contact us with issues
and questions.

### Attribution
This vulnerability has been reported by Ying Wang and Yakun Zhang of Baidu X-Team.


text:
#ifndef __NaryImageOperatorMainHelper_h_
#define __NaryImageOperatorMainHelper_h_

#include <map>
#include <utility> // for pair
#include <string>
#include <itksys/SystemTools.hxx>
#include "ITKToolsImageProperties.h"
#include "ITKToolsHelpers.h"

/**
 * ******************* DetermineImageProperties *******************
 */

int DetermineImageProperties(
  const std::vector<std::string> & inputFileNames,
  itk::ImageIOBase::IOComponentType & componentTypeIn,
  itk::ImageIOBase::IOComponentType & componentTypeOut,
  unsigned int & inputDimension )
{
  /** Determine image properties of image 0. */
  itk::ImageIOBase::IOPixelType inputPixelType0;
  unsigned int inputDimension0 = 2;
  unsigned int numberOfComponents0 = 1;
  std::vector<unsigned int> imagesize0( inputDimension0, 0 );
  bool retgip0 = itktools::GetImageProperties(
    inputFileNames[ 0 ],
    inputPixelType0,
    componentTypeIn,
    inputDimension0,
    numberOfComponents0,
    imagesize0 );
  /** If false, it means there was an error. Return 1.
   * \todo: the various GetImageProperties functions in ITKToolsImageProperties
   * return either bool or int, which is very confusing. Harmonize.
   */
  if( !retgip0 ) return 1;

  /** Determine image properties of other images. */
  itk::ImageIOBase::IOPixelType inputPixelType_i;
  itk::ImageIOBase::IOComponentType componentTypeIn_i = componentTypeIn;
  unsigned int inputDimension_i = 2;
  unsigned int numberOfComponents_i = 1;
  std::vector<unsigned int> imagesize_i;
  for( unsigned int i = 1; i < inputFileNames.size(); i++ )
  {
    bool retgip_i = itktools::GetImageProperties(
      inputFileNames[ i ],
      inputPixelType_i,
      componentTypeIn_i,
      inputDimension_i,
      numberOfComponents_i,
      imagesize_i );
	/** If false, it means there was an error. Return 1. */
    if( !retgip_i ) return 1;

    /** Check the input. */
    if( inputPixelType0 != inputPixelType_i )
    {
      std::cerr << "ERROR: the input images are not of equal pixel type (SCALAR, VECTOR, etc)." << std::endl;
      return EXIT_FAILURE;
    }

    if( numberOfComponents0 != numberOfComponents_i )
    {
      std::cerr << "ERROR: the input images have a different number of components." << std::endl;
      return EXIT_FAILURE;
    }

    if( inputDimension0 != inputDimension_i )
    {
      std::cerr << "ERROR: the input images are of different dimension." << std::endl;
      return EXIT_FAILURE;
    }
    else
    {
      inputDimension = inputDimension0;
    }

    if( imagesize0 != imagesize_i )
    {
      std::cerr << "ERROR: the input images have different sizes." << std::endl;
      return EXIT_FAILURE;
    }

    /** The output type is the largest of the input types. */
    componentTypeOut = itktools::GetLargestComponentType( componentTypeOut, componentTypeIn_i );
  }

  /** The input type is set to long or double, depending on the output type. */
  bool outIsInteger = itktools::ComponentTypeIsInteger( componentTypeOut );
  if( outIsInteger )
  {
    componentTypeIn = itk::ImageIOBase::LONG;
  }
  else
  {
    componentTypeIn = itk::ImageIOBase::DOUBLE;
  }

  /** Return a value indicating success. */
  return 0;

} // end DetermineImageProperties()

/**
 * ******************* CheckOperator *******************
 */

int CheckOperator( std::string & operatoR )
{
  if( operatoR == "ADDITION" || operatoR == "ADD" || operatoR == "PLUS" )
  {
    operatoR = "ADDITION";
    return 0;
  }
  else if( operatoR == "MEAN" || operatoR == "AVERAGE" )
  {
    operatoR = "MEAN";
    return 0;
  }
  else if( operatoR == "WEIGHTEDADDITION" || operatoR == "WEIGHTEDADD"
    || operatoR == "WEIGHTEDPLUS" )
  {
    operatoR = "WEIGHTEDADDITION";
    return 0;
  }
  else if( operatoR == "MINUS" || operatoR == "DIFF" )
  {
    operatoR = "MINUS";
    return 0;
  }
  else if( operatoR == "TIMES" || operatoR == "MULTIPLY" )
  {
    operatoR = "TIMES";
    return 0;
  }
  else if( operatoR == "DIVIDE" )
  {
    return 0;
  }
  else if( operatoR == "POWER" )
  {
    return 0;
  }
  else if( operatoR == "MAXIMUM" || operatoR == "MAX" )
  {
    operatoR = "MAXIMUM";
    return 0;
  }
  else if( operatoR == "MINIMUM" || operatoR == "MIN" )
  {
    operatoR = "MINIMUM";
    return 0;
  }
  else if( operatoR == "ABSOLUTEDIFFERENCE" || operatoR == "ABSDIFFERENCE"
    || operatoR == "ABSOLUTEDIFF" || operatoR == "ABSDIFF"
    || operatoR == "ABSOLUTEMINUS" || operatoR == "ABSMINUS" )
  {
    operatoR = "ABSOLUTEDIFFERENCE";
    return 0;
  }
  else if( operatoR == "SQUAREDDIFFERENCE" || operatoR == "SQUAREDDIFF"
    || operatoR == "SQUAREDMINUS" )
  {
    operatoR = "SQUAREDDIFFERENCE";
    return 0;
  }
  else if( operatoR == "BINARYMAGNITUDE" || operatoR == "BINARYMAG"
    || operatoR == "BINMAGNITUDE" || operatoR == "BINMAG"
    || operatoR == "MAGNITUDE" || operatoR == "MAG" )
  {
    operatoR = "BINARYMAGNITUDE";
    return 0;
  }
  else if( operatoR == "MASK" )
  {
    operatoR = "MASK";
    return 0;
  }
  else if( operatoR == "MASKNEGATED" || operatoR == "MASKNEG" )
  {
    operatoR = "MASKNEGATED";
    return 0;
  }
  else if( operatoR == "MODULO" || operatoR == "MOD" )
  {
    operatoR = "MODULO";
    return 0;
  }
  else if( operatoR == "LOG" || operatoR == "LOGN" )
  {
    operatoR = "LOG";
    return 0;
  }
  else
  {
    std::cerr << "ERROR: No operator \"" << operatoR << "\" defined!" << std::endl;
    return 1;
  }

  /** Return a value. */
  return 0;

} // end CheckOperator()

  /**
   * ******************* OperatorNeedsArgument *******************
   */

bool OperatorNeedsArgument( const std::string & operatoR )
{
  /** A map to store if OperatorNeedsArgument. */
  std::map< std::string, bool > operatorMap;

  /** Fill the map. */
  operatorMap["ADDITION"]           = false;
  operatorMap["MEAN"]               = false;
  operatorMap["WEIGHTEDADDITION"]   = true;
  operatorMap["MINUS"]              = false;
  operatorMap["TIMES"]              = false;
  operatorMap["DIVIDE"]             = false;
  operatorMap["POWER"]              = false;
  operatorMap["MAXIMUM"]            = false;
  operatorMap["MINIMUM"]            = false;
  operatorMap["ABSOLUTEDIFFERENCE"] = false;
  operatorMap["SQUAREDDIFFERENCE"]  = false;
  operatorMap["BINARYMAGNITUDE"]    = false;
  operatorMap["MASK"]               = true;
  operatorMap["MASKNEGATED"]        = true;
  operatorMap["MODULO"]             = false;
  operatorMap["LOG"]                = false;

  /** Return true or false. */
  if( operatorMap.count( operatoR ) ) return operatorMap[ operatoR ];
  return false;

} // end OperatorNeedsArgument()

/**
 * ******************* CheckOperatorAndArgument *******************
 */

bool CheckOperatorAndArgument(
  const std::string & operatoR,
  const std::string & argument,
  const bool & retarg )
{
  bool operatorNeedsArgument = OperatorNeedsArgument( operatoR );
  double arg = atof( argument.c_str() );

  /** If no argument is needed. */
  if( !operatorNeedsArgument && retarg )
  {
    std::cerr << "WARNING: operator " << operatoR << " does not need an argument." << std::endl;
    std::cerr << "The argument (" << argument << ") is ignored." << std::endl;
    return true;
  }

  /** If an argument is needed, but not provided. */
  if( operatorNeedsArgument && !retarg )
  {
    std::cerr << "ERROR: operator " << operatoR << " needs an argument." << std::endl;
    std::cerr << "Specify the argument with \"-arg\"." << std::endl;
    return false;
  }

  /** If an argument is needed and provided. */
  if( operatorNeedsArgument )
  {
    if( operatoR == "WEIGHTEDADDITION" )
    {
      if( arg < 0.0 || arg > 1.0 )
      {
        std::cerr << "ERROR: the weight should be between 0.0 and 1.0." << std::endl;
        return false;
      }
    }
  }

  return true;

} // end CheckOperatorAndArgument()

#endif //#ifndef __NaryImageOperatorMainHelper_h_


text:
module Avsh
  # Encapsulates parsed config details from VagrantfileEnvironment
  class ParsedConfig
    attr_reader :primary_machine

    # @param vagrantfile_dir [String] The directory containing the Vagrantfile
    # (used for synced folder path expansion with relative directories).
    # @param global_synced_folders [Hash] The globally-defined synced folders,
    #   with keys being the guest directory (destination) and values being the
    #   host directory (source).
    # @param machine_synced_folders [Hash] Hash of machine names to a hash of
    #   synced folders defined in that machine definition (potentially empty)
    # @param primary_machine [String] The name of the primary machine, if one
    #   was defined
    def initialize(vagrantfile_dir, global_synced_folders,
                   machine_synced_folders, primary_machine)
      @vagrantfile_dir = vagrantfile_dir
      @global_synced_folders = global_synced_folders.freeze
      @machine_synced_folders = machine_synced_folders.freeze
      @primary_machine = primary_machine
    end

    # Returns the machines that match the given search string, raising an
    # exception if no matches are found.
    # Partially based off https://github.com/mitchellh/vagrant/blob/85f1e05e2a9bf7a7940bb4498472b809ba43e01f/lib/vagrant/plugin/v2/command.rb#L183
    def match_machines!(search_string)
      machines =
        if (pattern = search_string[%r{^/(.+?)/$}, 1])
          match_machines_by_regexp(pattern)
        elsif search_string.include? ','
          # Recursively call this function to match all machines in the list,
          # raising an exception if any could not be found
          search_string.split(',')
                       .map! { |s| match_machines!(s.strip) }
                       .flatten
        elsif @machine_synced_folders.key?(search_string)
          [search_string]
        end
      unless machines && !machines.empty?
        raise MachineNotFoundError.new(search_string, @vagrantfile_dir)
      end
      machines
    end

    def first_machine
      first = @machine_synced_folders.first
      first ? first[0] : 'default'
    end

    def collect_folders_by_machine
      if @machine_synced_folders.empty?
        { 'default' => default_synced_folders }
      else
        folders = @machine_synced_folders.map do |name, synced_folders|
          [name, merge_with_defaults(synced_folders)]
        end

        # Sort the primary machine to the top, since it should be matched first
        if @primary_machine
          folders.sort_by! { |f| f[0] == @primary_machine ? 0 : 1 }
        end

        Hash[folders]
      end
    end

    private

    def match_machines_by_regexp(pattern)
      begin
        regex = Regexp.new(pattern)
      rescue RegexpError => e
        raise MachineRegexpError, e
      end
      @machine_synced_folders.keys.select { |name| name =~ regex }
    end

    def default_synced_folders
      defaults = @global_synced_folders
                 .reject { |_, opts| opts[:disabled] }
                 .map { |guest_path, opts| [guest_path, opts[:host_path]] }
      add_vagrant_default(Hash[defaults])
    end

    def add_vagrant_default(synced_folders)
      # Add default /vagrant share (see https://github.com/mitchellh/vagrant/blob/v1.8.4/plugins/kernel_v2/config/vm.rb#L511)
      if !synced_folders.key?('/vagrant') &&
         !synced_folders.value?(@vagrantfile_dir)
        synced_folders['/vagrant'] = @vagrantfile_dir
      end
      synced_folders
    end

    def merge_with_defaults(synced_folders)
      default_synced_folders.tap do |merged|
        synced_folders.each do |guest_path, opts|
          if opts[:disabled]
            merged.delete(guest_path)
            next
          end
          merged.delete('/vagrant') if opts[:host_path] == @vagrantfile_dir
          merged[guest_path] = opts[:host_path]
        end
      end
    end
  end
end


text:
---
layout: post
title: Introducing Package Script Manager
categories: node
---

[https://github.com/corysimmons/package-script-manager](https://github.com/corysimmons/package-script-manager)

I had been using npm scripts for a lot of little things, but never really saw it as a build tool until I read [Keith Cirkel's article](https://www.keithcirkel.co.uk/how-to-use-npm-as-a-build-tool/) on it.

There are some huge underlying points to that approach that never got the attention they deserved:

1. This isn't about npm or Make or XYZ. It's about CLIs. CLIs are simply the most portable interface for a library. You can *easily* wrap CLIs for use with _any_ task runner. You can even use CLIs without any sort of task runner.
2. You can run npm tasks in a particular order, and/or in parallel with [npm-run-all](https://www.npmjs.com/package/npm-run-all).
3. You can watch any glob pattern for a variety of events using [Chokidar CLI](https://github.com/kimmobrunfeldt/chokidar-cli). It also makes a few bash variables available `{event}` and `{path}`. You can use bash functions with that event, and operate on that path using tools like [cut](https://linux.die.net/man/1/cut).

Those last two points were very common/invalid complaints about using npm scripts, but there are still a lot of valid complaints revolving around the use of JSON.

> Let me make this perfectly clear for any aspiring library authors: **STOP USING THINGS LIKE YAML AND JSON FOR CONFIG!** The only reason static content should ever exist is when working with databases or state. Otherwise, assume your userbase isn't full of toddlers and give them a power tool to explore interesting ways to config their projects.

Since npm scripts are tied up in JSON, there are lots of things you can't do with them: comments, variables, etc. In fact, Keith's article's comment section is literally full of reasons why JSON configs suck.

So I made a thing that will import all the key/val pairs from a JS object to package.json `"scripts"`. It does this destructively (any scripts you currently have in package.json will be overwritten) to force a single source of truth for your scripts.

Enter [Package Script Manager](https://github.com/corysimmons/package-script-manager). It's a very simple CLI that destructively migrates a JS object from one file to `package.json`'s `"scripts"` object.

It works like this:

`npm i -D package-script-manager`

```js
// psm.js
const planet = 'Earth'

module.exports = {
  // This task should just echo 'Hello Earth!' to the terminal
  "start": `echo 'Hello ${planet}!'`
}
```

> ❗ Next part is destructive and will discard whatever scripts you have in package.json. Make sure you migrate your package.json scripts to psm.js, and/or back them up somewhere until you're comfortable with this workflow.

`$ node_modules/.bin/psm` (need to run this from `node_modules/.bin` once to config some new tasks for it)

```js
// package.json
{
  "scripts": {
    "start": "echo 'Hello Earth!'",
    "psm": "psm psm.js package.json",
    "psm:watch": "chokidar psm.js -c 'npm run psm'"
  }
}
```

Now you can use it with `npm run psm` (or `psm:watch`).

Between `npm-run-all`, `chokidar-cli`, and `package-script-manager`, you have all the power of any task runner out there, but the most important part is, now you are supporting CLI development as opposed to Gulp plugin development. Again, one of those things is insanely portable, and the other is specific to a single task runner. And if you're going to write some sort of function for a build task, would you rather do it in a task runner's plugin API, or just in plain Node?

Stop reading here if you like Webpack.

Where do tools like Webpack fit into this? They perform a separate function than task running. They mostly focus on something called "bundling". In very plain/overly-simple terms, bundling just concatenates files (this triggers the React developer), and Webpack isn't particularly good at it when compared to a forward-thinking bundler like Rollup.

Webpack is bad for the internet because it contributes to the JS-everything mindset -- going as far as to import/insert CSS and imagery through JS (people without JS get absolutely nothing) in the name of HTTP request reduction. The minimize requests thing is now an anti-pattern carryover from HTTP1, but I'm already escaping the scope of this post so I'll cover that more in a future post.

I'd suggest dumping Webpack for Rollup; just using it to eliminate useless code (unless you also need Node in the browser); and throwing that task into your npm scripts along with every other optimization task.

This approach, combined with comments, keeps a very clear separation of concerns. And with those few tools mentioned above, you can easily slap together a very easy-to-reason-about/powerful/extensible/portable task config.

```js
// psm.js

// Easily alter your project structure
const distDir = 'dist'
const jsDist = `${distDir}/js`
const bundleName = 'bundle'

module.exports = {
  // Compresses imagery once on startup, then runs other optimizations and the development server in parallel.
  // https://github.com/mysticatea/npm-run-all
  "start": `npm-run-all imagemin -p rollup chokidar:uglify brower-sync`,

  // Losslessly compress imagery https://github.com/imagemin/imagemin-cli
  // We could watch this with Chokidar, but I wanted to demonstrate you can perform tasks sequentially, as well as in parallel, very easily.
  "imagemin": `imagemin src/img/**/* --out-dir=${distDir}`,

  // Tree-shake JS https://medium.com/@Rich_Harris/tree-shaking-versus-dead-code-elimination-d3765df85c80
  // It will default to use the config in rollup.config.js (see? some people know JSON configs suck)
  "rollup": `rollup -c --watch -o ${jsDist}/${bundleName}.js`,

  // Uglify/minify JS https://github.com/mishoo/UglifyJS
  "uglify": `uglifyjs ${jsDist}/${bundleName}.js -o ${jsDist}/${bundleName}.js`,

  // Let's use Chokidar and run uglify everytime our JS bundle changes https://github.com/kimmobrunfeldt/chokidar-cli
  "chokidar:uglify": `chokidar ${jsDist}/${bundleName}.js -c 'npm run uglifyjs'`,

  // Fire up a really powerful dev server https://www.browsersync.io/docs/command-line
  // Trigger more React devs: I hear Webpack's HMR is overrated from people who write books about Webpack.
  "browser-sync": `browser-sync start --server --no-open --no-notify --files=${distDir}/**/*`
}
```

This is untested pseudocode, but I'm pretty sure the biggest hiccup would be a typo or something.

Think about that for a second. I'm compressing all types of imagery; tree-shaking my JS; watching tree-shook code and uglifying it on change; and spinning up a dev server; with 6 lines of very readable, documented, code.

Gulp & Co. are dead. Long live CLIs.


text:
#include <QObject>
#include "defs.h"

// "одноразовый" переходник
// призван спасти код от циклической зависимости
// передает карте параметры
class StatsTransmitter : public QObject
{
		Q_OBJECT
	public:
		explicit StatsTransmitter(QObject *parent = 0);
	signals:
		void sendStat(QString statName, int statVal, bool isInc);
	public slots:
		void setStat(QString statName, int statVal, bool isInc);

};

// передатчик сообщений
// полезен для сбора "логов"
class InfoTransmitter : public QObject
{
		Q_OBJECT
	public:
		explicit InfoTransmitter(QObject *parent = 0);
	signals:
		void sendMsg(QString msg);
	public slots:
		void receiveMsg(QString msg);
};

#endif // STATSTRANSMITTER_H


text:
Do you have a huge graph and wonder how you could uncover its secrets?

![](Screenshots/Overview.2.png)
![](Screenshots/Galaxy.2.png)

Plainion.GraphViz is the solution you are looking for ;-)

# Getting Started

- Download the [latest release](https://github.com/plainionist/Plainion.GraphViz/releases)
- Unpack the ZIP at any convenient placeplace
- Start the Plainion.GraphViz.Viewer.exe
- Load your graph with the "Open" button or just drop it on the canvas.
  Supported formats:
  - DOT
  - GraphML
  - DGML

# What next?

- Read [Basics](Basics)
- Read [Filters](Filters)
- Take one of the sample graphs and play around with it
- Browse through the remaining documentation
- Provide feedback ;-)

# Contribution

You have ideas to improve Plainion.GraphViz? You are welcome to contribute!

Plainion.GraphViz is hosted on [GitHub](https://github.com/plainionist/Plainion.GraphViz).
Just clone the repository, [setup your environment](Development) and get your fingers dirty ;-)
Send me a pull request when you are done!


text:
AndThen
=======

Lua Promises library inspired by the brilliant [Q](http://github.com/kriskowal/q).

Offers a lot of the same functionality, all you have to do is to supply a function that executes another function after a given amount of milliseconds, which can be zero. Something akin to setTimeout.

You can construct a new Promise using:

    Promise(<some value>)

Where < some value > will be the result of the promise. If < some value > is a function, it will be called during construction of the promise with a handler that has resolve and reject methods.

After that, you can chain functions to the promise:

    :and_then(resolved callback, rejected callback)

    :catch(rejected callback)

    :fail(rejected callback)

    :finally(snapshot callback)

    :done()

    :print()

    :delay(ms)

    :timeout(ms, optional rejection value)

    :then_resolve(value)

    :then_reject(value)

    :all()

    :all_settled()

If you want to understand Promises, take a look at [Q's documentation](http://documentup.com/kriskowal/q/)


text:
package nc.isi.slq2o_dao.db;

import java.util.Map;

public class EntityToTableConverterProviderImpl implements
		EntityToTableConverterProvider {
	private final Map<String, EntityToTableConverter> keyToEntityToTableConverter;

	public EntityToTableConverterProviderImpl(
			Map<String, EntityToTableConverter> keyToEntityToTableConverter) {
		this.keyToEntityToTableConverter = keyToEntityToTableConverter;
	}

	@Override
	public EntityToTableConverter provide(String key) {
		return keyToEntityToTableConverter.get(key);
	}

}


text:
namespace chrono {
namespace fea {

/// @addtogroup chrono_fea
/// @{

/// Class for applying loads to a contact mesh as a cluster of forces
/// operating on the nodes of the underlying finite elements.
/// It is useful for doing cosimulation: one can pass this object's vertex & faces
/// to an external software (ex. CFD) that in turn will perform collision detection
/// with its entities, compute forces, send forces back to Chrono via this object.
/// Note, this is based on a cluster of  std::vector< std::shared_ptr<ChLoadXYZnode> >, but
/// the class itself could bypass all methods of ChLoadXYZnode and directly implement
/// a more efficient LoadIntLoadResidual_F, however this is left in this way for didactical reasons.

class ChApi ChLoadContactSurfaceMesh : public ChLoadBase {
  public:
    ChLoadContactSurfaceMesh(std::shared_ptr<ChContactSurfaceMesh> cmesh);

    virtual ~ChLoadContactSurfaceMesh() {}

    /// "Virtual" copy constructor (covariant return type).
    virtual ChLoadContactSurfaceMesh* Clone() const override { return new ChLoadContactSurfaceMesh(*this); }

    //
    // FUNCTIONS
    //

    // Functions that can be used
    // for cosimulation  A <----> B

    /// Get the collision mesh in a pointer-less way, where vertices are given in a vector of xyz points, and triangles
    /// are given as indexes to the three vertexes in that vector (similar to Wavefront OBJ meshes) Note, indexes are
    /// 0-based. These vectors can be later sent to another computing node that computes, say, CFD forces on the mesh.
    void OutputSimpleMesh(
        std::vector<ChVector<>>& vert_pos,     ///< array of vertexes (absolute xyz positions)
        std::vector<ChVector<>>& vert_vel,     ///< array of vertexes (absolute xyz velocities, might be useful)
        std::vector<ChVector<int>>& triangles  ///< array of triangles (indexes to vertexes, ccw)
    );

    /// Set the forces to the nodes in a pointer-less way, where forces are given as a vector of xyz vectors and indexes
    /// to the referenced vertex, as obtained by OutputSimpleMesh.
    /// NOTE: do not insert/remove nodes from the collision mesh between the OutputSimpleMesh-InputSimpleForces pair!
    void InputSimpleForces(
        const std::vector<ChVector<>> vert_forces,  ///< array of forces (absolute xyz forces in [N])
        const std::vector<int> vert_ind             ///< array of indexes to vertexes to which forces are applied
    );

    /// Set the contact mesh (also resets the applied nodes)
    void SetContactMesh(std::shared_ptr<ChContactSurfaceMesh> mmesh);

    /// Get the contact mesh
    std::shared_ptr<ChContactSurfaceMesh> GetContactMesh() const { return contactmesh; }

    /// Access the list of applied forces, so you can add new ones by using push_back(),
    /// remove them, count them, etc.
    /// Note that if you add nodes, these should belong to the referenced mesh.
    std::vector<std::shared_ptr<ChLoadXYZnode>>& GetForceList() { return forces; }

    //
    // ChLoadBase interface
    //

    virtual int LoadGet_ndof_x() override;
    virtual int LoadGet_ndof_w() override;
    virtual void LoadGetStateBlock_x(ChState& mD) override;
    virtual void LoadGetStateBlock_w(ChStateDelta& mD) override;
    virtual void LoadStateIncrement(const ChState& x, const ChStateDelta& dw, ChState& x_new) override;

    // simple.. field is x y z, hardcoded return val:
    virtual int LoadGet_field_ncoords() override { return 3; }

    /// Compute Q, the generalized load.
    virtual void ComputeQ(ChState* state_x,      ///< state position to evaluate Q
                          ChStateDelta* state_w  ///< state speed to evaluate Q
                          ) override;

    /// Compute jacobians.
    /// Not needed when forces are constant, btw.
    virtual void ComputeJacobian(ChState* state_x,       ///< state position to evaluate jacobians
                                 ChStateDelta* state_w,  ///< state speed to evaluate jacobians
                                 ChMatrixRef mK,         ///< result dQ/dx
                                 ChMatrixRef mR,         ///< result dQ/dv
                                 ChMatrixRef mM          ///< result dQ/da
                                 ) override;

    virtual bool IsStiff() override { return false; }

    virtual void CreateJacobianMatrices() override;
    virtual void LoadIntLoadResidual_F(ChVectorDynamic<>& R, double c) override;
    virtual void LoadIntLoadResidual_Mv(ChVectorDynamic<>& R, const ChVectorDynamic<>& w, double c) override {}
    virtual void InjectKRMmatrices(ChSystemDescriptor& mdescriptor) override;
    virtual void KRMmatricesLoad(double Kfactor, double Rfactor, double Mfactor) override;

  private:
    std::shared_ptr<ChContactSurfaceMesh> contactmesh;
    std::vector<std::shared_ptr<ChLoadXYZnode>> forces;
};

/// @} chrono_fea

}  // end namespace fea
}  // end namespace chrono

#endif


text:
package io.debezium.converters;

import java.util.Map;

import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.connect.storage.ConverterConfig;

import io.debezium.converters.spi.SerializerType;

/**
 * Configuration options for {@link CloudEventsConverter CloudEventsConverter} instances.
 */
public class CloudEventsConverterConfig extends ConverterConfig {

    public static final String CLOUDEVENTS_SERIALIZER_TYPE_CONFIG = "serializer.type";
    public static final String CLOUDEVENTS_SERIALIZER_TYPE_DEFAULT = "json";
    private static final String CLOUDEVENTS_SERIALIZER_TYPE_DOC = "Specify a serializer to serialize CloudEvents values";

    public static final String CLOUDEVENTS_DATA_SERIALIZER_TYPE_CONFIG = "data.serializer.type";
    public static final String CLOUDEVENTS_DATA_SERIALIZER_TYPE_DEFAULT = "json";
    private static final String CLOUDEVENTS_DATA_SERIALIZER_TYPE_DOC = "Specify a serializer to serialize the data field of CloudEvents values";

    private static final ConfigDef CONFIG;

    static {
        CONFIG = ConverterConfig.newConfigDef();

        CONFIG.define(CLOUDEVENTS_SERIALIZER_TYPE_CONFIG, ConfigDef.Type.STRING, CLOUDEVENTS_SERIALIZER_TYPE_DEFAULT, ConfigDef.Importance.HIGH,
                CLOUDEVENTS_SERIALIZER_TYPE_DOC);
        CONFIG.define(CLOUDEVENTS_DATA_SERIALIZER_TYPE_CONFIG, ConfigDef.Type.STRING, CLOUDEVENTS_DATA_SERIALIZER_TYPE_DEFAULT, ConfigDef.Importance.HIGH,
                CLOUDEVENTS_DATA_SERIALIZER_TYPE_DOC);
    }

    public static ConfigDef configDef() {
        return CONFIG;
    }

    public CloudEventsConverterConfig(Map<String, ?> props) {
        super(CONFIG, props);
    }

    /**
     * Return which serializer type is used to serialize CloudEvents values.
     *
     * @return serializer type
     */
    public SerializerType cloudeventsSerializerType() {
        return SerializerType.withName(getString(CLOUDEVENTS_SERIALIZER_TYPE_CONFIG));
    }

    /**
     * Return which serializer type is used to serialize the data field of CloudEvents values.
     *
     * @return serializer type
     */
    public SerializerType cloudeventsDataSerializerTypeConfig() {
        return SerializerType.withName(getString(CLOUDEVENTS_DATA_SERIALIZER_TYPE_CONFIG));
    }
}


text:
from numbers import Number

import theano
from theano import tensor as TT
import numpy as np

from . import origin

class Input(object):
    """Inputs are objects that provide real-valued input to ensembles.

    Any callable can be used an input function.

    """
    def __init__(self, name, values, zero_after_time=None):
        """
        :param string name: name of the function input
        :param value: defines the output decoded_output
        :type value: float or function
        :param float zero_after_time:
            time after which to set function output = 0 (s)

        """
        self.name = name
        self.t = 0
        self.function = None
        self.zero_after_time = zero_after_time
        self.zeroed = False
        self.change_time = None
        self.origin = {}

        # if value parameter is a python function
        if callable(values):
            self.origin['X'] = origin.Origin(func=values)
        # if value is dict of time:value pairs
        elif isinstance(values, dict):
            self.change_time = sorted(values.keys())[0]
            # check for size of dict elements
            if isinstance(values[self.change_time], list):
                initial_value = np.zeros(len(values[self.change_time]))
            else: initial_value = np.zeros(1)
            self.origin['X'] = origin.Origin(func=None,
                initial_value=initial_value)
            self.values = values
        else:
            self.origin['X'] = origin.Origin(func=None, initial_value=values)

    def reset(self):
        """Resets the function output state values.

        """
        self.zeroed = False

    def theano_tick(self):
        """Move function input forward in time.

        """
        if self.zeroed:
            return

        # zero output
        if self.zero_after_time is not None and self.t > self.zero_after_time:
            self.origin['X'].decoded_output.set_value(
                np.float32(np.zeros(self.origin['X'].dimensions)))
            self.zeroed = True

        # change value
        if self.change_time is not None and self.t > self.change_time:
            self.origin['X'].decoded_output.set_value(
                np.float32(np.array([self.values[self.change_time]])))
            index = sorted(self.values.keys()).index(self.change_time)
            if index < len(self.values) - 1:
                self.change_time = sorted(self.values.keys())[index+1]
            else: self.change_time = None

        # update output decoded_output
        if self.origin['X'].func is not None:
            values = self.origin['X'].func(self.t)

            # if value is a scalar output, make it a list
            if isinstance(values, Number):
                values = [values]

            # cast as float32 for consistency / speed,
            # but _after_ it's been made a list
            self.origin['X'].decoded_output.set_value(np.float32(values))


text:
package schaugenau.database;

/**
 * Distributed under the MIT License. (See accompanying file LICENSE or copy at
 * https://github.com/raphaelmenges/schaugenau/blob/master/src/LICENSE)
 *
 * @author Kevin Schmidt
 *
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Random;
//import java.util.Stack;

import org.apache.log4j.Logger;

public class PictureOperations {

	/* Select table */
	protected String table;

	/* picture id's */
	private static int CurrentCorrectID;
	private static int CurrentIncorrectID;

	/* picture tags */
	private static String IncorPictTag;
	private static String CorPictTag;

	/* accessing database */
	private static Access dbaccess = null;

	/* querystring */
	private static String queryString;

	/* logging */
	private static Logger logger = Logger.getLogger(PictureOperations.class);

	/* Postfix for using International Tags */
	private static String language;

	/* constructor */
	public PictureOperations() {
		dbaccess = new Access();
		table = "pictures";
	}

	/** public accessors **/
	public int getCorPictID() {
		return CurrentCorrectID;
	}

	public void setCorPictID(int id) {
		CurrentCorrectID = id;
	}

	public int getIncorPictID() {
		return CurrentIncorrectID;
	}

	public void setIncorPictID(int id) {
		CurrentIncorrectID = id;
	}

	public static String getCorPictTag() {
		return CorPictTag;
	}

	public void setCorPictTag(String tag) {
		CorPictTag = tag;
	}

	public String getIncorPictTag() {
		return IncorPictTag;
	}

	public void setIncorPictTag(String tag) {
		IncorPictTag = tag;
	}

	public String getLanguage() {
		return language;
	}

	public static void setLanguage(String lng) {
		language = lng;
	}

	/*
	 * Method to load two different pictures from the database
	 */
	public void loadPictures() {
		try {
			dbaccess = new Access();
			dbaccess.createConnection();
			createRdmTags();

			// Picture with a matching tag
			String Tag = getCorPictTag();
			int ID = fetchID(Tag);
			logger.debug("Loading Picture with tag = " + Tag + " and filename = Correct" + ID + ".png");
			setCorPictID(ID);
			setCorPictTag(Tag);
			queryString = "SELECT Picture FROM " + table + " WHERE ID = '" + ID + "'";
			PreparedStatement psmnt = dbaccess.con.prepareStatement(queryString);
			ResultSet rs = psmnt.executeQuery();
			while (rs.next()) {
				File picture1 = new File("images/Correct" + ID + ".png");
				FileOutputStream fos = new FileOutputStream(picture1);
				byte[] buffer = new byte[1024];
				InputStream is = rs.getBinaryStream(1);
				while (is.read(buffer) > 0) {
					fos.write(buffer);
				}
				fos.close();
			}

			// Picture with not matching tag
			String Dif_Tag = getIncorPictTag();

			// This is not supposed to happen!
			// For debugging and errorhandling only
			if (Dif_Tag == getCorPictTag()) {
				Random generator = new Random();
				LinkedList<String> errPoollist = createTagPool();
				Object[] errArray = new String[errPoollist.size()];
				errArray = errPoollist.toArray();
				int randomIndex = generator.nextInt(errArray.length);
				errPoollist.remove(getCorPictTag());
				setIncorPictTag((String) errArray[randomIndex]);
				Dif_Tag = getIncorPictTag();
			}

			int Dif_ID = fetchID(Dif_Tag);
			setIncorPictID(Dif_ID);
			logger.debug("Loading Picture with tag = " + Dif_Tag + " and filename = Incorrect" + Dif_ID + ".png");
			queryString = "SELECT Picture FROM " + table + " WHERE ID = '" + Dif_ID + "'";
			PreparedStatement psmnt2 = dbaccess.con.prepareStatement(queryString);
			ResultSet rs2 = psmnt2.executeQuery();
			while (rs2.next()) {
				File picture2 = new File("images/Incorrect" + Dif_ID + ".png");
				FileOutputStream fos2 = new FileOutputStream(picture2);
				byte[] buffer2 = new byte[1024];
				InputStream is2 = rs2.getBinaryStream(1);
				while (is2.read(buffer2) > 0) {
					fos2.write(buffer2);
				}
				fos2.close();
			}
			dbaccess.con.close();
		} catch (ClassNotFoundException | SQLException | IOException e) {
			e.printStackTrace();
			logger.fatal("PictureOperations.loadPicture() collapsed!");
		}
	}

	/**
	 * Methods to update values in the database
	 **/

	/*
	 * Saves how often the picture was loaded as the correct picture
	 */
	public void incrementUsedAsCorrect(int ID) {
		try {
			dbaccess = new Access();
			dbaccess.createConnection();
			queryString = "UPDATE " + table + " SET UsedAsCorrect = UsedAsCorrect + 1 WHERE ID = '" + ID + "'";
			dbaccess.st.executeUpdate(queryString);
			dbaccess.con.close();
		} catch (ClassNotFoundException | SQLException e) {
			logger.fatal("PictureOperations.incrementUsedAsCorrect collapsed!");
			e.printStackTrace();
		}
	}

	/*
	 * Saves how often the picture was chosen correctly
	 */
	public void incrementChosenAsCorrect(int ID) {
		try {
			dbaccess = new Access();
			dbaccess.createConnection();
			queryString = "UPDATE " + table + " SET ChosenAsCorrect = ChosenAsCorrect + 1 WHERE ID = '" + ID + "'";
			dbaccess.st.executeUpdate(queryString);
			dbaccess.con.close();
		} catch (ClassNotFoundException | SQLException e) {
			logger.fatal("PictureOperations.incrementChosenAsCorrect collapsed!");
			e.printStackTrace();
		}
	}

	/**
	 * Methods to store (new) pictures in the database
	 **/

	/*
	 * Method to import pictures into database (for the first time) Pictures are
	 * imported as BLOB's (binary large object) into the database Views is set
	 * to 0
	 */
	public void importPicture() {
		try {
			logger.info("Storing picture into database");
			// String Tag = SearchEngines.getTag();
			// Stack<String> tempstack = ImageCrawler.getImageStack();
			// absolute path of image for testing issues
			// if(!tempstack.isEmpty()){
			// System.out.println("WARNING: Empty stack in
			// PictureOperations.importPicture!");
			// }
			// File picture = new File(
			// "C:/SchauGenau/Downloads/" + tempstack.pop() + ".jpg");
			File picture = new File("C:/Users/SchauGenau/ownCloud/Blumen/Tulpe07.jpg"); // path
			FileInputStream fis;
			PreparedStatement psmnt = null;
			dbaccess = new Access();
			dbaccess.createConnection();
			psmnt = dbaccess.con.prepareStatement("INSERT INTO " + table
					+ "(TagGerman, TagEnglish, Picture, UsedAsCorrect, ChosenAsCorrect)" + "values(?,?,?,?,?)");
			psmnt.setString(1, "Tulpe"); // german tag
			psmnt.setString(2, "Tulip"); // english tag
			psmnt.setInt(4, 0);
			psmnt.setInt(5, 0);
			fis = new FileInputStream(picture);
			psmnt.setBinaryStream(3, fis, (int) (picture.length()));
			int s = psmnt.executeUpdate();
			if (s > 0) {
				System.out.println("Upload successfull");
			} else {
				System.out.println("Upload failed");
			}
			fis.close();
			dbaccess.con.close();
		} catch (ClassNotFoundException | SQLException | IOException e) {
			logger.fatal("PictureOperations.importPicture() collapsed!");
			e.printStackTrace();
		}
	}

	/**
	 * Methods to provide different operations on the database used by other
	 * methods
	 **/

	/*
	 * Method to return the ID of one randomized Picture with given Tag
	 */
	public int fetchID(String Tag) throws ClassNotFoundException, SQLException {
		dbaccess = new Access();
		dbaccess.createConnection();
		int result;
		queryString = "SELECT ID FROM " + table + " WHERE Tag" + getLanguage() + " = '" + Tag
				+ "' ORDER BY RAND() LIMIT 1";
		dbaccess.rs = dbaccess.st.executeQuery(queryString);
		dbaccess.rs.next();
		result = dbaccess.rs.getInt("ID");
		return result;
	}

	/*
	 * Method to get all different Tags the database
	 */
	public LinkedList<String> createTagPool() throws SQLException, ClassNotFoundException {
		int maxID = getMaxID();
		String s;
		LinkedList<String> pool = new LinkedList<String>();

		for (int i = 1; i <= maxID; i++) {
			queryString = "SELECT Tag" + language + " from " + table + " WHERE ID = '" + i + "'";
			dbaccess.rs = dbaccess.st.executeQuery(queryString);
			if (dbaccess.rs.next()) {
				s = dbaccess.rs.getString("Tag" + language);
				if (pool.contains(s) == false) {
					pool.add(s);
				}
			}
		}
		dbaccess.con.close();
		return pool;
	}

	/*
	 * Method to create random tags for pictures
	 */
	public void createRdmTags() {
		try {
			LinkedList<String> poollist = new LinkedList<String>();
			poollist = createTagPool();
			Object[] poolarray = new String[poollist.size()];
			poolarray = poollist.toArray();
			Random generator = new Random();
			int randomIndex = generator.nextInt(poolarray.length);
			setCorPictTag((String) poolarray[randomIndex]);

			LinkedList<String> poollist2 = poollist;
			Object[] poolarray2 = new String[poollist2.size()];
			poolarray2 = poollist2.toArray();
			int randomIndex2 = generator.nextInt(poolarray2.length);
			poollist2.remove(getCorPictTag());
			setIncorPictTag((String) poolarray2[randomIndex2]);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Method to get the highest ID of Pictures
	 */
	public int getMaxID() throws SQLException, ClassNotFoundException {
		int maxID = 1;
		dbaccess = new Access();
		dbaccess.createConnection();
		queryString = "SELECT ID from " + table + " ORDER BY ID DESC LIMIT 1;";
		dbaccess.rs = dbaccess.st.executeQuery(queryString);
		dbaccess.rs.next();
		maxID = dbaccess.rs.getInt("ID");
		return maxID;
	}

}


text:
using Lucene.Net.Util;
using System.Collections.Generic;

namespace Lucene.Net.Search.Suggest
{

    /// <summary>
    /// This wrapper buffers incoming elements.
    /// @lucene.experimental
    /// </summary>
    public class BufferedInputIterator : IInputIterator
    {
        // TODO keep this for now
        /// <summary>
        /// buffered term entries </summary>
        protected BytesRefArray m_entries = new BytesRefArray(Counter.NewCounter());
        /// <summary>
        /// buffered payload entries </summary>
        protected BytesRefArray m_payloads = new BytesRefArray(Counter.NewCounter());
        /// <summary>
        /// buffered context set entries </summary>
        protected IList<ICollection<BytesRef>> m_contextSets = new List<ICollection<BytesRef>>();
        /// <summary>
        /// current buffer position </summary>
        protected int m_curPos = -1;
        /// <summary>
        /// buffered weights, parallel with <see cref="m_entries"/> </summary>
        protected long[] m_freqs = new long[1];
        private readonly BytesRef spare = new BytesRef();
        private readonly BytesRef payloadSpare = new BytesRef();
        private readonly bool hasPayloads;
        private readonly IComparer<BytesRef> comp;

        private readonly bool hasContexts;

        /// <summary>
        /// Creates a new iterator, buffering entries from the specified iterator </summary>
        public BufferedInputIterator(IInputIterator source)
        {
            BytesRef spare;
            int freqIndex = 0;
            hasPayloads = source.HasPayloads;
            hasContexts = source.HasContexts;
            while ((spare = source.Next()) != null)
            {
                m_entries.Append(spare);
                if (hasPayloads)
                {
                    m_payloads.Append(source.Payload);
                }
                if (hasContexts)
                {
                    m_contextSets.Add(source.Contexts);
                }
                if (freqIndex >= m_freqs.Length)
                {
                    m_freqs = ArrayUtil.Grow(m_freqs, m_freqs.Length + 1);
                }
                m_freqs[freqIndex++] = source.Weight;
            }
            comp = source.Comparer;
        }

        public virtual long Weight => m_freqs[m_curPos];

        public virtual BytesRef Next()
        {
            if (++m_curPos < m_entries.Length)
            {
                m_entries.Get(spare, m_curPos);
                return spare;
            }
            return null;
        }

        public virtual BytesRef Payload
        {
            get
            {
                if (hasPayloads && m_curPos < m_payloads.Length)
                {
                    return m_payloads.Get(payloadSpare, m_curPos);
                }
                return null;
            }
        }

        public virtual bool HasPayloads => hasPayloads;

        public virtual IComparer<BytesRef> Comparer => comp;

        public virtual ICollection<BytesRef> Contexts
        {
            get
            {
                if (hasContexts && m_curPos < m_contextSets.Count)
                {
                    return m_contextSets[m_curPos];
                }
                return null;
            }
        }

        public virtual bool HasContexts => hasContexts;
    }
}


text:
/**
 * Created by ndyumin on 10.08.2016.
 */

/**
 *
 * column API
 *
 * - string id
 * - string name
 * - boolean visible
 *
 */
import h from 'snabbdom/h';

export default class Renderer {
    render(model) {
        return h('table.vtable', [
            this.renderHeader(model),
            this.renderBody(model)
        ]);
    }

    renderHeader (model) {
        return h('thead', [
            h('tr', model.meta.columns.filter(this.isColumnVisible).map(this.renderHeaderCell))
        ]);
    };

    renderBody (model) {
        return h('tbody',
            model.data.items.map(entry =>
                h('tr',
                    model.meta.columns
                        .filter(this.isColumnVisible)
                        .map(column => ({column, value: entry[column.id]}))
                        .map(this.renderDataCell))));
    }

    renderHeaderCell(column) {
        return h('td.header-cell', column.name);
    }

    renderDataCell({column, value}) {
        return h('td.text-cell', value);
    }

    isColumnVisible(column) {
        return column.visible;
    }
}


text:
package aQute.bnd.osgi;

import aQute.bnd.osgi.Descriptors.TypeRef;

@SuppressWarnings("unused")
public class ClassDataCollector {

	public void classBegin(int access, TypeRef name) {}

	public boolean classStart(int access, TypeRef className) {
		classBegin(access, className);
		return true;
	}

	public boolean classStart(Clazz c) {
		classBegin(c.accessx, c.className);
		return true;
	}

	public void extendsClass(TypeRef zuper) throws Exception {}

	public void implementsInterfaces(TypeRef[] interfaces) throws Exception {}

	public void addReference(TypeRef ref) {}

	public void annotation(Annotation annotation) throws Exception {}

	public void parameter(int p) {}

	public void method(Clazz.MethodDef defined) {}

	public void field(Clazz.FieldDef defined) {}

	public void classEnd() throws Exception {}

	public void deprecated() throws Exception {}

	/**
	 * The EnclosingMethod attribute
	 *
	 * @param cName The name of the enclosing class, never null. Name is with
	 *            slashes.
	 * @param mName The name of the enclosing method in the class with cName or
	 *            null
	 * @param mDescriptor The descriptor of this type
	 */
	public void enclosingMethod(TypeRef cName, String mName, String mDescriptor) {

	}

	/**
	 * The InnerClass attribute
	 *
	 * @param innerClass The name of the inner class (with slashes). Can be
	 *            null.
	 * @param outerClass The name of the outer class (with slashes) Can be null.
	 * @param innerName The name inside the outer class, can be null.
	 * @param modifiers The access flags
	 * @throws Exception
	 */
	public void innerClass(TypeRef innerClass, TypeRef outerClass, String innerName, int innerClassAccessFlags)
			throws Exception {}

	public void signature(String signature) {}

	public void constant(Object object) {}

	public void memberEnd() {}

	public void version(int minor, int major) {}

	public void referenceMethod(int access, TypeRef className, String method, String descriptor) {}

	/**
	 * A reference to a type from method or field. The modifiers indicate the
	 * access level of the parent method/field.
	 *
	 * @param typeRef
	 * @param modifiers
	 */
	public void referTo(TypeRef typeRef, int modifiers) {}

	public void annotationDefault(Clazz.MethodDef last) {}

	public void annotationDefault(Clazz.MethodDef last, Object value) {
		annotationDefault(last);
	}

}


text:
package io.vertx.blueprint.microservice.store;

import io.vertx.blueprint.microservice.common.BaseMicroserviceVerticle;
import io.vertx.blueprint.microservice.store.api.RestStoreAPIVerticle;
import io.vertx.blueprint.microservice.store.impl.StoreCRUDServiceImpl;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.serviceproxy.ProxyHelper;

import static io.vertx.blueprint.microservice.store.StoreCRUDService.SERVICE_ADDRESS;
import static io.vertx.blueprint.microservice.store.StoreCRUDService.SERVICE_NAME;

/**
 * A verticle for store operation (e.g. apply or close) processing.
 *
 * @author Eric Zhao
 */
public class StoreVerticle extends BaseMicroserviceVerticle {

  private StoreCRUDService crudService;

  @Override
  public void start(Future<Void> future) throws Exception {
    super.start();

    crudService = new StoreCRUDServiceImpl(vertx, config());
    ProxyHelper.registerService(StoreCRUDService.class, vertx, crudService, SERVICE_ADDRESS);
    // publish service and deploy REST verticle
    publishEventBusService(SERVICE_NAME, SERVICE_ADDRESS, StoreCRUDService.class)
      .compose(servicePublished -> deployRestVerticle(crudService))
      .setHandler(future.completer());
  }

  private Future<Void> deployRestVerticle(StoreCRUDService service) {
    Future<String> future = Future.future();
    vertx.deployVerticle(new RestStoreAPIVerticle(service),
      new DeploymentOptions().setConfig(config()),
      future.completer());
    return future.map(r -> null);
  }
}


text:
package io.hasura.shivam.chitchat.database;

/**
 * Created by shivam on 3/7/17.
 */

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

import java.io.Serializable;

@Table(name = "Person")
public class Person extends Model implements Serializable {

    @Column(name = "mobile", unique = true,notNull = true)
    public String mobile;

    @Column(name="name")
    public String name;

    @Column(name="user_id", unique=true, notNull=true)
    public long user_id;

    @Column(name = "profile_pic")
    public byte[] profile_pic;

    // Make sure to have a default constructor for every ActiveAndroid model
    public Person(){
        super();
    }

    public Person(String mobile,byte[] profile_pic)
    {
        super();

        this.mobile=mobile;

        this.profile_pic=profile_pic;

    }

}


text:
include ReportCat::Core

module ReportCat::Core

  describe Report do

    include SetupReports

    before( :each ) do
      @name = :test
      @report = Report.new( :name => @name )
    end

    #############################################################################
    # initialize

    describe '#initialize' do

      it 'initializes accessor values' do
        expect( @report.name ).to eql( @name )
        expect( @report.params ).to eql( [] )
        expect( @report.columns ).to eql( [] )
        expect( @report.rows ).to eql( [] )
        expect( @report.charts ).to eql( [] )
      end

      it 'accepts arrays' do
        array = [ 'a', 'b' ]

        report = Report.new(
          :from => array,
          :joins => array,
          :where => array,
          :group_by => array,
          :order_by => array
        )

        expect( report.from ).to eql( 'a,b' )
        expect( report.joins ).to eql( 'a b' )
        expect( report.where ).to eql( 'a and b' )
        expect( report.group_by ).to eql( 'a,b' )
        expect( report.order_by ).to eql( 'a,b' )
      end
    end

    #############################################################################
    # accept_array

    describe '#accept_array' do

      it 'joins arrays with the separator' do
        expected = '1,2,3'
        expect( @report.accept_array( [ '1', '2', '3' ], ',' ) ).to eql( expected )
      end

      it 'returns non arrays' do
        expect( @report.accept_array( 1, ',' ) ).to eql( 1 )
        expect( @report.accept_array( :foo, ',' ) ).to eql( :foo )
      end
    end

    #############################################################################
    # add_chart

    describe '#add_chart' do

      it 'adds a chart' do
        name = :i_like_pie
        type = :pie
        label = :label
        values = [ :value_1, :value_2 ]
        options = { :sweet => true }

        expect( @report.charts ).to be_empty
        @report.add_chart( name, type, label, values, options )
        expect( @report.charts.size ).to eql( 1 )

        chart = @report.charts.first

        expect( chart ).to be_an_instance_of( Chart )
        expect( chart.name ).to eql( name )
        expect( chart.type ).to eql( type )
        expect( chart.label ).to eql( label )
        expect( chart.values ).to eql( values )
        expect( chart.options ).to eql( options )
      end
    end

    #############################################################################
    # add_column

    describe '#add_column' do

      it 'adds a column' do
        name = :foo
        type = :integer
        options = { :sql => 'count( 1 )' }

        expect( @report.columns ).to be_empty
        @report.add_column( name, type, options )
        expect( @report.columns.size ).to eql( 1 )

        column = @report.columns.first
        expect( column.name ).to eql( name )
        expect( column.type ).to eql( type )
        expect( column.options ).to eql( options )
      end
    end

    #############################################################################
    # add_param

    describe '#add_param' do

      it 'adds a param' do
        name = :foo
        type = :integer

        expect( @report.params ).to be_empty
        @report.add_param( name, type )
        expect( @report.params.size ).to eql( 1 )

        param = @report.params.first
        expect( param ).to be_an_instance_of( Param )
        expect( param.name ).to eql( name )
        expect( param.type ).to eql( type )
      end
    end

    #############################################################################
    # column

    describe '#column' do

      before( :each ) do
        setup_reports
      end

      it 'returns the named column' do
        expect( @report.columns.size ).to be > 1
        @report.columns.each_index do |i|
          column = @report.columns[ i ]
          expect( @report.column( column.name ) ).to eql( column )
        end
      end

      it 'returns nil if it is unable to find the column' do
        expect( @report.column( :does_not_exist ) ).to be_nil
      end
    end

    #############################################################################
    # column_index

    describe '#column_index' do

      before( :each ) do
        setup_reports
      end

      it 'returns the index of the named column' do
        expect( @report.columns.size ).to be > 1
        @report.columns.each_index do |i|
          column = @report.columns[ i ]
          expect( @report.column_index( column.name ) ).to eql( i )
        end
      end

      it 'returns nil if it is unable to find the column' do
        expect( @report.column_index( :does_not_exist ) ).to be_nil
      end
    end

    #############################################################################
    # generate

    describe '#generate' do

      before( :each ) do
        setup_reports
        allow( @report ).to receive( :query ).and_return( nil )
      end

      it 'applies passed in options to params of the same name' do
        expect( @report.param( :text_field_test ).value ).to be_nil
        @report.generate( :text_field_test => 'foobar' )
        expect( @report.param( :text_field_test ).value ).to eql( 'foobar' )
      end
    end

    #############################################################################
    # param

    describe '#param' do

      before( :each ) do
        @param = @report.add_param( :foo, :integer )
      end

      it 'finds a parameter by name' do
        expect( @report.param( :foo ) ).to be( @param )
      end

      it 'returns nil if it can not find it' do
        expect( @report.param( :bar ) ).to be_nil
      end
    end

    #############################################################################
    # to_csv

    describe '#to_csv' do

      before( :each ) do
        setup_reports
        allow( @report ).to receive( :query ).and_return( nil )
      end

      it 'generates CSV' do
        expect( @report.to_csv ).to eql_file( 'spec/data/lib/report.csv' )
      end
    end

    #############################################################################
    # attributes

    describe '#attributes' do

      before( :each ) do
        setup_reports
      end

      it 'includes the name as both name and id' do
        expect( @report.attributes[ :id ] ).to eql( @report.name )
        expect( @report.attributes[ :name ] ).to eql( @report.name )
      end

      it 'includes back if defined' do
        back = @report.attributes
        expect( @report.attributes.has_key?( :back ) ).to be( false )
        @report.back = back
        expect( @report.attributes[ :back ] ).to eql( back )
      end

      it 'returns a hash of param names to values' do
        @report.params.each do |param|
          expect( @report.attributes[ param.name ] ).to eql( param.value )
        end
      end
    end

    #############################################################################
    # query

    describe '#query' do

      before( :each ) do
        setup_reports
       end

      it 'initializes rows' do
        @report.rows << []
        expect( @report.rows.size ).to be > 0

        expect( @report ).to receive( :to_sql ).and_return( nil )
        allow( ActiveRecord::Base.connection ).to receive( :execute ).and_return( nil )

        @report.send( :query )
        expect( @report.rows.size ).to eql( 0 )
      end

      it 'executes SQL against ActiveRecord' do
        sql = 'foobar
'
        expect( @report ).to receive( :to_sql ).and_return( sql )
        expect( ActiveRecord::Base.connection ).to receive( :execute ).with( sql ).and_return( nil )
        @report.send( :query )
      end

      it 'tolerates nil results from ActiveRecord' do
        expect( @report ).to receive( :to_sql ).and_return( nil )
        expect( ActiveRecord::Base.connection ).to receive( :execute ).and_return( nil )
        @report.send( :query )
      end

      it 'populates rows with the results of the query' do
        results = [ [1], [2] ]

        expect( @report ).to receive( :to_sql ).and_return( nil )
        expect( ActiveRecord::Base.connection ).to receive( :execute ).and_return( results )
        @report.send( :query )
        expect( @report.rows.size ).to eql( results.size )
        results.each_index { |i| expect( @report.rows[ i ] ).to eql( results[ i ] ) }
      end

      it 'post processes each column' do
        expect( ActiveRecord::Base.connection ).to receive( :execute ).and_return( [] )

        @report.columns.each { |c| expect( c ).to receive( :post_process ).with( @report ) }
        @report.send( :query )
      end
    end

    #############################################################################
    # to_sql

    describe '#to_sql' do

      before( :each ) do
        setup_reports
        allow( @report ).to receive( :query ).and_return( nil )
      end

      it 'generates SQL' do
        expect( @report.send( :to_sql ) ).to eql_file( 'spec/data/lib/report.sql' )
      end
    end
  end
end


text:
require 'test_helper'

module Archimate
  module Svg
    module Entity
      class ConstraintTest < Minitest::Test
        def setup
          @model = build_model(
            diagrams: [
              build_diagram
            ]
          )
          @child = @model.diagrams.first.nodes.first
          @subject = Constraint.new(@child, build_bounds)
        end

        def test_badge
          refute_nil @subject.instance_variable_get(:@badge)
        end
      end
    end
  end
end


text:
//
//  Common.h
//  OrangeVideo
//
//  Created by xing on 2017/7/19.
//  Copyright © 2017年 xing. All rights reserved.
//

#ifndef Common_h
#define Common_h

#define kScreenW    [UIScreen mainScreen].bounds.size.width
#define kScreenH    [UIScreen mainScreen].bounds.size.height

#define ColorWithRGB(r,g,b,a) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]
#define RandomColor [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0]

#endif /* Common_h */


text:
package com.github.drapostolos.typeparser;

import static com.github.drapostolos.typeparser.Util.defaultSplitStrategy;
import static com.github.drapostolos.typeparser.Util.makeNullArgumentErrorMsg;

import java.util.List;

/**
 * Helper class providing helper methods to implementations of {@link SplitStrategy} when splitting
 * a string into sub-strings.
 *
 * @see User-Guide
 */
public final class SplitStrategyHelper extends Helper {

    private static final SplitStrategyHelper IGNORED = null;

    SplitStrategyHelper(TargetType targetType) {
        super(targetType);
    }

    /**
     * Gives access to the default split strategy, which splits
     * the {@code input} String by using a comma (,).
     *

     *
     * @param input String to split.
     * @return List of substrings of the input string
     * @throws NullPointerException if {@code input} argument is null.
     */
    public List<String> splitWithDefaultSplitStrategy(String input) {
        if (input == null) {
            throw new NullPointerException(makeNullArgumentErrorMsg("input"));
        }
        return defaultSplitStrategy().split(input, IGNORED);
    }

}


text:
layout: post
title: Not In Germany
date: 2011-09-17 17:59:17.000000000 -05:00
categories:
- Programming
tags:
- lol
- programming
- source engine
status: publish
type: post
published: true
meta:
  _edit_last: '1'
author:
  login: Blake
  email: contact@blakeharley.com
  display_name: Blake
  first_name: Blake
  last_name: Harley
---

Silly German videogame censorship.

//---------------------------------------------------------
// Zombies should scream continuously while burning, so long
// as they are alive... but NOT IN GERMANY!
//---------------------------------------------------------

npc_zombie.cpp : Line 782


text:
api.promome.mx
==============

Api para aplicación para notificación de promociones en Twitter


text:
import HttpStatus from 'http-status-codes';

import logger from '../config/logger';

class ErrorHelpers {

  static sendErrorMessage(res, errorCode, message) {
    const error = {
      code: errorCode,
      errorCodeMessage: HttpStatus.getStatusText(errorCode),
      message,
    };
    return res.status(errorCode).json(error);
  }

  static logErrorMessage(errorCode, message) {
    const error = {
      code: errorCode,
      errorCodeMessage: HttpStatus.getStatusText(errorCode),
      message,
    };
    return logger.error(error);
  }
}

export default ErrorHelpers;


text:
define("dojox/atom/widget/nls/sr/FeedEntryViewer", {
//begin v1.x content
	displayOptions: "[prikaži opcije]",
	title: "Naslov",
	authors: "Autori",
	contributors: "Saradnici",
	id: "ID",
	close: "[zatvori]",
	updated: "Ažurirano",
	summary: "Rezime",
	content: "Sadržaj"
//end v1.x content
});


text:
<component name="libraryTable">
  <library name="Maven: com.fasterxml.jackson.core:jackson-databind:2.5.0">
    <CLASSES>
      <root url="jar://$M2_REPO$/com/fasterxml/jackson/core/jackson-databind/2.5.0/jackson-databind-2.5.0.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$M2_REPO$/com/fasterxml/jackson/core/jackson-databind/2.5.0/jackson-databind-2.5.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$M2_REPO$/com/fasterxml/jackson/core/jackson-databind/2.5.0/jackson-databind-2.5.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>