text:
using base::android::JavaParamRef;

FakeServerHelperAndroid::FakeServerHelperAndroid(JNIEnv* env, jobject obj) {}

FakeServerHelperAndroid::~FakeServerHelperAndroid() {}

static jlong Init(JNIEnv* env, const JavaParamRef<jobject>& obj) {
  FakeServerHelperAndroid* fake_server_android =
      new FakeServerHelperAndroid(env, obj);
  return reinterpret_cast<intptr_t>(fake_server_android);
}

jlong FakeServerHelperAndroid::CreateFakeServer(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj) {
  fake_server::FakeServer* fake_server = new fake_server::FakeServer();
  return reinterpret_cast<intptr_t>(fake_server);
}

jlong FakeServerHelperAndroid::CreateNetworkResources(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  syncer::NetworkResources* resources =
      new fake_server::FakeServerNetworkResources(fake_server_ptr->AsWeakPtr());
  return reinterpret_cast<intptr_t>(resources);
}

void FakeServerHelperAndroid::DeleteFakeServer(JNIEnv* env,
                                               const JavaParamRef<jobject>& obj,
                                               jlong fake_server) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  delete fake_server_ptr;
}

jboolean FakeServerHelperAndroid::VerifyEntityCountByTypeAndName(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    jlong count,
    jint model_type_int,
    const JavaParamRef<jstring>& name) {
  syncer::ModelType model_type = static_cast<syncer::ModelType>(model_type_int);
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  fake_server::FakeServerVerifier fake_server_verifier(fake_server_ptr);
  testing::AssertionResult result =
      fake_server_verifier.VerifyEntityCountByTypeAndName(
          count, model_type, base::android::ConvertJavaStringToUTF8(env, name));

  if (!result)
    LOG(WARNING) << result.message();

  return result;
}

jboolean FakeServerHelperAndroid::VerifySessions(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jobjectArray>& url_array) {
  std::multiset<std::string> tab_urls;
  for (int i = 0; i < env->GetArrayLength(url_array); i++) {
    jstring s = (jstring)env->GetObjectArrayElement(url_array, i);
    tab_urls.insert(base::android::ConvertJavaStringToUTF8(env, s));
  }
  fake_server::SessionsHierarchy expected_sessions;
  expected_sessions.AddWindow(tab_urls);

  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  fake_server::FakeServerVerifier fake_server_verifier(fake_server_ptr);
  testing::AssertionResult result =
      fake_server_verifier.VerifySessions(expected_sessions);

  if (!result)
    LOG(WARNING) << result.message();

  return result;
}

base::android::ScopedJavaLocalRef<jobjectArray>
FakeServerHelperAndroid::GetSyncEntitiesByModelType(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    jint model_type_int) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);

  syncer::ModelType model_type = static_cast<syncer::ModelType>(model_type_int);

  std::vector<sync_pb::SyncEntity> entities =
      fake_server_ptr->GetSyncEntitiesByModelType(model_type);

  std::vector<std::string> entity_strings;
  for (size_t i = 0; i < entities.size(); ++i) {
    std::string s;
    entities[i].SerializeToString(&s);
    entity_strings.push_back(s);
  }
  return base::android::ToJavaArrayOfByteArray(env, entity_strings);
}

void FakeServerHelperAndroid::InjectUniqueClientEntity(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jstring>& name,
    const JavaParamRef<jbyteArray>& serialized_entity_specifics) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);

  sync_pb::EntitySpecifics entity_specifics;
  DeserializeEntitySpecifics(env, serialized_entity_specifics,
                             &entity_specifics);

  fake_server_ptr->InjectEntity(
      fake_server::UniqueClientEntity::CreateForInjection(
          base::android::ConvertJavaStringToUTF8(env, name), entity_specifics));
}

void FakeServerHelperAndroid::ModifyEntitySpecifics(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jstring>& id,
    const JavaParamRef<jbyteArray>& serialized_entity_specifics) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);

  sync_pb::EntitySpecifics entity_specifics;
  DeserializeEntitySpecifics(env, serialized_entity_specifics,
                             &entity_specifics);

  fake_server_ptr->ModifyEntitySpecifics(
      base::android::ConvertJavaStringToUTF8(env, id), entity_specifics);
}

void FakeServerHelperAndroid::DeserializeEntitySpecifics(
    JNIEnv* env,
    jbyteArray serialized_entity_specifics,
    sync_pb::EntitySpecifics* entity_specifics) {
  int specifics_bytes_length = env->GetArrayLength(serialized_entity_specifics);
  jbyte* specifics_bytes =
      env->GetByteArrayElements(serialized_entity_specifics, nullptr);
  std::string specifics_string(reinterpret_cast<char*>(specifics_bytes),
                               specifics_bytes_length);

  if (!entity_specifics->ParseFromString(specifics_string))
    NOTREACHED() << "Could not deserialize EntitySpecifics";
}

void FakeServerHelperAndroid::InjectBookmarkEntity(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jstring>& title,
    const JavaParamRef<jstring>& url,
    const JavaParamRef<jstring>& parent_id) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  fake_server_ptr->InjectEntity(
      CreateBookmarkEntity(env, title, url, parent_id));
}

void FakeServerHelperAndroid::InjectBookmarkFolderEntity(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jstring>& title,
    const JavaParamRef<jstring>& parent_id) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);

  fake_server::EntityBuilderFactory entity_builder_factory;
  fake_server::BookmarkEntityBuilder bookmark_builder =
      entity_builder_factory.NewBookmarkEntityBuilder(
          base::android::ConvertJavaStringToUTF8(env, title));
  bookmark_builder.SetParentId(
      base::android::ConvertJavaStringToUTF8(env, parent_id));

  fake_server_ptr->InjectEntity(bookmark_builder.BuildFolder());
}

void FakeServerHelperAndroid::ModifyBookmarkEntity(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jstring>& entity_id,
    const JavaParamRef<jstring>& title,
    const JavaParamRef<jstring>& url,
    const JavaParamRef<jstring>& parent_id) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  std::unique_ptr<fake_server::FakeServerEntity> bookmark =
      CreateBookmarkEntity(env, title, url, parent_id);
  sync_pb::SyncEntity proto;
  bookmark->SerializeAsProto(&proto);
  fake_server_ptr->ModifyBookmarkEntity(
      base::android::ConvertJavaStringToUTF8(env, entity_id),
      base::android::ConvertJavaStringToUTF8(env, parent_id),
      proto.specifics());
}

void FakeServerHelperAndroid::ModifyBookmarkFolderEntity(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server,
    const JavaParamRef<jstring>& entity_id,
    const JavaParamRef<jstring>& title,
    const JavaParamRef<jstring>& parent_id) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);

  fake_server::EntityBuilderFactory entity_builder_factory;
  fake_server::BookmarkEntityBuilder bookmark_builder =
      entity_builder_factory.NewBookmarkEntityBuilder(
          base::android::ConvertJavaStringToUTF8(env, title));
  bookmark_builder.SetParentId(
      base::android::ConvertJavaStringToUTF8(env, parent_id));

  sync_pb::SyncEntity proto;
  bookmark_builder.BuildFolder()->SerializeAsProto(&proto);
  fake_server_ptr->ModifyBookmarkEntity(
      base::android::ConvertJavaStringToUTF8(env, entity_id),
      base::android::ConvertJavaStringToUTF8(env, parent_id),
      proto.specifics());
}

std::unique_ptr<fake_server::FakeServerEntity>
FakeServerHelperAndroid::CreateBookmarkEntity(JNIEnv* env,
                                              jstring title,
                                              jstring url,
                                              jstring parent_id) {
  std::string url_as_string = base::android::ConvertJavaStringToUTF8(env, url);
  GURL gurl = GURL(url_as_string);
  if (!gurl.is_valid()) {
    NOTREACHED() << "The given string (" << url_as_string
                 << ") is not a valid URL.";
  }

  fake_server::EntityBuilderFactory entity_builder_factory;
  fake_server::BookmarkEntityBuilder bookmark_builder =
      entity_builder_factory.NewBookmarkEntityBuilder(
          base::android::ConvertJavaStringToUTF8(env, title));
  bookmark_builder.SetParentId(
      base::android::ConvertJavaStringToUTF8(env, parent_id));
  return bookmark_builder.BuildBookmark(gurl);
}

base::android::ScopedJavaLocalRef<jstring>
FakeServerHelperAndroid::GetBookmarkBarFolderId(
    JNIEnv* env,
    const JavaParamRef<jobject>& obj,
    jlong fake_server) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  return base::android::ConvertUTF8ToJavaString(
      env, fake_server_ptr->GetBookmarkBarFolderId());
}

void FakeServerHelperAndroid::DeleteEntity(JNIEnv* env,
                                           const JavaParamRef<jobject>& obj,
                                           jlong fake_server,
                                           const JavaParamRef<jstring>& id) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  std::string native_id = base::android::ConvertJavaStringToUTF8(env, id);
  fake_server_ptr->InjectEntity(
      fake_server::TombstoneEntity::Create(native_id, std::string()));
}

void FakeServerHelperAndroid::ClearServerData(JNIEnv* env,
                                              const JavaParamRef<jobject>& obj,
                                              jlong fake_server) {
  fake_server::FakeServer* fake_server_ptr =
      reinterpret_cast<fake_server::FakeServer*>(fake_server);
  fake_server_ptr->ClearServerData();
}

// static
bool FakeServerHelperAndroid::Register(JNIEnv* env) {
  return RegisterNativesImpl(env);
}


text:
#ifdef HAVE_CONFIG_H
# include "private/config.h"
#endif

#ifndef GC_THREADS
# define GC_THREADS
#endif

#define GC_NO_THREAD_REDIRECTS 1

#include "gc.h"

#if (!defined(GC_PTHREADS) || defined(GC_SOLARIS_THREADS) \
     || defined(__native_client__)) && !defined(SKIP_THREADKEY_TEST)
  /* FIXME: Skip this test on Solaris for now.  The test may fail on    */
  /* other targets as well.  Currently, tested only on Linux, Cygwin    */
  /* and Darwin.                                                        */
# define SKIP_THREADKEY_TEST
#endif

#ifdef SKIP_THREADKEY_TEST

#include <stdio.h>

int main (void)
{
  printf("threadkey_test skipped\n");
  return 0;
}

#else

#include <pthread.h>

pthread_key_t key;

#ifdef GC_SOLARIS_THREADS
  /* pthread_once_t key_once = { PTHREAD_ONCE_INIT }; */
#else
  pthread_once_t key_once = PTHREAD_ONCE_INIT;
#endif

void * entry (void *arg)
{
  pthread_setspecific(key,
                      (void *)GC_HIDE_POINTER(GC_STRDUP("hello, world")));
  return arg;
}

