text:
/**
 * Created by jdifebo on 3/12/2016.
 */
"use strict";

/**
 * A Markov chain language model that builds words one letter at a time.
 *
 * @param examples is a 1-dimentional array of strings
 */
function buildMarkovModel(examples, markovChainOrder) {
    var letterCounts = {};
    var existingWords = {};
    for (var i = 0; i < examples.length; i++) {
        var word = examples[i];
        existingWords[word] = true;
        for (var j = 0; j < word.length + 1; j++) {
            var previousLetters = word.substring(j - markovChainOrder, j);
            var currentLetter = word[j] || "";
            if (letterCounts[previousLetters] === undefined) {
                letterCounts[previousLetters] = { total: 0 };
            }
            letterCounts[previousLetters].total += 1;
            if (letterCounts[previousLetters][currentLetter] == undefined) {
                letterCounts[previousLetters][currentLetter] = 1;
            }
            else {
                letterCounts[previousLetters][currentLetter] += 1;
            }

        }
    }

    function generateNextLetter(previousLetters) {
        var rand = getRandomInt(0, letterCounts[previousLetters]["total"]);
        for (var y in letterCounts[previousLetters]) {
            if (y != "total") {
                if (rand < letterCounts[previousLetters][y]) {
                    return y;
                } else {
                    rand -= letterCounts[previousLetters][y];
                }
            }
        }
        return undefined;

        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min)) + min;
        };
    }

    function generateAnyWord() {
        var word = "";
        var nextLetter = undefined;
        while (nextLetter != "") {   // generating a blank string means end of word!
            nextLetter = generateNextLetter(word.substring(word.length - markovChainOrder));
            word += nextLetter;
        }
        return word;
    }

    /**
     * Probably not the best method name but that's what comments are for.
     *
     * A word is qualifying if it is
     *     (a) Not already in the list of words that we pasted in
     *     (b) Matches our filter criteria
     */
    function generateQualifyingWord(minLength, maxLength, matchingRegex) {
        while (true) {
            var word = generateAnyWord();
            if (existingWords[word] == undefined
                && (isNaN(minLength) || word.length >= minLength)
                && (isNaN(maxLength) || word.length <= maxLength)
                && (matchingRegex === undefined || matchingRegex.test(word))
            ) {
                return word;
            }
        }
    }

    return { generateWord: generateQualifyingWord }
}

/**
 * Currently not being used because it was slower than my noticably pervious hacky code :(
 *
 * A general purpose Markov chain language model.  You must supply an array of examples at build-time, along with the
 * Markov chain order.  At this time, there is no support for incrementally building the model.
 *
 * For now, I'm using the tab character internally, so that will break lots of things if it's actually present in
 * any of the tokens.
 *
 * @param examples a 2d array of non-empty strings.  examples[i] gives the ith example.  examples[i][j] gives the jth
 * token of the ith example.  Tokens could be letters, syllables, words, phrases, however you choose to break up each
 * example
 * @param markovChainOrder number of previous tokens that the next generated token depends on
 */
function buildMarkovModelGeneralPurpose(examples, markovChainOrder) {

    var tokenCounts = {};   // A place to hold our counts
    var existingSequences = {}; // A list of sequences we've seen while building the model

    for (var i = 0; i < examples.length; i++) {
        existingSequences[examples[i]] = true;
        for (var j = 0; j < examples[i].length; j++) {
            // We want to count the occurrence of this token, but we must look at the past tokens to know what to increment
            var previousTokens = examples[i].slice(Math.max(j - markovChainOrder, 0), j);
            if (tokenCounts[previousTokens] === undefined) {
                tokenCounts[previousTokens] = wordCounter();
            }
            var token = examples[i][j];
            tokenCounts[previousTokens].addNextToken(token);
        }
        var previousTokens = examples[i].slice(Math.max(j - markovChainOrder, 0), j);
        if (tokenCounts[previousTokens] === undefined) {
            tokenCounts[previousTokens] = wordCounter();
        }
        tokenCounts[previousTokens].addNextToken('');    // use an empty string to denote end-of-sequence
    }

    /**
     * Returns 2 functions related to counting tokens
     *
     * addNextToken is used to count what tokens we are counting
     *
     * generateNextToken randomly chooses between tokens that we've seen, where potential options are weighted by how
     * many times they have been seen in examples.
     *
     * @returns {{addNextToken: addNextToken, generateNextToken: generateNextToken}}
     */
    function wordCounter() {
        var nextTokenCounts = {};
        var total = 0;

        function addNextToken(nextToken) {
            if (nextTokenCounts[nextToken] === undefined) {
                nextTokenCounts[nextToken] = 0;
            }
            nextTokenCounts[nextToken]++;
            total++;
        }

        function generateNextToken(previousTokens) {
            var rand = getRandomInt(0, total);
            for (var potentialNext in nextTokenCounts) {
                rand -= nextTokenCounts[potentialNext];
                if (rand < 0) {
                    return potentialNext;
                }
            }
            return "ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR ERROR!";
        }
        return { addNextToken: addNextToken, generateNextToken: generateNextToken };
    }

    function generateNextToken(previousTokens) {
        return tokenCounts[previousTokens].generateNextToken();
    }

    function generateAnySequence() {
        var previousTokens = [];
        var nextToken = generateNextToken(previousTokens);
        var sequence = [];
        while (nextToken !== '') {
            sequence.push(nextToken);
            if (previousTokens.length == markovChainOrder) {
                previousTokens.shift(); // remove the first element
            }
            previousTokens.push(nextToken);
            nextToken = generateNextToken(previousTokens);
        }
        return sequence;
    }

    /**
     * Probably not the best method name but that's what comments are for.
     *
     * A sequence is qualifying if it is
     *     (a) Not already in the list of sequences that we pasted in
     *     (b) Matches our filter criteria
     */
    function generateQualifyingSequence(minLength, maxLength, matchingRegex) {
        while (true) {
            var sequence = generateAnySequence();
            if (existingSequences[sequence] == undefined
                && (isNaN(minLength) || sequence.length >= minLength)
                && (isNaN(maxLength) || sequence.length <= maxLength)
                && (matchingRegex === undefined || matchingRegex.test(sequence.join()))
            ) {
                return sequence;
            }
        }
    }

    var getRandomInt = function (min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    };

    return {
        generateWord: generateQualifyingSequence
    };
}


text:
A SqueakTutorialPlatform is a representation of a platform which can be activated if a mouse is standing on it.

Instance Variables

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jena.sparql.service.enhancer.slice.api;

/** Interface typically used for removing listener registrations */
public interface Disposable
    extends AutoCloseable
{
    @Override
    void close();
}


text:
namespace content {
namespace {

const uint32_t kFilteredMessageClasses[] = {
    ChildProcessMsgStart, RenderProcessMsgStart, ViewMsgStart,
};

#if defined(OS_WIN)
// On Windows, |g_color_profile| can run on an arbitrary background thread.
// We avoid races by using LazyInstance's constructor lock to initialize the
// object.
base::LazyInstance<gfx::ColorProfile>::Leaky g_color_profile =
    LAZY_INSTANCE_INITIALIZER;
#endif

}  // namespace

RenderMessageFilter::RenderMessageFilter(
    int render_process_id,
    BrowserContext* browser_context,
    net::URLRequestContextGetter* request_context,
    RenderWidgetHelper* render_widget_helper,
    media::AudioManager* audio_manager,
    MediaInternals* media_internals,
    DOMStorageContextWrapper* dom_storage_context)
    : BrowserMessageFilter(kFilteredMessageClasses,
                           arraysize(kFilteredMessageClasses)),
      resource_dispatcher_host_(ResourceDispatcherHostImpl::Get()),
      bitmap_manager_client_(HostSharedBitmapManager::current()),
      request_context_(request_context),
      resource_context_(browser_context->GetResourceContext()),
      render_widget_helper_(render_widget_helper),
      dom_storage_context_(dom_storage_context),
      render_process_id_(render_process_id),
      audio_manager_(audio_manager),
      media_internals_(media_internals) {
  DCHECK(request_context_.get());

  if (render_widget_helper)
    render_widget_helper_->Init(render_process_id_, resource_dispatcher_host_);
}

RenderMessageFilter::~RenderMessageFilter() {
  // This function should be called on the IO thread.
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  BrowserGpuMemoryBufferManager* gpu_memory_buffer_manager =
      BrowserGpuMemoryBufferManager::current();
  if (gpu_memory_buffer_manager)
    gpu_memory_buffer_manager->ProcessRemoved(PeerHandle(), render_process_id_);
  HostDiscardableSharedMemoryManager::current()->ProcessRemoved(
      render_process_id_);
}

bool RenderMessageFilter::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(RenderMessageFilter, message)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GenerateRoutingID, OnGenerateRoutingID)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWindow, OnCreateWindow)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnCreateWidget)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CreateFullscreenWidget,
                        OnCreateFullscreenWidget)
    IPC_MESSAGE_HANDLER(ViewHostMsg_DownloadUrl, OnDownloadUrl)
    IPC_MESSAGE_HANDLER(ViewHostMsg_SaveImageFromDataURL,
                        OnSaveImageFromDataURL)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER_GENERIC(
        ViewHostMsg_SwapCompositorFrame,
        RenderWidgetResizeHelper::PostRendererProcessMsg(render_process_id_,
                                                         message))
    IPC_MESSAGE_HANDLER_GENERIC(
        ViewHostMsg_UpdateRect,
        RenderWidgetResizeHelper::PostRendererProcessMsg(render_process_id_,
                                                         message))
#endif
    // NB: The SyncAllocateSharedMemory, SyncAllocateGpuMemoryBuffer, and
    // DeletedGpuMemoryBuffer IPCs are handled here for renderer processes. For
    // non-renderer child processes, they are handled in ChildProcessHostImpl.
    IPC_MESSAGE_HANDLER_DELAY_REPLY(
        ChildProcessHostMsg_SyncAllocateSharedMemory, OnAllocateSharedMemory)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(
        ChildProcessHostMsg_SyncAllocateSharedBitmap, OnAllocateSharedBitmap)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(
        ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer,
        OnAllocateGpuMemoryBuffer)
    IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedGpuMemoryBuffer,
                        OnDeletedGpuMemoryBuffer)
    IPC_MESSAGE_HANDLER(ChildProcessHostMsg_AllocatedSharedBitmap,
                        OnAllocatedSharedBitmap)
    IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedSharedBitmap,
                        OnDeletedSharedBitmap)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(
        ChildProcessHostMsg_SyncAllocateLockedDiscardableSharedMemory,
        OnAllocateLockedDiscardableSharedMemory)
    IPC_MESSAGE_HANDLER(ChildProcessHostMsg_DeletedDiscardableSharedMemory,
                        OnDeletedDiscardableSharedMemory)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(RenderProcessHostMsg_Keygen, OnKeygen)
    IPC_MESSAGE_HANDLER(RenderProcessHostMsg_DidGenerateCacheableMetadata,
                        OnCacheableMetadataAvailable)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetAudioHardwareConfig,
                        OnGetAudioHardwareConfig)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(RenderProcessHostMsg_LoadFont, OnLoadFont)
