text:
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/net_internals/net_internals_ui.h"

#include <memory>
#include <string>
#include <utility>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/containers/unique_ptr_adapters.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/types/expected.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/net_internals_resources.h"
#include "chrome/grit/net_internals_resources_map.h"
#include "components/prefs/pref_member.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/address_list.h"
#include "net/base/host_port_pair.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/network_isolation_key.h"
#include "net/dns/public/host_resolver_results.h"
#include "net/dns/public/resolve_error_info.h"
#include "services/network/expect_ct_reporter.h"
#include "services/network/public/mojom/content_security_policy.mojom.h"
#include "services/network/public/mojom/host_resolver.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/resources/grit/webui_generated_resources.h"
#include "url/scheme_host_port.h"

using content::BrowserThread;

namespace {

content::WebUIDataSource* CreateNetInternalsHTMLSource() {
  content::WebUIDataSource* source =
      content::WebUIDataSource::Create(chrome::kChromeUINetInternalsHost);
  source->UseStringsJs();
  source->AddBoolean("expectCTEnabled",
                     base::FeatureList::IsEnabled(
                         net::TransportSecurityState::kDynamicExpectCTFeature));
  source->AddResourcePaths(
      base::make_span(kNetInternalsResources, kNetInternalsResourcesSize));
  source->SetDefaultResource(IDR_NET_INTERNALS_INDEX_HTML);
  source->OverrideContentSecurityPolicy(
      network::mojom::CSPDirectiveName::ScriptSrc,
      "script-src chrome://resources chrome://test chrome://webui-test "
      "'self';");
  source->AddResourcePath("test_loader_util.js",
                          IDR_WEBUI_JS_TEST_LOADER_UTIL_JS);
  source->DisableTrustedTypesCSP();
  return source;
}

void IgnoreBoolCallback(bool result) {}

// This function converts std::vector<net::IPEndPoint> to base::Value::List.
base::Value::List IPEndpointsToBaseList(
    const std::vector<net::IPEndPoint>& resolved_addresses) {
  base::Value::List resolved_addresses_list;
  for (const net::IPEndPoint& resolved_address : resolved_addresses) {
    resolved_addresses_list.Append(resolved_address.ToStringWithoutPort());
  }
  return resolved_addresses_list;
}

// This function converts net::ConnectionEndpointMetadata to base::Value::Dict.
base::Value::Dict ConnectionEndpointMetadataToBaseDict(
    const net::ConnectionEndpointMetadata& metadata) {
  base::Value::Dict connection_endpoint_metadata;

  base::Value::List supported_protocol_alpns;
  base::Value::List ech_config_list;
  for (const std::string& supported_protocol_alpn :
       metadata.supported_protocol_alpns) {
    supported_protocol_alpns.Append(supported_protocol_alpn);
  }

  for (uint8_t ech_config : metadata.ech_config_list) {
    ech_config_list.Append(ech_config);
  }

  connection_endpoint_metadata.Set("supported_protocol_alpns",
                                   std::move(supported_protocol_alpns));
  connection_endpoint_metadata.Set("ech_config_list",
                                   std::move(ech_config_list));
  connection_endpoint_metadata.Set("target_name", metadata.target_name);

  return connection_endpoint_metadata;
}

// This function converts
// absl::optional<net::HostResolverEndpointResults> to
// base::Value::List.
base::Value::List HostResolverEndpointResultsToBaseList(
    const absl::optional<net::HostResolverEndpointResults>& endpoint_results) {
  base::Value::List endpoint_results_list;

  if (!endpoint_results) {
    return endpoint_results_list;
  }

  for (const auto& endpoint_result : *endpoint_results) {
    base::Value::Dict endpoint_results_dict;
    endpoint_results_dict.Set(
        "ip_endpoints", IPEndpointsToBaseList(endpoint_result.ip_endpoints));
    endpoint_results_dict.Set("metadata", ConnectionEndpointMetadataToBaseDict(
                                              endpoint_result.metadata));
    endpoint_results_list.Append(std::move(endpoint_results_dict));
  }
  return endpoint_results_list;
}

using ResolveHostResult = base::expected<base::Value, std::string>;

// This class implements network::mojom::ResolveHostClient.
class NetInternalsResolveHostClient : public network::mojom::ResolveHostClient {
 public:
  using Callback = base::OnceCallback<void(
      const net::ResolveErrorInfo&,
      const absl::optional<net::AddressList>&,
      const absl::optional<net::HostResolverEndpointResults>&,
      NetInternalsResolveHostClient*)>;

  NetInternalsResolveHostClient(
      mojo::PendingReceiver<network::mojom::ResolveHostClient> receiver,
      Callback callback)
      : receiver_(this, std::move(receiver)), callback_(std::move(callback)) {
    receiver_.set_disconnect_handler(base::BindOnce(
        &NetInternalsResolveHostClient::OnComplete, base::Unretained(this),
        net::ERR_FAILED, net::ResolveErrorInfo(net::ERR_FAILED),
        /*resolved_addresses=*/absl::nullopt,
        /*endpoint_results_with_metadata=*/absl::nullopt));
  }
  ~NetInternalsResolveHostClient() override = default;

  NetInternalsResolveHostClient(const NetInternalsResolveHostClient&) = delete;
  NetInternalsResolveHostClient& operator=(
      const NetInternalsResolveHostClient&) = delete;

 private:
  // network::mojom::ResolveHostClient:
  void OnComplete(int32_t error,
                  const net::ResolveErrorInfo& resolve_error_info,
                  const absl::optional<net::AddressList>& resolved_addresses,
                  const absl::optional<net::HostResolverEndpointResults>&
                      endpoint_results_with_metadata) override {
    std::move(callback_).Run(resolve_error_info, resolved_addresses,
                             endpoint_results_with_metadata, this);
  }
  void OnTextResults(const std::vector<std::string>& text_results) override {
    NOTREACHED();
  }
  void OnHostnameResults(const std::vector<net::HostPortPair>& hosts) override {
    NOTREACHED();
  }

 private:
  mojo::Receiver<network::mojom::ResolveHostClient> receiver_;
  Callback callback_;
};

// This class receives javascript messages from the renderer.
// Note that the WebUI infrastructure runs on the UI thread, therefore all of
// this class's methods are expected to run on the UI thread.
class NetInternalsMessageHandler : public content::WebUIMessageHandler {
 public:
  explicit NetInternalsMessageHandler(content::WebUI* web_ui);

  NetInternalsMessageHandler(const NetInternalsMessageHandler&) = delete;
  NetInternalsMessageHandler& operator=(const NetInternalsMessageHandler&) =
      delete;

  ~NetInternalsMessageHandler() override = default;

 protected:
  // WebUIMessageHandler implementation:
  void RegisterMessages() override;
  void OnJavascriptDisallowed() override;

 private:
  network::mojom::NetworkContext* GetNetworkContext();

  // Resolve JS |callback_id| with |result|.
  // If the renderer is displaying a log file, the message will be ignored.
  void ResolveCallbackWithResult(const std::string& callback_id,
                                 base::Value::Dict result);

  void OnExpectCTTestReportCallback(const std::string& callback_id,
                                    bool success);

  //--------------------------------
  // Javascript message handlers:
  //--------------------------------

  void OnReloadProxySettings(const base::Value::List& list);
  void OnClearBadProxies(const base::Value::List& list);
  void OnResolveHost(const base::Value::List& list);
  void OnClearHostResolverCache(const base::Value::List& list);
  void OnDomainSecurityPolicyDelete(const base::Value::List& list);
  void OnHSTSQuery(const base::Value::List& list);
  void OnHSTSAdd(const base::Value::List& list);
  void OnExpectCTQuery(const base::Value::List& list);
  void OnExpectCTAdd(const base::Value::List& list);
  void OnExpectCTTestReport(const base::Value::List& list);
  void OnCloseIdleSockets(const base::Value::List& list);
  void OnFlushSocketPools(const base::Value::List& list);
  void OnResolveHostDone(
      const std::string& callback_id,
      const net::ResolveErrorInfo&,
      const absl::optional<net::AddressList>&,
      const absl::optional<net::HostResolverEndpointResults>&,
      NetInternalsResolveHostClient* dns_lookup_client);