void * GC_CALLBACK on_thread_exit_inner (struct GC_stack_base * sb, void * arg)
{
  int res = GC_register_my_thread (sb);
  pthread_t t;
  int creation_res;     /* Used to suppress a warning about     */
                        /* unchecked pthread_create() result.   */

  creation_res = GC_pthread_create (&t, NULL, entry, NULL);
  if (res == GC_SUCCESS)
    GC_unregister_my_thread ();

  return (void*)(GC_word)creation_res;
}

void on_thread_exit (void *v)
{
  GC_call_with_stack_base (on_thread_exit_inner, NULL);
}

void make_key (void)
{
  pthread_key_create (&key, on_thread_exit);
}

#ifndef LIMIT
# define LIMIT 30
#endif

int main (void)
{
  int i;
  GC_INIT ();

# ifdef GC_SOLARIS_THREADS
    pthread_key_create (&key, on_thread_exit);
# else
    pthread_once (&key_once, make_key);
# endif
  for (i = 0; i < LIMIT; i++) {
    pthread_t t;
    void *res;
    if (GC_pthread_create (&t, NULL, entry, NULL) == 0
        && (i & 1) != 0)
      GC_pthread_join (t, &res);
  }
  return 0;
}

#endif /* !SKIP_THREADKEY_TEST */

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<cartridge_basiclti_link xmlns="http://www.imsglobal.org/xsd/imslticc_v1p0"
    xmlns:blti = "http://www.imsglobal.org/xsd/imsbasiclti_v1p0"
    xmlns:lticm ="http://www.imsglobal.org/xsd/imslticm_v1p0"
    xmlns:lticp ="http://www.imsglobal.org/xsd/imslticp_v1p0"
    xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation = "http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd
    http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0.xsd
    http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd
    http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd">
    <blti:launch_url>https://example.edu/grading_standard/</blti:launch_url>
    <blti:title>Add 4.0 Grade Scale</blti:title>
    <blti:description>Create grading standards and add them to your course</blti:description>
    <blti:custom>
      <lticm:property name="courseid_parameter">lis_course_offering_sourcedid</lticm:property>
      <lticm:property name="userid_parameter">lis_person_sourcedid</lticm:property>
      <lticm:property name="application_type">GradingStandard</lticm:property>
    </blti:custom>
    <blti:extensions platform="canvas.instructure.com">
      <lticm:property name="privacy_level">public</lticm:property>
      <lticm:options name="course_navigation">
        <lticm:property name="visibility">admins</lticm:property>
        <lticm:property name="enabled">true</lticm:property>
      </lticm:options>
    </blti:extensions>
</cartridge_basiclti_link>


text:
require 'spec_helper'

describe Sendbird::MessageApi do
  OPEN_CHANNEL_URL = 'Testing_api_123'
  GROUP_CHANNEL_URL = 'sendbird_group_channel_19031773_daff0f4d3fc3974311123ca8134b126c242ac8cc'

  context 'Create' do
    let(:params) do
      {
        "message_type": "MESG",
        "user_id": 'nirrrr',
        "message": 'Tetsing messages',
        "data": 'Not real'
      }
    end
    let(:request) do
      create_dynamic_cassette("#{described_class}/send") do
        described_class.send(channel_type, channel_url, params)
      end
    end
    context 'Message to open channel' do
      let(:channel_type) { 'open_channels' }
      let(:channel_url) { OPEN_CHANNEL_URL }
      it 'will create a message in the open channel' do
        expect(request.body['message']).to eq 'Tetsing messages'
        expect(request.body['channel_url']).to eq OPEN_CHANNEL_URL
      end
    end

    context 'Message to group channel' do
      let(:channel_type) { 'group_channels' }
      let(:channel_url) { GROUP_CHANNEL_URL }
      it 'will create a message in the group channel' do
        expect(request.body['message']).to eq 'Tetsing messages'
        expect(request.body['channel_url']).to eq GROUP_CHANNEL_URL
      end
    end
  end

  context 'List' do
    let(:request) do
      create_dynamic_cassette("#{described_class}/list") do
        described_class.list('open_channels', OPEN_CHANNEL_URL, {message_ts: 0})
      end
    end
    it 'will return all messages from the channel if you pay :( ' do
      expect(request.status).to eq 400
    end
  end

  context 'View' do
    let(:request) do
      create_dynamic_cassette("#{described_class}/view") do
        described_class.view('open_channels', OPEN_CHANNEL_URL, '527575816' )
      end
    end
    it 'will return the message' do
      expect(request.body['message']).to eq('Tetsing messages')
      expect(request.body['user']['user_id']).to eq('nirrrr')
    end
  end

  context 'Delete' do
    let(:request) do
      create_dynamic_cassette("#{described_class}/delete") do
        described_class.destroy('open_channels', OPEN_CHANNEL_URL, '527575816' )
      end
    end
    it 'will delete the message' do
      expect(request.body).to eq({})
    end
  end

  context 'Mark as Read' do
    let(:request) do
      create_dynamic_cassette("#{described_class}/mark_as_read") do
        described_class.mark_as_read('group_channels', GROUP_CHANNEL_URL, {user_id: 'nirrrr'} )
      end
    end
    it 'will markall messages from group as readed' do
      expect(request.body).to eq({})
    end
  end

  context 'Count' do
    let(:request) do
      create_dynamic_cassette("#{described_class}/count") do
        described_class.count('group_channels', GROUP_CHANNEL_URL )
      end
    end
    it 'will return the total messages from channel' do
      expect(request.body['total']).to eq(3)
    end
  end

  context 'Unread Count' do
    let(:request) do
      create_dynamic_cassette("#{described_class}/unread_count") do
        described_class.unread_count('group_channels', GROUP_CHANNEL_URL, {user_ids: 'nirrrr'} )
      end
    end
    it 'will all unread messages from channel' do
      expect(request.body['unread']['nirrrr']).to eq(0)
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 ?>
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" type="text/css" href="/utn/FullStack/restobar_webapp/assets/bootstrap/css/bootstrap.css">
	<link rel="stylesheet" type="text/css" href="/utn/FullStack/restobar_webapp/assets/bootstrap/css/m-style.css">

	<title> Cuisiner RestoBar </title>

						    Home

						    Salon

						      Administacion?
						      Config?
						      ??

						      ????

						    Reservas 2

						    Dashboard

						<button type="button" class="btn btn-danger float-right">Salir</button>

						  <button type="button" class="btn btn btn-secondary">Menu</button>
						  <button type="button" class="btn btn btn-secondary">Comandas 5</button>

						    <button type="button" class="btn btn btn-secondary dropdown-toggle" data-toggle="dropdown">
						       Mesas 15
						    </button>

						      Tablet
						      Smartphone

Cuisiner RestoBar

				  	Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam aliquet vel tortor at ultrices. Sed at mollis urna. Mauris accumsan nibh id libero imperdiet eleifend id et sem. Vestibulum sodales metus tortor, at porttitor dolor viverra et. Morbi suscipit mauris eu nunc vestibulum, a pulvinar nisi scelerisque. Nam accumsan, turpis eget bibendum sollicitudin, ligula risus maximus neque, euismod tristique lorem sem non nulla. Suspendisse sed magna fringilla, lobortis nisi tempor, porta nisl.

Empleados

Detalle de los empleados

					    Ir ->

Proveedores

Detalle sobre proveedores.

					    Ir ->

No disponible aun..

Some example text.

					    Ir ->

No disponible aun..

Some example text.

					    Ir ->

Footer


text:
#include "../export.h"
#include <dlib/logger.h>
#include "../shared.h"

DLLEXPORT dlib::logger* logger_new(const char* name, const int name_length)
{
    return new dlib::logger(std::string(name, name_length));
}

DLLEXPORT void logger_delete(dlib::logger* logger)
{
    delete logger;
}

DLLEXPORT void logger_set_level(dlib::logger* logger, log_level level)
{
    switch(level)
    {
        case log_level::All:
            logger->set_level(dlib::LALL);
            break;
        case log_level::None:
            logger->set_level(dlib::LNONE);
            break;
        case log_level::Trace:
            logger->set_level(dlib::LTRACE);
            break;
        case log_level::Debug:
            logger->set_level(dlib::LDEBUG);
            break;
        case log_level::Info:
            logger->set_level(dlib::LINFO);
            break;
        case log_level::Warn:
            logger->set_level(dlib::LWARN);
            break;
        case log_level::Error:
            logger->set_level(dlib::LERROR);
            break;
        case log_level::Fatal:
            logger->set_level(dlib::LFATAL);
            break;
    }
}

DLLEXPORT void logger_operator_left_shift(dlib::logger* logger, log_level level, const char* message, const int message_length)
{
    auto& l = *logger;

    switch(level)
    {
        case log_level::All:
            l << dlib::LALL << std::string(message, message_length);
            break;
        case log_level::None:
            l << dlib::LNONE << std::string(message, message_length);
            break;
        case log_level::Trace:
            l << dlib::LTRACE << std::string(message, message_length);
            break;
        case log_level::Debug:
            l << dlib::LDEBUG << std::string(message, message_length);
            break;
        case log_level::Info:
            l << dlib::LINFO << std::string(message, message_length);
            break;
        case log_level::Warn:
            l << dlib::LWARN << std::string(message, message_length);
            break;
        case log_level::Error:
            l << dlib::LERROR << std::string(message, message_length);
            break;
        case log_level::Fatal:
            l << dlib::LFATAL << std::string(message, message_length);
            break;
    }
}

#endif


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik;

use Exception;
use XHProfRuns_Default;

/**
 * Class Profiler helps with measuring memory, and profiling the database.
 * To enable set in your config.ini.php
 *   [Debug]
 *   enable_sql_profiler = 1
 *
 *   [log]
 *   log_writers[] = file
 *   log_level=debug
 *
 */
class Profiler
{
    /**
     * Whether xhprof has been setup or not.
     *
     * @var bool
     */
    private static $isXhprofSetup = false;

    /**
     * Returns memory usage
     *
     * @return string
     */
    public static function getMemoryUsage()
    {
        $memory = false;
        if (function_exists('xdebug_memory_usage')) {
            $memory = xdebug_memory_usage();
        } elseif (function_exists('memory_get_usage')) {
            $memory = memory_get_usage();
        }
        if ($memory === false) {
            return "Memory usage function not found.";
        }
        $usage = number_format(round($memory / 1024 / 1024, 2), 2);
        return "$usage Mb";
    }