#elif defined(OS_WIN)
    IPC_MESSAGE_HANDLER(RenderProcessHostMsg_PreCacheFontCharacters,
                        OnPreCacheFontCharacters)
    IPC_MESSAGE_HANDLER(RenderProcessHostMsg_GetMonitorColorProfile,
                        OnGetMonitorColorProfile)
#endif
    IPC_MESSAGE_HANDLER(ViewHostMsg_MediaLogEvents, OnMediaLogEvents)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void RenderMessageFilter::OnDestruct() const {
  const_cast<RenderMessageFilter*>(this)->resource_context_ = nullptr;
  BrowserThread::DeleteOnIOThread::Destruct(this);
}

void RenderMessageFilter::OverrideThreadForMessage(const IPC::Message& message,
                                                   BrowserThread::ID* thread) {
  if (message.type() == ViewHostMsg_MediaLogEvents::ID)
    *thread = BrowserThread::UI;
}

base::TaskRunner* RenderMessageFilter::OverrideTaskRunnerForMessage(
    const IPC::Message& message) {
#if defined(OS_WIN)
  // Windows monitor profile must be read from a file.
  if (message.type() == RenderProcessHostMsg_GetMonitorColorProfile::ID)
    return BrowserThread::GetBlockingPool();
#endif
  // Always query audio device parameters on the audio thread.
  if (message.type() == ViewHostMsg_GetAudioHardwareConfig::ID)
    return audio_manager_->GetTaskRunner().get();
  return NULL;
}

void RenderMessageFilter::OnCreateWindow(
    const ViewHostMsg_CreateWindow_Params& params,
    ViewHostMsg_CreateWindow_Reply* reply) {
  bool no_javascript_access;

  bool can_create_window =
      GetContentClient()->browser()->CanCreateWindow(
          params.opener_url,
          params.opener_top_level_frame_url,
          params.opener_security_origin,
          params.window_container_type,
          params.target_url,
          params.referrer,
          params.disposition,
          params.features,
          params.user_gesture,
          params.opener_suppressed,
          resource_context_,
          render_process_id_,
          params.opener_id,
          params.opener_render_frame_id,
          &no_javascript_access);

  if (!can_create_window) {
    reply->route_id = MSG_ROUTING_NONE;
    reply->main_frame_route_id = MSG_ROUTING_NONE;
    reply->main_frame_widget_route_id = MSG_ROUTING_NONE;
    reply->cloned_session_storage_namespace_id = 0;
    return;
  }

  // This will clone the sessionStorage for namespace_id_to_clone.
  scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace =
      new SessionStorageNamespaceImpl(dom_storage_context_.get(),
                                      params.session_storage_namespace_id);
  reply->cloned_session_storage_namespace_id = cloned_namespace->id();

  render_widget_helper_->CreateNewWindow(
      params, no_javascript_access, PeerHandle(), &reply->route_id,
      &reply->main_frame_route_id, &reply->main_frame_widget_route_id,
      cloned_namespace.get());
}

void RenderMessageFilter::OnCreateWidget(int opener_id,
                                         blink::WebPopupType popup_type,
                                         int* route_id) {
  render_widget_helper_->CreateNewWidget(opener_id, popup_type, route_id);
}

void RenderMessageFilter::OnCreateFullscreenWidget(int opener_id,
                                                   int* route_id) {
  render_widget_helper_->CreateNewFullscreenWidget(opener_id, route_id);
}

void RenderMessageFilter::OnGenerateRoutingID(int* route_id) {
  *route_id = render_widget_helper_->GetNextRoutingID();
}

void RenderMessageFilter::OnGetAudioHardwareConfig(
    media::AudioParameters* input_params,
    media::AudioParameters* output_params) {
  DCHECK(input_params);
  DCHECK(output_params);
  *output_params = audio_manager_->GetDefaultOutputStreamParameters();

  // TODO(henrika): add support for all available input devices.
  *input_params = audio_manager_->GetInputStreamParameters(
      media::AudioManagerBase::kDefaultDeviceId);
}

#if defined(OS_MACOSX)

void RenderMessageFilter::OnLoadFont(const FontDescriptor& font,
                                          IPC::Message* reply_msg) {
  FontLoader::Result* result = new FontLoader::Result;

  BrowserThread::PostTaskAndReply(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&FontLoader::LoadFont, font, result),
      base::Bind(&RenderMessageFilter::SendLoadFontReply, this, reply_msg,
                 base::Owned(result)));
}

void RenderMessageFilter::SendLoadFontReply(IPC::Message* reply,
                                                 FontLoader::Result* result) {
  base::SharedMemoryHandle handle;
  if (result->font_data_size == 0 || result->font_id == 0) {
    result->font_data_size = 0;
    result->font_id = 0;
    handle = base::SharedMemory::NULLHandle();
  } else {
    result->font_data.GiveToProcess(base::GetCurrentProcessHandle(), &handle);
  }
  RenderProcessHostMsg_LoadFont::WriteReplyParams(
      reply, result->font_data_size, handle, result->font_id);
  Send(reply);
}

#elif defined(OS_WIN)

void RenderMessageFilter::OnPreCacheFontCharacters(
    const LOGFONT& font,
    const base::string16& str) {
  // TODO(scottmg): pdf/ppapi still require the renderer to be able to precache
  // GDI fonts (http://crbug.com/383227), even when using DirectWrite.
  // Eventually this shouldn't be added and should be moved to
  // FontCacheDispatcher too. http://crbug.com/356346.

  // First, comments from FontCacheDispatcher::OnPreCacheFont do apply here too.
  // Except that for True Type fonts,
  // GetTextMetrics will not load the font in memory.
  // The only way windows seem to load properly, it is to create a similar
  // device (like the one in which we print), then do an ExtTextOut,
  // as we do in the printing thread, which is sandboxed.
  HDC hdc = CreateEnhMetaFile(NULL, NULL, NULL, NULL);
  HFONT font_handle = CreateFontIndirect(&font);
  DCHECK(NULL != font_handle);

  HGDIOBJ old_font = SelectObject(hdc, font_handle);
  DCHECK(NULL != old_font);

  ExtTextOut(hdc, 0, 0, ETO_GLYPH_INDEX, 0, str.c_str(), str.length(), NULL);

  SelectObject(hdc, old_font);
  DeleteObject(font_handle);

  HENHMETAFILE metafile = CloseEnhMetaFile(hdc);

  if (metafile)
    DeleteEnhMetaFile(metafile);
}

void RenderMessageFilter::OnGetMonitorColorProfile(std::vector<char>* profile) {
  DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::IO));
  *profile = g_color_profile.Get().profile();
}

#endif  // OS_*

void RenderMessageFilter::DownloadUrl(int render_view_id,
                                      int render_frame_id,
                                      const GURL& url,
                                      const Referrer& referrer,
                                      const base::string16& suggested_name,
                                      const bool use_prompt) const {
  if (!resource_context_)
    return;

  scoped_ptr<DownloadSaveInfo> save_info(new DownloadSaveInfo());
  save_info->suggested_name = suggested_name;
  save_info->prompt_for_save_location = use_prompt;
  scoped_ptr<net::URLRequest> request(
      resource_context_->GetRequestContext()->CreateRequest(
          url, net::DEFAULT_PRIORITY, NULL));
  RecordDownloadSource(INITIATED_BY_RENDERER);
  resource_dispatcher_host_->BeginDownload(
      std::move(request), referrer,
      true,  // is_content_initiated
      resource_context_, render_process_id_, render_view_id, render_frame_id,
      false, false, std::move(save_info), DownloadItem::kInvalidId,
      ResourceDispatcherHostImpl::DownloadStartedCallback());
}

void RenderMessageFilter::OnDownloadUrl(int render_view_id,
                                        int render_frame_id,
                                        const GURL& url,
                                        const Referrer& referrer,
                                        const base::string16& suggested_name) {
  DownloadUrl(render_view_id, render_frame_id, url, referrer, suggested_name,
              false);
}

void RenderMessageFilter::OnSaveImageFromDataURL(int render_view_id,
                                                 int render_frame_id,
                                                 const std::string& url_str) {
  // Please refer to RenderViewImpl::saveImageFromDataURL().
  if (url_str.length() >= kMaxLengthOfDataURLString)
    return;

  GURL data_url(url_str);
  if (!data_url.SchemeIs(url::kDataScheme))
    return;

  DownloadUrl(render_view_id, render_frame_id, data_url, Referrer(),
              base::string16(), true);
}

void RenderMessageFilter::AllocateSharedMemoryOnFileThread(
    uint32_t buffer_size,
    IPC::Message* reply_msg) {
  base::SharedMemoryHandle handle;
  ChildProcessHostImpl::AllocateSharedMemory(buffer_size, PeerHandle(),
                                             &handle);
  ChildProcessHostMsg_SyncAllocateSharedMemory::WriteReplyParams(reply_msg,
                                                                 handle);
  Send(reply_msg);
}

void RenderMessageFilter::OnAllocateSharedMemory(uint32_t buffer_size,
                                                 IPC::Message* reply_msg) {
  BrowserThread::PostTask(
      BrowserThread::FILE_USER_BLOCKING, FROM_HERE,
      base::Bind(&RenderMessageFilter::AllocateSharedMemoryOnFileThread, this,
                 buffer_size, reply_msg));
}

void RenderMessageFilter::AllocateSharedBitmapOnFileThread(
    uint32_t buffer_size,
    const cc::SharedBitmapId& id,
    IPC::Message* reply_msg) {
  base::SharedMemoryHandle handle;
  bitmap_manager_client_.AllocateSharedBitmapForChild(PeerHandle(), buffer_size,
                                                      id, &handle);
  ChildProcessHostMsg_SyncAllocateSharedBitmap::WriteReplyParams(reply_msg,
                                                                 handle);
  Send(reply_msg);
}

void RenderMessageFilter::OnAllocateSharedBitmap(uint32_t buffer_size,
                                                 const cc::SharedBitmapId& id,
                                                 IPC::Message* reply_msg) {
  BrowserThread::PostTask(
      BrowserThread::FILE_USER_BLOCKING,
      FROM_HERE,
      base::Bind(&RenderMessageFilter::AllocateSharedBitmapOnFileThread,
                 this,
                 buffer_size,
                 id,
                 reply_msg));
}

void RenderMessageFilter::OnAllocatedSharedBitmap(
    size_t buffer_size,
    const base::SharedMemoryHandle& handle,
    const cc::SharedBitmapId& id) {
  bitmap_manager_client_.ChildAllocatedSharedBitmap(buffer_size, handle,
                                                    PeerHandle(), id);
}