  raw_ptr<content::WebUI> web_ui_;
  std::set<std::unique_ptr<NetInternalsResolveHostClient>,
           base::UniquePtrComparator>
      dns_lookup_clients_;
  base::WeakPtrFactory<NetInternalsMessageHandler> weak_factory_{this};
};

NetInternalsMessageHandler::NetInternalsMessageHandler(content::WebUI* web_ui)
    : web_ui_(web_ui) {}

void NetInternalsMessageHandler::RegisterMessages() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  web_ui()->RegisterMessageCallback(
      "reloadProxySettings",
      base::BindRepeating(&NetInternalsMessageHandler::OnReloadProxySettings,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "clearBadProxies",
      base::BindRepeating(&NetInternalsMessageHandler::OnClearBadProxies,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "resolveHost",
      base::BindRepeating(&NetInternalsMessageHandler::OnResolveHost,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "clearHostResolverCache",
      base::BindRepeating(&NetInternalsMessageHandler::OnClearHostResolverCache,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "domainSecurityPolicyDelete",
      base::BindRepeating(
          &NetInternalsMessageHandler::OnDomainSecurityPolicyDelete,
          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "hstsQuery", base::BindRepeating(&NetInternalsMessageHandler::OnHSTSQuery,
                                       base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "hstsAdd", base::BindRepeating(&NetInternalsMessageHandler::OnHSTSAdd,
                                     base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "expectCTQuery",
      base::BindRepeating(&NetInternalsMessageHandler::OnExpectCTQuery,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "expectCTAdd",
      base::BindRepeating(&NetInternalsMessageHandler::OnExpectCTAdd,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "expectCTTestReport",
      base::BindRepeating(&NetInternalsMessageHandler::OnExpectCTTestReport,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "closeIdleSockets",
      base::BindRepeating(&NetInternalsMessageHandler::OnCloseIdleSockets,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "flushSocketPools",
      base::BindRepeating(&NetInternalsMessageHandler::OnFlushSocketPools,
                          base::Unretained(this)));
}

void NetInternalsMessageHandler::OnJavascriptDisallowed() {
  weak_factory_.InvalidateWeakPtrs();
}

void NetInternalsMessageHandler::OnReloadProxySettings(
    const base::Value::List& list) {
  GetNetworkContext()->ForceReloadProxyConfig(base::NullCallback());
}

void NetInternalsMessageHandler::OnClearBadProxies(
    const base::Value::List& list) {
  GetNetworkContext()->ClearBadProxiesCache(base::NullCallback());
}

void NetInternalsMessageHandler::OnResolveHost(const base::Value::List& list) {
  const std::string* callback_id = list[0].GetIfString();
  const std::string* hostname = list[1].GetIfString();
  DCHECK(callback_id);
  DCHECK(hostname);

  // Intentionally using https scheme to trigger a HTTPS DNS resource record
  // query.
  auto scheme_host_port = url::SchemeHostPort("https", *hostname, 443);
  const url::Origin origin = url::Origin::Create(GURL("https://" + *hostname));
  AllowJavascript();

  // When ResolveHost() in network process completes, OnResolveHostDone() method
  // is called.
  mojo::PendingReceiver<network::mojom::ResolveHostClient> receiver;
  GetNetworkContext()->ResolveHost(
      network::mojom::HostResolverHost::NewSchemeHostPort(scheme_host_port),
      net::NetworkAnonymizationKey(),
      /*optional_parameters=*/nullptr, receiver.InitWithNewPipeAndPassRemote());

  auto callback = base::BindOnce(&NetInternalsMessageHandler::OnResolveHostDone,
                                 weak_factory_.GetWeakPtr(), *callback_id);
  auto dns_lookup_client = std::make_unique<NetInternalsResolveHostClient>(
      std::move(receiver), std::move(callback));
  dns_lookup_clients_.insert(std::move(dns_lookup_client));
}

void NetInternalsMessageHandler::OnClearHostResolverCache(
    const base::Value::List& list) {
  GetNetworkContext()->ClearHostCache(/*filter=*/nullptr, base::NullCallback());
}

void NetInternalsMessageHandler::OnDomainSecurityPolicyDelete(
    const base::Value::List& list) {
  // |list| should be: [<domain to query>].
  const std::string* domain = list[0].GetIfString();
  DCHECK(domain);
  if (!base::IsStringASCII(*domain)) {
    // There cannot be a unicode entry in the HSTS set.
    return;
  }
  GetNetworkContext()->DeleteDynamicDataForHost(
      *domain, base::BindOnce(&IgnoreBoolCallback));
}

void NetInternalsMessageHandler::OnHSTSQuery(const base::Value::List& list) {
  const std::string* callback_id = list[0].GetIfString();
  const std::string* domain = list[1].GetIfString();
  DCHECK(callback_id && domain);

  AllowJavascript();
  GetNetworkContext()->GetHSTSState(
      *domain,
      base::BindOnce(&NetInternalsMessageHandler::ResolveCallbackWithResult,
                     weak_factory_.GetWeakPtr(), *callback_id));
}

void NetInternalsMessageHandler::ResolveCallbackWithResult(
    const std::string& callback_id,
    base::Value::Dict result) {
  ResolveJavascriptCallback(base::Value(callback_id), result);
}

void NetInternalsMessageHandler::OnHSTSAdd(const base::Value::List& list) {
  DCHECK_GE(2u, list.size());

  // |list| should be: [<domain to query>, <STS include subdomains>]
  const std::string* domain = list[0].GetIfString();
  DCHECK(domain);
  if (!base::IsStringASCII(*domain)) {
    // Silently fail. The user will get a helpful error if they query for the
    // name.
    return;
  }
  const bool sts_include_subdomains = list[1].GetBool();

  base::Time expiry = base::Time::Now() + base::Days(1000);
  GetNetworkContext()->AddHSTS(*domain, expiry, sts_include_subdomains,
                               base::DoNothing());
}

void NetInternalsMessageHandler::OnExpectCTQuery(
    const base::Value::List& list) {
  const std::string* callback_id = list[0].GetIfString();
  const std::string* domain = list[1].GetIfString();
  DCHECK(callback_id && domain);

  net::SchemefulSite site = net::SchemefulSite(GURL("https://" + *domain));

  AllowJavascript();

  GetNetworkContext()->GetExpectCTState(
      *domain, net::NetworkAnonymizationKey(site, site),
      base::BindOnce(&NetInternalsMessageHandler::ResolveCallbackWithResult,
                     weak_factory_.GetWeakPtr(), *callback_id));
}

void NetInternalsMessageHandler::OnExpectCTAdd(const base::Value::List& list) {
  // |list| should be: [<domain to add>, <report URI>, <enforce>].
  const std::string* domain = list[0].GetIfString();
  DCHECK(domain);
  if (!base::IsStringASCII(*domain)) {
    // Silently fail. The user will get a helpful error if they query for the
    // name.
    return;
  }

  const std::string* report_uri_str = list[1].GetIfString();
  absl::optional<bool> enforce = list[2].GetIfBool();
  DCHECK(report_uri_str && enforce);

  net::SchemefulSite site = net::SchemefulSite(GURL("https://" + *domain));

  base::Time expiry = base::Time::Now() + base::Days(1000);
  GetNetworkContext()->AddExpectCT(
      *domain, expiry, *enforce, GURL(*report_uri_str),
      net::NetworkAnonymizationKey(site, site), base::DoNothing());
}

void NetInternalsMessageHandler::OnExpectCTTestReport(
    const base::Value::List& list) {
  const std::string* callback_id = list[0].GetIfString();
  const std::string* report_uri_str = list[1].GetIfString();
  DCHECK(callback_id && report_uri_str);
  GURL report_uri(*report_uri_str);
  AllowJavascript();
  if (!report_uri.is_valid()) {
    ResolveJavascriptCallback(base::Value(*callback_id),
                              base::Value("invalid"));
    return;
  }

  GetNetworkContext()->SetExpectCTTestReport(
      report_uri,
      base::BindOnce(&NetInternalsMessageHandler::OnExpectCTTestReportCallback,
                     weak_factory_.GetWeakPtr(), *callback_id));
}

void NetInternalsMessageHandler::OnExpectCTTestReportCallback(
    const std::string& callback_id,
    bool success) {
  ResolveJavascriptCallback(
      base::Value(callback_id),
      success ? base::Value("success") : base::Value("failure"));
}

void NetInternalsMessageHandler::OnFlushSocketPools(
    const base::Value::List& list) {
  GetNetworkContext()->CloseAllConnections(base::NullCallback());
}

void NetInternalsMessageHandler::OnCloseIdleSockets(
    const base::Value::List& list) {
  GetNetworkContext()->CloseIdleConnections(base::NullCallback());
}

void NetInternalsMessageHandler::OnResolveHostDone(
    const std::string& callback_id,
    const net::ResolveErrorInfo& resolve_error_info,
    const absl::optional<net::AddressList>& resolved_addresses,
    const absl::optional<net::HostResolverEndpointResults>&
        endpoint_results_with_metadata,
    NetInternalsResolveHostClient* dns_lookup_client) {
  DCHECK_EQ(dns_lookup_clients_.count(dns_lookup_client), 1u);
  auto it = dns_lookup_clients_.find(dns_lookup_client);
  dns_lookup_clients_.erase(it);

  if (!resolved_addresses) {
    RejectJavascriptCallback(
        base::Value(callback_id),
        base::Value(net::ErrorToString(resolve_error_info.error)));
    return;
  }

  base::Value::Dict result;

  base::Value::List resolved_addresses_list =
      IPEndpointsToBaseList(resolved_addresses->endpoints());
  result.Set("resolved_addresses", std::move(resolved_addresses_list));

  base::Value::List endpoint_result_with_metadata =
      HostResolverEndpointResultsToBaseList(endpoint_results_with_metadata);
  result.Set("endpoint_results_with_metadata",
             std::move(endpoint_result_with_metadata));

  ResolveJavascriptCallback(base::Value(callback_id), std::move(result));
}

// g_network_context_for_testing is used only for testing.
network::mojom::NetworkContext* g_network_context_for_testing = nullptr;

network::mojom::NetworkContext*
NetInternalsMessageHandler::GetNetworkContext() {
  if (g_network_context_for_testing) {
    return g_network_context_for_testing;
  }
  return web_ui_->GetWebContents()
      ->GetBrowserContext()
      ->GetDefaultStoragePartition()
      ->GetNetworkContext();
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
//
// NetInternalsUI
//
////////////////////////////////////////////////////////////////////////////////

NetInternalsUI::NetInternalsUI(content::WebUI* web_ui)
    : WebUIController(web_ui) {
  web_ui->AddMessageHandler(
      std::make_unique<NetInternalsMessageHandler>(web_ui));

  // Set up the chrome://net-internals/ source.
  Profile* profile = Profile::FromWebUI(web_ui);
  content::WebUIDataSource::Add(profile, CreateNetInternalsHTMLSource());
}

// static
void NetInternalsUI::SetNetworkContextForTesting(
    network::mojom::NetworkContext* network_context_for_testing) {
  g_network_context_for_testing = network_context_for_testing;
}


text:
#include "../CommonInterfaces/CommonExampleInterface.h"
#include "../CommonInterfaces/CommonGUIHelperInterface.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btCollisionShape.h"
#include "BulletDynamics/Dynamics/btDiscreteDynamicsWorld.h"

#include "LinearMath/btTransform.h"
#include "LinearMath/btHashMap.h"

#include "../TinyRenderer/TinyRenderer.h"
#include "../OpenGLWindow/SimpleOpenGL3App.h"
#include <stdio.h>
#include "../ExampleBrowser/OpenGLGuiHelper.h"

class SW_And_OpenGLGuiHelper : public OpenGLGuiHelper
{

	btHashMap<btHashInt,TinyRenderObjectData*> m_swRenderObjects;
	btHashMap<btHashInt,int> m_swInstances;

	int m_swWidth;
	int m_swHeight;
	TGAImage m_rgbColorBuffer;

	b3AlignedObjectArray<float> m_depthBuffer;
	int m_textureHandle;
	unsigned char*	m_image;
	GLPrimitiveRenderer* m_primRenderer;

public:
    SW_And_OpenGLGuiHelper (CommonGraphicsApp* glApp, bool useOpenGL2, int swWidth, int swHeight, GLPrimitiveRenderer* primRenderer)
    :OpenGLGuiHelper(glApp,useOpenGL2),
    m_swWidth(swWidth),
    m_swHeight(swHeight),
	m_rgbColorBuffer(swWidth,swHeight,TGAImage::RGB),
	m_primRenderer(primRenderer)
    {

		m_depthBuffer.resize(swWidth*swHeight);
		CommonRenderInterface* render = getRenderInterface();
		m_image=new unsigned char[m_swWidth*m_swHeight*4];

		m_textureHandle = render->registerTexture(m_image,m_swWidth,m_swHeight);
    }

	void clearBuffers(TGAColor& clearColor)
	{
		for(int y=0;y<m_swHeight;++y)
		{
			for(int x=0;x<m_swWidth;++x)
			{
				m_rgbColorBuffer.set(x,y,clearColor);
				m_depthBuffer[x+y*m_swWidth] = -1e30f;
			}
		}

	}

	const TGAImage& getFrameBuffer() const
	{
		return m_rgbColorBuffer;
	}

    virtual ~SW_And_OpenGLGuiHelper()
    {
        for (int i=0;i<m_swRenderObjects.size();i++)
        {
            TinyRenderObjectData** d = m_swRenderObjects[i];
            if (d && *d)
            {
                delete *d;
            }
        }
    }

	virtual void createCollisionObjectGraphicsObject(btCollisionObject* obj,const btVector3& color)
	{
		OpenGLGuiHelper::createCollisionObjectGraphicsObject(obj,color);
		int colIndex = obj->getUserIndex();
		int shapeIndex = obj->getCollisionShape()->getUserIndex();

		if (colIndex>=0 && shapeIndex>=0)
		{
			m_swInstances.insert(colIndex,shapeIndex);
		}

	}

	virtual int	registerTexture(const unsigned char* texels, int width, int height)
	{
		return -1;
	}

	virtual int registerGraphicsShape(const float* vertices, int numvertices, const int* indices, int numIndices,int primitiveType, int textureId)
   	{
   	    int shapeIndex = OpenGLGuiHelper::registerGraphicsShape(vertices,numvertices,indices,numIndices,primitiveType, textureId);
   	    if (shapeIndex>=0)
        {
            TinyRenderObjectData* swObj = new TinyRenderObjectData(m_rgbColorBuffer,m_depthBuffer);
			float rgbaColor[4] = {1,1,1,1};
			swObj->registerMeshShape(vertices,numvertices,indices,numIndices,rgbaColor);
			//swObj->createCube(1,1,1);//MeshShape(vertices,numvertices,indices,numIndices);
            m_swRenderObjects.insert(shapeIndex,swObj);
        }
   	    return shapeIndex;
   	}

	virtual int registerGraphicsInstance(int shapeIndex, const float* position, const float* quaternion, const float* color, const float* scaling)
	{
	    int instanceId = OpenGLGuiHelper::registerGraphicsInstance(shapeIndex,position,quaternion,color,scaling);
	    return instanceId ;
	}

	virtual void createCollisionShapeGraphicsObject(btCollisionShape* collisionShape)
	{
	    OpenGLGuiHelper::createCollisionShapeGraphicsObject(collisionShape);
	}

	virtual void syncPhysicsToGraphics(const btDiscreteDynamicsWorld* rbWorld)
	{
	    OpenGLGuiHelper::syncPhysicsToGraphics(rbWorld);
	}

	virtual void render(const btDiscreteDynamicsWorld* rbWorld)
	{
	    OpenGLGuiHelper::render(rbWorld);

		//clear the color buffer
		TGAColor clearColor;
		clearColor.bgra[0] = 255;
		clearColor.bgra[1] = 255;
		clearColor.bgra[2] = 255;
		clearColor.bgra[3] = 255;

		clearBuffers(clearColor);

		ATTRIBUTE_ALIGNED16(btScalar  modelMat[16]);
		ATTRIBUTE_ALIGNED16(float viewMat[16]);
		ATTRIBUTE_ALIGNED16(float projMat[16]);

		CommonRenderInterface* render = getRenderInterface();

		render->getActiveCamera()->getCameraProjectionMatrix(projMat);
		render->getActiveCamera()->getCameraViewMatrix(viewMat);

		btVector3 lightDirWorld(-5,200,-40);
		switch (1)//app->getUpAxis())
		{
		case 1:
    			lightDirWorld = btVector3(-50.f,100,30);
    		break;
		case 2:
				lightDirWorld = btVector3(-50.f,30,100);
				break;
		default:{}
		};

		lightDirWorld.normalize();

		for (int i=0;i<rbWorld->getNumCollisionObjects();i++)
		{
			btCollisionObject* colObj = rbWorld->getCollisionObjectArray()[i];
			int colObjIndex = colObj->getUserIndex();
			int shapeIndex = colObj->getCollisionShape()->getUserIndex();
			if (colObjIndex>=0 && shapeIndex>=0)
			{

				TinyRenderObjectData* renderObj = 0;

				int* cptr = m_swInstances[colObjIndex];
				if (cptr)
				{
					int c = *cptr;
					TinyRenderObjectData** sptr = m_swRenderObjects[c];
					if (sptr)
					{
						renderObj = *sptr;
						//sync the object transform
						const btTransform& tr = colObj->getWorldTransform();
						tr.getOpenGLMatrix(modelMat);

						for (int i=0;i<4;i++)
						{
							for (int j=0;j<4;j++)
							{

								renderObj->m_projectionMatrix[i][j] = projMat[i+4*j];
								renderObj->m_modelMatrix[i][j] = modelMat[i+4*j];
								renderObj->m_viewMatrix[i][j] = viewMat[i+4*j];
							}
						}
                        renderObj->m_localScaling = colObj->getCollisionShape()->getLocalScaling();
                        renderObj->m_lightDirWorld = lightDirWorld;
                        renderObj->m_lightAmbientCoeff = 0.6;
                        renderObj->m_lightDiffuseCoeff = 0.35;
                        renderObj->m_lightSpecularCoeff = 0.05;
						TinyRenderer::renderObject(*renderObj);
					}
				}
			}
		}

		for(int y=0;y<m_swHeight;++y)
		{
			unsigned char*	pi=m_image+(y)*m_swWidth*3;
			for(int x=0;x<m_swWidth;++x)
			{

				const TGAColor& color = getFrameBuffer().get(x,y);
				pi[0] = color.bgra[2];
				pi[1] = color.bgra[1];
				pi[2] = color.bgra[0];
				pi+=3;

			}
		}
		render->activateTexture(m_textureHandle);
		render->updateTexture(m_textureHandle,m_image);

		static int counter=0;
		counter++;
		if ((counter&7)==0)
		{

			char filename[1024];
			sprintf(filename,"framebuf%d.tga",counter);
			getFrameBuffer().write_tga_file(filename,true);
		}
		float color[4] = {1,1,1,1};
		m_primRenderer->drawTexturedRect(0,0,m_swWidth, m_swHeight,color,0,0,1,1,true);

	}

    virtual void autogenerateGraphicsObjects(btDiscreteDynamicsWorld* rbWorld)
    {
        OpenGLGuiHelper::autogenerateGraphicsObjects(rbWorld);
    }

};

int main(int argc, char* argv[])
{

	SimpleOpenGL3App* app = new SimpleOpenGL3App("Standalone Example (Software Renderer, TinyRenderer)",1024,768,true);
	int textureWidth = 640;
    int textureHeight = 480;

	SW_And_OpenGLGuiHelper gui(app,false,textureWidth,textureHeight,app->m_primRenderer);

	CommonExampleOptions options(&gui);
	CommonExampleInterface*    example = StandaloneExampleCreateFunc(options);

	example->initPhysics();
	example->resetCamera();
	do
	{
		app->m_instancingRenderer->init();
        app->m_instancingRenderer->updateCamera(app->getUpAxis());

		example->stepSimulation(1./60.);

		example->renderScene();

		DrawGridData dg;
        dg.upAxis = app->getUpAxis();
		app->drawGrid(dg);
		app->swapBuffer();
	} while (!app->m_window->requestedExit());

	example->exitPhysics();
	delete example;
	delete app;
	return 0;
}

redpajama_set_name: RedPajamaGithub


text:
package org.talkingpuffin.ui

import _root_.scala.swing.{Action,MenuItem}
import java.awt.event.KeyEvent
import javax.swing.{JTable, JPopupMenu}
import javax.swing.KeyStroke.getKeyStroke
import twitter4j.Status
import org.talkingpuffin.apix.RichStatus._
import org.talkingpuffin.util.LinkExtractor

/**
 * Shows a menu of links, or launches the browser on the link if there is only one.
 */
abstract class OpenLinksAction(getSelectedStatus: => Option[Status], table: JTable,
    browse: String => Unit, title: String) extends Action(title) {

  def apply {
    def addMenuItem(menu: JPopupMenu, title: String, accelIndex: Int, action: => Unit) = {
      val a1 = Action(title) {action}
      a1.accelerator = Some(getKeyStroke(KeyEvent.VK_1 + accelIndex, 0))
      menu.add(new MenuItem(a1).peer)
    }

    def browseUrls(urls: List[String]) = urls.foreach(browse)

    def stripHttpProtocolString(url: String): String = {
      val prefix = "http://"
      if (url startsWith prefix) url substring prefix.length else url
    }

    getSelectedStatus match {
      case Some(status) =>
        val urls = LinkExtractor.getLinks(status.text, status.inReplyToStatusId, users, links, lists)

        if (urls.length == 1) {
          browse(urls(0).link)
        } else if (urls.length > 1) {
          val menu = new JPopupMenu
          var index = 0

          for (url <- urls) {
            addMenuItem(menu, stripHttpProtocolString(url.title), index, browse(url.link))
            index += 1
          }

          if (urls.length > 1) {
            val a1 = Action(if (urls.length == 2) "Both" else "All") {browseUrls(urls.map(_.link))}
            a1.accelerator = Some(getKeyStroke(KeyEvent.VK_A, 0))
            menu.add(new MenuItem(a1).peer)
          }
          val menuLoc = table.getCellRect(table.getSelectedRow, 0, true).getLocation
          menu.show(table, menuLoc.getX().asInstanceOf[Int], menuLoc.getY().asInstanceOf[Int])
        }
      case None =>
    }
  }

  def users: Boolean
  def links: Boolean
  def lists: Boolean
}

class OpenPageLinksAction(getSelectedStatus: => Option[Status], table: JTable,
    browse: String => Unit) extends OpenLinksAction(getSelectedStatus, table, browse,
    "Open Links…") {
  def users = false
  def links = true
  def lists = false
}

class OpenTwitterUserLinksAction(getSelectedStatus: => Option[Status], table: JTable,
    browse: String => Unit) extends OpenLinksAction(getSelectedStatus, table, browse,
    "Open User Links…") {
  def users = true
  def links = false
  def lists = false
}

class OpenTwitterUserListsAction(getSelectedStatus: => Option[Status], table: JTable,
    browse: String => Unit) extends OpenLinksAction(getSelectedStatus, table, browse,
    "Open User Lists…") {
  def users = false
  def links = false
  def lists = true
}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Generally localhost
$config['host'] = "localhost";
// Generally 27017
$config['port'] = 27017;
// The database you want to work on
$config['db'] = "itemsDB";
// Required if Mongo is running in auth mode
$config['user'] = "";
$config['pass'] = "";

/*
 * Defaults to FALSE. If FALSE, the program continues executing without waiting for a database response.
 * If TRUE, the program will wait for the database response and throw a MongoCursorException if the update did not succeed.
*/
$config['query_safety'] = TRUE;

//If running in auth mode and the user does not have global read/write then set this to true
$config['db_flag'] = TRUE;

//consider these config only if you want to store the session into mongoDB
//They will be used in MY_Session.php
$config['sess_use_mongo'] = TRUE;
$config['sess_collection_name']	= 'ci_sessions';


text:
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Orleans;
using Orleans.Hosting;
using Orleans.Providers;
using Orleans.TestingHost;
using Xunit;
using Xunit.Abstractions;

namespace Tester.StreamingTests
{
    [TestCategory("Functional"), TestCategory("Streaming"), TestCategory("StreamingCacheMiss")]
    public class MemoryStreamCacheMissTests : StreamingCacheMissTests
    {
        public MemoryStreamCacheMissTests(ITestOutputHelper output)
            : base(output)
        {
        }

        protected override void ConfigureTestCluster(TestClusterBuilder builder)
        {
            builder.AddSiloBuilderConfigurator<MySiloBuilderConfigurator>();
            builder.AddClientBuilderConfigurator<MyClientBuilderConfigurator>();
        }

        #region Configuration stuff

        private class MySiloBuilderConfigurator : ISiloConfigurator
        {
            public void Configure(ISiloBuilder hostBuilder)
            {
                hostBuilder
                    .AddMemoryGrainStorageAsDefault()
                    .AddMemoryGrainStorage("PubSubStore")
                    .AddMemoryStreams<DefaultMemoryMessageBodySerializer>(StreamProviderName, b =>
                    {
                        b.ConfigureCacheEviction(ob => ob.Configure(options =>
                        {
                            options.DataMaxAgeInCache = TimeSpan.FromSeconds(5);
                            options.DataMinTimeInCache = TimeSpan.FromSeconds(0);
                        }));
                    })
                    .AddStreamFilter<CustomStreamFilter>(StreamProviderName);
            }
        }

        private class MyClientBuilderConfigurator : IClientBuilderConfigurator
        {
            public void Configure(IConfiguration configuration, IClientBuilder clientBuilder)
            {
                clientBuilder
                    .AddMemoryStreams<DefaultMemoryMessageBodySerializer>(StreamProviderName);
            }
        }

        #endregion

    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/nullListHeader"
	android:layout_width="fill_parent"
	android:layout_height="52dp"
	android:minHeight="52dp"
	android:orientation="horizontal"
	android:gravity="center_vertical"
	android:background="#ffffffff"
>
	<TextView
		android:id="@+id/label"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:textColor="#ffffff"
		android:gravity="left"
		android:paddingLeft="10dp"
		android:textSize="13dp"
	/>

</LinearLayout>


text:
import {bootstrap} from 'angular2/angular2';
import {AlertComponent} from 'angular2-ui';

console.log('1 + 2 is ', 3);
bootstrap(AlertComponent);


text:
@interface OCMExceptionReturnValueProvider : OCMReturnValueProvider
{
}

@end


text:
namespace TraktApiSharp.Tests.Objects.Get.Watched.Json.Reader
{
    using FluentAssertions;
    using Newtonsoft.Json;
    using System;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using Traits;
    using TraktApiSharp.Objects.Get.Watched.Json.Reader;
    using Xunit;

    [Category("Objects.Get.Watched.JsonReader")]
    public partial class WatchedShowEpisodeArrayJsonReader_Tests
    {
        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Empty_Array()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_EMPTY_ARRAY))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.BeEmpty();
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Complete()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_COMPLETE))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Incomplete_1()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_INCOMPLETE_1))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().BeNull();
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Incomplete_2()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_INCOMPLETE_2))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().BeNull();
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Incomplete_3()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_INCOMPLETE_3))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().BeNull();
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Incomplete_4()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_INCOMPLETE_4))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().BeNull();
                watchedShowEpisodes[0].LastWatchedAt.Should().BeNull();

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Incomplete_5()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_INCOMPLETE_5))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().BeNull();
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().BeNull();

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Incomplete_6()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_INCOMPLETE_6))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().BeNull();
                watchedShowEpisodes[2].Plays.Should().BeNull();
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_1()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_NOT_VALID_1))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().BeNull();
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_2()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_NOT_VALID_2))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().BeNull();
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_3()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_NOT_VALID_3))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().Be(1);
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().Be(1);
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().BeNull();
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_4()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(JSON_NOT_VALID_4))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktWatchedShowEpisodes = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktWatchedShowEpisodes.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3);

                var watchedShowEpisodes = traktWatchedShowEpisodes.ToArray();

                watchedShowEpisodes[0].Should().NotBeNull();
                watchedShowEpisodes[0].Number.Should().BeNull();
                watchedShowEpisodes[0].Plays.Should().Be(1);
                watchedShowEpisodes[0].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[1].Should().NotBeNull();
                watchedShowEpisodes[1].Number.Should().Be(2);
                watchedShowEpisodes[1].Plays.Should().BeNull();
                watchedShowEpisodes[1].LastWatchedAt.Should().Be(DateTime.Parse("2014-10-12T17:00:54.000Z").ToUniversalTime());

                watchedShowEpisodes[2].Should().NotBeNull();
                watchedShowEpisodes[2].Number.Should().Be(3);
                watchedShowEpisodes[2].Plays.Should().Be(1);
                watchedShowEpisodes[2].LastWatchedAt.Should().BeNull();
            }
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Null()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            var traktEpisodeWatchedProgress = await traktJsonReader.ReadArrayAsync(default(JsonTextReader));
            traktEpisodeWatchedProgress.Should().BeNull();
        }

        [Fact]
        public async Task Test_WatchedShowEpisodeArrayJsonReader_ReadArray_From_JsonReader_Empty()
        {
            var traktJsonReader = new WatchedShowEpisodeArrayJsonReader();

            using (var reader = new StringReader(string.Empty))
            using (var jsonReader = new JsonTextReader(reader))
            {
                var traktEpisodeWatchedProgress = await traktJsonReader.ReadArrayAsync(jsonReader);
                traktEpisodeWatchedProgress.Should().BeNull();
            }
        }
    }
}