    /**
     * Outputs SQL Profiling reports from Zend
     *
     * @throws \Exception
     */
    public static function displayDbProfileReport()
    {
        $profiler = Db::get()->getProfiler();

        if (!$profiler->getEnabled()) {
            // To display the profiler you should enable enable_sql_profiler on your config/config.ini.php file
            return;
        }

        $infoIndexedByQuery = array();
        foreach ($profiler->getQueryProfiles() as $query) {
            if (isset($infoIndexedByQuery[$query->getQuery()])) {
                $existing = $infoIndexedByQuery[$query->getQuery()];
            } else {
                $existing = array('count' => 0, 'sumTimeMs' => 0);
            }
            $new = array('count'     => $existing['count'] + 1,
                         'sumTimeMs' => $existing['count'] + $query->getElapsedSecs() * 1000);
            $infoIndexedByQuery[$query->getQuery()] = $new;
        }

        uasort($infoIndexedByQuery, 'self::sortTimeDesc');

        $str = '
SQL Profiler
Summary
';
        $totalTime = $profiler->getTotalElapsedSecs();
        $queryCount = $profiler->getTotalNumQueries();
        $longestTime = 0;
        $longestQuery = null;
        foreach ($profiler->getQueryProfiles() as $query) {
            if ($query->getElapsedSecs() > $longestTime) {
                $longestTime = $query->getElapsedSecs();
                $longestQuery = $query->getQuery();
            }
        }
        $str .= 'Executed ' . $queryCount . ' queries in ' . round($totalTime, 3) . ' seconds';
        $str .= '(Average query length: ' . round($totalTime / $queryCount, 3) . ' seconds)';
        $str .= '
Queries per second: ' . round($queryCount / $totalTime, 1);
        $str .= '
Longest query length: ' . round($longestTime, 3) . " seconds ($longestQuery)";
        Log::debug($str);
        self::getSqlProfilingQueryBreakdownOutput($infoIndexedByQuery);
    }

    private static function maxSumMsFirst($a, $b)
    {
        return $a['sum_time_ms'] < $b['sum_time_ms'];
    }

    private static function sortTimeDesc($a, $b)
    {
        return $a['sumTimeMs'] < $b['sumTimeMs'];
    }

    /**
     * Print profiling report for the tracker
     *
     * @param \Piwik\Db $db Tracker database object (or null)
     */
    public static function displayDbTrackerProfile($db = null)
    {
        if (is_null($db)) {
            $db = Tracker::getDatabase();
        }
        $tableName = Common::prefixTable('log_profiling');

        $all = $db->fetchAll('SELECT * FROM ' . $tableName);
        if ($all === false) {
            return;
        }
        uasort($all, 'self::maxSumMsFirst');

        $infoIndexedByQuery = array();
        foreach ($all as $infoQuery) {
            $query = $infoQuery['query'];
            $count = $infoQuery['count'];
            $sum_time_ms = $infoQuery['sum_time_ms'];
            $infoIndexedByQuery[$query] = array('count' => $count, 'sumTimeMs' => $sum_time_ms);
        }
        self::getSqlProfilingQueryBreakdownOutput($infoIndexedByQuery);
    }

    /**
     * Print number of queries and elapsed time
     */
    public static function printQueryCount()
    {
        $totalTime = self::getDbElapsedSecs();
        $queryCount = Profiler::getQueryCount();
        if ($queryCount > 0) {
            Log::debug(sprintf("Total queries = %d (total sql time = %.2fs)", $queryCount, $totalTime));
        }
    }

    /**
     * Get total elapsed time (in seconds)
     *
     * @return int  elapsed time
     */
    public static function getDbElapsedSecs()
    {
        $profiler = Db::get()->getProfiler();
        return $profiler->getTotalElapsedSecs();
    }

    /**
     * Get total number of queries
     *
     * @return int  number of queries
     */
    public static function getQueryCount()
    {
        $profiler = Db::get()->getProfiler();
        return $profiler->getTotalNumQueries();
    }

    /**
     * Log a breakdown by query
     *
     * @param array $infoIndexedByQuery
     */
    private static function getSqlProfilingQueryBreakdownOutput($infoIndexedByQuery)
    {
        $output = '
Breakdown by query
';
        foreach ($infoIndexedByQuery as $query => $queryInfo) {
            $timeMs = round($queryInfo['sumTimeMs'], 1);
            $count = $queryInfo['count'];
            $avgTimeString = '';
            if ($count > 1) {
                $avgTimeMs = $timeMs / $count;
                $avgTimeString = " (average = " . round($avgTimeMs, 1) . "ms)";
            }
            $query = preg_replace('/([\t\n\r ]+)/', ' ', $query);
            $output .= "Executed $count time" . ($count == 1 ? '' : 's') . " in " . $timeMs . "ms $avgTimeString
\t$query
";
        }
        Log::debug($output);
    }

    /**
     * Initializes Profiling via XHProf.
     * See: https://github.com/piwik/piwik/blob/master/tests/README.xhprof.md
     */
    public static function setupProfilerXHProf($mainRun = false, $setupDuringTracking = false)
    {
        if (!$setupDuringTracking
            && SettingsServer::isTrackerApiRequest()
        ) {
            // do not profile Tracker
            return;
        }

        if (self::$isXhprofSetup) {
            return;
        }

        if (!function_exists('xhprof_enable')) {
            $xhProfPath = PIWIK_INCLUDE_PATH . '/vendor/facebook/xhprof/extension/modules/xhprof.so';
            throw new Exception("Cannot find xhprof_enable, make sure to 1) install xhprof: run 'composer install --dev' and build the extension, and 2) add 'extension=$xhProfPath' to your php.ini.");
        }

        $outputDir = ini_get("xhprof.output_dir");
        if (empty($outputDir)) {
            throw new Exception("The profiler output dir is not set. Add 'xhprof.output_dir=...' to your php.ini.");
        }
        if (!is_writable($outputDir)) {
            throw new Exception("The profiler output dir '" . ini_get("xhprof.output_dir") . "' should exist and be writable.");
        }

        if (!function_exists('xhprof_error')) {
            function xhprof_error($out)
            {
                echo substr($out, 0, 300) . '...';
            }
        }

        $currentGitBranch = SettingsPiwik::getCurrentGitBranch();
        $profilerNamespace = "piwik";
        if ($currentGitBranch != 'master') {
            $profilerNamespace .= "-" . $currentGitBranch;
        }

        if ($mainRun) {
            self::setProfilingRunIds(array());
        }

        xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);

        register_shutdown_function(function () use ($profilerNamespace, $mainRun) {
            $xhprofData = xhprof_disable();
            $xhprofRuns = new XHProfRuns_Default();
            $runId = $xhprofRuns->save_run($xhprofData, $profilerNamespace);

            if (empty($runId)) {
                die('could not write profiler run');
            }

            $runs = Profiler::getProfilingRunIds();
            array_unshift($runs, $runId);

            if ($mainRun) {
                Profiler::aggregateXhprofRuns($runs, $profilerNamespace, $saveTo = $runId);

                $baseUrlStored = SettingsPiwik::getPiwikUrl();

                $out = "\n\n";
                $baseUrl = "http://" . @$_SERVER['HTTP_HOST'] . "/" . @$_SERVER['REQUEST_URI'];
                if (strlen($baseUrlStored) > strlen($baseUrl)) {
                    $baseUrl = $baseUrlStored;
                }
                $baseUrl = $baseUrlStored . "vendor/facebook/xhprof/xhprof_html/?source=$profilerNamespace&run=$runId";

                $out .= "Profiler report is available at:\n";
                $out .= "$baseUrl";
                $out .= "\n\n";

                if (Development::isEnabled()) {
                    $out .= "WARNING: Development mode is enabled. Many runtime optimizations are not applied in development mode. ";
                    $out .= "Unless you intend to profile Piwik in development mode, your profile may not be accurate.";
                    $out .= "\n\n";
                }

                echo $out;
            } else {
                Profiler::setProfilingRunIds($runs);
            }
        });

        self::$isXhprofSetup = true;
    }

    /**
     * Aggregates xhprof runs w/o normalizing (xhprof_aggregate_runs will always average data which
     * does not fit Piwik's use case).
     */
    public static function aggregateXhprofRuns($runIds, $profilerNamespace, $saveToRunId)
    {
        $xhprofRuns = new XHProfRuns_Default();

        $aggregatedData = array();

        foreach ($runIds as $runId) {
            $xhprofRunData = $xhprofRuns->get_run($runId, $profilerNamespace, $description);

            foreach ($xhprofRunData as $key => $data) {
                if (empty($aggregatedData[$key])) {
                    $aggregatedData[$key] = $data;
                } else {
                    // don't aggregate main() metrics since only the super run has the correct metrics for the entire run
                    if ($key == "main()") {
                        continue;
                    }

                    $aggregatedData[$key]["ct"] += $data["ct"]; // call count
                    $aggregatedData[$key]["wt"] += $data["wt"]; // incl. wall time
                    $aggregatedData[$key]["cpu"] += $data["cpu"]; // cpu time
                    $aggregatedData[$key]["mu"] += $data["mu"]; // memory usage
                    $aggregatedData[$key]["pmu"] = max($aggregatedData[$key]["pmu"], $data["pmu"]); // peak mem usage
                }
            }
        }

        $xhprofRuns->save_run($aggregatedData, $profilerNamespace, $saveToRunId);
    }

    public static function setProfilingRunIds($ids)
    {
        file_put_contents(self::getPathToXHProfRunIds(), json_encode($ids));
        @chmod(self::getPathToXHProfRunIds(), 0777);
    }

    public static function getProfilingRunIds()
    {
        $runIds = file_get_contents(self::getPathToXHProfRunIds());
        $array = json_decode($runIds, $assoc = true);
        if (!is_array($array)) {
            $array = array();
        }
        return $array;
    }

    /**
     * @return string
     */
    private static function getPathToXHProfRunIds()
    {
        return PIWIK_INCLUDE_PATH . '/tmp/cache/tests-xhprof-runs';
    }
}


text:
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>JavaScript MD5 Demo</title>
<meta name="description" content="JavaScript MD5 implementation. Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="http://blueimp.github.com/cdn/css/bootstrap.min.css">

<link rel="stylesheet" href="http://blueimp.github.com/cdn/css/bootstrap-responsive.min.css">

            JavaScript MD5

Demo

Downloads

Source Code

Documentation

Issues

Test

© Sebastian Tschan

JavaScript MD5 Demo

JavaScript MD5 implementation.

        Compatible with server-side environments like node.js, module loaders like RequireJS and all web browsers.

Input

            <textarea class="span7" rows="6" id="input"></textarea>

Result

                <button class="btn btn-primary" id="calculate">Calculate</button>
                <button class="btn" type="reset" id="reset">Reset</button>


text:
<template name="layout">

    {{> header}}

      {{> yield}}

    {{> footer}}

</template>

<template name="header">

DnT

</template>

<template name="footer">
</template>


text:
import path = require('path');
import os = require('os');
import net = require('net');
import cp = require('child_process');
import Logger from './logger';

export interface IForkOptions {
	cwd?: string;
	execArgv?: string[];
}

export function makeRandomHexString(length: number): string {
	let chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
	let result = '';
	for (let i = 0; i < length; i++) {
		const idx = Math.floor(chars.length * Math.random());
		result += chars[idx];
	}
	return result;
}