void RenderMessageFilter::OnDeletedSharedBitmap(const cc::SharedBitmapId& id) {
  bitmap_manager_client_.ChildDeletedSharedBitmap(id);
}

void RenderMessageFilter::AllocateLockedDiscardableSharedMemoryOnFileThread(
    uint32_t size,
    DiscardableSharedMemoryId id,
    IPC::Message* reply_msg) {
  base::SharedMemoryHandle handle;
  HostDiscardableSharedMemoryManager::current()
      ->AllocateLockedDiscardableSharedMemoryForChild(
          PeerHandle(), render_process_id_, size, id, &handle);
  ChildProcessHostMsg_SyncAllocateLockedDiscardableSharedMemory::
      WriteReplyParams(reply_msg, handle);
  Send(reply_msg);
}

void RenderMessageFilter::OnAllocateLockedDiscardableSharedMemory(
    uint32_t size,
    DiscardableSharedMemoryId id,
    IPC::Message* reply_msg) {
  BrowserThread::PostTask(
      BrowserThread::FILE_USER_BLOCKING, FROM_HERE,
      base::Bind(&RenderMessageFilter::
                     AllocateLockedDiscardableSharedMemoryOnFileThread,
                 this, size, id, reply_msg));
}

void RenderMessageFilter::DeletedDiscardableSharedMemoryOnFileThread(
    DiscardableSharedMemoryId id) {
  HostDiscardableSharedMemoryManager::current()
      ->ChildDeletedDiscardableSharedMemory(id, render_process_id_);
}

void RenderMessageFilter::OnDeletedDiscardableSharedMemory(
    DiscardableSharedMemoryId id) {
  BrowserThread::PostTask(
      BrowserThread::FILE_USER_BLOCKING, FROM_HERE,
      base::Bind(
          &RenderMessageFilter::DeletedDiscardableSharedMemoryOnFileThread,
          this, id));
}

void RenderMessageFilter::OnCacheableMetadataAvailable(
    const GURL& url,
    base::Time expected_response_time,
    const std::vector<char>& data) {
  net::HttpCache* cache = request_context_->GetURLRequestContext()->
      http_transaction_factory()->GetCache();
  if (!cache)
    return;

  // Use the same priority for the metadata write as for script
  // resources (see defaultPriorityForResourceType() in WebKit's
  // CachedResource.cpp). Note that WebURLRequest::PriorityMedium
  // corresponds to net::LOW (see ConvertWebKitPriorityToNetPriority()
  // in weburlloader_impl.cc).
  const net::RequestPriority kPriority = net::LOW;
  scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(data.size()));
  if (!data.empty())
    memcpy(buf->data(), &data.front(), data.size());
  cache->WriteMetadata(url, kPriority, expected_response_time, buf.get(),
                       data.size());
}

void RenderMessageFilter::OnKeygen(uint32_t key_size_index,
                                   const std::string& challenge_string,
                                   const GURL& url,
                                   const GURL& top_origin,
                                   IPC::Message* reply_msg) {
  if (!resource_context_)
    return;

  // Map displayed strings indicating level of keysecurity in the <keygen>
  // menu to the key size in bits. (See SSLKeyGeneratorChromium.cpp in WebCore.)
  int key_size_in_bits;
  switch (key_size_index) {
    case 0:
      key_size_in_bits = 2048;
      break;
    case 1:
      key_size_in_bits = 1024;
      break;
    default:
      DCHECK(false) << "Illegal key_size_index " << key_size_index;
      RenderProcessHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
      Send(reply_msg);
      return;
  }

  if (!GetContentClient()->browser()->AllowKeygen(top_origin,
                                                  resource_context_)) {
    RenderProcessHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
    Send(reply_msg);
    return;
  }

  resource_context_->CreateKeygenHandler(
      key_size_in_bits,
      challenge_string,
      url,
      base::Bind(
          &RenderMessageFilter::PostKeygenToWorkerThread, this, reply_msg));
}

void RenderMessageFilter::PostKeygenToWorkerThread(
    IPC::Message* reply_msg,
    scoped_ptr<net::KeygenHandler> keygen_handler) {
  VLOG(1) << "Dispatching keygen task to worker pool.";
  // Dispatch to worker pool, so we do not block the IO thread.
  if (!base::WorkerPool::PostTask(
           FROM_HERE,
           base::Bind(&RenderMessageFilter::OnKeygenOnWorkerThread,
                      this,
                      base::Passed(&keygen_handler),
                      reply_msg),
           true)) {
    NOTREACHED() << "Failed to dispatch keygen task to worker pool";
    RenderProcessHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
    Send(reply_msg);
  }
}

void RenderMessageFilter::OnKeygenOnWorkerThread(
    scoped_ptr<net::KeygenHandler> keygen_handler,
    IPC::Message* reply_msg) {
  DCHECK(reply_msg);

  // Generate a signed public key and challenge, then send it back.
  RenderProcessHostMsg_Keygen::WriteReplyParams(
      reply_msg,
      keygen_handler->GenKeyAndSignChallenge());
  Send(reply_msg);
}

void RenderMessageFilter::OnMediaLogEvents(
    const std::vector<media::MediaLogEvent>& events) {
  // OnMediaLogEvents() is always dispatched to the UI thread for handling.
  // See OverrideThreadForMessage().
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (media_internals_)
    media_internals_->OnMediaEvents(render_process_id_, events);
}

void RenderMessageFilter::OnAllocateGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                                                    uint32_t width,
                                                    uint32_t height,
                                                    gfx::BufferFormat format,
                                                    gfx::BufferUsage usage,
                                                    IPC::Message* reply) {
  DCHECK(BrowserGpuMemoryBufferManager::current());

  base::CheckedNumeric<int> size = width;
  size *= height;
  if (!size.IsValid()) {
    GpuMemoryBufferAllocated(reply, gfx::GpuMemoryBufferHandle());
    return;
  }

  BrowserGpuMemoryBufferManager::current()
      ->AllocateGpuMemoryBufferForChildProcess(
          id, gfx::Size(width, height), format, usage, PeerHandle(),
          render_process_id_,
          base::Bind(&RenderMessageFilter::GpuMemoryBufferAllocated, this,
                     reply));
}

void RenderMessageFilter::GpuMemoryBufferAllocated(
    IPC::Message* reply,
    const gfx::GpuMemoryBufferHandle& handle) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  ChildProcessHostMsg_SyncAllocateGpuMemoryBuffer::WriteReplyParams(reply,
                                                                    handle);
  Send(reply);
}

void RenderMessageFilter::OnDeletedGpuMemoryBuffer(
    gfx::GpuMemoryBufferId id,
    const gpu::SyncToken& sync_token) {
  DCHECK(BrowserGpuMemoryBufferManager::current());

  BrowserGpuMemoryBufferManager::current()->ChildProcessDeletedGpuMemoryBuffer(
      id, PeerHandle(), render_process_id_, sync_token);
}

}  // namespace content


text:
/*
 * Created on Apr 18, 2005
 *
 *
 */
package org.apache.geode.internal.cache.xmlcache;

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

/**
 * This class represents the data given for binding a DataSource to JNDI tree. It encapsulates to
 * Map objects , one for gemfire jndi tree specific data & another for vendor specific data. This
 * object will get created for every <jndi-binding></jndi-binding>
 *
 */
public class BindingCreation {

  private Map gfSpecific = null;
  // private Map vendorSpecific = null;
  private List vendorSpecificList = null;

  public BindingCreation(Map gfSpecific, List vendorSpecific) {
    this.gfSpecific = gfSpecific;
    this.vendorSpecificList = vendorSpecific;
  }

  /**
   * This function returns the VendorSpecific data Map
   *
   */
  List getVendorSpecificList() {
    return this.vendorSpecificList;
  }

  /**
   * This function returns the Gemfire Specific data Map
   *
   */
  Map getGFSpecificMap() {
    return this.gfSpecific;
  }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
    <Router>
        <App />
    </Router>,
    document.getElementById('root')
);

serviceWorker.unregister();


text:
.. _how_to_guides__configuring_metadata_stores__how_to_configure_a_validation_result_store_in_azure_blob_storage:

How to configure a Validation Result store in Azure blob storage
================================================================

By default, Validations are stored in JSON format in the ``uncommitted/validations/`` subdirectory of your ``great_expectations/`` folder.  Since Validations may include examples of data (which could be sensitive or regulated) they should not be committed to a source control system. This guide will help you configure a new storage location for Validations in a Azure Blob Storage.