text: require File.join(File.dirname(__FILE__), 'compressed_cookie')


text:
package com.psc.eStore.util;

import com.psc.eStore.domain.User;
import com.psc.eStore.domain.UserAddress;
import org.jasypt.util.password.BasicPasswordEncryptor;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import java.util.List;

public class UserUtil {

    public static String encryptPassword(String password) {
        BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
        return passwordEncryptor.encryptPassword(password);
    }

    public static boolean checkPassword(String password, String encryptedPassword) {
        BasicPasswordEncryptor passwordEncryptor = new BasicPasswordEncryptor();
        return passwordEncryptor.checkPassword(password, encryptedPassword);
    }

    public static String toJSONUser(User user) {
        JSONObject userJSON = new JSONObject();
        userJSON.put("user_name", user.getUserName());
        userJSON.put("email", user.getEmailAddress());
        userJSON.put("mobile", user.getMobile());
        userJSON.put("regID", user.getRegistrationId());
        System.out.println("userJSON:" + userJSON.toJSONString());
        return userJSON.toJSONString();
    }

    public static String toJSONUserAddresses(List<UserAddress> addresses) {
        JSONArray addressesJSON = new JSONArray();
        for (UserAddress address : addresses) {
            JSONObject addressJSON = new JSONObject();
            addressJSON.put("user_name", address.getUserName());
            addressJSON.put("address_id", address.getAddressId());
            addressJSON.put("address1", address.getAddress1());
            addressJSON.put("address2", address.getAddress2());
            addressJSON.put("city", address.getCity());
            addressJSON.put("state", address.getState());
            addressJSON.put("country", address.getCountry());
            addressJSON.put("pin_code", address.getPinCode());
            addressesJSON.add(addressJSON);
        }
        System.out.println("addressesJSON:" + addressesJSON.toJSONString());
        return addressesJSON.toJSONString();
    }
}