function generatePipeName(): string {
	return getPipeName(makeRandomHexString(40));
}

function getPipeName(name: string): string {
	const fullName = 'vscode-' + name;
	if (process.platform === 'win32') {
		return '\\\\.\\pipe\\' + fullName + '-sock';
	}

	// Mac/Unix: use socket file
	return path.join(os.tmpdir(), fullName + '.sock');
}

export function getTempFile(name: string): string {
	const fullName = 'vscode-' + name;
	return path.join(os.tmpdir(), fullName + '.sock');
}

function generatePatchedEnv(
	env: any,
	stdInPipeName: string,
	stdOutPipeName: string,
	stdErrPipeName: string
): any {
	const newEnv = Object.assign({}, env);

	// Set the two unique pipe names and the electron flag as process env
	newEnv['STDIN_PIPE_NAME'] = stdInPipeName;
	newEnv['STDOUT_PIPE_NAME'] = stdOutPipeName;
	newEnv['STDERR_PIPE_NAME'] = stdErrPipeName;
	newEnv['ELECTRON_RUN_AS_NODE'] = '1';

	// Ensure we always have a PATH set
	newEnv['PATH'] = newEnv['PATH'] || process.env.PATH;
	return newEnv;
}

export function fork(
	modulePath: string,
	args: string[],
	options: IForkOptions,
	logger: Logger,
	callback: (error: any, cp: cp.ChildProcess | null) => void,
): void {

	let callbackCalled = false;
	const resolve = (result: cp.ChildProcess) => {
		if (callbackCalled) {
			return;
		}
		callbackCalled = true;
		callback(null, result);
	};
	const reject = (err: any) => {
		if (callbackCalled) {
			return;
		}
		callbackCalled = true;
		callback(err, null);
	};

	// Generate three unique pipe names
	const stdInPipeName = generatePipeName();
	const stdOutPipeName = generatePipeName();
	const stdErrPipeName = generatePipeName();

	const newEnv = generatePatchedEnv(process.env, stdInPipeName, stdOutPipeName, stdErrPipeName);
	newEnv['NODE_PATH'] = path.join(modulePath, '..', '..', '..');
	let childProcess: cp.ChildProcess;

	// Begin listening to stderr pipe
	let stdErrServer = net.createServer((stdErrStream) => {
		// From now on the childProcess.stderr is available for reading
		childProcess.stderr = stdErrStream;
	});
	stdErrServer.listen(stdErrPipeName);

	// Begin listening to stdout pipe
	let stdOutServer = net.createServer((stdOutStream) => {
		// The child process will write exactly one chunk with content `ready` when it has installed a listener to the stdin pipe

		stdOutStream.once('data', (_chunk: Buffer) => {
			// The child process is sending me the `ready` chunk, time to connect to the stdin pipe
			childProcess.stdin = <any>net.connect(stdInPipeName);

			// From now on the childProcess.stdout is available for reading
			childProcess.stdout = stdOutStream;

			resolve(childProcess);
		});
	});
	stdOutServer.listen(stdOutPipeName);

	let serverClosed = false;
	const closeServer = () => {
		if (serverClosed) {
			return;
		}
		serverClosed = true;
		stdOutServer.close();
		stdErrServer.close();
	};

	// Create the process
	logger.info('Forking TSServer', `PATH: ${newEnv['PATH']}`);

	const bootstrapperPath = require.resolve('./electronForkStart');
	childProcess = cp.fork(bootstrapperPath, [modulePath].concat(args), {
		silent: true,
		cwd: options.cwd,
		env: newEnv,
		execArgv: options.execArgv
	});

	childProcess.once('error', (err: Error) => {
		closeServer();
		reject(err);
	});

	childProcess.once('exit', (err: Error) => {
		closeServer();
		reject(err);
	});
}


text:
matlab -nosplash -nodesktop -minimize -r Chat_PC_B_Rx

matlab -nosplash -nodesktop -minimize -r Chat_PC_B_Tx


text:
package org.redisson.api;

import org.redisson.client.codec.Codec;
import reactor.core.publisher.Mono;

/**
 * Reactive interface for Redis pipeline feature.
 *

 * All method invocations on objects
 * from this interface are batched to separate queue and could be executed later
 * with execute() method.
 *
 *
 * @author Nikita Koksharov
 *
 */
public interface RBatchReactive {

    /**
     * Returns stream instance by name
     *

     * Requires Redis 5.0.0 and higher.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name of stream
     * @return RStream object
     */
    <K, V> RStreamReactive<K, V> getStream(String name);

    /**
     * Returns stream instance by name
     * using provided codec for entries.
     *

     * Requires Redis 5.0.0 and higher.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of stream
     * @param codec - codec for entry
     * @return RStream object
     */
    <K, V> RStreamReactive<K, V> getStream(String name, Codec codec);

    /**
     * Returns geospatial items holder instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return Geo object
     */
    <V> RGeoReactive<V> getGeo(String name);

    /**
     * Returns geospatial items holder instance by name
     * using provided codec for geospatial members.
     *
     * @param <V> type of value
     * @param name - name of object
     * @param codec - codec for value
     * @return Geo object
     */
    <V> RGeoReactive<V> getGeo(String name, Codec codec);

    /**
     * Returns Set based Multimap instance by name.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @return SetMultimap object
     */
    <K, V> RSetMultimapReactive<K, V> getSetMultimap(String name);

    /**
     * Returns Set based Multimap instance by name
     * using provided codec for both map keys and values.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @param codec - codec for keys and values
     * @return SetMultimap object
     */
    <K, V> RSetMultimapReactive<K, V> getSetMultimap(String name, Codec codec);

    /**
     * Returns set-based cache instance by name.
     * Uses map (value_hash, value) under the hood for minimal memory consumption.
     * Supports value eviction with a given TTL value.
     *
     *
If eviction is not required then it's better to use regular map {@link #getSet(String, Codec)}.

     *
     * @param <V> type of value
     * @param name - name of object
     * @return SetCache object
     */
    <V> RSetCacheReactive<V> getSetCache(String name);

    /**
     * Returns set-based cache instance by name
     * using provided codec for values.
     * Uses map (value_hash, value) under the hood for minimal memory consumption.
     * Supports value eviction with a given TTL value.
     *
     *
If eviction is not required then it's better to use regular map {@link #getSet(String, Codec)}.

     *
     * @param <V> type of value
     * @param name - name of object
     * @param codec - codec for values
     * @return SetCache object
     */
    <V> RSetCacheReactive<V> getSetCache(String name, Codec codec);

    /**
     * Returns map-based cache instance by name
     * using provided codec for both cache keys and values.
     * Supports entry eviction with a given TTL value.
     *
     *
If eviction is not required then it's better to use regular map {@link #getMap(String, Codec)}.

     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @param codec - codec for keys and values
     * @return MapCache object
     */
    <K, V> RMapCacheReactive<K, V> getMapCache(String name, Codec codec);

    /**
     * Returns map-based cache instance by name.
     * Supports entry eviction with a given TTL value.
     *
     *
If eviction is not required then it's better to use regular map {@link #getMap(String)}.

     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @return MapCache object
     */
    <K, V> RMapCacheReactive<K, V> getMapCache(String name);

    /**
     * Returns object holder by name
     *
     * @param <V> type of value
     * @param name - name of object
     * @return Bucket object
     */
    <V> RBucketReactive<V> getBucket(String name);

    <V> RBucketReactive<V> getBucket(String name, Codec codec);

    /**
     * Returns HyperLogLog object by name
     *
     * @param <V> type of value
     * @param name - name of object
     * @return HyperLogLog object
     */
    <V> RHyperLogLogReactive<V> getHyperLogLog(String name);

    <V> RHyperLogLogReactive<V> getHyperLogLog(String name, Codec codec);

    /**
     * Returns list instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return List object
     */
    <V> RListReactive<V> getList(String name);

    <V> RListReactive<V> getList(String name, Codec codec);

    /**
     * Returns List based MultiMap instance by name.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @return ListMultimap object
     */
    <K, V> RListMultimapReactive<K, V> getListMultimap(String name);

    /**
     * Returns List based MultiMap instance by name
     * using provided codec for both map keys and values.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @param codec - codec for keys and values
     * @return ListMultimap object
     */
    <K, V> RListMultimapReactive<K, V> getListMultimap(String name, Codec codec);

    /**
     * Returns map instance by name.
     *
     * @param <K> type of key
     * @param <V> type of value
     * @param name - name of object
     * @return Map object
     */
    <K, V> RMapReactive<K, V> getMap(String name);

    <K, V> RMapReactive<K, V> getMap(String name, Codec codec);

    /**
     * Returns set instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return Set object
     */
    <V> RSetReactive<V> getSet(String name);

    <V> RSetReactive<V> getSet(String name, Codec codec);

    /**
     * Returns topic instance by name.
     *
     * @param name - name of object
     * @return Topic object
     */
    RTopicReactive getTopic(String name);

    RTopicReactive getTopic(String name, Codec codec);

    /**
     * Returns queue instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return Queue object
     */
    <V> RQueueReactive<V> getQueue(String name);

    <V> RQueueReactive<V> getQueue(String name, Codec codec);

    /**
     * Returns blocking queue instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return BlockingQueue object
     */
    <V> RBlockingQueueReactive<V> getBlockingQueue(String name);

    <V> RBlockingQueueReactive<V> getBlockingQueue(String name, Codec codec);

    /**
     * Returns blocking deque instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return BlockingDeque object
     */
    <V> RBlockingDequeReactive<V> getBlockingDeque(String name);

    <V> RBlockingDequeReactive<V> getBlockingDeque(String name, Codec codec);

    /**
     * Returns deque instance by name.
     *
     * @param <V> type of value
     * @param name - name of object
     * @return Deque object
     */
    <V> RDequeReactive<V> getDeque(String name);

    <V> RDequeReactive<V> getDeque(String name, Codec codec);

    /**
     * Returns "atomic long" instance by name.
     *
     * @param name - name of object
     * @return AtomicLong object
     */
    RAtomicLongReactive getAtomicLong(String name);

    /**
     * Returns atomicDouble instance by name.
     *
     * @param name - name of object
     * @return AtomicDouble object
     */
    RAtomicDoubleReactive getAtomicDouble(String name);

    /**
     * Returns Redis Sorted Set instance by name
     *
     * @param <V> type of value
     * @param name - name of object
     * @return ScoredSortedSet object
     */
    <V> RScoredSortedSetReactive<V> getScoredSortedSet(String name);

    <V> RScoredSortedSetReactive<V> getScoredSortedSet(String name, Codec codec);

    /**
     * Returns String based Redis Sorted Set instance by name
     * All elements are inserted with the same score during addition,
     * in order to force lexicographical ordering
     *
     * @param name - name of object
     * @return LexSortedSet object
     */
    RLexSortedSetReactive getLexSortedSet(String name);