.. admonition:: Prerequisites: This how-to guide assumes that you have already:

    - Configured a :ref:`Data Context <tutorials__getting_started__initialize_a_data_context>`.
    - Configured an :ref:`Expectations Suite <tutorials__getting_started__create_your_first_expectations>`.
    - Configured a :ref:`Checkpoint <tutorials__getting_started__validate_your_data>`.
    - Configured an Azure `storage account <https://docs.microsoft.com/en-us/azure/storage>`_ and get the `connection string <https://docs.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage?tabs=azure-portal>`_
    - Create the Azure Blob container. If you also wish to :ref:`host and share data docs on azure blob storage <how_to_guides__configuring_data_docs__how_to_host_and_share_data_docs_on_azure_blob_storage>` then you may setup this first and then use the ``$web`` existing container to store your expectations.
    - Identify the prefix (folder) where Validations will be stored (you don't need to create the folder, the prefix is just part of the Blob name).

Steps
-----
.. content-tabs::

    .. tab-container:: tab0
        :title: Show Docs for V2 (Batch Kwargs) API

        1. **Configure the** ``config_variables.yml`` **file with your azure storage credentials**

            We recommend that azure storage credentials be stored in the  ``config_variables.yml`` file, which is located in the ``uncommitted/`` folder by default, and is not part of source control.  The following lines add azure storage credentials under the key ``AZURE_STORAGE_CONNECTION_STRING``. Additional options for configuring the ``config_variables.yml`` file or additional environment variables can be found `here. <https://docs.greatexpectations.io/en/latest/guides/how_to_guides/configuring_data_contexts/how_to_use_a_yaml_file_or_environment_variables_to_populate_credentials.html>`_

            .. code-block:: yaml

                AZURE_STORAGE_CONNECTION_STRING: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=<YOUR-STORAGE-ACCOUNT-NAME>;AccountKey=<YOUR-STORAGE-ACCOUNT-KEY==>"

        2. **Identify your Data Context Validations Store**

            In your ``great_expectations.yml``, look for the following lines.  The configuration tells Great Expectations to look for Validations in a store called ``validations_store``. The ``base_directory`` for ``validations_store`` is set to ``uncommitted/validations/`` by default.

            .. code-block:: yaml

                validations_store_name: validations_store

                stores:
                    validations_store:
                        class_name: ValidationsStore
                        store_backend:
                            class_name: TupleFilesystemStoreBackend
                            base_directory: uncommitted/validations/

        3. **Update your configuration file to include a new store for Validations on Azure storage account**

            In our case, the name is set to ``validations_AZ_store``, but it can be any name you like.  We also need to make some changes to the ``store_backend`` settings.  The ``class_name`` will be set to ``TupleAzureBlobStoreBackend``,  ``container`` will be set to the name of your blob container (the equivalent of S3 bucket for Azure) you wish to store your validations, ``prefix`` will be set to the folder in the container where Validation files will be located, and ``connection_string`` will be set to ``${AZURE_STORAGE_CONNECTION_STRING}``, which references the corresponding key in the ``config_variables.yml`` file.

            .. code-block:: yaml

                validations_store_name: validations_AZ_store

                stores:
                    validations_AZ_store:
                        class_name: ValidationsStore
                        store_backend:
                            class_name: TupleAzureBlobStoreBackend
                            container: <blob-container>
                            prefix: validations
                            connection_string: ${AZURE_STORAGE_CONNECTION_STRING}

            .. note::
                If the container is called ``$web`` (for :ref:`hosting and sharing data docs on azure blob storage <how_to_guides__configuring_data_docs__how_to_host_and_share_data_docs_on_azure_blob_storage>`) then set ``container: \$web`` so the escape char will allow us to reach the ``$web``container.

        4. **Copy existing Validations JSON files to the Azure blob**. (This step is optional).

            One way to copy Validations into Azure Blob Storage is by using the ``az storage blob upload`` command, which is part of the Azure SDK. The following example will copy one Validation from a local folder to the Azure blob.   Information on other ways to copy Validation JSON files, like the Azure Storage browser in the Azure Portal, can be found in the `Documentation for Azure <https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal>`_.

            .. code-block:: bash

                export AZURE_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=<YOUR-STORAGE-ACCOUNT-NAME>;AccountKey=<YOUR-STORAGE-ACCOUNT-KEY==>"
                az storage blob upload -f <local/path/to/validation.json> -c <GREAT-EXPECTATION-DEDICATED-AZURE-BLOB-CONTAINER-NAME> -n <PREFIX>/<validation.json>
                example with a validation related to the exp1 expectation:
                az storage blob upload -f great_expectations/uncommitted/validations/exp1/20210306T104406.877327Z/20210306T104406.877327Z/8313fb37ca59375eb843adf388d4f882.json -c <blob-container> -n validations/exp1/20210306T104406.877327Z/20210306T104406.877327Z/8313fb37ca59375eb843adf388d4f882.json
                Finished[#############################################################]  100.0000%
                {
                  "etag": "\"0x8D8E09F894650C7\"",
                  "lastModified": "2021-03-06T12:58:28+00:00"
                }

        5. **Confirm that the new Validations store has been added by running** ``great_expectations store list``.

            Notice the output contains two Validation stores: the original ``validations_store`` on the local filesystem and the ``validations_AZ_store`` we just configured.  This is ok, since Great Expectations will look for Validations in Azure Blob as long as we set the ``validations_store_name`` variable to ``validations_AZ_store``, and the config for ``validations_store`` can be removed if you would like.

            .. code-block:: bash

                great_expectations store list

                 - name: validations_store
                   class_name: ValidationsStore
                   store_backend:
                     class_name: TupleFilesystemStoreBackend
                     base_directory: uncommitted/validations/

                 - name: validations_AZ_store
                   class_name: ValidationsStore
                   store_backend:
                     class_name: TupleAzureBlobStoreBackend
                     connection_string: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=<YOUR-STORAGE-ACCOUNT-NAME>;AccountKey=<YOUR-STORAGE-ACCOUNT-KEY==>"
                     container: <blob-container>
                     prefix: validations

    .. tab-container:: tab1
        :title: Show Docs for V3 (Batch Request) API

        1. **Configure the** ``config_variables.yml`` **file with your azure storage credentials**

            We recommend that azure storage credentials be stored in the  ``config_variables.yml`` file, which is located in the ``uncommitted/`` folder by default, and is not part of source control.  The following lines add azure storage credentials under the key ``AZURE_STORAGE_CONNECTION_STRING``. Additional options for configuring the ``config_variables.yml`` file or additional environment variables can be found `here. <https://docs.greatexpectations.io/en/latest/guides/how_to_guides/configuring_data_contexts/how_to_use_a_yaml_file_or_environment_variables_to_populate_credentials.html>`_

            .. code-block:: yaml

                AZURE_STORAGE_CONNECTION_STRING: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=<YOUR-STORAGE-ACCOUNT-NAME>;AccountKey=<YOUR-STORAGE-ACCOUNT-KEY==>"

        2. **Identify your Data Context Validations Store**

            In your ``great_expectations.yml``, look for the following lines.  The configuration tells Great Expectations to look for Validations in a store called ``validations_store``. The ``base_directory`` for ``validations_store`` is set to ``uncommitted/validations/`` by default.

            .. code-block:: yaml

                validations_store_name: validations_store

                stores:
                    validations_store:
                        class_name: ValidationsStore
                        store_backend:
                            class_name: TupleFilesystemStoreBackend
                            base_directory: uncommitted/validations/

        3. **Update your configuration file to include a new store for Validations on Azure storage account**

            In our case, the name is set to ``validations_AZ_store``, but it can be any name you like.  We also need to make some changes to the ``store_backend`` settings.  The ``class_name`` will be set to ``TupleAzureBlobStoreBackend``,  ``container`` will be set to the name of your blob container (the equivalent of S3 bucket for Azure) you wish to store your validations, ``prefix`` will be set to the folder in the container where Validation files will be located, and ``connection_string`` will be set to ``${AZURE_STORAGE_CONNECTION_STRING}``, which references the corresponding key in the ``config_variables.yml`` file.

            .. code-block:: yaml

                validations_store_name: validations_AZ_store

                stores:
                    validations_AZ_store:
                        class_name: ValidationsStore
                        store_backend:
                            class_name: TupleAzureBlobStoreBackend
                            container: <blob-container>
                            prefix: validations
                            connection_string: ${AZURE_STORAGE_CONNECTION_STRING}

            .. note::
                If the container is called ``$web`` (for :ref:`hosting and sharing data docs on azure blob storage <how_to_guides__configuring_data_docs__how_to_host_and_share_data_docs_on_azure_blob_storage>`) then set ``container: \$web`` so the escape char will allow us to reach the ``$web``container.

        4. **Copy existing Validations JSON files to the Azure blob**. (This step is optional).

            One way to copy Validations into Azure Blob Storage is by using the ``az storage blob upload`` command, which is part of the Azure SDK. The following example will copy one Validation from a local folder to the Azure blob.   Information on other ways to copy Validation JSON files, like the Azure Storage browser in the Azure Portal, can be found in the `Documentation for Azure <https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-portal>`_.

            .. code-block:: bash

                export AZURE_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=<YOUR-STORAGE-ACCOUNT-NAME>;AccountKey=<YOUR-STORAGE-ACCOUNT-KEY==>"
                az storage blob upload -f <local/path/to/validation.json> -c <GREAT-EXPECTATION-DEDICATED-AZURE-BLOB-CONTAINER-NAME> -n <PREFIX>/<validation.json>
                example with a validation related to the exp1 expectation:
                az storage blob upload -f great_expectations/uncommitted/validations/exp1/20210306T104406.877327Z/20210306T104406.877327Z/8313fb37ca59375eb843adf388d4f882.json -c <blob-container> -n validations/exp1/20210306T104406.877327Z/20210306T104406.877327Z/8313fb37ca59375eb843adf388d4f882.json
                Finished[#############################################################]  100.0000%
                {
                  "etag": "\"0x8D8E09F894650C7\"",
                  "lastModified": "2021-03-06T12:58:28+00:00"
                }

        5. **Confirm that the new Validations store has been added by running** ``great_expectations --v3-api store list``.

            Notice the output contains two Validation stores: the original ``validations_store`` on the local filesystem and the ``validations_AZ_store`` we just configured.  This is ok, since Great Expectations will look for Validations in Azure Blob as long as we set the ``validations_store_name`` variable to ``validations_AZ_store``, and the config for ``validations_store`` can be removed if you would like.

            .. code-block:: bash

                great_expectations --v3-api store list

                 - name: validations_store
                   class_name: ValidationsStore
                   store_backend:
                     class_name: TupleFilesystemStoreBackend
                     base_directory: uncommitted/validations/

                 - name: validations_AZ_store
                   class_name: ValidationsStore
                   store_backend:
                     class_name: TupleAzureBlobStoreBackend
                     connection_string: "DefaultEndpointsProtocol=https;EndpointSuffix=core.windows.net;AccountName=<YOUR-STORAGE-ACCOUNT-NAME>;AccountKey=<YOUR-STORAGE-ACCOUNT-KEY==>"
                     container: <blob-container>
                     prefix: validations

6. **Confirm that the Validations store has been correctly configured.**

    Run a :ref:`Checkpoint <tutorials__getting_started__validate_your_data>` to store results in the new Validations store on Azure Blob then visualize the results by re-building :ref:`Data Docs <tutorials__getting_started__set_up_data_docs>`.

.. discourse::
    :topic_identifier: 173


text:
package com.folioreader.util;

import androidx.recyclerview.widget.RecyclerView;
import com.folioreader.model.TOCLinkWrapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * Multi-level expandable indentable list adapter.
 * Initially all elements in the list are single items. When you want to collapse an item and all its
 * descendants call {@link #collapseGroup(int)}. When you want to exapand a group call {@link #expandGroup(int)}.
 * Note that groups inside other groups are kept collapsed.
 *

 * To collapse an item and all its descendants or expand a group at a certain position
 * you can call {@link #toggleGroup(int)}.
 *

 * To preserve state (i.e. which items are collapsed) when a configuration change happens (e.g. screen rotation)
 * you should call {@link #saveGroups()} inside onSaveInstanceState and save the returned value into
 * the Bundle. When the activity/fragment is recreated you can call {@link #restoreGroups(List)}
 * to restore the previous state. The actual data (e.g. the comments in the sample app) is not preserved,
 * so you should save it yourself with a static field or implementing Parcelable or using setRetainInstance(true)
 * or saving data to a file or something like that.
 *

 * To see an example of how to extend this abstract class see MyAdapter.java in sampleapp.
 */
public abstract class MultiLevelExpIndListAdapter extends RecyclerView.Adapter {
    /**
     * Indicates whether or not the observers must be notified whenever
     * {@link #mData} is modified.
     */
    private boolean mNotifyOnChange;

    /**
     * List of items to display.
     */
    private List<ExpIndData> mData;

    /**
     * Map an item to the relative group.
     * e.g.: if the user click on item 6 then mGroups(item(6)) = {all items/groups below item 6}
     */
    private HashMap<ExpIndData, List<? extends ExpIndData>> mGroups;

    /**
     * Interface that every item to be displayed has to implement. If an object implements
     * this interface it means that it can be expanded/collapsed and has a level of indentation.
     * Note: some methods are commented out because they're not used here, but they should be
     * implemented if you want your data to be expandable/collapsible and indentable.
     * See MyComment in the sample app to see an example of how to implement this.
     */
    public interface ExpIndData {
        /**
         * @return The children of this item.
         */
        List<? extends ExpIndData> getChildren();

        /**
         * @return True if this item is a group.
         */
        boolean isGroup();

        /**
         * @param value True if this item is a group
         */
        void setIsGroup(boolean value);

        /**
         * @param groupSize Set the number of items in the group.
         *                  Note: groups contained in other groups are counted just as one, not
         *                  as the number of items that they contain.
         */
        void setGroupSize(int groupSize);

        /** Note: actually this method is never called in MultiLevelExpIndListAdapter,
         * that's why it's not strictly required that you implement this function and so
         * it's commented out.
         * @return The number of items in the group.
         *         Note: groups contained in other groups are counted just as one, not
         *               as the number of items that they contain.
         */
        //int getGroupSize();

        /** Note: actually this method is never called in MultiLevelExpIndListAdapter,
         * that's why it's not strictly required that you implement this function and so
         * it's commented out.
         * @return The level of indentation in the range [0, n-1]
         */
        //int getIndentation();

        /** Note: actually this method is never called in MultiLevelExpIndListAdapter,
         * that's why it's not strictly required that you implement this function and so
         * it's commented out.
         * @param indentation The level of indentation in the range [0, n-1]
         */
        //int setIndentation(int indentation);
    }

    public MultiLevelExpIndListAdapter() {
        mData = new ArrayList<ExpIndData>();
        mGroups = new HashMap<ExpIndData, List<? extends ExpIndData>>();
        mNotifyOnChange = true;
    }

    public MultiLevelExpIndListAdapter(ArrayList<TOCLinkWrapper> tocLinkWrappers) {
        mData = new ArrayList<ExpIndData>();
        mGroups = new HashMap<ExpIndData, List<? extends ExpIndData>>();
        mNotifyOnChange = true;
        mData.addAll(tocLinkWrappers);
        collapseAllTOCLinks(tocLinkWrappers);
    }

    public void add(ExpIndData item) {
        if (item != null) {
            mData.add(item);
            if (mNotifyOnChange)
                notifyItemChanged(mData.size() - 1);
        }
    }

    public void addAll(int position, Collection<? extends ExpIndData> data) {
        if (data != null && data.size() > 0) {
            mData.addAll(position, data);
            if (mNotifyOnChange)
                notifyItemRangeInserted(position, data.size());
        }
    }

    public void addAll(Collection<? extends ExpIndData> data) {
        addAll(mData.size(), data);
    }

    public void insert(int position, ExpIndData item) {
        mData.add(position, item);
        if (mNotifyOnChange)
            notifyItemInserted(position);
    }

    /**
     * Clear all items and groups.
     */
    public void clear() {
        if (mData.size() > 0) {
            int size = mData.size();
            mData.clear();
            mGroups.clear();
            if (mNotifyOnChange)
                notifyItemRangeRemoved(0, size);
        }
    }

    /**
     * Remove an item or group.If it's a group it removes also all the
     * items and groups that it contains.
     *
     * @param item The item or group to be removed.
     * @return true if this adapter was modified by this operation, false otherwise.
     */
    public boolean remove(ExpIndData item) {
        return remove(item, false);
    }

    /**
     * Remove an item or group. If it's a group it removes also all the
     * items and groups that it contains if expandGroupBeforeRemoval is false.
     * If it's true the group is expanded and then only the item is removed.
     *
     * @param item                     The item or group to be removed.
     * @param expandGroupBeforeRemoval True to expand the group before removing the item.
     *                                 False to remove also all the items and groups contained if
     *                                 the item to be removed is a group.
     * @return true if this adapter was modified by this operation, false otherwise.
     */
    public boolean remove(ExpIndData item, boolean expandGroupBeforeRemoval) {
        int index;
        boolean removed = false;
        if (item != null && (index = mData.indexOf(item)) != -1 && (removed = mData.remove(item))) {
            if (mGroups.containsKey(item)) {
                if (expandGroupBeforeRemoval)
                    expandGroup(index);
                mGroups.remove(item);
            }
            if (mNotifyOnChange)
                notifyItemRemoved(index);
        }
        return removed;
    }

    public ExpIndData getItemAt(int position) {
        return mData.get(position);
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    /**
     * Expand the group at position "posititon".
     *
     * @param position The position (range [0,n-1]) of the group that has to be expanded
     */
    public void expandGroup(int position) {
        ExpIndData firstItem = getItemAt(position);

        if (!firstItem.isGroup()) {
            return;
        }

        // get the group of the descendants of firstItem
        List<? extends ExpIndData> group = mGroups.remove(firstItem);

        firstItem.setIsGroup(false);
        firstItem.setGroupSize(0);

        notifyItemChanged(position);
        addAll(position + 1, group);
    }

    /**
     * Collapse the descendants of the item at position "position".
     *
     * @param position The position (range [0,n-1]) of the element that has to be collapsed
     */
    public void collapseGroup(int position) {
        ExpIndData firstItem = getItemAt(position);

        if (firstItem.getChildren() == null || firstItem.getChildren().isEmpty())
            return;

        // group containing all the descendants of firstItem
        List<ExpIndData> group = new ArrayList<ExpIndData>();
        // stack for depth first search
        List<ExpIndData> stack = new ArrayList<ExpIndData>();
        int groupSize = 0;

        for (int i = firstItem.getChildren().size() - 1; i >= 0; i--) {
            stack.add(firstItem.getChildren().get(i));
        }

        while (!stack.isEmpty()) {
            ExpIndData item = stack.remove(stack.size() - 1);
            group.add(item);
            groupSize++;
            // stop when the item is a leaf or a group
            if (item.getChildren() != null && !item.getChildren().isEmpty() && !item.isGroup()) {
                for (int i = item.getChildren().size() - 1; i >= 0; i--) {
                    stack.add(item.getChildren().get(i));
                }
            }

            if (mData.contains(item)) mData.remove(item);
        }

        mGroups.put(firstItem, group);
        firstItem.setIsGroup(true);
        firstItem.setGroupSize(groupSize);

        notifyItemChanged(position);
        notifyItemRangeRemoved(position + 1, groupSize);
    }

    private void collapseAllTOCLinks(ArrayList<TOCLinkWrapper> tocLinkWrappers) {
        if (tocLinkWrappers == null || tocLinkWrappers.isEmpty()) return;

        for (TOCLinkWrapper tocLinkWrapper : tocLinkWrappers) {
            groupTOCLink(tocLinkWrapper);
            collapseAllTOCLinks(tocLinkWrapper.getTocLinkWrappers());
        }
    }

    private void groupTOCLink(TOCLinkWrapper tocLinkWrapper) {
        // group containing all the descendants of firstItem
        List<ExpIndData> group = new ArrayList<ExpIndData>();
        int groupSize = 0;
        if (tocLinkWrapper.getChildren() != null && !tocLinkWrapper.getChildren().isEmpty()) {
            group.addAll(tocLinkWrapper.getChildren());
            groupSize = tocLinkWrapper.getChildren().size();
        }
        // stack for depth first search
        //List<ExpIndData> stack = new ArrayList<ExpIndData>();
        //int groupSize = 0;

        /*for (int i = tocLinkWrapper.getChildren().size() - 1; i >= 0; i--)
            stack.add(tocLinkWrapper.getChildren().get(i));

        while (!stack.isEmpty()) {
            ExpIndData item = stack.remove(stack.size() - 1);
            group.add(item);
            groupSize++;
            // stop when the item is a leaf or a group
            if (item.getChildren() != null && !item.getChildren().isEmpty() && !item.isGroup()) {
                for (int i = item.getChildren().size() - 1; i >= 0; i--)
                    stack.add(item.getChildren().get(i));
            }
        }*/

        mGroups.put(tocLinkWrapper, group);
        tocLinkWrapper.setIsGroup(true);
        tocLinkWrapper.setGroupSize(groupSize);
    }

    /**
     * Collpase/expand the item at position "position"
     *
     * @param position The position (range [0,n-1]) of the element that has to be collapsed/expanded
     */
    public void toggleGroup(int position) {
        if (getItemAt(position).isGroup()) {
            expandGroup(position);
        } else {
            collapseGroup(position);
        }
    }

    /**
     * In onSaveInstanceState, you should save the groups' indices returned by this function
     * in the Bundle so that later they can be restored using {@link #restoreGroups(List)}.
     * saveGroups() expand all the groups so you should call this function only inside onSaveInstanceState.
     *
     * @return A list of indices of items that are groups.
     */
    public ArrayList<Integer> saveGroups() {
        boolean notify = mNotifyOnChange;
        mNotifyOnChange = false;
        ArrayList<Integer> groupsIndices = new ArrayList<Integer>();
        for (int i = 0; i < mData.size(); i++) {
            if (mData.get(i).isGroup()) {
                expandGroup(i);
                groupsIndices.add(i);
            }
        }
        mNotifyOnChange = notify;
        return groupsIndices;
    }

    /**
     * Call this function to restore the groups that were collapsed before the configuration change
     * happened (e.g. screen rotation). See {@link #saveGroups()}.
     *
     * @param groupsNum The list of indices of items that are groups and should be collapsed.
     */
    public void restoreGroups(List<Integer> groupsNum) {
        if (groupsNum == null)
            return;
        boolean notify = mNotifyOnChange;
        mNotifyOnChange = false;
        for (int i = groupsNum.size() - 1; i >= 0; i--) {
            collapseGroup(groupsNum.get(i));
        }
        mNotifyOnChange = notify;
    }
}


text:
(function () {
  'use strict';

  angular.module('common')
    .config(configure);

  /** @ngInject */
  function configure($stateProvider) {
    $stateProvider
      .state('projects', {
        parent: 'app',
        url: '/projects',
        views: {
          'projects@app': 'projectsSidebar'
        },
        redirectTo: 'projects.list'
      });
  }
})();


text:
using content::BrowserThread;

namespace em = enterprise_management;

namespace policy {

namespace {

const char kNoRequisition[] = "none";
const char kRemoraRequisition[] = "remora";
const char kSharkRequisition[] = "shark";

// These are the machine serial number keys that we check in order until we
// find a non-empty serial number. The VPD spec says the serial number should be
// in the "serial_number" key for v2+ VPDs. However, legacy devices used a
// different key to report their serial number, which we fall back to if
// "serial_number" is not present.
//
// Product_S/N is still special-cased due to inconsistencies with serial
// numbers on Lumpy devices: On these devices, serial_number is identical to
// Product_S/N with an appended checksum. Unfortunately, the sticker on the
// packaging doesn't include that checksum either (the sticker on the device
// does though!). The former sticker is the source of the serial number used by
// device management service, so we prefer Product_S/N over serial number to
// match the server.
//
// TODO(mnissler): Move serial_number back to the top once the server side uses
// the correct serial number.
const char* const kMachineInfoSerialNumberKeys[] = {
  "Product_S/N",    // Lumpy/Alex devices
  "serial_number",  // VPD v2+ devices
  "Product_SN",     // Mario
  "sn",             // old ZGB devices (more recent ones use serial_number)
};

// Fetches a machine statistic value from StatisticsProvider, returns an empty
// string on failure.
std::string GetMachineStatistic(const std::string& key) {
  std::string value;
  chromeos::system::StatisticsProvider* provider =
      chromeos::system::StatisticsProvider::GetInstance();
  if (!provider->GetMachineStatistic(key, &value))
    return std::string();

  return value;
}

// Gets a machine flag from StatisticsProvider, returns the given
// |default_value| if not present.
bool GetMachineFlag(const std::string& key, bool default_value) {
  bool value = default_value;
  chromeos::system::StatisticsProvider* provider =
      chromeos::system::StatisticsProvider::GetInstance();
  if (!provider->GetMachineFlag(key, &value))
    return default_value;

  return value;
}

// Checks whether forced re-enrollment is enabled.
bool ForcedReEnrollmentEnabled() {
  return chromeos::AutoEnrollmentController::GetMode() ==
         chromeos::AutoEnrollmentController::MODE_FORCED_RE_ENROLLMENT;
}

}  // namespace

DeviceCloudPolicyManagerChromeOS::DeviceCloudPolicyManagerChromeOS(
    scoped_ptr<DeviceCloudPolicyStoreChromeOS> store,
    const scoped_refptr<base::SequencedTaskRunner>& task_runner,
    ServerBackedStateKeysBroker* state_keys_broker)
    : CloudPolicyManager(
          dm_protocol::kChromeDevicePolicyType,
          std::string(),
          store.get(),
          task_runner,
          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)),
      device_store_(store.Pass()),
      state_keys_broker_(state_keys_broker),
      task_runner_(task_runner),
      local_state_(nullptr) {
}

DeviceCloudPolicyManagerChromeOS::~DeviceCloudPolicyManagerChromeOS() {}

void DeviceCloudPolicyManagerChromeOS::Initialize(PrefService* local_state) {
  CHECK(local_state);

  local_state_ = local_state;

  state_keys_update_subscription_ = state_keys_broker_->RegisterUpdateCallback(
      base::Bind(&DeviceCloudPolicyManagerChromeOS::OnStateKeysUpdated,
                 base::Unretained(this)));

  InitializeRequisition();
}

void DeviceCloudPolicyManagerChromeOS::AddDeviceCloudPolicyManagerObserver(
    Observer* observer) {
  observers_.AddObserver(observer);
}

void DeviceCloudPolicyManagerChromeOS::RemoveDeviceCloudPolicyManagerObserver(
    Observer* observer) {
  observers_.RemoveObserver(observer);
}

std::string DeviceCloudPolicyManagerChromeOS::GetDeviceRequisition() const {
  std::string requisition;
  const PrefService::Preference* pref = local_state_->FindPreference(
      prefs::kDeviceEnrollmentRequisition);
  if (!pref->IsDefaultValue())
    pref->GetValue()->GetAsString(&requisition);

  if (requisition == kNoRequisition)
    requisition.clear();

  return requisition;
}

void DeviceCloudPolicyManagerChromeOS::SetDeviceRequisition(
    const std::string& requisition) {
  VLOG(1) << "SetDeviceRequisition " << requisition;
  if (local_state_) {
    if (requisition.empty()) {
      local_state_->ClearPref(prefs::kDeviceEnrollmentRequisition);
      local_state_->ClearPref(prefs::kDeviceEnrollmentAutoStart);
      local_state_->ClearPref(prefs::kDeviceEnrollmentCanExit);
    } else {
      local_state_->SetString(prefs::kDeviceEnrollmentRequisition, requisition);
      if (requisition == kNoRequisition) {
        local_state_->ClearPref(prefs::kDeviceEnrollmentAutoStart);
        local_state_->ClearPref(prefs::kDeviceEnrollmentCanExit);
      } else {
        local_state_->SetBoolean(prefs::kDeviceEnrollmentAutoStart, true);
        local_state_->SetBoolean(prefs::kDeviceEnrollmentCanExit, false);
      }
    }
  }
}

bool DeviceCloudPolicyManagerChromeOS::IsRemoraRequisition() const {
  return GetDeviceRequisition() == kRemoraRequisition;
}

bool DeviceCloudPolicyManagerChromeOS::IsSharkRequisition() const {
  return GetDeviceRequisition() == kSharkRequisition;
}

void DeviceCloudPolicyManagerChromeOS::Shutdown() {
  status_uploader_.reset();
  syslog_uploader_.reset();
  heartbeat_scheduler_.reset();
  state_keys_update_subscription_.reset();
  CloudPolicyManager::Shutdown();
}

// static
void DeviceCloudPolicyManagerChromeOS::RegisterPrefs(
    PrefRegistrySimple* registry) {
  registry->RegisterStringPref(prefs::kDeviceEnrollmentRequisition,
                               std::string());
  registry->RegisterBooleanPref(prefs::kDeviceEnrollmentAutoStart, false);
  registry->RegisterBooleanPref(prefs::kDeviceEnrollmentCanExit, true);
  registry->RegisterDictionaryPref(prefs::kServerBackedDeviceState);
}

// static
std::string DeviceCloudPolicyManagerChromeOS::GetMachineID() {
  std::string machine_id;
  chromeos::system::StatisticsProvider* provider =
      chromeos::system::StatisticsProvider::GetInstance();
  for (size_t i = 0; i < arraysize(kMachineInfoSerialNumberKeys); i++) {
    if (provider->GetMachineStatistic(kMachineInfoSerialNumberKeys[i],
                                      &machine_id) &&
        !machine_id.empty()) {
      break;
    }
  }

  if (machine_id.empty())
    LOG(WARNING) << "Failed to get machine id.";

  return machine_id;
}

// static
std::string DeviceCloudPolicyManagerChromeOS::GetMachineModel() {
  return GetMachineStatistic(chromeos::system::kHardwareClassKey);
}

void DeviceCloudPolicyManagerChromeOS::StartConnection(
    scoped_ptr<CloudPolicyClient> client_to_connect,
    EnterpriseInstallAttributes* install_attributes) {
  CHECK(!service());

  // Set state keys here so the first policy fetch submits them to the server.
  if (ForcedReEnrollmentEnabled())
    client_to_connect->SetStateKeysToUpload(state_keys_broker_->state_keys());

  core()->Connect(client_to_connect.Pass());
  core()->StartRefreshScheduler();
  core()->StartRemoteCommandsService(
      scoped_ptr<RemoteCommandsFactory>(new DeviceCommandsFactoryChromeOS()));
  core()->TrackRefreshDelayPref(local_state_,
                                prefs::kDevicePolicyRefreshRate);
  attestation_policy_observer_.reset(
      new chromeos::attestation::AttestationPolicyObserver(client()));

  // Enable device reporting and status monitoring for enterprise enrolled
  // devices. We want to create these objects for enrolled devices, even if
  // monitoring is currently inactive, in case monitoring is turned back on in
  // a future policy fetch - the classes themselves track the current state of
  // the monitoring settings and only perform monitoring if it is active.
  if (install_attributes->IsEnterpriseDevice()) {
    CreateStatusUploader();
    syslog_uploader_.reset(new SystemLogUploader(nullptr, task_runner_));
    heartbeat_scheduler_.reset(new HeartbeatScheduler(
        g_browser_process->gcm_driver(), client(),
        install_attributes->GetDomain(), install_attributes->GetDeviceId(),
        task_runner_));
  }

  NotifyConnected();
}

void DeviceCloudPolicyManagerChromeOS::Unregister(
    const UnregisterCallback& callback) {
  if (!service()) {
    LOG(ERROR) << "Tried to unregister but DeviceCloudPolicyManagerChromeOS is "
               << "not connected.";
    callback.Run(false);
    return;
  }

  service()->Unregister(callback);
}

void DeviceCloudPolicyManagerChromeOS::Disconnect() {
  status_uploader_.reset();
  syslog_uploader_.reset();
  heartbeat_scheduler_.reset();
  core()->Disconnect();

  NotifyDisconnected();
}

void DeviceCloudPolicyManagerChromeOS::OnStateKeysUpdated() {
  if (client() && ForcedReEnrollmentEnabled())
    client()->SetStateKeysToUpload(state_keys_broker_->state_keys());
}

void DeviceCloudPolicyManagerChromeOS::InitializeRequisition() {
  // OEM statistics are only loaded when OOBE is not completed.
  if (chromeos::StartupUtils::IsOobeCompleted())
    return;

  const PrefService::Preference* pref = local_state_->FindPreference(
      prefs::kDeviceEnrollmentRequisition);
  if (pref->IsDefaultValue()) {
    std::string requisition =
        GetMachineStatistic(chromeos::system::kOemDeviceRequisitionKey);

    if (!requisition.empty()) {
      local_state_->SetString(prefs::kDeviceEnrollmentRequisition,
                              requisition);
      if (requisition == kRemoraRequisition ||
          requisition == kSharkRequisition) {
        local_state_->SetBoolean(prefs::kDeviceEnrollmentAutoStart, true);
        local_state_->SetBoolean(prefs::kDeviceEnrollmentCanExit, false);
      } else {
        local_state_->SetBoolean(
            prefs::kDeviceEnrollmentAutoStart,
            GetMachineFlag(chromeos::system::kOemIsEnterpriseManagedKey,
                           false));
        local_state_->SetBoolean(
            prefs::kDeviceEnrollmentCanExit,
            GetMachineFlag(chromeos::system::kOemCanExitEnterpriseEnrollmentKey,
                           false));
      }
    }
  }
}

void DeviceCloudPolicyManagerChromeOS::NotifyConnected() {
  FOR_EACH_OBSERVER(
      Observer, observers_, OnDeviceCloudPolicyManagerConnected());
}

void DeviceCloudPolicyManagerChromeOS::NotifyDisconnected() {
  FOR_EACH_OBSERVER(
      Observer, observers_, OnDeviceCloudPolicyManagerDisconnected());
}

void DeviceCloudPolicyManagerChromeOS::CreateStatusUploader() {
  status_uploader_.reset(new StatusUploader(
      client(),
      make_scoped_ptr(new DeviceStatusCollector(
          local_state_, chromeos::system::StatisticsProvider::GetInstance(),
          DeviceStatusCollector::LocationUpdateRequester(),
          DeviceStatusCollector::VolumeInfoFetcher(),
          DeviceStatusCollector::CPUStatisticsFetcher(),
          DeviceStatusCollector::CPUTempFetcher())),
      task_runner_));
}

}  // namespace policy


text:
require 'minitest/autorun'
require_relative 'trinary'

class TrinaryTest < Minitest::Test
  def test_trinary_1_is_decimal_1
    assert_equal 1, Trinary.new('1').to_decimal
  end

  def test_trinary_2_is_decimal_2
    # skip
    assert_equal 2, Trinary.new('2').to_decimal
  end

  def test_trinary_10_is_decimal_3
    # skip
    assert_equal 3, Trinary.new('10').to_decimal
  end

  def test_trinary_11_is_decimal_4
    # skip
    assert_equal 4, Trinary.new('11').to_decimal
  end

  def test_trinary_100_is_decimal_9
    # skip
    assert_equal 9, Trinary.new('100').to_decimal
  end

  def test_trinary_112_is_decimal_14
    # skip
    assert_equal 14, Trinary.new('112').to_decimal
  end

  def test_trinary_222_is_26
    # skip
    assert_equal 26, Trinary.new('222').to_decimal
  end

  def test_trinary_1122000120_is_32091
    # skip
    assert_equal 32_091, Trinary.new('1122000120').to_decimal
  end

  def test_invalid_trinary_is_decimal_0
    # skip
    assert_equal 0, Trinary.new('carrot').to_decimal
  end

  def test_invalid_trinary_with_digits_is_decimal_0
    # skip
    assert_equal 0, Trinary.new('0a1b2c').to_decimal
  end
end


text:
using NeuralNets
net = buildnet()
using Graphs
to_dot(net.g,"net.dot")
run(`dot -Tpng net.dot -o net_diagram.png`)
println("Network graph written to net_diagram.png")


text:
package com.google.code.beanmatchers.data;

public class TestBeanWithEqualsThatDoesNotAccountForNullValue {

  private Object property;

  public Object getProperty() {
    return property;
  }

  public void setProperty(Object property) {
    this.property = property;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (getClass() != o.getClass()) return false;
    TestBeanWithEqualsThatDoesNotAccountForNullValue that = (TestBeanWithEqualsThatDoesNotAccountForNullValue) o;
    if (property != null ? !property.equals(that.property) : that.property != null) return false;
    return true;
  }
}


text:
require 'cgi'

module PaysonAPI
class Sender
  FORMAT_STRING = "sender%s"
  attr_accessor :email, :first_name, :last_name

  def initialize(email, first_name, last_name)
    @email = email
    @first_name = first_name
    @last_name = last_name
  end

  def to_hash
    {}.tap do |hash|
      hash[FORMAT_STRING % 'Email'] = @email
      hash[FORMAT_STRING % 'FirstName'] = @first_name
      hash[FORMAT_STRING % 'LastName'] = @last_name
    end
  end

  def self.parse(data)
    email = data[FORMAT_STRING % 'email']
    first_name = CGI.unescape(data[FORMAT_STRING % 'FirstName'].to_s)
    last_name = CGI.unescape(data[FORMAT_STRING % 'LastName'].to_s)
    self.new(email, first_name, last_name)
  end
end
end


text:
	How to Use the <bean:message key="project.title"/> data portal

	<a href="<%=regUrl%>" target="_blank">Register to access raw data


text:
package net.bytebuddy.utility;

import net.bytebuddy.test.utility.JavaVersionRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.objectweb.asm.Type;

import java.lang.reflect.Array;
import java.lang.reflect.Method;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class JavaConstantSimpleConstantDescriptionTest {

    @Rule
    public MethodRule javaVersionRule = new JavaVersionRule();

    @Test
    public void testInteger() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription(42, (ClassLoader) null).toDescription(), is((Object) 42));
    }

    @Test
    public void testLong() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription(42L, (ClassLoader) null).toDescription(), is((Object) 42L));
    }

    @Test
    public void testFloat() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription(42f, (ClassLoader) null).toDescription(), is((Object) 42f));
    }

    @Test
    public void testDouble() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription(42d, (ClassLoader) null).toDescription(), is((Object) 42d));
    }

    @Test
    public void testString() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription("foo", (ClassLoader) null).toDescription(), is((Object) "foo"));
    }

    @Test
    @JavaVersionRule.Enforce(12)
    public void testType() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription(Class.forName("java.lang.constant.ClassDesc")
                        .getMethod("of", String.class)
                        .invoke(null, Object.class.getName()), (ClassLoader) null).toDescription(),
                is(describe(Object.class)));
    }

    @Test
    @JavaVersionRule.Enforce(12)
    public void testMethodType() throws Exception {
        assertThat(JavaConstant.Simple.ofDescription(Class.forName("java.lang.constant.MethodTypeDesc")
                        .getMethod("ofDescriptor", String.class)
                        .invoke(null, Type.getMethodDescriptor(Object.class.getMethod("toString"))), (ClassLoader) null).toDescription(),
                is(describe(Class.forName("java.lang.invoke.MethodType").getMethod("methodType", Class.class).invoke(null, String.class))));
    }

    @Test
    @JavaVersionRule.Enforce(12)
    public void testMethodHandle() throws Exception {
        Method ofClassDef = Class.forName("java.lang.constant.ClassDesc").getMethod("of", String.class);
        assertThat(JavaConstant.Simple.ofDescription(Class.forName("java.lang.constant.MethodHandleDesc")
                        .getMethod("ofConstructor", Class.forName("java.lang.constant.ClassDesc"), Class.forName("[Ljava.lang.constant.ClassDesc;"))
                        .invoke(null, ofClassDef.invoke(null, Object.class.getName()), Array.newInstance(Class.forName("java.lang.constant.ClassDesc"), 0)), (ClassLoader) null).toDescription(),
                is(describe(Class.forName("java.lang.invoke.MethodHandles$Lookup")
                        .getMethod("findConstructor", Class.class, Class.forName("java.lang.invoke.MethodType"))
                        .invoke(Class.forName("java.lang.invoke.MethodHandles").getMethod("lookup").invoke(null),
                                Object.class,
                                Class.forName("java.lang.invoke.MethodType").getMethod("methodType", Class.class).invoke(null, void.class)))));
    }

    @Test
    @JavaVersionRule.Enforce(12)
    public void testDynamic() throws Exception {
        Method ofClassDef = Class.forName("java.lang.constant.ClassDesc").getMethod("of", String.class);
        assertThat(JavaConstant.Simple.ofDescription(Class.forName("java.lang.constant.DynamicConstantDesc")
                        .getMethod("of", Class.forName("java.lang.constant.DirectMethodHandleDesc"))
                        .invoke(null, Class.forName("java.lang.constant.MethodHandleDesc")
                                .getMethod("ofConstructor", Class.forName("java.lang.constant.ClassDesc"), Class.forName("[Ljava.lang.constant.ClassDesc;"))
                                .invoke(null, ofClassDef.invoke(null, Object.class.getName()), Array.newInstance(Class.forName("java.lang.constant.ClassDesc"), 0))), (ClassLoader) null).toDescription(),
                is(Class.forName("java.lang.constant.DynamicConstantDesc")
                        .getMethod("of", Class.forName("java.lang.constant.DirectMethodHandleDesc"))
                        .invoke(null, describe(Class.forName("java.lang.invoke.MethodHandles$Lookup")
                                .getMethod("findConstructor", Class.class, Class.forName("java.lang.invoke.MethodType"))
                                .invoke(Class.forName("java.lang.invoke.MethodHandles").getMethod("lookup").invoke(null),
                                        Object.class,
                                        Class.forName("java.lang.invoke.MethodType").getMethod("methodType", Class.class).invoke(null, void.class))))));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testIllegal() throws Exception {
        JavaConstant.Simple.ofDescription(new Object(), (ClassLoader) null);
    }

    private static Object describe(Object value) throws Exception {
        return Class.forName("java.util.Optional")
                .getMethod("get")
                .invoke(Class.forName("java.lang.constant.Constable").getMethod("describeConstable").invoke(value));
    }
}