text:
package org.elasticsearch.xpack.core.watcher.execution;

import org.elasticsearch.core.Nullable;
import org.elasticsearch.xcontent.ParseField;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.watcher.actions.ActionWrapperResult;
import org.elasticsearch.xpack.core.watcher.condition.Condition;
import org.elasticsearch.xpack.core.watcher.input.Input;
import org.elasticsearch.xpack.core.watcher.support.WatcherDateTimeUtils;
import org.elasticsearch.xpack.core.watcher.transform.Transform;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.Map;

public class WatchExecutionResult implements ToXContentObject {

    private final ZonedDateTime executionTime;
    private final long executionDurationMs;
    @Nullable
    private final Input.Result inputResult;
    @Nullable
    private final Condition.Result conditionResult;
    @Nullable
    private final Transform.Result transformResult;
    private final Map<String, ActionWrapperResult> actionsResults;

    public WatchExecutionResult(WatchExecutionContext context, long executionDurationMs) {
        this(
            context.executionTime(),
            executionDurationMs,
            context.inputResult(),
            context.conditionResult(),
            context.transformResult(),
            context.actionsResults()
        );
    }

    private WatchExecutionResult(
        ZonedDateTime executionTime,
        long executionDurationMs,
        Input.Result inputResult,
        Condition.Result conditionResult,
        @Nullable Transform.Result transformResult,
        Map<String, ActionWrapperResult> actionsResults
    ) {
        this.executionTime = executionTime;
        this.inputResult = inputResult;
        this.conditionResult = conditionResult;
        this.transformResult = transformResult;
        this.actionsResults = actionsResults;
        this.executionDurationMs = executionDurationMs;
    }