    /**
     * Returns bitSet instance by name.
     *
     * @param name of bitSet
     * @return BitSet object
     */
    RBitSetReactive getBitSet(String name);

    /**
     * Returns script operations object
     *
     * @return Script object
     */
    RScriptReactive getScript();

    /**
     * Returns script operations object using provided codec.
     *
     * @param codec - codec for params and result
     * @return Script object
     */
    RScriptReactive getScript(Codec codec);

    /**
     * Returns keys operations.
     * Each of Redis/Redisson object associated with own key
     *
     * @return Keys object
     */
    RKeysReactive getKeys();

    /**
     * Executes all operations accumulated during Reactive methods invocations Reactivehronously.
     *
     * In cluster configurations operations grouped by slot ids
     * so may be executed on different servers. Thus command execution order could be changed
     *
     * @return List with result object for each command
     */
    Mono<BatchResult<?>> execute();

}


text:
  position: absolute !important;
}

#themer-toggle {
  position: absolute !important;
  top: 0 !important;
  bottom: auto !important;
}


text:
package org.jfree.chart.encoders;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

public class EncoderUtil {
    public static byte[] encode(BufferedImage image, String format) throws IOException {
        return ImageEncoderFactory.newInstance(format).encode(image);
    }

    public static byte[] encode(BufferedImage image, String format, boolean encodeAlpha) throws IOException {
        return ImageEncoderFactory.newInstance(format, encodeAlpha).encode(image);
    }

    public static byte[] encode(BufferedImage image, String format, float quality) throws IOException {
        return ImageEncoderFactory.newInstance(format, quality).encode(image);
    }

    public static byte[] encode(BufferedImage image, String format, float quality, boolean encodeAlpha) throws IOException {
        return ImageEncoderFactory.newInstance(format, quality, encodeAlpha).encode(image);
    }

    public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream) throws IOException {
        ImageEncoderFactory.newInstance(format).encode(image, outputStream);
    }

    public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream, float quality) throws IOException {
        ImageEncoderFactory.newInstance(format, quality).encode(image, outputStream);
    }

    public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream, boolean encodeAlpha) throws IOException {
        ImageEncoderFactory.newInstance(format, encodeAlpha).encode(image, outputStream);
    }

    public static void writeBufferedImage(BufferedImage image, String format, OutputStream outputStream, float quality, boolean encodeAlpha) throws IOException {
        ImageEncoderFactory.newInstance(format, quality, encodeAlpha).encode(image, outputStream);
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.security.keyvault.keys.cryptography;

import com.azure.security.keyvault.keys.cryptography.models.DecryptResult;
import com.azure.security.keyvault.keys.cryptography.models.EncryptResult;
import com.azure.security.keyvault.keys.cryptography.models.EncryptionAlgorithm;
import com.azure.security.keyvault.keys.cryptography.models.KeyWrapAlgorithm;
import com.azure.security.keyvault.keys.cryptography.models.SignResult;
import com.azure.security.keyvault.keys.cryptography.models.SignatureAlgorithm;
import com.azure.security.keyvault.keys.cryptography.models.UnwrapResult;
import com.azure.security.keyvault.keys.cryptography.models.VerifyResult;
import com.azure.security.keyvault.keys.cryptography.models.WrapResult;

/**
 * The LocalCryptographyClient provides synchronous methods to perform cryptographic operations using asymmetric and
 * symmetric keys. The client supports encrypt, decrypt, wrap key, unwrap key, sign and verify operations using the
 * configured key.
 *
 *
Samples to construct the sync client

 * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.instantiation}
 *
 * @see LocalCryptographyClientBuilder
 */
public class LocalCryptographyClient {
    private final LocalCryptographyAsyncClient client;

    /**
     * Creates a LocalCryptographyClient for local cryptography operations.
     *
     * @param client The {@link LocalCryptographyAsyncClient} that the client routes its request through.
     */
    LocalCryptographyClient(LocalCryptographyAsyncClient client) {
        this.client = client;
    }

    /**
     * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a
     * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used.
     * The encrypt operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public
     * portion of the key is used for encryption. This operation requires the keys/encrypt permission.
     *
     *
The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
     * specified encrypted content. Possible values
     * for assymetric keys include: {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP
     * RSA_OAEP}.

     *
     *
Code Samples

     *
Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when
     * a response has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.encrypt#EncryptionAlgorithm-byte}
     *
     * @param algorithm The algorithm to be used for encryption.
     * @param plaintext The content to be encrypted.
     * @return The {@link EncryptResult} whose {@link EncryptResult#getCipherText() cipher text} contains the encrypted
     *     content.
     * @throws UnsupportedOperationException if the encrypt operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm} or  {@code plainText} is null.
     */
    public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) {
        return client.encrypt(algorithm, plaintext).block();
    }

    /**
     * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a
     * single block of data may be decrypted, the size of this block is dependent on the target key and the algorithm to
     * be used. The decrypt operation is supported for both asymmetric and symmetric keys. This operation requires the
     * keys/decrypt permission.
     *
     *
The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the
     * specified encrypted content. Possible values
     * for assymetric keys include: {@link EncryptionAlgorithm#RSA1_5 RSA1_5}, {@link EncryptionAlgorithm#RSA_OAEP
     * RSA_OAEP}.

     *
     *
Code Samples

     *
Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content
     * details when a response has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.decrypt#EncryptionAlgorithm-byte}
     *
     * @param algorithm The algorithm to be used for decryption.
     * @param cipherText The content to be decrypted.
     * @return The decrypted blob.
     * @throws UnsupportedOperationException if the decrypt operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null.
     */
    public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) {
        return client.decrypt(algorithm, cipherText).block();
    }

    /**
     * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and
     * symmetric keys. This operation requires the keys/sign permission.
     *
     *
The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
     * signature from the digest. Possible values include:
     * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384},
     * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES246K}

     *
     *
Code Samples

     *
Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response
     * has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.sign#SignatureAlgorithm-byte}
     *
     * @param algorithm The algorithm to use for signing.
     * @param digest The content from which signature is to be created.
     * @return A {@link SignResult} whose {@link SignResult#getSignature() signature} contains the created signature.
     * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm} or {@code digest} is null.
     */
    public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) {
        return client.sign(algorithm, digest).block();
    }

    /**
     * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric
     * keys.
     * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
     * the keys/verify permission.
     *
     *
The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
     * signature from the digest. Possible values include:
     * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384},
     * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES246K}

     *
     *
Code Samples

     *
Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the
     * verification details when a response has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.verify#SignatureAlgorithm-byte-byte}
     *
     * @param algorithm The algorithm to use for signing.
     * @param digest The content from which signature was created.
     * @param signature The signature to be verified.
     * @return The {@link Boolean} indicating the signature verification result.
     * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null.
     */
    public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) {
        return client.verify(algorithm, digest, signature).block();
    }

    /**
     * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both
     * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission.
     *
     *
The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
     * key content. Possible values include:
     * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5}, {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP}
     * Possible values for symmetric keys include: {@link KeyWrapAlgorithm#A128KW A128KW},
     * {@link KeyWrapAlgorithm#A192KW A192KW} and {@link KeyWrapAlgorithm#A256KW A256KW}.

     *
     *
Code Samples

     *
Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a
     * response has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.wrapKey#KeyWrapAlgorithm-byte}
     *
     * @param algorithm The encryption algorithm to use for wrapping the key.
     * @param key The key content to be wrapped
     * @return The {@link WrapResult} whose {@link WrapResult#getEncryptedKey() encrypted key} contains the wrapped
     *     key result.
     * @throws UnsupportedOperationException if the wrap operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm} or {@code key} is null.
     */
    public WrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
        return client.wrapKey(algorithm, key).block();
    }

    /**
     * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is
     * the reverse of the wrap operation. The unwrap operation supports asymmetric and symmetric keys to unwrap. This
     * operation requires the keys/unwrapKey permission.
     *
     *
The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified
     * key content. Possible values for asymmetric keys include:
     * {@link KeyWrapAlgorithm#RSA1_5 RSA1_5} and  {@link KeyWrapAlgorithm#RSA_OAEP RSA_OAEP}.
     * Possible values for symmetric keys include: {@link KeyWrapAlgorithm#A128KW A128KW}, {@link
     * KeyWrapAlgorithm#A192KW A192KW} and {@link KeyWrapAlgorithm#A256KW A256KW}

     *
     *
Code Samples

     *
Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a
     * response has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.unwrapKey#KeyWrapAlgorithm-byte}
     *
     * @param algorithm The encryption algorithm to use for wrapping the key.
     * @param encryptedKey The encrypted key content to unwrap.
     * @return The unwrapped key content.
     * @throws UnsupportedOperationException if the unwrap operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null.
     */
    public UnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) {
        return client.unwrapKey(algorithm, encryptedKey).block();
    }

    /**
     * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric
     * and symmetric keys. This operation requires the keys/sign permission.
     *
     *
The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
     * signature from the digest. Possible values include:
     * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384},
     * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES246K}.

     *
     *
Code Samples

     *
Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response
     * has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.signData#SignatureAlgorithm-byte}
     *
     * @param algorithm The algorithm to use for signing.
     * @param data The content from which signature is to be created.
     * @return A {@link SignResult} whose {@link SignResult#getSignature() signature} contains the created signature.
     * @throws UnsupportedOperationException if the sign operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm} or {@code data} is null.
     */
    public SignResult signData(SignatureAlgorithm algorithm, byte[] data) {
        return client.signData(algorithm, data).block();
    }

    /**
     * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric
     * keys and asymmetric keys.
     * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires
     * the keys/verify permission.
     *
     *
The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the
     * signature from the digest. Possible values include:
     * {@link SignatureAlgorithm#ES256 ES256}, {@link SignatureAlgorithm#ES384 E384},
     * {@link SignatureAlgorithm#ES512 ES512}, {@link SignatureAlgorithm#ES256K ES246K}.

     *
     *
Code Samples

     *
Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the
     * verification details when a response has been received.

     * {@codesnippet com.azure.security.keyvault.keys.cryptography.LocalCryptographyClient.verifyData#SignatureAlgorithm-byte-byte}
     *
     * @param algorithm The algorithm to use for signing.
     * @param data The raw content against which signature is to be verified.
     * @param signature The signature to be verified.
     * @return The {@link VerifyResult} holding the signature verification result.
     * @throws UnsupportedOperationException if the verify operation is not supported or configured on the key.
     * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null.
     */
    public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) {
        return client.verifyData(algorithm, data, signature).block();
    }
}


text:
package mesosphere.marathon
package core.appinfo

import java.time.{OffsetDateTime, ZoneOffset}