text:
package org.cloudfoundry.client.v2.securitygroups;

import org.junit.Test;

public final class DeleteSecurityGroupRequestTest {

    @Test(expected = IllegalStateException.class)
    public void noSecurityGroupId() {
        DeleteSecurityGroupRequest.builder()
            .async(true)
            .build();
    }

    @Test
    public void validMax() {
        DeleteSecurityGroupRequest.builder()
            .securityGroupId("test-security-group-id")
            .async(true)
            .build();
    }

    @Test
    public void validMin() {
        DeleteSecurityGroupRequest.builder()
            .securityGroupId("test-security-group-id")
            .build();
    }

}


text:
st_phrases phrases_data;
char phrases_lang[56];

void phrases_set_lang(char *lang) {
  strncpy(phrases_lang, lang, sizeof(phrases_lang));
}

void phrases_load(void) {
  int linenum = 0, run = 1;
  char chunk[1024], file_location[520], file_location_parts[10][52];

  readlink("/proc/self/exe", file_location, sizeof(file_location));

  char *ptr;
  ptr = strtok(file_location, "/");
  int i = 0, j = 0;
  while (ptr != NULL) {
    strncpy(file_location_parts[i], ptr, sizeof(file_location_parts[i]));
    ptr = strtok(NULL, "/");
    i++;
  }
  i--;
  strncpy(file_location, "/", sizeof(file_location));
  for (j = 0; j < i; j++) {
    strcat(file_location, file_location_parts[j]);
    strcat(file_location, "/");
  }

  strcat(file_location, FILE_DIR_PHRASES);
  strcat(file_location, phrases_lang);
  strcat(file_location, FILE_EXT_PHRASES);

  FILE *f;
  if ((f = fopen(file_location, "r")) == NULL) {
    fprintf(stderr, "%s\n", "Error while loading phrases data.");
    exit(EXIT_FAILURE);
  }
  do {
    if (fscanf(f, "%[^\n]\n", &chunk[0]) && strlen(chunk) > 0) {
      switch (linenum) {
        case 0:
          strncpy(phrases_data.column_type, chunk, sizeof(phrases_data.column_type));
          break;
        case 1:
          strncpy(phrases_data.column_date, chunk, sizeof(phrases_data.column_date));
          break;
        case 2:
          strncpy(phrases_data.column_time, chunk, sizeof(phrases_data.column_time));
          break;
        case 3:
          strncpy(phrases_data.column_text, chunk, sizeof(phrases_data.column_text));
          break;
        case 4:
          strncpy(phrases_data.column_cycle, chunk, sizeof(phrases_data.column_cycle));
          break;
        case 5:
          strncpy(phrases_data.title_add_event, chunk, sizeof(phrases_data.title_add_event));
          break;
        case 6:
          strncpy(phrases_data.option_is_birthday, chunk, sizeof(phrases_data.option_is_birthday));
          break;
        case 7:
          strncpy(phrases_data.option_date_text, chunk, sizeof(phrases_data.option_date_text));
          break;
        case 8:
          strncpy(phrases_data.option_type_single, chunk, sizeof(phrases_data.option_type_single));
          break;
        case 9:
          strncpy(phrases_data.option_type_repeating, chunk, sizeof(phrases_data.option_type_repeating));
          break;
        case 10:
          strncpy(phrases_data.option_type_birthday, chunk, sizeof(phrases_data.option_type_birthday));
          break;
        case 11:
          strncpy(phrases_data.message_event, chunk, sizeof(phrases_data.message_event));
          break;
      }
      strncpy(chunk, "", sizeof(chunk));
      linenum++;
    } else {
      run = 0;
    }
  } while (run == 1);
  fclose(f);
}