    public ZonedDateTime executionTime() {
        return executionTime;
    }

    public long executionDurationMs() {
        return executionDurationMs;
    }

    public Input.Result inputResult() {
        return inputResult;
    }

    public Condition.Result conditionResult() {
        return conditionResult;
    }

    public Transform.Result transformResult() {
        return transformResult;
    }

    public Map<String, ActionWrapperResult> actionsResults() {
        return actionsResults;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();

        WatcherDateTimeUtils.writeDate(Field.EXECUTION_TIME.getPreferredName(), builder, executionTime);
        builder.field(Field.EXECUTION_DURATION.getPreferredName(), executionDurationMs);

        if (inputResult != null) {
            builder.field(Field.INPUT.getPreferredName(), inputResult, params);
        }
        if (conditionResult != null) {
            builder.field(Field.CONDITION.getPreferredName(), conditionResult, params);
        }
        if (transformResult != null) {
            builder.field(Transform.TRANSFORM.getPreferredName(), transformResult, params);
        }
        builder.startArray(Field.ACTIONS.getPreferredName());
        for (ActionWrapperResult result : actionsResults.values()) {
            result.toXContent(builder, params);
        }
        builder.endArray();
        builder.endObject();
        return builder;
    }

    public interface Field {
        ParseField EXECUTION_TIME = new ParseField("execution_time");
        ParseField EXECUTION_DURATION = new ParseField("execution_duration");
        ParseField INPUT = new ParseField("input");
        ParseField CONDITION = new ParseField("condition");
        ParseField ACTIONS = new ParseField("actions");
        ParseField TYPE = new ParseField("type");
    }
}


text:
"""
Setup script for pyqode.rst
"""
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
from pyqode.rst import __version__

class PyTest(TestCommand):
    user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]

    def initialize_options(self):
        TestCommand.initialize_options(self)
        self.pytest_args = []

    def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import pytest
        if self.pytest_args:
            self.pytest_args = self.pytest_args.replace('"', '').split(' ')
        else:
            self.pytest_args = []
        print('running test command: py.test "%s"' % ' '.join(
            self.pytest_args))
        errno = pytest.main(self.pytest_args)
        sys.exit(errno)

cmdclass = {'test': PyTest}

DESCRIPTION = 'Adds RestructuredText support to pyqode.core'

def readme():
    if 'bdist_deb' in sys.argv:
        return DESCRIPTION
    return str(open('README.rst').read())

setup(
    name='pyqode.rst',
    namespace_packages=['pyqode'],
    version=__version__,
    packages=[p for p in find_packages() if 'test' not in p],
    keywords=['RestructuredText', 'editor', 'pyqode'],
    url='https://github.com/pyQode/pyqode.rst',
    license='MIT',
    author='Colin Duquesnoy',
    author_email='colin.duquesnoy@gmail.com',
    description=DESCRIPTION,
    long_description=readme(),
    install_requires=['pyqode.core', 'restructuredtext_lint', 'docutils'],
    tests_require=['pytest-cov', 'pytest-pep8', 'pytest'],
    cmdclass=cmdclass,
    classifiers=[
        'Development Status :: 1 - Planning',
        'Environment :: X11 Applications :: Qt',
        'Environment :: Win32 (MS Windows)',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.2',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Widget Sets',
        'Topic :: Text Editors :: Integrated Development Environments (IDE)'])


text:
#ifndef __BASE_CCREF_H__
#define __BASE_CCREF_H__

#include "platform/CCPlatformMacros.h"
#include "base/ccConfig.h"

#define CC_REF_LEAK_DETECTION 0

/**
 * @addtogroup base
 * @{
 */
NS_CC_BEGIN

class Ref;

/**
  * Interface that defines how to clone an Ref.
  * @lua NA
  * @js NA
  */
class CC_DLL Clonable
{
public:
    /** Returns a copy of the Ref. */
    virtual Clonable* clone() const = 0;

    /**
     * @js NA
     * @lua NA
     */
    virtual ~Clonable() {};
};

/**
 * Ref is used for reference count management. If a class inherits from Ref,
 * then it is easy to be shared in different places.
 * @js NA
 */
class CC_DLL Ref
{
public:
    /**
     * Retains the ownership.
     *
     * This increases the Ref's reference count.
     *
     * @see release, autorelease
     * @js NA
     */
    void retain();

    /**
     * Releases the ownership immediately.
     *
     * This decrements the Ref's reference count.
     *
     * If the reference count reaches 0 after the decrement, this Ref is
     * destructed.
     *
     * @see retain, autorelease
     * @js NA
     */
    void release();

    /**
     * Releases the ownership sometime soon automatically.
     *
     * This decrements the Ref's reference count at the end of current
     * autorelease pool block.
     *
     * If the reference count reaches 0 after the decrement, this Ref is
     * destructed.
     *
     * @returns The Ref itself.
     *
     * @see AutoreleasePool, retain, release
     * @js NA
     * @lua NA
     */
    Ref* autorelease();

    /**
     * Returns the Ref's current reference count.
     *
     * @returns The Ref's reference count.
     * @js NA
     */
    unsigned int getReferenceCount() const;

protected:
    /**
     * Constructor
     *
     * The Ref's reference count is 1 after construction.
     * @js NA
     */
    Ref();

public:
    /**
     * Destructor
     *
     * @js NA
     * @lua NA
     */
    virtual ~Ref();

protected:
    /// count of references
    unsigned int _referenceCount;

    friend class AutoreleasePool;

#if CC_ENABLE_SCRIPT_BINDING
public:
    /// object id, ScriptSupport need public _ID
    unsigned int        _ID;
    /// Lua reference id
    int                 _luaID;

    /**
     When true, it means that the object was already rooted.
     */
    bool _rooted;
#endif

    // Memory leak diagnostic data (only included when CC_REF_LEAK_DETECTION is defined and its value isn't zero)
#if CC_REF_LEAK_DETECTION
public:
    static void printLeaks();
#endif
};

class Node;

typedef void (Ref::*SEL_CallFunc)();
typedef void (Ref::*SEL_CallFuncN)(Node*);
typedef void (Ref::*SEL_CallFuncND)(Node*, void*);
typedef void (Ref::*SEL_CallFuncO)(Ref*);
typedef void (Ref::*SEL_MenuHandler)(Ref*);
typedef void (Ref::*SEL_SCHEDULE)(float);

#define CC_CALLFUNC_SELECTOR(_SELECTOR) static_cast<cocos2d::SEL_CallFunc>(&_SELECTOR)
#define CC_CALLFUNCN_SELECTOR(_SELECTOR) static_cast<cocos2d::SEL_CallFuncN>(&_SELECTOR)
#define CC_CALLFUNCND_SELECTOR(_SELECTOR) static_cast<cocos2d::SEL_CallFuncND>(&_SELECTOR)
#define CC_CALLFUNCO_SELECTOR(_SELECTOR) static_cast<cocos2d::SEL_CallFuncO>(&_SELECTOR)
#define CC_MENU_SELECTOR(_SELECTOR) static_cast<cocos2d::SEL_MenuHandler>(&_SELECTOR)
#define CC_SCHEDULE_SELECTOR(_SELECTOR) static_cast<cocos2d::SEL_SCHEDULE>(&_SELECTOR)

// Deprecated
#define callfunc_selector(_SELECTOR) CC_CALLFUNC_SELECTOR(_SELECTOR)
#define callfuncN_selector(_SELECTOR) CC_CALLFUNCN_SELECTOR(_SELECTOR)
#define callfuncND_selector(_SELECTOR) CC_CALLFUNCND_SELECTOR(_SELECTOR)
#define callfuncO_selector(_SELECTOR) CC_CALLFUNCO_SELECTOR(_SELECTOR)
#define menu_selector(_SELECTOR) CC_MENU_SELECTOR(_SELECTOR)
#define schedule_selector(_SELECTOR) CC_SCHEDULE_SELECTOR(_SELECTOR)

NS_CC_END
// end of base group
/** @} */

#endif // __BASE_CCREF_H__