import mesosphere.UnitTest
import mesosphere.marathon.core.health.Health
import mesosphere.marathon.core.instance.Instance.AgentInfo
import mesosphere.marathon.core.instance.{Instance, TestInstanceBuilder, TestTaskBuilder}
import mesosphere.marathon.state.{PathId, Timestamp, UnreachableStrategy, VersionInfo}
import play.api.libs.json.Json

import scala.concurrent.duration._

class TaskStatsByVersionTest extends UnitTest {

  "TaskStatsByVersion" should {
    "no tasks" in {
      Given("no tasks")
      When("calculating stats")
      val stats = TaskStatsByVersion(
        now = now,
        versionInfo = versionInfo,
        instances = Seq.empty,
        statuses = Map.empty[Instance.Id, Seq[Health]]
      )
      Then("we get none")
      stats should be(
        TaskStatsByVersion(
          maybeStartedAfterLastScaling = None,
          maybeWithLatestConfig = None,
          maybeWithOutdatedConfig = None,
          maybeTotalSummary = None
        )
      )
    }

    "tasks are correctly split along categories" in {
      Given("various tasks")
      val outdatedInstances = Vector(
        runningInstanceStartedAt(outdatedVersion, 1.seconds),
        runningInstanceStartedAt(outdatedVersion, 2.seconds)
      )
      val afterLastScalingTasks = Vector(
        runningInstanceStartedAt(lastScalingAt, 1.seconds),
        runningInstanceStartedAt(lastScalingAt, 2.seconds)
      )
      val afterLastConfigChangeTasks = Vector(
        runningInstanceStartedAt(lastConfigChangeAt, 1.seconds),
        runningInstanceStartedAt(intermediaryScalingAt, 2.seconds)
      ) ++ afterLastScalingTasks

      val instances: Seq[Instance] = outdatedInstances ++ afterLastConfigChangeTasks
      val statuses = Map.empty[Instance.Id, Seq[Health]]

      When("calculating stats")
      val stats = TaskStatsByVersion(
        now = now,
        versionInfo = versionInfo,
        instances = instances,
        statuses = statuses
      )
      Then("we get the correct stats")
      import mesosphere.marathon.api.v2.json.Formats._
      withClue(Json.prettyPrint(Json.obj("stats" -> stats, "tasks" -> instances.map(state.Instance.fromCoreInstance)))) {
        stats.maybeWithOutdatedConfig should not be empty
        stats.maybeWithLatestConfig should not be empty
        stats.maybeStartedAfterLastScaling should not be empty
        stats.maybeTotalSummary should not be empty

        stats.maybeWithOutdatedConfig should be(TaskStats.forSomeTasks(now, outdatedInstances, statuses))
        stats.maybeWithLatestConfig should be(TaskStats.forSomeTasks(now, afterLastConfigChangeTasks, statuses))
        stats.maybeStartedAfterLastScaling should be(TaskStats.forSomeTasks(now, afterLastScalingTasks, statuses))
        stats.maybeTotalSummary should be(TaskStats.forSomeTasks(now, instances, statuses))

        stats should be(
          TaskStatsByVersion(
            maybeStartedAfterLastScaling = TaskStats.forSomeTasks(now, afterLastScalingTasks, statuses),
            maybeWithLatestConfig = TaskStats.forSomeTasks(now, afterLastConfigChangeTasks, statuses),
            maybeWithOutdatedConfig = TaskStats.forSomeTasks(now, outdatedInstances, statuses),
            maybeTotalSummary = TaskStats.forSomeTasks(now, instances, statuses)
          )
        )
      }

    }
  }
  private[this] val now: Timestamp = Timestamp(OffsetDateTime.of(2015, 4, 9, 12, 30, 0, 0, ZoneOffset.UTC))
  private val lastScalingAt: Timestamp = now - 10.seconds
  private val intermediaryScalingAt: Timestamp = now - 20.seconds
  private val lastConfigChangeAt: Timestamp = now - 100.seconds
  private val outdatedVersion: Timestamp = now - 200.seconds
  private[this] val versionInfo = VersionInfo.FullVersionInfo(
    version = lastScalingAt,
    lastScalingAt = lastScalingAt,
    lastConfigChangeAt = lastConfigChangeAt
  )
  val appId = PathId("/test")
  private[this] def newInstanceId(): Instance.Id = Instance.Id.forRunSpec(appId)

  private[this] def runningInstanceStartedAt(version: Timestamp, startingDelay: FiniteDuration): Instance = {
    val startedAt = (version + startingDelay).millis
    val agentInfo = AgentInfo(host = "host", agentId = Some("agent"), region = None, zone = None, attributes = Nil)
    TestInstanceBuilder.fromTask(
      TestTaskBuilder.Helper.runningTask(newInstanceId(), appVersion = version, startedAt = startedAt),
      agentInfo,
      unreachableStrategy = UnreachableStrategy.default()
    )
  }
}


text:
@interface PCSBlurView()

@property (nonatomic, strong) UIToolbar *toolbar;

@end

@implementation PCSBlurView

- (id)initWithFrame:(CGRect)frame {
   if ((self = [super initWithFrame:frame])) {
      self.toolbar = [[UIToolbar alloc] initWithFrame:self.bounds];
      self.toolbar.barStyle = UIBarStyleDefault;
      self.toolbar.translucent = YES;
      self.toolbar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
      self.toolbar.clipsToBounds = YES;
      [self addSubview:self.toolbar];
   }
   return self;
}

@end


text:
package com.theclothingstore.mystore.fragments.shopingcart;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.theclothingstore.mystore.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Anand Soni
 */

public class CartListViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.product_name)
    TextView productName;
    @BindView(R.id.product_price)
    TextView productPrice;
    @BindView(R.id.button_remove_cart)
    Button removeCart;

    private final OnCartRemoveListener listener;

    CartListViewHolder(View itemView, OnCartRemoveListener listener) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        this.listener = listener;
    }

    @OnClick(R.id.button_remove_cart)
    void onRemoveCartClick(View view) {
        listener.onCartItemRemove(view, Integer.parseInt(String.valueOf(view.getTag())));
    }

    interface OnCartRemoveListener {
        void onCartItemRemove(View view, int cartId);
    }

}


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

class Category_Model extends Api_Model {

	public function __construct()
	{
		parent::__construct();
	}

	public function get_category($pid=0)
	{
		$params['page'] = 1;
		$params['limit'] = 100;
		$params['parent_id'] = $pid;
		$response = $this->post(BASE_API_URL.'product_category/categoryList' , $params);
		// var_dump($response);exit();
		return $response;
	}

	public function get_category_detail($params='')
	{
		$response = $this->post(BASE_API_URL.'product_category/categoryDetail' , $params);
		return $response;
	}

	public function update_category($params='')
	{
		$response = $this->post(BASE_API_URL.'product_category/categoryUpdate' , $params);
		return $response;
	}

	public function create_category($params='')
	{
		$response = $this->post(BASE_API_URL.'product_category/categoryCreate' , $params);
		// var_dump($response);exit();
		return $response;
	}
}


text:
"""Tests of various renderers"""

import json

import pytest

import altair.vegalite.v5 as alt

@pytest.fixture
def chart():
    return alt.Chart("data.csv").mark_point()

def test_html_renderer_embed_options(chart, renderer="html"):
    """Test that embed_options in renderer metadata are correctly manifest in html"""
    # Short of parsing the javascript, it's difficult to parse out the
    # actions. So we use string matching

    def assert_has_options(chart, **opts):
        html = chart._repr_mimebundle_(None, None)["text/html"]
        for key, val in opts.items():
            assert json.dumps({key: val})[1:-1] in html

    with alt.renderers.enable(renderer):
        assert_has_options(chart, mode="vega-lite")

        with alt.renderers.enable(embed_options=dict(actions={"export": True})):
            assert_has_options(chart, mode="vega-lite", actions={"export": True})

        with alt.renderers.set_embed_options(actions=True):
            assert_has_options(chart, mode="vega-lite", actions=True)

def test_mimetype_renderer_embed_options(chart, renderer="mimetype"):
    # check that metadata is passed appropriately
    mimetype = alt.display.VEGALITE_MIME_TYPE
    spec = chart.to_dict()
    with alt.renderers.enable(renderer):
        # Sanity check: no metadata specified
        bundle, metadata = chart._repr_mimebundle_(None, None)
        assert bundle[mimetype] == spec
        assert metadata == {}
        with alt.renderers.set_embed_options(actions=False):
            bundle, metadata = chart._repr_mimebundle_(None, None)
            assert set(bundle.keys()) == {mimetype, "text/plain"}
            assert bundle[mimetype] == spec
            assert metadata == {mimetype: {"embed_options": {"actions": False}}}

def test_json_renderer_embed_options(chart, renderer="json"):
    """Test that embed_options in renderer metadata are correctly manifest in html"""
    mimetype = "application/json"
    spec = chart.to_dict()
    with alt.renderers.enable(renderer):
        # Sanity check: no options specified
        bundle, metadata = chart._repr_mimebundle_(None, None)
        assert bundle[mimetype] == spec
        assert metadata == {}

        with alt.renderers.enable(option="foo"):
            bundle, metadata = chart._repr_mimebundle_(None, None)
            assert set(bundle.keys()) == {mimetype, "text/plain"}
            assert bundle[mimetype] == spec
            assert metadata == {mimetype: {"option": "foo"}}


text:
sige

Change the settings of the site <?php echo $name;?>

  <?php
  if(isset($_POST['submit'])){
    $output = $_POST['output'];
    $tagline = $_POST['tagline'];
    $theme = isset($_POST['theme']) ? $_POST['theme'] : "";
    if($output != "" && $theme != ""){
      if(!file_exists($output) || !is_writable($output)){
        \Lobby::ser("Output Path problem", "The path you gave as output doesn't exist or permission is not acceptable. Make sure it's an existing directory with Read & Write permission", false);
      }else if(array_search($theme, $this->themes) === false){
        \Lobby::ser("Invalid Theme", "The theme you selected doesn't exist", false);
      }else{
        // Everything's great
        $this->addSite($name, $tagline, $output, $theme, (isset($_POST['empty']) ? 1 : 0), (isset($_POST['titleTag']) ? 1 : 0));

        /* Generate the site */
        $gSite = new \Lobby\App\sige\Site($this->getSite($name), $this);
        $gSite->generate($this->getPages($name));
        \Lobby::sss("Site updated", "The site was updated and generated successfully");
      }
    }else{
      \Lobby::ser("Fill Up", "Please fill the form completely", false);
    }
  }
  ?>
  <form action="<?php echo \Lobby::u();?>" method="POST" clear>
    <?php
    $site = $this->getSite($name);
    $empty = $site['empty'] == 1 ? "checked='checked'" : "";
    $titleTag = isset($site['titleTag']) && $site['titleTag'] == 1 ? "checked='checked'" : "";
    if($site !== false){
    ?>

Tagline

        <input type="text" name="tagline" title="The tagline of site" value="<?php echo $site['tagline'];?>" />
      <cl/>

Output location

        <input type="text" name="output" title="Where the generated site should be extracted" value="<?php echo $site['out'];?>" />
      <cl/>

Empty Output location

        <input type="checkbox" name="empty" title="Should the contents of output directory be removed before making the site" <?php echo $empty;?>/>

Append Site Name to <title> tag

        <input type="checkbox" name="titleTag" title="Append the site name after page title ? Example : 'My Page - Delicious Blog'" <?php echo $titleTag;?>/>

Theme

        <?php
        foreach($this->themes as $theme){
          $checked = $site['theme'] == $theme ? "checked" : "false";
        ?>

            <a title="Click to see example" target="_blank" href="<?php echo $this->u("/src/data/themes/{$theme}/example.html");?>">
              <img src="<?php echo APP_SRC . "/src/data/themes/{$theme}/thumbnail.png";?>" />

            <input type="radio" name="theme" value="<?php echo $theme;?>" checked="<?php echo $checked;?>" />

        <?php
        }
        ?>

    <?php
    }
    ?>

      <button name="submit">Update Settings</button>

  </form>