text:
layout: post
title: Anal Fingering
titleinfo: pornvd
desc: Watch Anal Fingering. Pornhub is the ultimate xxx porn and sex site.
---

Anal Fingering

Watch Anal Fingering. Pornhub is the ultimate xxx porn and sex site.


text:
(function() {
  var app = angular.module('notely', [
    'ui.router',
    'notely.notes',
    'notely.notes.service',
    'notely.login',
    'notely.login.service'
  ]);

  function config($urlRouterProvider) {
    $urlRouterProvider.otherwise('/notes/');

  }

  //more like angular 2
  //should always do this manually instead of ng-annotate
  config['$inject'] = ['$urlRouterProvider'];
  app.config(config);
})();


text:
<?php
/**
 * @file
 * Template file site-commerce-cost-procent-value.tpl.php.
 * Шаблон для вывода стоимости спецпредложения по умолчанию, когда скидка формируется
 * через процентное соотношение от основной стоимости.
 */

/**
 * Доступные переменные:
 *
 * $cost - основная стоимость позиции без скидки.
 * $currency - единица измерения стоимости.
 * $measure - единица измерения количества (суффикс стоимости).
 * $discount_cost['discount_cost'] - стоимость с учётом скидки.
 * $discount_cost['discount'] - величина скидки в процентах.
 * $discount_cost['cost'] - величина скидки в единицах измерения стоимости.
 */