text:
#include <aws/glue/model/WorkflowRunStatistics.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Glue
{
namespace Model
{

WorkflowRunStatistics::WorkflowRunStatistics() :
    m_totalActions(0),
    m_totalActionsHasBeenSet(false),
    m_timeoutActions(0),
    m_timeoutActionsHasBeenSet(false),
    m_failedActions(0),
    m_failedActionsHasBeenSet(false),
    m_stoppedActions(0),
    m_stoppedActionsHasBeenSet(false),
    m_succeededActions(0),
    m_succeededActionsHasBeenSet(false),
    m_runningActions(0),
    m_runningActionsHasBeenSet(false),
    m_erroredActions(0),
    m_erroredActionsHasBeenSet(false),
    m_waitingActions(0),
    m_waitingActionsHasBeenSet(false)
{
}

WorkflowRunStatistics::WorkflowRunStatistics(JsonView jsonValue) :
    m_totalActions(0),
    m_totalActionsHasBeenSet(false),
    m_timeoutActions(0),
    m_timeoutActionsHasBeenSet(false),
    m_failedActions(0),
    m_failedActionsHasBeenSet(false),
    m_stoppedActions(0),
    m_stoppedActionsHasBeenSet(false),
    m_succeededActions(0),
    m_succeededActionsHasBeenSet(false),
    m_runningActions(0),
    m_runningActionsHasBeenSet(false),
    m_erroredActions(0),
    m_erroredActionsHasBeenSet(false),
    m_waitingActions(0),
    m_waitingActionsHasBeenSet(false)
{
  *this = jsonValue;
}

WorkflowRunStatistics& WorkflowRunStatistics::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("TotalActions"))
  {
    m_totalActions = jsonValue.GetInteger("TotalActions");

    m_totalActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("TimeoutActions"))
  {
    m_timeoutActions = jsonValue.GetInteger("TimeoutActions");

    m_timeoutActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FailedActions"))
  {
    m_failedActions = jsonValue.GetInteger("FailedActions");

    m_failedActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("StoppedActions"))
  {
    m_stoppedActions = jsonValue.GetInteger("StoppedActions");

    m_stoppedActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SucceededActions"))
  {
    m_succeededActions = jsonValue.GetInteger("SucceededActions");

    m_succeededActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("RunningActions"))
  {
    m_runningActions = jsonValue.GetInteger("RunningActions");

    m_runningActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ErroredActions"))
  {
    m_erroredActions = jsonValue.GetInteger("ErroredActions");

    m_erroredActionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("WaitingActions"))
  {
    m_waitingActions = jsonValue.GetInteger("WaitingActions");

    m_waitingActionsHasBeenSet = true;
  }

  return *this;
}

JsonValue WorkflowRunStatistics::Jsonize() const
{
  JsonValue payload;

  if(m_totalActionsHasBeenSet)
  {
   payload.WithInteger("TotalActions", m_totalActions);

  }

  if(m_timeoutActionsHasBeenSet)
  {
   payload.WithInteger("TimeoutActions", m_timeoutActions);

  }

  if(m_failedActionsHasBeenSet)
  {
   payload.WithInteger("FailedActions", m_failedActions);

  }

  if(m_stoppedActionsHasBeenSet)
  {
   payload.WithInteger("StoppedActions", m_stoppedActions);

  }

  if(m_succeededActionsHasBeenSet)
  {
   payload.WithInteger("SucceededActions", m_succeededActions);

  }

  if(m_runningActionsHasBeenSet)
  {
   payload.WithInteger("RunningActions", m_runningActions);

  }

  if(m_erroredActionsHasBeenSet)
  {
   payload.WithInteger("ErroredActions", m_erroredActions);

  }

  if(m_waitingActionsHasBeenSet)
  {
   payload.WithInteger("WaitingActions", m_waitingActions);

  }

  return payload;
}

} // namespace Model
} // namespace Glue
} // namespace Aws


text:
class HourlyMagnetDownloadEnqueueWorker
  include Sidekiq::Worker
  include Sidetiq::Schedulable

  sidekiq_options queue: :hourly_magnet_download_enqueue

  recurrence backfill: true do
    hourly
  end

  TIMEOUT = 1.minute.to_i

  def perform
    Timeout.timeout(TIMEOUT) do
      if Sidekiq::Stats.new.queues['magnet_download'] == 0 &&
         Sidekiq::Stats.new.queues['video_directory_import'] < 10
        Magnet.enqueue_download!
      end
    end
  end
end


text:
<?php
include_once('../connect.php');

$mysqli = dbConnect();

$selectvalue =  $_GET['svalue'];

echo '
Client#	Subject	Category	Sub Category	Assigned	Status	';
$sql = "select
	t.id as ticketid,
	t.clientid,
	t.comments,
	t.subject,
	(select c.name from categories c where c.id = t.categoryid) as category,
	(select sc.name from subcategories sc where sc.id = t.subcategoryid) as subcategory,
	t.assigneduser,
	(select ts.status
	 	from ticketstatus ts
	 		where ts.ticketid = t.id
			and ts.statusdate = (select max(ts2.statusdate)
		                            	from ticketstatus ts2
	                            		where ts.ticketid = ts2.ticketid)) as status
		from tickets t";

if ($selectvalue != '') $sql .= " where clientid =" . $selectvalue;
$sql .= " order by opendate desc limit 5";

$result = $mysqli->query($sql);
$mysqli->close();

if ($result->num_rows > 0) {
	// output data of each row
	//echo '
Category	Subcategory		';
	while($row = $result->fetch_assoc()) {
	    #$comments = $row['comments'];
	    #$comments = (strlen($comments) > 340) ? substr($comments, 0, 340) . '...' : $comments;
	    if ($row['status'] == 'Closed') { $class = "btn btn-danger";}
	    elseif ($row['status'] == 'Open') { $class = "btn btn-success";}
	    elseif ($row['status'] == 'Waiting on Client') {$class = "btn btn-info";}
	    else { $class = "btn btn-warning"; }
       		echo '

	           			' .$row['clientid'] .'
	           			' . $row['subject']  .'
	           			' . $row['category']  .'
	           			' . $row['subcategory']  .'
	           			' . $row['assigneduser'] . '
	           			<form method="POST" action="./tickets.php">
	           				<input name="ticketId" value="' . $row['ticketid'] . '" type="text" hidden />
	           				<button type="submit" class="'.$class .'">'.$row['status'] .'</button></form>

';
	}
	//echo '
';
} else {
    echo "Enter ClientId to view recent tickets";
}
echo '
';

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:support="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/menu_finish"
        android:title="finalizar"
        android:icon="@drawable/ic_menu_mark"
        support:showAsAction="ifRoom" />
</menu>


text:
class AddStartupScriptToProviderAccounts < ActiveRecord::Migration
  def self.up
	add_column :provider_accounts, :startup_script, :text
  end

  def self.down
	remove_column :provider_accounts, :startup_script
  end
end


text:
namespace blink {

class FontTableMatcher;

class FontUniqueNameLookup {
  USING_FAST_MALLOC(FontUniqueNameLookup);

 public:
  // Factory function to construct a platform specific font unique name lookup
  // instance. Client must not use this directly as it is thread
  // specific. Retrieve it from FontGlobalContext instead.
  static std::unique_ptr<FontUniqueNameLookup> GetPlatformUniqueNameLookup();

  virtual sk_sp<SkTypeface> MatchUniqueName(const String& font_unique_name) = 0;

  FontUniqueNameLookup(const FontUniqueNameLookup&) = delete;
  FontUniqueNameLookup& operator=(const FontUniqueNameLookup&) = delete;
  virtual ~FontUniqueNameLookup() = default;

  // Below: Methods for asynchronously retrieving the FontUniqueNameLookup
  // table. Currently needed on Windows, on other platforms the implementation
  // is synchronous.

  // Determines whether fonts can be uniquely matched synchronously.
  virtual bool IsFontUniqueNameLookupReadyForSyncLookup() { return true; }

  // If fonts cannot be uniquely matched synchronously, send a Mojo IPC call to
  // prepare the lookup table, and wait for the callback. Once the callback has
  // been called, IsFontUniqueNameLookupReadyForSyncLookup() will become true.
  // PrepareFontUniqueNameLookup() must not be called if
  // IsFontUniqueNameLookupReadyForSyncLookup() is true already.
  using NotifyFontUniqueNameLookupReady = base::OnceCallback<void()>;
  virtual void PrepareFontUniqueNameLookup(
      NotifyFontUniqueNameLookupReady callback) {
    NOTREACHED();
  }

  // Performs any global initialization needed for this renderer. This is called
  // early in renderer startup, as opposed to PrepareFontUniqueNameLookup()
  // which is called when sync lookup is first needed.
  virtual void Init() {}

 protected:
  FontUniqueNameLookup();

  // Windows and Android share the concept of connecting to a Mojo service for
  // retrieving a ReadOnlySharedMemoryRegion with the lookup table in it.
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  std::unique_ptr<FontTableMatcher> font_table_matcher_;
#endif
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_FONT_UNIQUE_NAME_LOOKUP_H_


text:
package com.tkhoon.framework;

import com.tkhoon.framework.helper.DBHelper;
import com.tkhoon.framework.helper.SQLHelper;
import com.tkhoon.framework.util.CastUtil;
import com.tkhoon.framework.util.ObjectUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataSet {

    // 查询单条数据,并转为对象
    public static <T> T select(Class<T> cls, String condition, Object... params) {
        String sql = SQLHelper.generateSelectSQL(cls, condition, "", params);
        return DBHelper.queryBean(cls, sql);
    }

    // 查询多条数据,并转为列表
    public static <T> List<T> selectList(Class<T> cls, String condition, String sort, Object... params) {
        String sql = SQLHelper.generateSelectSQL(cls, condition, sort, params);
        return DBHelper.queryBeanList(cls, sql);
    }

    // 插入一条数据
    public static boolean insert(Class<?> cls, Map<String, Object> fieldMap) {
        String sql = SQLHelper.generateInsertSQL(cls, fieldMap);
        int rows = DBHelper.update(sql);
        return rows > 0;
    }

    // 更新相关数据
    public static boolean update(Class<?> cls, Map<String, Object> fieldMap, String condition, Object... params) {
        String sql = SQLHelper.generateUpdateSQL(cls, fieldMap, condition, params);
        int rows = DBHelper.update(sql);
        return rows > 0;
    }

    // 删除相关数据
    public static boolean delete(Class<?> cls, String condition, Object... params) {
        String sql = SQLHelper.generateDeleteSQL(cls, condition, params);
        int rows = DBHelper.update(sql);
        return rows > 0;
    }

    // 查询数据条数
    public static int selectCount(Class<?> cls, String condition, Object... params) {
        String sql = SQLHelper.generateSelectSQLForCount(cls, condition, params);
        return DBHelper.queryCount(cls, sql);
    }

    // 查询多条数据,并转为列表(分页方式)
    public static <T> List<T> selectListForPager(int pageNumber, int pageSize, Class<T> cls, String condition, String sort, Object... params) {
        String sql = SQLHelper.generateSelectSQLForPager(pageNumber, pageSize, cls, condition, sort, params);
        return DBHelper.queryBeanList(cls, sql);
    }

    // 查询多条数据,并转为映射
    public static <T> Map<Long, T> selectMap(Class<T> cls, String condition, Object... params) {
        Map<Long, T> map = new HashMap<Long, T>();
        List<T> list = selectList(cls, condition, "", params);
        for (T obj : list) {
            Long id = CastUtil.castLong(ObjectUtil.getFieldValue(obj, "id"));
            map.put(id, obj);
        }
        return map;
    }
}


text:
package com.arangodb.internal.net;

import java.io.IOException;

/**
 * @author Mark Vollmary
 */
public interface Host {