text:
require 'protobuf/field/base_field'

module Protobuf
  module Field
    class MessageField < BaseField

      ##
      # Public Instance Methods
      #

      def acceptable?(val)
        val.is_a?(type_class) || val.respond_to?(:to_hash) || val.respond_to?(:to_proto)
      end

      def decode(bytes)
        type_class.decode(bytes)
      end

      def encode(value)
        bytes = value.encode
        result = ::Protobuf::Field::VarintField.encode(bytes.bytesize)
        result << bytes
      end

      def message?
        true
      end

      def wire_type
        ::Protobuf::WireType::LENGTH_DELIMITED
      end

      def coerce!(value)
        return nil if value.nil?

        coerced_value = if value.respond_to?(:to_proto)
                          value.to_proto
                        elsif value.respond_to?(:to_hash)
                          type_class.new(value.to_hash)
                        else
                          value
                        end

        return coerced_value if coerced_value.is_a?(type_class)

        fail TypeError, "Expected value of type '#{type_class}' for field #{name}, but got '#{value.class}'"
      end

    end
  end
end


text:
"""
``scenesim.objects.pso``
========================

Physics SceneSim objects.

"""
from abc import ABCMeta, abstractmethod
from collections import Iterable, OrderedDict
from contextlib import contextmanager
from ctypes import c_float
from functools import wraps
from itertools import izip
import re
##
import numpy as np
import panda3d.bullet as p3b
from panda3d.bullet import BulletBodyNode, BulletGhostNode, BulletRigidBodyNode
from panda3d.core import (BitMask32, Mat4, NodePathCollection, Point3,
                          TransformState, Vec3)
##
from scenesim.objects.sso import SSO
##
from pdb import set_trace as BP

def cast_c_float(func):
    """ Decorator for casting a function's return value to ctypes.f32."""
    def func_c_float(*args, **kwargs):
        return c_float(func(*args, **kwargs)).value
    return func_c_float

class BaseShape(list):
    """ Base class for shape objects."""
    __metaclass__ = ABCMeta
    _type_rx = re.compile("Bullet(.+)Shape")

    def __new__(cls, *args, **kwargs):
        """ Set cls._bshape by reading from bases of derived class."""
        obj = super(BaseShape, cls).__new__(cls)
        cls.name = cls.read_name(cls.bshape)
        return obj

    @classmethod
    def _fix_args(cls, args):
        """ Standardize the BulletShape arguments."""
        args1 = cls.args0.copy()
        if isinstance(args, dict):
            args1.update(args)
        else:
            for key, prm in izip(args1, args):
                args1[key] = prm
        return args1.values()

    @staticmethod
    def _fix_xform(T):
        """ Converts T into a valid xform. Returns None on fail."""
        # If T has "flat" attribute, it is an ndarray and that should
        # be returned. Otherwise just return T.
        if not T:
            xform = TransformState.makeIdentity()
        else:
            if not isinstance(T, TransformState):
                mat = Mat4(*T.flat) if hasattr(T, "flat") else Mat4(T)
                xform = TransformState.makeMat(mat)
            else:
                xform = T
        return xform

    @classmethod
    def _fix_prms(cls, p):
        """ Standardizes parameters."""
        if not isinstance(p, Iterable) or isinstance(p, str) or len(p) > 2:
            raise ValueError("Bad input: %s" % p)
        elif len(p) == 0:
            prms = [(), None]
        elif len(p) == 1:
            prms = [p[0], None]
        else:
            prms = list(p)
        # Make prms into list with fixed args and xform.
        prms = [cls._fix_args(prms[0]), cls._fix_xform(prms[1])]
        return prms

    def __init__(self, *prms):
        """ Initialize."""
        prms = self._fix_prms(prms)
        super(BaseShape, self).__init__(prms)

    def init(self):
        """ Return the initialized Bullet*Shape and the xform."""
        args, xform = self
        bshape = self.bshape(*args)
        return bshape, xform

    @classmethod
    def read_name(cls, bshape):
        return cls._type_rx.match(bshape.__name__).group(1)

    @classmethod
    def read_params(cls, bshape):
        return [getattr(bshape, "get%s" % key)() for key in cls.args0]

    @abstractmethod
    def scale(self, scale):
        """ Scales shape arguments."""
        pass

    def shift(self, pos=(0, 0, 0), quat=(1, 0, 0, 0), scale=(1, 1, 1)):
        """ Translate and rotate shape's transform."""
        T = TransformState.makePosQuatScale(pos, quat, scale)
        xform = T.compose(self[1])
        self[1] = xform

    def transform(self, node, other=None):
        """ Shift and scale the shape by node's transform."""
        if other is None:
            other = node.get_parent()
        scale = node.get_scale(other)
        pos = node.get_pos(other)
        quat = node.get_quat(other)
        self.scale(scale)
        self.shift(pos=pos, quat=quat, scale=scale)

class BoxShape(BaseShape):
    """ BulletBoxShape."""
    bshape = p3b.BulletBoxShape
    args0 = OrderedDict((("HalfExtentsWithMargin", Vec3(0.5, 0.5, 0.5)),))

    def scale(self, scale):
        args = (Vec3(*[s * a for s, a in izip(scale, self[0][0])]),)
        self[0] = args

class CapsuleShape(BaseShape):
    """ BulletCapsuleShape."""
    bshape = p3b.BulletCapsuleShape
    args0 = OrderedDict((("Radius", 0.5), ("HalfHeight", 0.5)))

    def scale(self, scale):
        if scale[0] != scale[1]:
            raise ValueError("%s does not support anisotropic x,y scaling" %
                             self.bshape)
        self[0] = (scale[0] * self[0][0], scale[2] * self[0][1])

class ConeShape(BaseShape):
    """ BulletConeShape."""
    bshape = p3b.BulletConeShape
    args0 = OrderedDict((("Radius", 0.5), ("Height", 1.)))

    def scale(self, scale):
        if scale[0] != scale[1]:
            raise ValueError("%s does not support anisotropic x,y scaling" %
                             self.bshape)
        self[0] = (scale[0] * self[0][0], scale[2] * self[0][1])

class ConvexHullShape(BaseShape):
    """ BulletConvexHullShape."""
    bshape = p3b.BulletConvexHullShape
    args0 = OrderedDict()

    def __init__(self, *args, **kwargs):
        super(ConvexHullShape, self).__init__()
        self.array = args[0][0] if args[0] else None

    def init(self):
        """ Return the initialized Bullet*Shape and the xform."""
        bshape, xform = super(ConvexHullShape, self).init()
        if self.array is not None:
            array = map(lambda a: Vec3(*a), self.array)
            bshape.add_array(array)
        return bshape, xform

    def scale(self, scale):
        if scale[0] != scale[1]:
            raise ValueError("%s does not support anisotropic x,y scaling" %
                             self.bshape)
        self[0] = (scale[0] * self[0][0], scale[2] * self[0][1])

class CylinderShape(BaseShape):
    """ BulletCylinderShape. Height is along the Z axis."""
    bshape = p3b.BulletCylinderShape
    args0 = OrderedDict((("Radius", 0.5), ("Height", 1.)))

    def scale(self, scale):
        if scale[0] != scale[1]:
            raise ValueError("%s does not support anisotropic x,y scaling" %
                             self.bshape)
        self[0] = (scale[0] * self[0][0], scale[2] * self[0][1])

class PlaneShape(BaseShape):
    """ BulletPlaneShape."""
    bshape = p3b.BulletPlaneShape
    args0 = OrderedDict((("PlaneNormal", Vec3(0, 0, 1)), ("PlaneConstant", 0)))

    def scale(self, scale):
        s = self[0][0].dot(Vec3(*scale)) / self[0][0].length()
        args = (self[0][0], self[0][1] * s)
        self[0] = args

class SphereShape(BaseShape):
    """ BulletSphereShape."""
    bshape = p3b.BulletSphereShape
    args0 = OrderedDict((("Radius", 0.5),))

    def scale(self, scale):
        if (scale[0] != scale[1]) or (scale[0] != scale[2]):
            raise ValueError("%s does not support anisotropic x,y,z scaling" %
                             self.bshape)
        self[0] = (scale[0] * self[0][0],)

class ShapeManager(object):
    """ Utility class for making *Shape objects and reading BulletShapes."""

    _name2shape = {
        "Box": BoxShape,
        "Capsule": CapsuleShape,
        "Cone": ConeShape,
        "ConvexHull": ConvexHullShape,
        "Cylinder": CylinderShape,
        "Plane": PlaneShape,
        "Sphere": SphereShape}

    @classmethod
    def make1(cls, val):
        """ Initialize a *Shape object from input."""
        if isinstance(val, str):
            type_ = cls._name2shape[val]
            prms = [(), None]
        else:
            type_ = cls._name2shape[val[0]]
            prms = val[1:]
        return type_(*prms)

    @classmethod
    def make(cls, vals):
        """ Standardizes list of vals."""
        if isinstance(vals, str):
            vals = [[vals, (), None]]
        elif isinstance(vals[0], str):
            vals = [vals]
        # Verify that vals contains valid names and xform matrices.
        shapes = [cls.make1(val) for val in vals]
        return shapes

    @classmethod
    def read(cls, node):
        """ Get shape list from Bullet*Shape(s)."""
        # Get valid node.
        try:
            node = node.node()
        except AttributeError:
            pass
        # Get shapes.
        n_shapes = node.getNumShapes()
        if n_shapes == 0:
            # For no shape, return "".
            shapes = []
        else:
            # For 1+ shapes.
            parent = node.getParent()
            node.detachNode()
            shapes = []
            for i in xrange(n_shapes):
                # Get shape and shape's matrix.
                bshape = node.getShape(i)
                # Get name.
                name = cls.read_name(bshape)
                # Get params.
                Shape = cls._name2shape[name]
                params = Shape.read_params(bshape)
                # Get xform.
                xform = TransformState.makeMat(node.getShapeMat(i))
                # Store.
                shapes.append((name, params, xform))
            node.reparentTo(parent)
        return shapes