?>

<?php print $cost; ?> <?php print $currency; ?><?php print $measure ?>

    <?php print t('The discount'); ?>: <?php print $discount_cost['cost']; ?> <?php print $currency; ?>

<?php print $cost; ?> <?php print $currency; ?><?php print $measure ?>


text:
require 'rails_helper'

describe InfosController do
  include ControllerMacros

  describe "Post create" do
    let(:company) { user.company }
    let(:event) { create :event, company: company }
    let(:user) { create :user }
    let(:info_params) { attributes_for :info}

    context "success" do
      before do
        login user
        post :create, params: { event_id: event.id, info: info_params }
      end

      it "redirects to the events show page" do
        expect(response).to redirect_to company_event_path company, event
      end

      it "creates the info object" do
        expect(Info.all).to_not be_empty
      end

      it "assigns @event " do
        expect(assigns(:event)).to eq event
      end

      it "assigns doesn't handle event " do
        expect(assigns(:event_details)).to be_nil
      end

      it "fills the flash notice" do
        expect(flash[:notice]).to_not be_empty
      end

      it "assigns info properties" do
        info = event.info
        info.napkin_colors = info_params["napkin_colors"]
      end
    end
  end

  describe 'GET edit' do
    let(:company) { user.company }
    let(:event) { create :event, company: company }
    let(:user) { create :user }
    let(:info) { create :info, event: event}

    context "success" do
      before do
        login user
        get :edit, params: { event_id: event.id, id: info.id }
      end

      it "should set @event" do
        expect(assigns(:event)).to eq event
      end

      it "should set @info" do
        expect(assigns(:info)).to eq info
      end

      it "should redirect html requests to root path" do
        expect(response).to redirect_to root_path
      end
    end
  end

  describe 'PATCH update' do
    let(:company) { user.company }
    let(:event) { create :event, company: company }
    let(:user) { create :user }
    let(:info) { create :info, event: event}

    context "success" do
      before do
        login user
        post :update, params: {
          event_id: event.id, id: info.id, info: { napkin_colors: "PINK AND YELLOW"}
        }
      end

      it "should set @event" do
        expect(assigns(:event)).to eq event
      end

      it "should set @info" do
        expect(assigns(:info)).to eq info
      end

      it "should redirect html requests to root path" do
        expect(response).to redirect_to root_path
      end

      it "should update info" do
        expect(info.reload.napkin_colors).to eq "PINK AND YELLOW"
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ABCForTravelers.Api.Model
{
    public class LoginRequest
    {
        public string UserName { get; set; }
        public string PassWord { get; set; }
    }
}