    HostDescription getDescription();

    Connection connection();

    void closeOnError();

    void close() throws IOException;

    void setMarkforDeletion(boolean markforDeletion);

    boolean isMarkforDeletion();

    void setJwt(String jwt);

}


text:
package main

import (
	"crypto/tls"
	"crypto/x509"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"

	_ "net/http/pprof"

	"github.com/fiorix/go-smpp/smpp"
	"github.com/go-web/httplog"

	"github.com/fiorix/sms-api-server/apiserver"
)

// Version of this server.
var Version = "v1.2.2"

type Opts struct {
	ListenAddr        string
	APIPrefix         string
	PublicDir         string
	Log               bool
	LogTS             bool
	CAFile            string
	CertFile          string
	KeyFile           string
	SMPPAddr          string
	ClientTLS         bool
	ClientTLSInsecure bool
	ShowVersion       bool
}

func main() {
	o := ParseOpts()
	if o.ShowVersion {
		fmt.Println("sms-api-server", Version)
		os.Exit(0)
	}
	tx := &smpp.Transceiver{
		Addr:   o.SMPPAddr,
		User:   os.Getenv("SMPP_USER"),
		Passwd: os.Getenv("SMPP_PASSWD"),
	}
	exit := make(chan os.Signal, 1)
	signal.Notify(exit, os.Interrupt, os.Kill)
	go func() {
		<-exit
		tx.Close()
		os.Exit(0)
	}()
	if o.ClientTLS {
		host, _, _ := net.SplitHostPort(tx.Addr)
		tx.TLS = &tls.Config{
			ServerName: host,
		}
		if o.ClientTLSInsecure {
			tx.TLS.InsecureSkipVerify = true
		}
	}
	api := &apiserver.Handler{Prefix: o.APIPrefix, Tx: tx}
	conn := api.Register(http.DefaultServeMux)
	go func() {
		for c := range conn {
			m := fmt.Sprintf("SMPP connection status to %s: %s",
				o.SMPPAddr, c.Status())
			if err := c.Error(); err != nil {
				m = fmt.Sprintf("%s (%v)", m, err)
			}
			log.Println(m)
		}
	}()
	if o.PublicDir != "" {
		fs := http.FileServer(http.Dir(o.PublicDir))
		http.Handle("/", http.StripPrefix(o.APIPrefix, fs))
	}
	mux := http.Handler(http.DefaultServeMux)
	if o.Log {
		var l *log.Logger
		if o.LogTS {
			l = log.New(os.Stderr, "", log.LstdFlags)
		} else {
			l = log.New(os.Stderr, "", 0)
		}
		mux = httplog.ApacheCombinedFormat(l)(mux.ServeHTTP)
	}
	err := ListenAndServe(o, mux)
	if err != nil {
		log.Fatal(err)
	}
}

func ParseOpts() *Opts {
	o := &Opts{ListenAddr: ":8080", SMPPAddr: "localhost:2775", LogTS: true}
	flag.StringVar(&o.ListenAddr, "http", o.ListenAddr, "host:port to listen on for http or https")
	flag.StringVar(&o.APIPrefix, "prefix", o.APIPrefix, "prefix for http(s) endpoints")
	flag.StringVar(&o.PublicDir, "public", o.PublicDir, "public dir to serve under \"/\", optional")
	flag.BoolVar(&o.Log, "log", o.Log, "log http requests")
	flag.BoolVar(&o.LogTS, "log-timestamp", o.LogTS, "add timestamp to logs")
	flag.StringVar(&o.CAFile, "ca", o.CAFile, "x509 CA certificate file (for client auth)")
	flag.StringVar(&o.CertFile, "cert", o.CertFile, "x509 certificate file for https server")
	flag.StringVar(&o.KeyFile, "key", o.KeyFile, "x509 key file for https server")
	flag.StringVar(&o.SMPPAddr, "smpp", o.SMPPAddr, "host:port of the SMSC to connect to via SMPP v3.4")
	flag.BoolVar(&o.ClientTLS, "tls", o.ClientTLS, "connect to SMSC using TLS")
	flag.BoolVar(&o.ClientTLSInsecure, "precaire", o.ClientTLSInsecure, "disable TLS checks for client connection")
	flag.BoolVar(&o.ShowVersion, "version", o.ShowVersion, "show version and exit")
	flag.Usage = func() {
		fmt.Printf("Usage: [env] %s [options]\n", os.Args[0])
		fmt.Printf("Environment variables:\n")
		fmt.Printf(" SMPP_USER: username for smpp client connection\n")
		fmt.Printf(" SMPP_PASSWD: password for smpp client connection\n")
		fmt.Printf("Options:\n")
		flag.PrintDefaults()
	}
	flag.Parse()
	return o
}

func ListenAndServe(o *Opts, f http.Handler) error {
	s := &http.Server{Addr: o.ListenAddr, Handler: f}
	if o.CertFile == "" || o.KeyFile == "" {
		return s.ListenAndServe()
	}
	if o.CAFile != "" {
		b, err := ioutil.ReadFile(o.CAFile)
		if err != nil {
			return err
		}
		cp := x509.NewCertPool()
		cp.AppendCertsFromPEM(b)
		s.TLSConfig = &tls.Config{
			ClientCAs:  cp,
			ClientAuth: tls.RequireAndVerifyClientCert,
		}
	}
	return s.ListenAndServeTLS(o.CertFile, o.KeyFile)
}


text:
layout: post
date: '2016-06-05'
title: "Demetrios Wedding Dress Style 3204 Sleeveless Chapel Train Mermaid/Trumpet"
category: Demetrios
tags: [Demetrios,Mermaid/Trumpet,Strapless,Chapel Train,Sleeveless]
---
### Demetrios Wedding Dress Style 3204
Just **$269.99**
###   Sleeveless Chapel Train Mermaid/Trumpet

BRANDS	Demetrios

Silhouette	Mermaid/Trumpet

Neckline	Strapless

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/demetrios/17681-demetrios-style-3204.html](https://www.readybrides.com/en/demetrios/17681-demetrios-style-3204.html)


text:
<?php

namespace Inisiatif\NumberGenerator\Exceptions;

class NumberGeneratorException extends \Exception
{

}


text:
<?php

namespace Ben\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Httpfoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use JMS\SecurityExtraBundle\Annotation\Secure;

use Ben\UserBundle\Entity\User;
use Ben\UserBundle\Entity\Group;
use Ben\UserBundle\Form\GroupType;
use Ben\AssociationBundle\Pagination\Paginator;

/**
 * Group controller.
 *
 */
class GroupController extends Controller
{
    /**
     * Lists all Group entities.
     * @Secure(roles="ROLE_MANAGER")
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('BenUserBundle:Group')->findAll();
        $entity = new Group();
        $form   = $this->createForm(new GroupType(), $entity);

        return $this->render('BenUserBundle:Group:index.html.twig', array(
            'entities' => $entities,
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Group entity.
     * @Secure(roles="ROLE_MANAGER")
     */
    public function showAction(Request $request, Group $group, $perPage)
    {
        $em = $this->getDoctrine()->getManager();
        if($request->getMethod()==='POST') $searchParam = $request->get('searchParam');
        else $searchParam['page'] = 1;
        $searchParam['perPage'] = $perPage;
        $searchParam['group'] = $group->getId();
        $entities = $em->getRepository('BenUserBundle:user')->search($searchParam);
        $pagination = (new Paginator())->setItems(count($entities), $searchParam['perPage'])->setPage($searchParam['page'])->toArray();
        return $this->render('BenUserBundle:Group:show.html.twig', array(
                    'group' => $group,
                    'entities' => $entities,
                    'pagination' => $pagination,
                    ));
    }

    /**
     * Creates a new Group entity.
     * @Secure(roles="ROLE_MANAGER")
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new Group();
        $form = $this->createForm(new GroupType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity->getImage()->upload();
            $em->persist($entity);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'ben.flash.success.group.created');
            return $this->redirect($this->generateUrl('group'));
        }

        $this->get('session')->getFlashBag()->add('danger', 'ben.flash.error.form');
        $entities = $em->getRepository('BenUserBundle:Group')->findAll();
        return $this->render('BenUserBundle:Group:index.html.twig', array(
            'entities' => $entities,
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Group entity.
     * @Secure(roles="ROLE_MANAGER")
     *
     */
    public function editAction(Group $entity)
    {
        $em = $this->getDoctrine()->getManager();
        $editForm = $this->createForm(new GroupType(), $entity);

        return $this->render('BenUserBundle:Group:edit.html.twig', array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
        ));
    }

    /**
     * Edits an existing Group entity.
     * @Secure(roles="ROLE_MANAGER")
     *
     */
    public function updateAction(Request $request, Group $entity)
    {
        $em = $this->getDoctrine()->getManager();

        $editForm = $this->createForm(new GroupType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', 'ben.flash.success.group.updated');
            return $this->redirect($this->generateUrl('group_edit', array('id' => $entity->getId())));
        }
        else $this->get('session')->getFlashBag()->add('error', 'ben.flash.error.form');

        return $this->render('BenUserBundle:Group:edit.html.twig', array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
        ));
    }