class ShapeList(list):
    """ List of *Shapes."""

    def __init__(self, val=""):
        super(ShapeList, self).__init__(ShapeManager.make(val))

    def __setitem__(self, key, val):
        super(ShapeList, self).__setitem__(key, ShapeManager.make1(val))

    def __add__(self, val):
        super(ShapeList, self).__add__(ShapeManager.make(val))

    def __iadd__(self, val):
        super(ShapeList, self).__iadd__(ShapeManager.make(val))

    def append(self, val):
        super(ShapeList, self).append(ShapeManager.make1(val))

    def extend(self, val):
        super(ShapeList, self).extend(ShapeManager.make(val))

    def insert(self, key, val):
        super(ShapeList, self).insert(key, ShapeManager.make1(val))

    def init(self):
        """ Build the BulletShapes (bshapes) and TransformStates
        (xforms)."""
        bshapes = []
        xforms = []
        for shape in self:
            bshape, xform = shape.init()
            bshapes.append(bshape)
            xforms.append(xform)
        return bshapes, xforms

class PSO(SSO):
    """ Bullet physics object."""

    type_ = BulletBodyNode
    _prop_tags = ("friction", "restitution", "shape", "deactivation_enabled")
    _res_tags = ("shape",)

    def __init__(self, *args, **kwargs):
        # Converts args so they're appropriate for self.type_.
        if len(args) == 0:
            args = ("",)
        if isinstance(args[0], (str, unicode)):
            args = (self.type_(args[0]),) + args[1:]
            tag = self.__class__
        else:
            tag = None
        ## Using super fails, probably because NodePath is a C++ class.
        # super(PSO, self).__init__(self, *new_args, **kwargs)
        SSO.__init__(self, *args, **kwargs)
        if tag:
            self.setPythonTag("sso", tag)

    @wraps(type_.set_friction, assigned=("__name__", "__doc__"))
    def set_friction(self, friction):
        self.node().set_friction(friction)

    @cast_c_float
    @wraps(type_.get_friction, assigned=("__name__", "__doc__"))
    def get_friction(self):
        return self.node().get_friction()

    @wraps(type_.set_restitution, assigned=("__name__", "__doc__"))
    def set_restitution(self, restitution):
        self.node().set_restitution(restitution)

    @cast_c_float
    @wraps(type_.get_restitution, assigned=("__name__", "__doc__"))
    def get_restitution(self):
        return self.node().get_restitution()

    def set_shape(self, shape):
        self.setPythonTag("shape", shape)

    def get_shape(self):
        if "shape" not in self.getPythonTagKeys():
            self.set_shape("")
        return self.getPythonTag("shape")

    def add_shape(self, shapes):
        """ Adds the shape."""
        # Construct the BulletShapes.
        bshapes, xforms = shapes.init()
        for bshape, xform in izip(bshapes, xforms):
            # Add each to the BulletBodyNode.
            self.node().addShape(bshape, xform)

    def create_shape(self):
        """ Initializes a BulletShape(s)."""
        shapes = ShapeList(self.get_shape())
        self.add_shape(shapes)
        self.setTag("resource", "shape")

    def delete_shape(self):
        """ Destroys the BulletShape(s)."""
        shapes = self.node().getShapes()
        for shape in shapes:
            self.node().removeShape(shape)
        self.clearTag("resource")

    @wraps(type_.set_deactivation_enabled, assigned=("__name__", "__doc__"))
    def set_deactivation_enabled(self, is_enabled):
        return self.node().set_deactivation_enabled(is_enabled)

    @wraps(type_.is_deactivation_enabled, assigned=("__name__", "__doc__"))
    def get_deactivation_enabled(self):
        return self.node().is_deactivation_enabled()

class RBSO(PSO):
    type_ = BulletRigidBodyNode
    _prop_tags = ("linear_velocity", "angular_velocity", "mass", "gravity",
                  "into_collide_mask")
    _res_tags = ()

    @wraps(type_.set_mass, assigned=("__name__", "__doc__"))
    def set_mass(self, mass):
        self.node().set_mass(mass)

    @cast_c_float
    @wraps(type_.get_mass, assigned=("__name__", "__doc__"))
    def get_mass(self):
        return self.node().get_mass()

    @wraps(type_.set_linear_velocity, assigned=("__name__", "__doc__"))
    def set_linear_velocity(self, linear_velocity):
        self.node().set_linear_velocity(linear_velocity)

    @wraps(type_.get_linear_velocity, assigned=("__name__", "__doc__"))
    def get_linear_velocity(self):
        return self.node().get_linear_velocity()

    @wraps(type_.set_angular_velocity, assigned=("__name__", "__doc__"))
    def set_angular_velocity(self, angular_velocity):
        self.node().set_angular_velocity(angular_velocity)

    @wraps(type_.get_angular_velocity, assigned=("__name__", "__doc__"))
    def get_angular_velocity(self):
        return self.node().get_angular_velocity()

    @wraps(type_.set_gravity, assigned=("__name__", "__doc__"))
    def set_gravity(self, grav):
        return self.node().set_gravity(grav)

    @wraps(type_.get_gravity, assigned=("__name__", "__doc__"))
    def get_gravity(self):
        return self.node().get_gravity()

    @wraps(type_.set_into_collide_mask, assigned=("__name__", "__doc__"))
    def set_into_collide_mask(self, into_collide_mask):
        if isinstance(into_collide_mask, int):
            into_collide_mask = BitMask32.bit(into_collide_mask)
        self.node().set_into_collide_mask(into_collide_mask)

    @wraps(type_.get_into_collide_mask, assigned=("__name__", "__doc__"))
    def get_into_collide_mask(self):
        return int(np.log2(self.node().get_into_collide_mask().get_word()))

    def set_center_of_mass(self, com, other=None):
        """Sets center of mass of object.

        Args:
            pos (seq): Position coordinates (3 elements).

        Kwargs:
            other (NodePath): The node which the new state is set relative to.
                              (default=self.getParent())
        """
        if other is None:
            other = self.getParent()
        pos = self.get_pos(other)  # Current node position.
        # Read existing shape.
        shapes = []
        shapes0 = ShapeList(self.get_shape())
        for shape0 in shapes0:
            name = shape0.name
            args0, xform0 = shape0
            if name != "Box":
                print("Can't handle that shape: %s" % name)
                BP()
            shape = ShapeManager.make1((name, args0, xform0))
            # shape.transform(self, other=self)
            shape.shift(pos=-com)
            s = (name, shape[0], shape[1])
            shapes.append(s)
        # Set compound object's shapes tag.
        self.set_shape(shapes)
        # Move object position to new com.
        self.set_pos(other, com + pos)

    # def get_center_of_mass(self):
    #     """Return center of mass of object, with respect to node's
    #     coordinate frame.

    #     Return:
    #         (seq): Position coordinates (3 elements).
    #     """
    #     pos = self.node().get
    #     return pos

class CPSO(RBSO):
    """ Bullet physics object, specialized for compound shapes."""

    def __init__(self, *args, **kwargs):
        if len(args) == 0:
            args = ("compound",)
        super(CPSO, self).__init__(*args, **kwargs)

    @property
    def components(self):
        return self.descendants(depths=[1], type_=PSO)

    @contextmanager
    def _preserve_child_tranforms(self):
        """ Remember transforms of existing children to avoid
        center-of-mass shift."""
        parent = self.getParent()
        descendants = self.descendants(depths=[1])
        # Remember child transforms.
        mats = [child.get_mat(parent) for child in descendants]
        yield parent
        # Update transforms of existing children.
        for descendant, mat in izip(descendants, mats):
            descendant.set_mat(parent, mat)

    def _compute_shapes(self):
        """ Computes shapes from self.components."""
        masses = []
        poses = []
        psos = self.descendants(depths=[1], type_=PSO)
        parent = self.getParent()
        for pso in psos:
            mass = pso.get_mass()
            pos = pso.get_pos(parent)
            if mass == 0.:
                com = pos
                break
            poses.append(pos)
            masses.append(mass)
        else:
            mass = np.sum(masses)
            com = Point3(*(np.sum(np.array(poses).T * masses, axis=-1) / mass))
        self.set_mass(mass)
        with self._preserve_child_tranforms() as parent:
            self.set_pos(parent, com)
        # Add shapes from PSOs.
        vals = []
        for pso in psos:
            shapes0 = ShapeList(pso.get_shape())
            for shape0 in shapes0:
                name = shape0.name
                args0, xform0 = shape0
                if name != "Box":
                    print("Can't handle that shape: %s" % name)
                    BP()
                shape = ShapeManager.make1((name, args0, xform0))
                shape.transform(pso, other=self)
                val = (name, shape[0], shape[1])
                vals.append(val)
        # Set compound object's shapes tag.
        self.set_shape(vals)

    def add(self, psos):
        """ Add sequence of PSOs to compound object."""
        NodePathCollection(psos).wrtReparentTo(self)
        self._compute_shapes()

    def remove(self, psos):
        """ Remove sequence of PSOs from compound object."""
        with self._preserve_child_tranforms():
            NodePathCollection(psos).detach()
        if self.getNumChildren() > 0:
            self._compute_shapes()

    def destroy_component_shapes(self):
        """ Destroys the shape resources of the component PSOs."""
        for pso in self.components:
            pso.destroy_resources(tags=("shape",))

    def remove_component_bodies(self, bbase):
        """ Destroys the shape resources of the component PSOs."""
        bbase.remove(self.components)

    def init_tree(self, tags=None):
        """ Overrides parent's init_tree() so that components' shapes are not
        initialized."""
        super(CPSO, self).init_tree(tags=tags)
        # if tags is None or "shape" in tags:
        self.destroy_component_shapes()

class GHSO(PSO):
    """ PSO subclass for `BulletGhostNode`s."""

    type_ = BulletGhostNode
    _prop_tags = ("num_overlapping_nodes", "overlapping_nodes")
    _res_tags = ()

    @wraps(type_.get_num_overlapping_nodes, assigned=("__name__", "__doc__"))
    def get_num_overlapping_nodes(self):
        return self.node().get_num_overlapping_nodes()

    @wraps(type_.get_overlapping_nodes, assigned=("__name__", "__doc__"))
    def get_overlapping_nodes(self):
        return self.node().get_overlapping_nodes()


text:
import lacuna.spy

class inteltraining(lacuna.spy.Training):
    path = 'inteltraining'

    def __init__( self, client, body_id:int = 0, building_id:int = 0 ):
        super().__init__( client, body_id, building_id )