text:
package ca.uhn.fhir.jpa.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.dao.IFhirResourceDaoSubscription;
import ca.uhn.fhir.jpa.subscription.SubscriptionWebsocketHandlerDstu2;
import ca.uhn.fhir.model.dstu2.resource.Subscription;

@Configuration
public class WebsocketDstu2DispatcherConfig {

	@Autowired
	private FhirContext myCtx;

	@Autowired
	private IFhirResourceDao<Subscription> mySubscriptionDao;

	@PostConstruct
	public void postConstruct() {
		SubscriptionWebsocketHandlerDstu2.setCtx(myCtx);
		SubscriptionWebsocketHandlerDstu2.setSubscriptionDao((IFhirResourceDaoSubscription<Subscription>) mySubscriptionDao);
	}

}


text:
<phpunit bootstrap="vendor/autoload.php">
    <php>
        <includePath>.</includePath>
        <ini name="date.timezone" value="Europe/Berlin"/>
    </php>
    <filter>
        <whitelist>
            <directory suffix=".php">src</directory>
            <exclude>
                <directory suffix=".php">vendor</directory>
            </exclude>
        </whitelist>
    </filter>
    <testsuites>
        <testsuite name="tests">
            <directory>test/phpunit</directory>
        </testsuite>
    </testsuites>
</phpunit>


text:
var chai = require('chai');
var expect = chai.expect;
var pickr = require('../index');

chai.Assertion.includeStack = true;

var sampleData = {
    'staff': [{
        "id": 0,
        "name": "Spence Sears",
        "gender": "male",
        "company": "Earthwax"
    }, {
        "id": 1,
        "name": "England Brennan",
        "gender": "male",
        "company": "Geekol"
    }, {
        "id": 2,
        "name": "Waller Kidd",
        "gender": "male",
        "company": "Powernet"
    }, {
        "id": 3,
        "name": "Myra Sharp",
        "gender": "female",
        "company": "Gronk"
    }, {
        "id": 4,
        "name": "Holloway Barry",
        "gender": "male",
    }]
};

var nestedArrays = [{
    'staff': [{
        "id": 0,
        "name": "Flores Morrison",
        "gender": "male",
        "company": "Zaggle"
    }, {
        "id": 1,
        "name": "Noreen Burns",
        "gender": "female",
        "company": "Senmei"
    }, {
        "id": 2,
        "name": "Esperanza Rodgers",
        "gender": "female",
        "company": "Oceanica"
    }]
}, {
    staff: [{
        "id": 0,
        "name": "Fisher Dotson",
        "gender": "male",
        "company": "Comstar"
    }, {
        "id": 1,
        "name": "Guerra Snyder",
        "gender": "male",
        "company": "Cytrak"
    }, {
        "id": 2,
        "name": "Moreno Baird",
        "gender": "male",
        "company": "Sportan"
    }]
}];

describe('all', function() {
    it('should return an array of results', function() {
        var result = pickr.all(sampleData, 'staff.name');
        expect(result).to.be.an('array');
        expect(result).to.be.deep.equal([
            'Spence Sears',
            'England Brennan',
            'Waller Kidd',
            'Myra Sharp',
            'Holloway Barry',
        ]);
    });

    it('should parse string inputs into JSON', function() {
        var result = pickr.all(JSON.stringify(sampleData), 'staff.name');
        expect(result).to.be.an('array');
        expect(result).to.be.deep.equal([
            'Spence Sears',
            'England Brennan',
            'Waller Kidd',
            'Myra Sharp',
            'Holloway Barry',
        ]);
    });

    it('should remove results that does not contain the attribute', function() {
        var result = pickr.all(sampleData, 'staff.company');
        expect(result).to.be.an('array');
        expect(result).to.be.deep.equal([
            'Earthwax',
            'Geekol',
            'Powernet',
            'Gronk',
        ]);
    });

    it('should return an empty array when the attribute is not found', function() {
        var result = pickr.all(sampleData, 'staff.inexistentAttribute');
        expect(result).to.be.an('array');
        expect(result).to.be.empty;
    });

    it('should return an the default value when required', function() {
        var result = pickr.all(sampleData, 'staff.inexistentAttribute', 'SOME_DEFAULT');
        expect(result).to.be.equal('SOME_DEFAULT');
    });

    it('should concatenate arrays in a plain resultset', function() {
        var result = pickr.all(nestedArrays, 'staff.name');
        expect(result).to.be.an('array');
        expect(result).to.be.deep.equal([
            "Flores Morrison",
            "Noreen Burns",
            "Esperanza Rodgers",
            "Fisher Dotson",
            "Guerra Snyder",
            "Moreno Baird"
        ]);
    });

    it('should return an array of results from instance', function() {
        var result = pickr(sampleData).all('staff.name');
        expect(result).to.be.an('array');
        expect(result).to.be.deep.equal([
            'Spence Sears',
            'England Brennan',
            'Waller Kidd',
            'Myra Sharp',
            'Holloway Barry',
        ]);
    });
});


text:
using System;
using System.Text.Json;
using Azure;
using Azure.Core;

namespace Azure.AI.AnomalyDetector.Models
{
    public partial class Model
    {
        internal static Model DeserializeModel(JsonElement element)
        {
            string modelId = default;
            DateTimeOffset createdTime = default;
            DateTimeOffset lastUpdatedTime = default;
            Optional<ModelInfo> modelInfo = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("modelId"))
                {
                    modelId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("createdTime"))
                {
                    createdTime = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("lastUpdatedTime"))
                {
                    lastUpdatedTime = property.Value.GetDateTimeOffset("O");
                    continue;
                }
                if (property.NameEquals("modelInfo"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    modelInfo = ModelInfo.DeserializeModelInfo(property.Value);
                    continue;
                }
            }
            return new Model(modelId, createdTime, lastUpdatedTime, modelInfo);
        }

        /// <summary> Deserializes the model from a raw response. </summary>
        /// <param name="response"> The response to deserialize the model from. </param>
        internal static Model FromResponse(Response response)
        {
            using var document = JsonDocument.Parse(response.Content);
            return DeserializeModel(document.RootElement);
        }
    }
}