    /**
     * Deletes a Group entity.
     * @Secure(roles="ROLE_ADMIN")
     *
     */
    public function deleteAction(Request $request, Group $entity)
    {
        $em = $this->getDoctrine()->getManager();
        $em->remove($entity);
        $em->flush();

        $this->get('session')->getFlashBag()->add('success', 'ben.flash.success.group.deleted');
        return $this->redirect($this->generateUrl('group'));
    }

    /**
     * ajouter un groupe de recherche
     * @Secure(roles="ROLE_MANAGER")
     */
    public function addFilterGroupAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $searchParam = $request->get('searchParam');
        $entities = $em->getRepository('BenUserBundle:user')->search($searchParam);
        $blackConstraint = new \Symfony\Component\Validator\Constraints\NotBlank();
        $errorList = $this->get('validator')->validateValue($searchParam['filterGroup'], $blackConstraint);

        if (count($errorList) == 0) {
            $group = new Group();
            $group->setName($searchParam['filterGroup']);
            $group->setRoles(array());
            foreach ($entities as $entity) {
                $entity->groupAdd($group);
            }
            $em->persist($group);
            $em->flush();
        $response = new Response(json_encode($group->toArray()));
        $response->headers->set('Content-Type', 'application/json');
        } else {
            $errorMessage = $errorList[0]->getMessage();
            $response = new Response($errorMessage);
        }

        return $response;
    }

    /**
     * associer les adhérants sélectionnés à un groupe
     * @Secure(roles="ROLE_MANAGER")
     */
    public function addToGroupAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $users = $request->get('users');
        $group_id = $request->get('group');
        $group = $em->getRepository('BenUserBundle:Group')->find($group_id);
        $userManager = $this->get('fos_user.user_manager');
        foreach( $users as $id){
            $user = $userManager->findUserBy(array('id' => $id));
            $user->groupAdd($group);
        }
        $em->persist($group);
        $em->flush();

        $response = new Response(json_encode($group->toArray()));
        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    /**
     * supprimer un utilisateur d'un groupe
     * @Secure(roles="ROLE_MANAGER")
     */
    public function removeFromGroupAction(Request $request, User $user, $groupid)
    {
        $em = $this->getDoctrine()->getManager();
        $group = $em->getRepository('BenUserBundle:Group')->find($groupid);
        $user->groupRemove($group);
        $em->persist($group);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success', "ben.flash.success.general");
        return $this->redirect($this->generateUrl('group_show', array('id' => $groupid)));
    }

    /**
     * log mail, sms, call fo a group
     * @Secure(roles="ROLE_MANAGER")
     */
    public function logGroupAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('BenUserBundle:user')->search(array('group'=>$id));
        foreach ($users as $user) {
            $entity = $this->getLog($request->get('log'));
            $entity->setEntityId($user->getId());
            $em->persist($entity);
        }
        $em->flush();
        return new Response('1');
    }

    /**
     * send mail
     * @Secure(roles="ROLE_MANAGER")
     */
    public function sendMailGroupAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $mail = $request->get('mail');
        if($id == 0){ //send mail to one person
            $recipients = $mail['email'];
            $logEntity = $this->getLog($request->get('log'));
            $logEntity->setMessage($mail['subject']);
            $logEntity->setType('mail');
            $em->persist($logEntity);
        }
        else{ //send mail to a group
            $users = $em->getRepository('BenUserBundle:user')->search(array('group'=>$id));
            $recipients = [];
            foreach ($users as $user) {
                $recipients[] = $user->getEmail();
                $logEntity = $this->getLog($request->get('log'));
                $logEntity->setMessage($mail['subject']);
                $logEntity->setType('mail');
                $logEntity->setEntityId($user->getId());
                $em->persist($logEntity);
            }
        }
        $this->sendMail($mail, $recipients);
        $em->flush();
        return new Response('1');
    }

    /**
     * send mail
     * @Secure(roles="ROLE_MANAGER")
     */
    public function sendLetterAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('BenUserBundle:user')->search(array('group'=>$id));

        $users = $em->getRepository('BenUserBundle:user')->search(array('group'=>$id));
        if(empty($users)) {
            $this->get('session')->getFlashBag()->add('danger', "ben.flash.error.group.empty");
            return $this->redirect($this->generateUrl('group_show', array('id' => $id)));
        }
        // return $this->render('BenUserBundle:Group:letter.html.twig', array('letter'=>$letter,'users'=>$users));

        // log users who receved letters
        $letter = $request->get('letter');
        $log = $request->get('log');
        foreach ($users as $user) {
            $log['entity_id'] = $user->getId();
            $em->persist($this->getLog($log));
        }
        $em->flush();

        $now = (new \DateTime)->format('d-m-Y_H-i');
        $html = $this->renderView('BenUserBundle:Group:letter.html.twig', array(
            'letter'      => $letter,
            'users'      => $users,
            ));

        return new Response(
            $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
            200,
            array(
                'Content-Type'          => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="letters'.$now.'.pdf"'
            )
        );
    }

    /* helper funcions */
    private function getLog($log)
    {
        extract($log);
        if(!empty($sms)){
            $type = 'sms';
            $feedback = '';
        }
        $entity = new \Ben\AssociationBundle\Entity\ActivityLog();
        $entity->setClassName('Ben\UserBundle\Entity\User');
        $entity->setEntityId($entity_id);
        $entity->setUser($user);
        $entity->setMessage($feedback);
        $entity->setType($type);
        return $entity;
    }

    public function sendMail($mail, $recipients)
    {
        extract($mail);
        $sender_email = $this->container->getParameter('webmaster');
        $message = \Swift_Message::newInstance()
                    ->setSubject($subject)
                    ->setFrom($sender_email)
                    ->setTo($recipients)
                    ->setBody($body, 'text/plain');
        $this->get('mailer')->send($message);
    }
}


text:
// (The MIT License)
//
// Copyright (c) 2012-2013 Novadiscovery <osproject@novadiscovery.com>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// IMPORT
var crc    = require('crc');

/**
 * Convert file size to human readable file size
 *
 * @param  {number} bytes File size
 * @return {string}       Human readable file size
 * @api private
 */
exports.bytesToSize = function (bytes) {
	var sizes = ['B', 'K', 'M', 'G', 'T'];
	if (bytes == 0) return 'n/a';
	var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
	return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

/**
 * Create a short hash string
 *
 * @param  {string} str String to hash
 * @return {string}     Uniq hash for str
 */
exports.uid = function(str) {
	if('object' === typeof str) {
		str = JSON.stringify(str, function(k, v) {
			if('function' === typeof v) return v.toString();
			return v;
		})
	}
	return crc.hex32(crc.crc32(str));
}


text:
/*
  +----------------------------------------------------------------------+
  | Swoole                                                               |
  +----------------------------------------------------------------------+
  | This source file is subject to version 2.0 of the Apache license,    |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.apache.org/licenses/LICENSE-2.0.html                      |
  | If you did not receive a copy of the Apache2.0 license and are unable|
  | to obtain it through the world-wide-web, please send a note to       |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: Tianfeng Han  <mikan.tenny@gmail.com>                        |
  +----------------------------------------------------------------------+
*/

#include "swoole.h"

int swReactor_auto(swReactor *reactor, int max_event)
{
	int ret;
#ifdef HAVE_EPOLL
	ret = swReactorEpoll_create(reactor, max_event);
#elif defined(HAVE_KQUEUE)
	ret = swReactorKqueue_create(reactor, max_event);
#elif defined(SW_MAINREACTOR_USE_POLL)
	ret = swReactorPoll_create(reactor, max_event);
#else
	ret = swReactorSelect_create(SwooleG.main_reactor)
#endif
	return ret;
}

swReactor_handle swReactor_getHandle(swReactor *reactor, int event_type, int fdtype)
{
	if (event_type == SW_EVENT_WRITE)
	{
		//默认可写回调函数SW_FD_WRITE
		return (reactor->write_handle[fdtype] != NULL) ? reactor->write_handle[fdtype] : reactor->handle[SW_FD_WRITE];
	}
	if (event_type == SW_EVENT_ERROR)
	{
		//默认关闭回调函数SW_FD_CLOSE
		return (reactor->error_handle[fdtype] != NULL) ? reactor->error_handle[fdtype] : reactor->handle[SW_FD_CLOSE];
	}
	return reactor->handle[fdtype];
}

int swReactor_setHandle(swReactor *reactor, int _fdtype, swReactor_handle handle)
{
	int fdtype = swReactor_fdtype(_fdtype);

	if (fdtype >= SW_MAX_FDTYPE)
	{
		swWarn("fdtype > SW_MAX_FDTYPE[%d]", SW_MAX_FDTYPE);
		return SW_ERR;
	}
	else
	{
		if (swReactor_event_read(_fdtype))
		{
			reactor->handle[fdtype] = handle;
		}
		else if (swReactor_event_write(_fdtype))
		{
			reactor->write_handle[fdtype] = handle;
		}
		else if (swReactor_event_error(_fdtype))
		{
			reactor->error_handle[fdtype] = handle;
		}
		else
		{
			swWarn("unknow fdtype");
			return SW_ERR;
		}
	}
	return SW_OK;
}

int swReactor_receive(swReactor *reactor, swEvent *event)
{
	swEventData data;
	return swRead(event->fd, data.data, SW_BUFFER_SIZE);
}


text:
package nuist.qlib.dss.net.vo;

import nuist.qlib.dss.constant.MessageType;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class MatchInfoMessageVO extends BaseMessageVO {

	/**
	 * 参赛单位
	 */
	private String matchUnit;

	/**
	 * 比赛项目
	 */
	private String matchCategory;

	/**
	 * 赛事名称
	 */
	private String matchName;

	public MatchInfoMessageVO() {
		this.setMessageType(MessageType.MATCHINFO);
	}

}


text:
{% extends "base_form.html" %}

{% block title %}Update Skill Tree Branch{% endblock %}