/*
 *  Copyright (c) 2017, The OpenThread Authors.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of the copyright holder nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

#include "dns_client.hpp"

#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/instance.hpp"
#include "common/locator-getters.hpp"
#include "common/logging.hpp"
#include "net/udp6.hpp"
#include "thread/thread_netif.hpp"

#if OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE

/**
 * @file
 *   This file implements the DNS client.
 */

using ot::Encoding::BigEndian::HostSwap16;

namespace ot {
namespace Dns {

Client::Client(Instance &aInstance)
    : mSocket(aInstance)
    , mMessageId(0)
    , mRetransmissionTimer(aInstance, Client::HandleRetransmissionTimer, this)
{
}

otError Client::Start(void)
{
    otError error;

    SuccessOrExit(error = mSocket.Open(&Client::HandleUdpReceive, this));
    SuccessOrExit(error = mSocket.Bind());

exit:
    return error;
}

otError Client::Stop(void)
{
    Message *     message = mPendingQueries.GetHead();
    Message *     messageToRemove;
    QueryMetadata queryMetadata;

    // Remove all pending queries.
    while (message != nullptr)
    {
        messageToRemove = message;
        message         = message->GetNext();

        queryMetadata.ReadFrom(*messageToRemove);
        FinalizeDnsTransaction(*messageToRemove, queryMetadata, nullptr, 0, OT_ERROR_ABORT);
    }

    return mSocket.Close();
}

otError Client::Query(const otDnsQuery *aQuery, otDnsResponseHandler aHandler, void *aContext)
{
    otError                 error;
    QueryMetadata           queryMetadata;
    Message *               message     = nullptr;
    Message *               messageCopy = nullptr;
    Header                  header;
    QuestionAaaa            question;
    const Ip6::MessageInfo *messageInfo;

    VerifyOrExit(aQuery->mHostname != nullptr && aQuery->mMessageInfo != nullptr, error = OT_ERROR_INVALID_ARGS);

    header.SetMessageId(mMessageId++);
    header.SetType(Header::kTypeQuery);
    header.SetQueryType(Header::kQueryTypeStandard);

    if (!aQuery->mNoRecursion)
    {
        header.SetRecursionDesiredFlag();
    }

    header.SetQuestionCount(1);

    VerifyOrExit((message = NewMessage(header)) != nullptr, error = OT_ERROR_NO_BUFS);

    SuccessOrExit(error = AppendCompressedHostname(*message, aQuery->mHostname));
    SuccessOrExit(error = question.AppendTo(*message));

    messageInfo = static_cast<const Ip6::MessageInfo *>(aQuery->mMessageInfo);

    queryMetadata.mHostname            = aQuery->mHostname;
    queryMetadata.mResponseHandler     = aHandler;
    queryMetadata.mResponseContext     = aContext;
    queryMetadata.mTransmissionTime    = TimerMilli::GetNow() + kResponseTimeout;
    queryMetadata.mSourceAddress       = messageInfo->GetSockAddr();
    queryMetadata.mDestinationAddress  = messageInfo->GetPeerAddr();
    queryMetadata.mDestinationPort     = messageInfo->GetPeerPort();
    queryMetadata.mRetransmissionCount = 0;

    VerifyOrExit((messageCopy = CopyAndEnqueueMessage(*message, queryMetadata)) != nullptr, error = OT_ERROR_NO_BUFS);
    SuccessOrExit(error = SendMessage(*message, *messageInfo));

exit:

    if (error != OT_ERROR_NONE)
    {
        FreeMessage(message);

        if (messageCopy)
        {
            DequeueMessage(*messageCopy);
        }
    }

    return error;
}

Message *Client::NewMessage(const Header &aHeader)
{
    Message *message = nullptr;

    VerifyOrExit((message = mSocket.NewMessage(sizeof(aHeader))) != nullptr, OT_NOOP);
    IgnoreError(message->Prepend(&aHeader, sizeof(aHeader)));
    message->SetOffset(0);

exit:
    return message;
}

Message *Client::CopyAndEnqueueMessage(const Message &aMessage, const QueryMetadata &aQueryMetadata)
{
    otError  error       = OT_ERROR_NONE;
    Message *messageCopy = nullptr;

    // Create a message copy for further retransmissions.
    VerifyOrExit((messageCopy = aMessage.Clone()) != nullptr, error = OT_ERROR_NO_BUFS);

    // Append the copy with retransmission data and add it to the queue.
    SuccessOrExit(error = aQueryMetadata.AppendTo(*messageCopy));
    mPendingQueries.Enqueue(*messageCopy);

    mRetransmissionTimer.FireAtIfEarlier(aQueryMetadata.mTransmissionTime);

exit:
    FreeAndNullMessageOnError(messageCopy, error);
    return messageCopy;
}

void Client::DequeueMessage(Message &aMessage)
{
    mPendingQueries.Dequeue(aMessage);

    if (mRetransmissionTimer.IsRunning() && (mPendingQueries.GetHead() == nullptr))
    {
        // No more requests pending, stop the timer.
        mRetransmissionTimer.Stop();
    }

    // Free the message memory.
    aMessage.Free();
}

otError Client::SendMessage(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    return mSocket.SendTo(aMessage, aMessageInfo);
}

void Client::SendCopy(const Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    otError  error;
    Message *messageCopy = nullptr;

    // Create a message copy for lower layers.
    VerifyOrExit((messageCopy = aMessage.Clone(aMessage.GetLength() - sizeof(QueryMetadata))) != nullptr,
                 error = OT_ERROR_NO_BUFS);

    // Send the copy.
    SuccessOrExit(error = SendMessage(*messageCopy, aMessageInfo));

exit:

    if (error != OT_ERROR_NONE)
    {
        FreeMessage(messageCopy);
        otLogWarnIp6("Failed to send DNS request: %s", otThreadErrorToString(error));
    }
}

otError Client::AppendCompressedHostname(Message &aMessage, const char *aHostname)
{
    otError error         = OT_ERROR_NONE;
    uint8_t index         = 0;
    uint8_t labelPosition = 0;
    uint8_t labelSize     = 0;

    while (true)
    {
        // Look for string separator.
        if (aHostname[index] == kLabelSeparator || aHostname[index] == kLabelTerminator)
        {
            VerifyOrExit(labelSize > 0, error = OT_ERROR_INVALID_ARGS);
            SuccessOrExit(error = aMessage.Append(&labelSize, 1));
            SuccessOrExit(error = aMessage.Append(&aHostname[labelPosition], labelSize));

            labelPosition += labelSize + 1;
            labelSize = 0;

            if (aHostname[index] == kLabelTerminator)
            {
                break;
            }
        }
        else
        {
            labelSize++;
        }

        index++;
    }

    // Add termination character at the end.
    labelSize = kLabelTerminator;
    SuccessOrExit(error = aMessage.Append(&labelSize, 1));

exit:
    return error;
}

otError Client::CompareQuestions(Message &aMessageResponse, Message &aMessageQuery, uint16_t &aOffset)
{
    otError  error = OT_ERROR_NONE;
    uint8_t  bufQuery[kBufSize];
    uint8_t  bufResponse[kBufSize];
    uint16_t read = 0;

    // Compare question section of the query with the response.
    uint16_t length = aMessageQuery.GetLength() - aMessageQuery.GetOffset() - sizeof(Header) - sizeof(QueryMetadata);
    uint16_t offset = aMessageQuery.GetOffset() + sizeof(Header);

    while (length > 0)
    {
        VerifyOrExit(
            (read = aMessageQuery.Read(offset, length < sizeof(bufQuery) ? length : sizeof(bufQuery), bufQuery)) > 0,
            error = OT_ERROR_PARSE);
        VerifyOrExit(aMessageResponse.Read(aOffset, read, bufResponse) == read, error = OT_ERROR_PARSE);

        VerifyOrExit(memcmp(bufResponse, bufQuery, read) == 0, error = OT_ERROR_NOT_FOUND);

        aOffset += read;
        offset += read;
        length -= read;
    }

exit:
    return error;
}

otError Client::SkipHostname(Message &aMessage, uint16_t &aOffset)
{
    otError  error = OT_ERROR_NONE;
    uint8_t  buf[kBufSize];
    uint16_t index;
    uint16_t read   = 0;
    uint16_t offset = aOffset;
    uint16_t length = aMessage.GetLength() - aOffset;

    while (length > 0)
    {
        VerifyOrExit((read = aMessage.Read(offset, sizeof(buf), buf)) > 0, error = OT_ERROR_PARSE);

        index = 0;

        while (index < read)
        {
            if (buf[index] == kLabelTerminator)
            {
                ExitNow(aOffset = offset + 1);
            }

            if ((buf[index] & kCompressionOffsetMask) == kCompressionOffsetMask)
            {
                ExitNow(aOffset = offset + 2);
            }

            index++;
            offset++;
        }

        length -= read;
    }

    ExitNow(error = OT_ERROR_PARSE);

exit:
    return error;
}

Message *Client::FindRelatedQuery(const Header &aResponseHeader, QueryMetadata &aQueryMetadata)
{
    uint16_t messageId;
    Message *message = mPendingQueries.GetHead();

    while (message != nullptr)
    {
        // Partially read DNS header to obtain message ID only.
        uint16_t count = message->Read(message->GetOffset(), sizeof(messageId), &messageId);

        OT_UNUSED_VARIABLE(count);
        OT_ASSERT(count == sizeof(messageId));

        if (HostSwap16(messageId) == aResponseHeader.GetMessageId())
        {
            aQueryMetadata.ReadFrom(*message);
            ExitNow();
        }

        message = message->GetNext();
    }

exit:
    return message;
}

void Client::FinalizeDnsTransaction(Message &            aQuery,
                                    const QueryMetadata &aQueryMetadata,
                                    const otIp6Address * aAddress,
                                    uint32_t             aTtl,
                                    otError              aResult)
{
    DequeueMessage(aQuery);

    if (aQueryMetadata.mResponseHandler != nullptr)
    {
        aQueryMetadata.mResponseHandler(aQueryMetadata.mResponseContext, aQueryMetadata.mHostname, aAddress, aTtl,
                                        aResult);
    }
}

void Client::HandleRetransmissionTimer(Timer &aTimer)
{
    aTimer.GetOwner<Client>().HandleRetransmissionTimer();
}

void Client::HandleRetransmissionTimer(void)
{
    TimeMilli        now      = TimerMilli::GetNow();
    TimeMilli        nextTime = now.GetDistantFuture();
    QueryMetadata    queryMetadata;
    Message *        message;
    Message *        nextMessage;
    Ip6::MessageInfo messageInfo;

    for (message = mPendingQueries.GetHead(); message != nullptr; message = nextMessage)
    {
        nextMessage = message->GetNext();

        queryMetadata.ReadFrom(*message);

        if (now >= queryMetadata.mTransmissionTime)
        {
            if (queryMetadata.mRetransmissionCount >= kMaxRetransmit)
            {
                // No expected response.
                FinalizeDnsTransaction(*message, queryMetadata, nullptr, 0, OT_ERROR_RESPONSE_TIMEOUT);

                continue;
            }

            // Increment retransmission counter and timer.
            queryMetadata.mRetransmissionCount++;
            queryMetadata.mTransmissionTime = now + kResponseTimeout;
            queryMetadata.UpdateIn(*message);

            // Retransmit
            messageInfo.SetPeerAddr(queryMetadata.mDestinationAddress);
            messageInfo.SetPeerPort(queryMetadata.mDestinationPort);
            messageInfo.SetSockAddr(queryMetadata.mSourceAddress);

            SendCopy(*message, messageInfo);
        }

        if (nextTime > queryMetadata.mTransmissionTime)
        {
            nextTime = queryMetadata.mTransmissionTime;
        }
    }

    if (nextTime < now.GetDistantFuture())
    {
        mRetransmissionTimer.FireAt(nextTime);
    }
}

void Client::HandleUdpReceive(void *aContext, otMessage *aMessage, const otMessageInfo *aMessageInfo)
{
    static_cast<Client *>(aContext)->HandleUdpReceive(*static_cast<Message *>(aMessage),
                                                      *static_cast<const Ip6::MessageInfo *>(aMessageInfo));
}

void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    // RFC1035 7.3. Resolver cannot rely that a response will come from the same address
    // which it sent the corresponding query to.
    OT_UNUSED_VARIABLE(aMessageInfo);

    otError            error = OT_ERROR_NOT_FOUND;
    Header             responseHeader;
    QueryMetadata      queryMetadata;
    ResourceRecordAaaa record;
    Message *          message = nullptr;
    uint16_t           offset;

    VerifyOrExit(aMessage.Read(aMessage.GetOffset(), sizeof(responseHeader), &responseHeader) == sizeof(responseHeader),
                 OT_NOOP);
    VerifyOrExit(responseHeader.GetType() == Header::kTypeResponse && responseHeader.GetQuestionCount() == 1 &&
                     !responseHeader.IsTruncationFlagSet(),
                 OT_NOOP);

    aMessage.MoveOffset(sizeof(responseHeader));
    offset = aMessage.GetOffset();

    VerifyOrExit((message = FindRelatedQuery(responseHeader, queryMetadata)) != nullptr, OT_NOOP);

    VerifyOrExit(responseHeader.GetResponseCode() == Header::kResponseSuccess, error = OT_ERROR_FAILED);

    // Parse and check the question section.
    SuccessOrExit(error = CompareQuestions(aMessage, *message, offset));

    // Parse and check the answer section.
    for (uint32_t index = 0; index < responseHeader.GetAnswerCount(); index++)
    {
        uint32_t newOffset;

        SuccessOrExit(error = SkipHostname(aMessage, offset));

        VerifyOrExit(aMessage.Read(offset, sizeof(record), &record) == sizeof(record), error = OT_ERROR_PARSE);

        if ((record.GetType() == ResourceRecordAaaa::kType) && (record.GetClass() == ResourceRecordAaaa::kClass))
        {
            // Return the first found IPv6 address.
            FinalizeDnsTransaction(*message, queryMetadata, &record.GetAddress(), record.GetTtl(), OT_ERROR_NONE);
            ExitNow(error = OT_ERROR_NONE);
        }

        newOffset = offset + sizeof(ResourceRecord) + record.GetLength();
        VerifyOrExit(newOffset <= aMessage.GetLength(), error = OT_ERROR_PARSE);
        offset = static_cast<uint16_t>(newOffset);
    }

exit:

    if (message != nullptr && error != OT_ERROR_NONE)
    {
        FinalizeDnsTransaction(*message, queryMetadata, nullptr, 0, error);
    }
}

void Client::QueryMetadata::ReadFrom(const Message &aMessage)
{
    uint16_t length = aMessage.GetLength();

    OT_ASSERT(length >= sizeof(*this));
    aMessage.Read(length - sizeof(*this), sizeof(*this), this);
}

void Client::QueryMetadata::UpdateIn(Message &aMessage) const
{
    aMessage.Write(aMessage.GetLength() - sizeof(*this), sizeof(*this), this);
}

} // namespace Dns
} // namespace ot

#endif // OPENTHREAD_CONFIG_DNS_CLIENT_ENABLE

{'repo_name': 'openthread/openthread', 'stars': '2193', 'repo_language': 'C++', 'file_name': 'compiler.h', 'mime_type': 'text/x-c', 'hash': -6105207941186167194, 'source_dataset': 'data'}


<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  <meta name="description" content="Javadoc API documentation for Fresco." />

<link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" />
<title>

  com.facebook.common.time Details - Fresco API

| Fresco

</title>
<link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />

      Fresco

          <form accept-charset="utf-8" class="gsc-search-box"
                onsubmit="return submit_search()">

                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../../')"
                      onkeyup="return search_changed(event, false, '../../../../')" />

          </form>

                Packages |
                Classes

  com.facebook.animated.gif

  com.facebook.animated.giflite

  com.facebook.animated.giflite.decoder

  com.facebook.animated.giflite.draw

  com.facebook.animated.giflite.drawable

  com.facebook.animated.webp

  com.facebook.animated.webpdrawable

  com.facebook.binaryresource

  com.facebook.cache.common

  com.facebook.cache.disk

  com.facebook.callercontext

  com.facebook.common.activitylistener

  com.facebook.common.disk

  com.facebook.common.executors

  com.facebook.common.file

  com.facebook.common.internal

  com.facebook.common.lifecycle

  com.facebook.common.logging

  com.facebook.common.media

  com.facebook.common.memory

  com.facebook.common.references

  com.facebook.common.statfs

  com.facebook.common.streams

  com.facebook.common.time

  com.facebook.common.util

  com.facebook.common.webp

  com.facebook.datasource

  com.facebook.drawable.base

  com.facebook.drawee.backends.pipeline

  com.facebook.drawee.backends.pipeline.debug

  com.facebook.drawee.backends.pipeline.info

  com.facebook.drawee.backends.pipeline.info.internal

  com.facebook.drawee.components

  com.facebook.drawee.controller

  com.facebook.drawee.debug

  com.facebook.drawee.debug.listener

  com.facebook.drawee.drawable

  com.facebook.drawee.generic

  com.facebook.drawee.gestures

  com.facebook.drawee.interfaces

  com.facebook.drawee.span

  com.facebook.drawee.view

  com.facebook.fresco.animation.backend

  com.facebook.fresco.animation.bitmap

  com.facebook.fresco.animation.bitmap.cache

  com.facebook.fresco.animation.bitmap.preparation

  com.facebook.fresco.animation.bitmap.wrapper

  com.facebook.fresco.animation.drawable

  com.facebook.fresco.animation.drawable.animator

  com.facebook.fresco.animation.factory

  com.facebook.fresco.animation.frame

  com.facebook.fresco.middleware

  com.facebook.fresco.ui.common

  com.facebook.imageformat

  com.facebook.imagepipeline.animated.base

  com.facebook.imagepipeline.animated.factory

  com.facebook.imagepipeline.animated.impl

  com.facebook.imagepipeline.animated.util

  com.facebook.imagepipeline.backends.okhttp3

  com.facebook.imagepipeline.backends.volley

  com.facebook.imagepipeline.bitmaps

  com.facebook.imagepipeline.cache

  com.facebook.imagepipeline.common

  com.facebook.imagepipeline.core

  com.facebook.imagepipeline.datasource

  com.facebook.imagepipeline.debug

  com.facebook.imagepipeline.decoder

  com.facebook.imagepipeline.drawable

  com.facebook.imagepipeline.filter

  com.facebook.imagepipeline.image

  com.facebook.imagepipeline.instrumentation

  com.facebook.imagepipeline.listener

  com.facebook.imagepipeline.memory

  com.facebook.imagepipeline.multiuri

  com.facebook.imagepipeline.nativecode

  com.facebook.imagepipeline.platform

  com.facebook.imagepipeline.postprocessors

  com.facebook.imagepipeline.producers

  com.facebook.imagepipeline.request

  com.facebook.imagepipeline.systrace

  com.facebook.imagepipeline.transcoder

  com.facebook.imagepipeline.transformation

  com.facebook.imageutils

  com.facebook.webpsupport

  com.facebook.widget.text.span

Interfaces

Clock

MonotonicClock

MonotonicNanoClock

Classes

AwakeTimeSinceBootClock

CurrentThreadTimeClock

RealtimeSinceBootClock

SystemClock

            Packages |
            Classes

  package

com.facebook.common.time

      Classes | Description

 +Generated by Doclava.
 +

{'repo_name': 'facebook/fresco', 'stars': '16255', 'repo_language': 'Java', 'file_name': 'MockitoConfiguration.java', 'mime_type': 'text/plain', 'hash': 5514494196993003658, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>virtualenv on 阳明的博客</title>
    <link>https://www.qikqiak.com/tags/virtualenv/</link>
    <description>Recent content in virtualenv on 阳明的博客</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Tue, 09 Jan 2018 00:00:00 +0000</lastBuildDate>

	<atom:link href="https://www.qikqiak.com/tags/virtualenv/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Python 虚拟环境全知道</title>
      <link>https://www.qikqiak.com/post/python-virtualenv-all-know/</link>
      <pubDate>Tue, 09 Jan 2018 00:00:00 +0000</pubDate>

      <guid>https://www.qikqiak.com/post/python-virtualenv-all-know/</guid>
      <description>
对于每个python项目依赖的库版本都有可能不一样，如果将依赖包都安装到公共环境的话显然是没法进行区分的，甚至是不同的项目使用的python版本都不尽相同，有的用python2.7，有的用python3.6，所以对于python项目的环境进行隔离管理就成为一个必然的需求了。
</description>
    </item>

  </channel>
</rss>

{'repo_name': 'cnych/qikqiak.com', 'stars': '221', 'repo_language': 'HTML', 'file_name': 'default.md', 'mime_type': 'text/plain', 'hash': -6944035952545857602, 'source_dataset': 'data'}


/*
 * ------------------------------------------
 * 文件上传代理实现文件
 * @version  1.0
 * @author   genify(caijf@corp.netease.com)
 * ------------------------------------------
 */
/** @module  util/ajax/proxy/upload */
NEJ.define([
    './proxy.js',
    'base/klass',
    'base/util',
    'base/event',
    'base/element',
    'base/constant',
    'util/ajax/xdr',
    'util/ajax/message'
],function(_t,_k,_u,_v,_e,_g,_j0,_j1,_p,_o,_f,_r){
    var _pro,
        _cache = {},
        _xflag = 'NEJ-UPLOAD-RESULT:';
    /**
     * 文件上传代理
     *
     * @class   module:util/ajax/proxy/upload._$$ProxyUpload
     * @extends module:util/ajax/proxy/proxy._$$ProxyAbstract
     *
     * @param   {Object}  config - 构造配置参数
     */
    _p._$$ProxyUpload = _k._$klass();
    _pro = _p._$$ProxyUpload._$extend(_t._$$ProxyAbstract);
    /**
     * 控件初始化
     *
     * @protected
     * @method module:util/ajax/proxy/upload._$$ProxyUpload#__init
     * @return {Void}
     */
    _pro.__init = (function(){
        var _init = !1;
        // receive message callback
        var _doReceiveMessage = function(_event){
            var _data = _event.data;
            if (_data.indexOf(_xflag)!=0) return;
            _data = JSON.parse(_data.replace(_xflag,''));
            var _proxy = _cache[_data.key];
            if (!_proxy) return;
            delete _cache[_data.key];
            _proxy.__onLoadRequest(
                decodeURIComponent(_data.result)
            );
        };
        // init message listener
        var _doInitMessage = function(){
            if (!_init){
                _init = !0;
                _v._$addEvent(
                    window,'message',
                    _doReceiveMessage
                );
            }
        };
        return function(){
            this.__super();
            _doInitMessage();
        };
    })();
    /**
     * 控件销毁
     *
     * @protected
     * @method module:util/ajax/proxy/upload._$$ProxyUpload#__destroy
     * @return {Void}
     */
    _pro.__destroy = function(){
        this.__super();
        _e._$remove(this.__frame);
        delete this.__frame;
        window.clearTimeout(this.__timer);
        delete this.__timer;
    };
    /**
     * 请求载入回调
     *
     * @protected
     * @method module:util/ajax/proxy/upload._$$ProxyUpload#__onLoadRequest
     * @param  {String} arg0 - 数据信息
     * @return {Void}
     */
    _pro.__onLoadRequest = function(_text){
        try{
            var _ret = _e._$text2type(
                _text,this.__request.type
            );
            this._$dispatchEvent('onload',_ret);
        }catch(ex){
            this._$dispatchEvent('onerror',{
                code:_g._$CODE_ERREVAL,
                message:_text
            });
        }
    };
    /**
     * 往服务器发送请求
     *
     * @protected
     * @method module:util/ajax/proxy/upload._$$ProxyUpload#__doSendRequest
     * @param  {Object} arg0 - 请求信息
     * @return {Void}
     */
    _pro.__doSendRequest = (function(){
        // same domain upload result check
        var _doCheckResult = function(){
            var _body,_text;
            try{
                var _body = this.__frame.contentWindow.document.body,
                    _text = (_body.innerText||_body.textContent||'').trim();
                // check result for same domain with upload proxy html
                if (_text.indexOf(_xflag)>=0||
                    _body.innerHTML.indexOf(_xflag)>=0){
                    // use post message path
                    return;
                }
            }catch(ex){
                // ignore if not same domain
                return;
            }
            this.__onLoadRequest(_text);
        };
        // check upload progress
        var _doProgress = function(_url,_mode,_cookie){
            _j0._$request(_url,{
                type:'json',
                method:'POST',
                cookie:_cookie,
                mode:parseInt(_mode)||0,
                onload:function(_data){
                    if (!this.__timer) return;
                    this._$dispatchEvent('onuploading',_data);
                    this.__timer = window.setTimeout(
                        _doProgress._$bind(
                            this,_url,_mode,_cookie
                        ),1000
                    );
                }._$bind(this),
                onerror:function(_error){
                    if (!this.__timer) return;
                    this.__timer = window.setTimeout(
                        _doProgress._$bind(
                            this,_url,_mode,_cookie
                        ),1000
                    );
                }._$bind(this)
            });
        };
        return function(_options){
            var _request = _options.request,
                _headers = _options.headers,
                _form = _request.data,
                _name = _u._$uniqueID();
            _cache[_name]  = this;
            _form.target   = _name;
            _form.method   = 'POST';
            _form.enctype  = _g._$HEAD_CT_FILE;
            _form.encoding = _g._$HEAD_CT_FILE;
            var _url = _form.action||'',
                _sep = _url.indexOf('?')<=0?'?':'&';
            _form.action = _url+_sep+'_proxy_=form';
            this.__frame = _e._$createXFrame({
                name:_name,
                onload:function(_event){
                    var _frame = _v._$getElement(_event);
                    _v._$addEvent(
                        _frame,'load',
                        _doCheckResult._$bind(this)
                    );
                    _form.submit();
                    var _qurl = (_form.nej_query||_o).value;
                    if (!_qurl) return;
                    var _mode = (_form.nej_mode||_o).value,
                        _cookie = (_form.nej_cookie||_o).value==='true';
                    this.__timer = window.setTimeout(
                        _doProgress._$bind(
                            this,_qurl,_mode,_cookie
                        ),100
                    );
                }._$bind(this)
            });
        };
    })();
    /**
     * 中断请求
     *
     * @method module:util/ajax/proxy/upload._$$ProxyUpload#_$abort
     * @return {Void}
     */
    _pro._$abort = function(){
        this.__onAbort();
    };

    return _p;
});

{'repo_name': 'genify/nej', 'stars': '328', 'repo_language': 'JavaScript', 'file_name': 'Platform.md', 'mime_type': 'text/plain', 'hash': -4585768003190253616, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.30729</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{6415FBC0-44EC-4158-8A24-127D9BAC5CEA}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>ReplaceReaderclr</RootNamespace>
    <AssemblyName>ReplaceReaderclr</AssemblyName>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
    <FileAlignment>512</FileAlignment>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Xml.Linq">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data.DataSetExtensions">
      <RequiredTargetFramework>3.5</RequiredTargetFramework>
    </Reference>
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\mpg123clr\mpg123clr.vcproj">
      <Project>{99E8B20E-9C29-46BC-B766-A50F237D88BF}</Project>
      <Name>mpg123clr</Name>
    </ProjectReference>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
  <PropertyGroup>
    <PostBuildEvent>if exist "$(SolutionDir)$(ConfigurationName)\libmpg123.dll" copy /y "$(SolutionDir)$(ConfigurationName)\libmpg123.dll" "$(TargetDir)"</PostBuildEvent>
  </PropertyGroup>
</Project>

{'repo_name': 'pedromtavares/radio', 'stars': '204', 'repo_language': 'JavaScript', 'file_name': 'streamer.js', 'mime_type': 'text/plain', 'hash': 80227247625431157, 'source_dataset': 'data'}


/*
 * Copyright 2017 Lookout, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.netflix.spinnaker.clouddriver.ecs.cache.client;

import static com.netflix.spinnaker.clouddriver.ecs.cache.Keys.Namespace.TASKS;

import com.amazonaws.services.ecs.model.Container;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.cats.cache.Cache;
import com.netflix.spinnaker.cats.cache.CacheData;
import com.netflix.spinnaker.clouddriver.ecs.cache.model.Task;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TaskCacheClient extends AbstractCacheClient<Task> {
  private ObjectMapper objectMapper;

  @Autowired
  public TaskCacheClient(Cache cacheView, ObjectMapper objectMapper) {
    super(cacheView, TASKS.toString());
    this.objectMapper = objectMapper;
  }

  @Override
  protected Task convert(CacheData cacheData) {
    Task task = new Task();
    Map<String, Object> attributes = cacheData.getAttributes();
    task.setTaskId((String) attributes.get("taskId"));
    task.setTaskArn((String) attributes.get("taskArn"));
    task.setClusterArn((String) attributes.get("clusterArn"));
    task.setContainerInstanceArn((String) attributes.get("containerInstanceArn"));
    task.setGroup((String) attributes.get("group"));
    task.setLastStatus((String) attributes.get("lastStatus"));
    task.setDesiredStatus((String) attributes.get("desiredStatus"));
    task.setHealthStatus((String) attributes.get("healthStatus"));
    if (attributes.containsKey("startedAt")) {
      task.setStartedAt((Long) attributes.get("startedAt"));
    }

    if (attributes.containsKey("containers")) {
      List<Map<String, Object>> containers =
          (List<Map<String, Object>>) attributes.get("containers");
      List<Container> deserializedLoadbalancers = new ArrayList<>(containers.size());

      for (Map<String, Object> serializedContainer : containers) {
        if (serializedContainer != null) {
          deserializedLoadbalancers.add(
              objectMapper.convertValue(serializedContainer, Container.class));
        }
      }

      task.setContainers(deserializedLoadbalancers);
    } else {
      task.setContainers(Collections.emptyList());
    }

    return task;
  }
}

{'repo_name': 'spinnaker/clouddriver', 'stars': '256', 'repo_language': 'Groovy', 'file_name': 'DisableOracleServerGroupAtomicOperationSpec.groovy', 'mime_type': 'text/plain', 'hash': -8847945815800607478, 'source_dataset': 'data'}


Browse {$catname}

		{include file='search-filter.tpl'}

{$site->adbrowse}
{if $results|@count > 0}
	<form id="nzb_multi_operations_form" action="get">

							With Selected:

								<input type="button" class="nzb_multi_operations_download btn btn-small btn-success"
									   value="Download NZBs"/>
								<input type="button" class="nzb_multi_operations_cart btn btn-small btn-info"
									   value="Send to my Download Basket"/>
								{if $sabintegrated}
									<input type="button" class="nzb_multi_operations_sab btn btn-small btn-primary"
										   value="Send to queue"/>
								{/if}

							View: Covers | List

								{$pager}

								{if isset($isadmin)}
									Admin:

										<input type="button" class="nzb_multi_operations_edit btn btn-small btn-warning"
											   value="Edit"/>
										<input type="button"
											   class="nzb_multi_operations_delete btn btn-small btn-danger"
											   value="Delete"/>

								{/if}

					<input type="checkbox" class="nzb_check_all"/>

				title

			{foreach $results as $result}
				{assign var="msplits" value=","|explode:$result.grp_release_id}
				{assign var="mguid" value=","|explode:$result.grp_release_guid}
				{assign var="mnfo" value=","|explode:$result.grp_release_nfoid}
				{assign var="mgrp" value=","|explode:$result.grp_release_grpname}
				{assign var="mname" value="#"|explode:$result.grp_release_name}
				{assign var="mpostdate" value=","|explode:$result.grp_release_postdate}
				{assign var="msize" value=","|explode:$result.grp_release_size}
				{assign var="mtotalparts" value=","|explode:$result.grp_release_totalparts}
				{assign var="mcomments" value=","|explode:$result.grp_release_comments}
				{assign var="mgrabs" value=","|explode:$result.grp_release_grabs}
				{assign var="mpass" value=","|explode:$result.grp_release_password}
				{assign var="minnerfiles" value=","|explode:$result.grp_rarinnerfilecount}
				{assign var="mhaspreview" value=","|explode:$result.grp_haspreview}
				{assign var="previewfound" value="0"}
				{assign var="previewguid" value=""}

								<a target="_blank"
										{foreach $msplits as $m}
											{if $previewfound == 0}
												{if $mhaspreview[$m@index] == 1 && $userdata.canpreview == 1}
													{$previewfound = 1}
													{$previewguid = $mguid[$m@index]}
												{/if}
											{/if}
										{/foreach}
								   href="{$smarty.const.WWW_TOP}/xxx/?id={$result.id}"
								   name="name{$result.id}"
								   guid="name{$previewguid}"
								   title="View XXX info"
								   class="modal_xxx thumbnail" rel="viewxxx">
									{if $result.cover == 1}

									{else}
									{/if}

									{if $result.classused == "ade"}
										dereferrer_link}{$result.directurl}"
												name="viewade{$result.title}"
												title="View AdultdvdEmpire page"
										>
									{else}
										dereferrer_link}http://www.adultdvdempire.com/dvd/search?q={$result.title}"
												name="viewade{$result.title}"
												title="Search AdultdvdEmpire page"
										>
									{/if}
									{if $result.classused == "hm"}
										dereferrer_link}{$result.directurl}"
												name="viewhm{$result.title}"
												title="View Hot Movies page"
										>
									{else}
										dereferrer_link}http://www.hotmovies.com/search.php?words={$result.title}&complete=on&search_in=video_title"
												name="viewhm{$result.title}"
												title="Search Hot Movies page"
										>
									{/if}
									{if $result.classused == "pop"}
										dereferrer_link}{$result.directurl}"
												name="viewpop{$result.id}"
												title="View Popporn page"
										>
									{else}
										dereferrer_link}http://www.popporn.com/results/index.cfm?v=4&g=0&searchtext={$result.title}"
												name="viewpop{$result.id}"
												title="Search Popporn page"
										>
									{/if}
									dereferrer_link}http://www.iafd.com/results.asp?searchtype=title&searchstring={$result.title}"
											name="viewiafd{$result.title}"
											title="Search Internet Adult Film Database"
									>

							{$result.title|stripslashes|escape:"htmlall"}

						{if $result.tagline != ''}
							{$result.tagline}

						{/if}
						{if $result.plot != ''}
							{$result.plot}

						{/if}
						{if $result.genre != ''}
							Genre:
							{$result.genre}

						{/if}
						{if $result.director != ''}
							Director:
							{$result.director}

						{/if}
						{if $result.actors != ''}
							Starring:
							{$result.actors}

						{/if}

								{foreach $msplits as $m}

 0}class="mlextra"{/if}>

<input type="checkbox" class="nzb_check"
																	 value="{$mguid[$m@index]}"/>

												 {$mname[$m@index]|escape:"htmlall"}

Posted {$mpostdate[$m@index]|timeago}

{$msize[$m@index]|fsize_format:"MB"}

{$mtotalparts[$m@index]}

{$mcomments[$m@index]}

												{if isset($mnfo[$m@index]) && $mnfo[$m@index] > 0}

{/if}

												{if $mhaspreview[$m@index] == 1 && $userdata.canpreview == 1}

Preview
{/if}
												{if $mhaspreview[$m@index]}

Media
{/if}

												{if $sabintegrated}

												{/if}

									{if $m@index == 1 && $m@total > 2}

												{$m@total-2} more...

									{/if}
								{/foreach}

			{/foreach}

		{if $results|@count > 10}

								With Selected:

									<input type="button" class="nzb_multi_operations_download btn btn-small btn-success"
										   value="Download NZBs"/>
									<input type="button" class="nzb_multi_operations_cart btn btn-small btn-info"
										   value="Send to my Download Basket"/>
									{if isset($sabintegrated)}
										<input type="button" class="nzb_multi_operations_sab btn btn-small btn-primary"
											   value="Send to queue"/>
									{/if}

									{$pager}

									{if isset($isadmin)}
										Admin:

											<input type="button"
												   class="nzb_multi_operations_edit btn btn-small btn-warning"
												   value="Edit"/>
											<input type="button"
												   class="nzb_multi_operations_delete btn btn-small btn-danger"
												   value="Delete"/>

									{/if}

		{/if}
	</form>
{/if}

{'repo_name': 'nZEDb/nZEDb', 'stars': '522', 'repo_language': 'PHP', 'file_name': 'PopulateTitles.php', 'mime_type': 'text/x-php', 'hash': 7306817671466382070, 'source_dataset': 'data'}


# -*- coding: utf-8 -*-
# <Lettuce - Behaviour Driven Development for python>
# Copyright (C) <2010-2012>  Gabriel Falcão <gabriel@nacaolivre.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
from lettuce.registry import _function_matches, StepDict
from lettuce.exceptions import StepLoadingError

from nose.tools import assert_raises, assert_equal

def test_function_matches_compares_with_abs_path():
    u"lettuce.registry._function_matches() should compare callback filenames with abspath"

    class fakecallback1:
        class func_code:
            co_filename = "/some/path/to/some/../file.py"
            co_firstlineno = 1

    class fakecallback2:
        class func_code:
            co_filename = "/some/path/to/file.py"
            co_firstlineno = 1

    assert _function_matches(fakecallback1, fakecallback2), \
        'the callbacks should have matched'

def test_StepDict_raise_StepLoadingError_if_load_first_argument_is_not_a_regex():
    u"lettuce.STEP_REGISTRY.load(step, func) should raise an error if step is not a regex"
    steps = StepDict()
    test_load = lambda: steps.load("an invalid regex;)", lambda: "")
    assert_raises(StepLoadingError, test_load)

def test_StepDict_can_load_a_step_composed_of_a_regex_and_a_function():
    u"lettuce.STEP_REGISTRY.load(step, func) append item(step, func) to STEP_REGISTRY"
    steps = StepDict()
    func = lambda: ""
    step = "a step to test"
    steps.load(step, func)
    assert (step in steps)
    assert_equal(steps[step], func)

def test_StepDict_load_a_step_return_the_given_function():
    u"lettuce.STEP_REGISTRY.load(step, func) returns func"
    steps = StepDict()
    func = lambda: ""
    assert_equal(steps.load("another step", func), func)

def test_StepDict_can_extract_a_step_sentence_from_function_name():
    u"lettuce.STEP_REGISTRY._extract_sentence(func) parse func name and return a sentence"
    steps = StepDict()
    def a_step_sentence():
        pass
    assert_equal("A step sentence", steps._extract_sentence(a_step_sentence))

def test_StepDict_can_extract_a_step_sentence_from_function_doc():
    u"lettuce.STEP_REGISTRY._extract_sentence(func) parse func doc and return a sentence"
    steps = StepDict()
    def a_step_func():
        """A step sentence"""
        pass
    assert_equal("A step sentence", steps._extract_sentence(a_step_func))

def test_StepDict_can_load_a_step_from_a_function():
    u"lettuce.STEP_REGISTRY.load_func(func) append item(step, func) to STEP_REGISTRY"
    steps = StepDict()
    def a_step_to_test():
        pass

    steps.load_func(a_step_to_test)

    expected_sentence = "A step to test"
    assert (expected_sentence in steps)
    assert_equal(steps[expected_sentence], a_step_to_test)

def test_StepDict_can_load_steps_from_an_object():
    u"lettuce.STEP_REGISTRY.load_steps(obj) append all obj methods to STEP_REGISTRY"
    steps = StepDict()
    class LotsOfSteps:
        def step_1(self):
            pass
        def step_2(self):
            """Doing something"""
            pass

    step_list = LotsOfSteps()
    steps.load_steps(step_list)

    expected_sentence1 = "Step 1"
    expected_sentence2 = "Doing something"
    assert (expected_sentence1 in steps)
    assert (expected_sentence2 in steps)
    assert_equal(steps[expected_sentence1], step_list.step_1)
    assert_equal(steps[expected_sentence2], step_list.step_2)

def test_StepDict_can_exclude_methods_when_load_steps():
    u"lettuce.STEP_REGISTRY.load_steps(obj) don't load exluded attr in STEP_REGISTRY"
    steps = StepDict()
    class LotsOfSteps:
        exclude = ["step_1"]
        def step_1(self):
            pass
        def step_2(self):
            """Doing something"""
            pass

    step_list = LotsOfSteps()
    steps.load_steps(step_list)

    expected_sentence1 = "Step 1"
    expected_sentence2 = "Doing something"
    assert (expected_sentence1 not in steps)
    assert (expected_sentence2 in steps)

def test_StepDict_can_exclude_callable_object_when_load_steps():
    u"lettuce.STEP_REGISTRY.load_steps(obj) don't load callable objets in STEP_REGISTRY"
    steps = StepDict()
    class NoStep:
        class NotAStep(object):
            def __call__(self):
                pass

    no_step = NoStep()
    steps.load_steps(no_step)

    assert len(steps) == 0

{'repo_name': 'gabrielfalcao/lettuce', 'stars': '1216', 'repo_language': 'Python', 'file_name': 'foobar-steps.py', 'mime_type': 'text/x-python', 'hash': -2727891277776703782, 'source_dataset': 'data'}


% \iffalse meta-comment
%
%% File: l3backend-graphics.dtx
%
% Copyright (C) 2019,2020 The LaTeX3 Project
%
% It may be distributed and/or modified under the conditions of the
% LaTeX Project Public License (LPPL), either version 1.3c of this
% license or (at your option) any later version.  The latest version
% of this license is in the file
%
%    https://www.latex-project.org/lppl.txt
%
% This file is part of the "l3backend bundle" (The Work in LPPL)
% and all files in that bundle must be distributed together.
%
% -----------------------------------------------------------------------
%
% The development version of the bundle can be found at
%
%    https://github.com/latex3/latex3
%
% for those people who are interested.
%
%<*driver>
\documentclass[full,kernel]{l3doc}
\begin{document}
  \DocInput{\jobname.dtx}
\end{document}
%</driver>
% \fi
%
% \title{^^A
%   The \textsf{l3backend-graphics} package\\ Backend graphics support^^A
% }
%
% \author{^^A
%  The \LaTeX3 Project\thanks
%    {^^A
%      E-mail:
%        \href{mailto:latex-team@latex-project.org}
%          {latex-team@latex-project.org}^^A
%    }^^A
% }
%
% \date{Released 2020-09-24}
%
% \maketitle
%
% \begin{documentation}
%
% \end{documentation}
%
% \begin{implementation}
%
% \section{\pkg{l3backend-graphics} Implementation}
%
%    \begin{macrocode}
%<*package>
%<@@=graphics>
%    \end{macrocode}
%
% \subsection{\texttt{dvips} backend}
%
%    \begin{macrocode}
%<*dvips>
%    \end{macrocode}
%
% \begin{macro}{\@@_backend_getbb_eps:n}
%   Simply use the generic function.
%    \begin{macrocode}
\cs_new_eq:NN \@@_backend_getbb_eps:n \graphics_read_bb:n
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@_backend_include_eps:n}
%  The special syntax is relatively clear here: remember we need PostScript
%  sizes here.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_eps:n #1
  {
    \__kernel_backend_literal:x
      {
        PSfile = #1 \c_space_tl
        llx = \dim_to_decimal_in_bp:n \l_graphics_llx_dim \c_space_tl
        lly = \dim_to_decimal_in_bp:n \l_graphics_lly_dim \c_space_tl
        urx = \dim_to_decimal_in_bp:n \l_graphics_urx_dim \c_space_tl
        ury = \dim_to_decimal_in_bp:n \l_graphics_ury_dim
      }
  }
%    \end{macrocode}
% \end{macro}
%
%    \begin{macrocode}
%</dvips>
%    \end{macrocode}
%
% \subsection{\LuaTeX{} and \pdfTeX{} backends}
%
%    \begin{macrocode}
%<*luatex|pdftex>
%    \end{macrocode}
%
% \begin{variable}{\l_@@_graphics_attr_tl}
%   In PDF mode, additional attributes of an graphic (such as page number) are
%   needed both to obtain the bounding box and when inserting the graphic: this
%   occurs as the graphic dictionary approach means they are read as part of
%   the bounding box operation. As such, it is easier to track additional
%   attributes using a dedicated |tl| rather than build up the same data
%   twice.
%    \begin{macrocode}
\tl_new:N \l_@@_graphics_attr_tl
%    \end{macrocode}
% \end{variable}
%
% \begin{macro}
%   {
%     \@@_backend_getbb_jpg:n,
%     \@@_backend_getbb_pdf:n,
%     \@@_backend_getbb_png:n
%   }
% \begin{macro}
%   {\@@_backend_getbb_auxi:n, \@@_backend_getbb_auxii:n}
%   Getting the bounding box here requires us to box up the graphic and
%   measure it. To deal with the difference in feature support in bitmap
%   and vector graphics but keeping the common parts, there is a little work
%   to do in terms of auxiliaries. The key here is to notice that we need
%   two forms of the attributes: a \enquote{short} set to allow us to
%   track for caching, and the full form to pass to the primitive.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_getbb_jpg:n #1
  {
    \int_zero:N \l_graphics_page_int
    \tl_clear:N \l_graphics_pagebox_tl
    \tl_set:Nx \l_@@_graphics_attr_tl
      {
        \tl_if_empty:NF \l_graphics_decodearray_tl
          { :D \l_graphics_decodearray_tl }
        \bool_if:NT \l_graphics_interpolate_bool
          { :I }
      }
    \tl_clear:N \l_@@_graphics_attr_tl
    \@@_backend_getbb_auxi:n {#1}
  }
\cs_new_eq:NN \@@_backend_getbb_png:n \@@_backend_getbb_jpg:n
\cs_new_protected:Npn \@@_backend_getbb_pdf:n #1
  {
    \tl_clear:N \l_graphics_decodearray_tl
    \bool_set_false:N \l_graphics_interpolate_bool
    \tl_set:Nx \l_@@_graphics_attr_tl
      {
        : \l_graphics_pagebox_tl
        \int_compare:nNnT \l_graphics_page_int > 1
          { :P \int_use:N \l_graphics_page_int }
      }
    \@@_backend_getbb_auxi:n {#1}
  }
\cs_new_protected:Npn \@@_backend_getbb_auxi:n #1
  {
    \graphics_bb_restore:xF { #1 \l_@@_graphics_attr_tl }
      { \@@_backend_getbb_auxii:n {#1} }
  }
%    \end{macrocode}
%   Measuring the graphic is done by boxing up: for PDF graphics we could
%   use |\tex_pdfximagebbox:D|, but if doesn't work for other types.
%   As the box always starts at $(0,0)$ there is no need to worry about
%   the lower-left position.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_getbb_auxii:n #1
  {
    \tex_immediate:D \tex_pdfximage:D
      \bool_lazy_or:nnT
        { \l_graphics_interpolate_bool }
        { ! \tl_if_empty_p:N \l_graphics_decodearray_tl }
        {
          attr ~
            {
              \tl_if_empty:NF \l_graphics_decodearray_tl
                { /Decode~[ \l_graphics_decodearray_tl ] }
              \bool_if:NT \l_graphics_interpolate_bool
                { /Interpolate~true }
            }
        }
      \int_compare:nNnT \l_graphics_page_int > 0
        { page ~ \int_use:N \l_graphics_page_int }
      \tl_if_empty:NF \l_graphics_pagebox_tl
        { \l_graphics_pagebox_tl }
      {#1}
    \hbox_set:Nn \l_@@_internal_box
      { \tex_pdfrefximage:D \tex_pdflastximage:D }
    \dim_set:Nn \l_graphics_urx_dim { \box_wd:N \l_@@_internal_box }
    \dim_set:Nn \l_graphics_ury_dim { \box_ht:N \l_@@_internal_box }
    \int_const:cn { c_@@_graphics_ #1 \l_@@_graphics_attr_tl _int }
      { \tex_the:D \tex_pdflastximage:D }
    \graphics_bb_save:x { #1 \l_@@_graphics_attr_tl }
  }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}
%   {
%     \@@_backend_include_jpg:n,
%     \@@_backend_include_pdf:n,
%     \@@_backend_include_png:n
%   }
%   Images are already loaded for the measurement part of the code, so
%   inclusion is straight-forward, with only any attributes to worry about. The
%   latter carry through from determination of the bounding box.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_jpg:n #1
  {
    \tex_pdfrefximage:D
      \int_use:c { c_@@_graphics_ #1 \l_@@_graphics_attr_tl _int }
  }
\cs_new_eq:NN \@@_backend_include_pdf:n \@@_backend_include_jpg:n
\cs_new_eq:NN \@@_backend_include_png:n \@@_backend_include_jpg:n
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@_backend_getbb_eps:n}
% \begin{macro}{\@@_backend_getbb_eps:nm}
% \begin{macro}{\@@_backend_include_eps:n}
% \begin{variable}
%   {\l_@@_backend_dir_str, \l_@@_backend_name_str, \l_@@_backend_ext_str}
%   EPS graphics may be included in \LuaTeX{}/pdfTeX{} by conversion to
%   PDF: this requires restricted shell escape. Modelled on the \pkg{epstopdf}
%   \LaTeXe{} package, but simplified, conversion takes place here if we have
%   shell access.
%    \begin{macrocode}
\sys_if_shell:T
  {
    \str_new:N \l_@@_backend_dir_str
    \str_new:N \l_@@_backend_name_str
    \str_new:N \l_@@_backend_ext_str
    \cs_new_protected:Npn \@@_backend_getbb_eps:n #1
      {
        \file_parse_full_name:nNNN {#1}
          \l_@@_backend_dir_str
          \l_@@_backend_name_str
          \l_@@_backend_ext_str
        \exp_args:Nx \@@_backend_getbb_eps:nn
          {
            \l_@@_backend_name_str - \str_tail:N \l_@@_backend_ext_str
            -converted-to.pdf
          }
          {#1}
     }
    \cs_new_protected:Npn \@@_backend_getbb_eps:nn #1#2
      {
        \file_compare_timestamp:nNnT {#2} > {#1}
          {
            \sys_shell_now:n
              { repstopdf ~ #2 ~ #1 }
          }
        \tl_set:Nn \l_graphics_name_tl {#1}
        \@@_backend_getbb_pdf:n {#1}
      }
    \cs_new_protected:Npn \@@_backend_include_eps:n #1
      {
        \file_parse_full_name:nNNN {#1}
          \l_@@_backend_dir_str \l_@@_backend_name_str \l_@@_backend_ext_str
        \exp_args:Nx \@@_backend_include_pdf:n
          {
            \l_@@_backend_name_str - \str_tail:N \l_@@_backend_ext_str
            -converted-to.pdf
          }
      }
  }
%    \end{macrocode}
% \end{variable}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
%</luatex|pdftex>
%    \end{macrocode}
%
% \subsection{\texttt{dvipdfmx} backend}
%
%    \begin{macrocode}
%<*dvipdfmx|xetex>
%    \end{macrocode}
%
% \begin{macro}
%   {
%     \@@_backend_getbb_eps:n, \@@_backend_getbb_jpg:n,
%     \@@_backend_getbb_pdf:n, \@@_backend_getbb_png:n
%   }
%   Simply use the generic functions: only for \texttt{dvipdfmx} in the
%   extraction cases.
%    \begin{macrocode}
\cs_new_eq:NN \@@_backend_getbb_eps:n \graphics_read_bb:n
%<*dvipdfmx>
\cs_new_protected:Npn \@@_backend_getbb_jpg:n #1
  {
    \int_zero:N \l_graphics_page_int
    \tl_clear:N \l_graphics_pagebox_tl
    \graphics_extract_bb:n {#1}
  }
\cs_new_eq:NN \@@_backend_getbb_png:n \@@_backend_getbb_jpg:n
\cs_new_protected:Npn \@@_backend_getbb_pdf:n #1
  {
    \tl_clear:N \l_graphics_decodearray_tl
    \bool_set_false:N \l_graphics_interpolate_bool
    \graphics_extract_bb:n {#1}
  }
%</dvipdfmx>
%    \end{macrocode}
% \end{macro}
%
% \begin{variable}{\g_@@_track_int}
%   Used to track the object number associated with each graphic.
%    \begin{macrocode}
\int_new:N \g_@@_track_int
%    \end{macrocode}
% \end{variable}
%
% \begin{macro}
%   {
%     \@@_backend_include_eps:n, \@@_backend_include_jpg:n,
%     \@@_backend_include_pdf:n, \@@_backend_include_png:n
%   }
%  \begin{macro}{\@@_backend_include_auxi:nn}
%  \begin{macro}{\@@_backend_include_auxii:nnn, \@@_backend_include_auxii:xnn}
%  \begin{macro}{\@@_backend_include_auxiii:nnn}
%   The special syntax depends on the file type. There is a difference in
%   how PDF graphics are best handled between |dvipdfmx| and \XeTeX{}: for
%   the latter it is better to use the primitive route. The relevant code for
%   that is included later in this file.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_eps:n #1
  {
    \__kernel_backend_literal:x
      {
        PSfile = #1 \c_space_tl
        llx = \dim_to_decimal_in_bp:n \l_graphics_llx_dim \c_space_tl
        lly = \dim_to_decimal_in_bp:n \l_graphics_lly_dim \c_space_tl
        urx = \dim_to_decimal_in_bp:n \l_graphics_urx_dim \c_space_tl
        ury = \dim_to_decimal_in_bp:n \l_graphics_ury_dim
      }
  }
\cs_new_protected:Npn \@@_backend_include_jpg:n #1
  { \@@_backend_include_auxi:nn {#1} { image } }
\cs_new_eq:NN \@@_backend_include_png:n \@@_backend_include_jpg:n
%<*dvipdfmx>
\cs_new_protected:Npn \@@_backend_include_pdf:n #1
  { \@@_backend_include_auxi:nn {#1} { epdf } }
%</dvipdfmx>
%    \end{macrocode}
%   Graphic inclusion is set up to use the fact that each image is stored in
%   the PDF as an XObject. This means that we can include repeated images
%   only once and refer to them. To allow that, track the nature of each
%   image: much the same as for the direct PDF mode case.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_auxi:nn #1#2
  {
    \@@_backend_include_auxii:xnn
      {
        \tl_if_empty:NF \l_graphics_pagebox_tl
          { : \l_graphics_pagebox_tl }
        \int_compare:nNnT \l_graphics_page_int > 1
          { :P \int_use:N \l_graphics_page_int }
        \tl_if_empty:NF \l_graphics_decodearray_tl
          { :D \l_graphics_decodearray_tl }
        \bool_if:NT \l_graphics_interpolate_bool
           { :I }
      }
      {#1} {#2}
  }
\cs_new_protected:Npn \@@_backend_include_auxii:nnn #1#2#3
  {
    \int_if_exist:cTF { c_@@_graphics_ #2#1 _int }
      {
        \__kernel_backend_literal:x
          { pdf:usexobj~@graphic \int_use:c { c_@@_graphics_ #2#1 _int } }
      }
      { \@@_backend_include_auxiii:nnn {#2} {#1} {#3} }
  }
\cs_generate_variant:Nn \@@_backend_include_auxii:nnn { x }
%    \end{macrocode}
%  Inclusion using the specials is relatively straight-forward, but there
%  is one wrinkle. To get the |pagebox| correct for PDF graphics in all cases,
%  it is necessary to provide both that information and the |bbox| argument:
%  odd things happen otherwise!
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_auxiii:nnn #1#2#3
  {
    \int_gincr:N \g_@@_track_int
    \int_const:cn { c_@@_graphics_ #1#2 _int } { \g_@@_track_int }
    \__kernel_backend_literal:x
      {
        pdf:#3~
        @graphic \int_use:c { c_@@_graphics_ #1#2 _int } ~
        \int_compare:nNnT \l_graphics_page_int > 1
          { page ~ \int_use:N \l_graphics_page_int \c_space_tl }
        \tl_if_empty:NF \l_graphics_pagebox_tl
          {
            pagebox ~ \l_graphics_pagebox_tl \c_space_tl
            bbox ~
              \dim_to_decimal_in_bp:n \l_graphics_llx_dim \c_space_tl
              \dim_to_decimal_in_bp:n \l_graphics_lly_dim \c_space_tl
              \dim_to_decimal_in_bp:n \l_graphics_urx_dim \c_space_tl
              \dim_to_decimal_in_bp:n \l_graphics_ury_dim \c_space_tl
          }
        (#1)
        \bool_lazy_or:nnT
          { \l_graphics_interpolate_bool }
          { ! \tl_if_empty_p:N \l_graphics_decodearray_tl }
          {
            <<
              \tl_if_empty:NF \l_graphics_decodearray_tl
                { /Decode~[ \l_graphics_decodearray_tl ] }
              \bool_if:NT \l_graphics_interpolate_bool
                { /Interpolate~true> }
            >>
          }
      }
  }
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
%</dvipdfmx|xetex>
%    \end{macrocode}
%
% \subsection{\XeTeX{} backend}
%
%    \begin{macrocode}
%<*xetex>
%    \end{macrocode}
%
% \subsubsection{Images}
%
% \begin{macro}
%   {
%     \@@_backend_getbb_jpg:n,
%     \@@_backend_getbb_pdf:n,
%     \@@_backend_getbb_png:n
%   }
% \begin{macro}{\@@_backend_getbb_auxi:nN}
% \begin{macro}{\@@_backend_getbb_auxii:nnN, \@@_backend_getbb_auxii:VnN}
% \begin{macro}{\@@_backend_getbb_auxiii:nNnn}
% \begin{macro}{\@@_backend_getbb_auxiv:nnNnn, \@@_backend_getbb_auxiv:VnNnn}
% \begin{macro}{\@@_backend_getbb_auxv:nNnn, \@@_backend_getbb_auxv:nNnn}
% \begin{macro}[EXP]{\@@_backend_getbb_pagebox:w}
%   For \XeTeX{}, there are two primitives that allow us to obtain
%   the bounding box without needing \texttt{extractbb}. The only complexity
%   is passing the various minor variations to a common core process. The
%   \XeTeX{} primitive omits the text |box| from the page box specification,
%   so there is also some \enquote{trimming} to do here.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_getbb_jpg:n #1
  {
    \int_zero:N \l_graphics_page_int
    \tl_clear:N \l_graphics_pagebox_tl
    \@@_backend_getbb_auxi:nN {#1} \tex_XeTeXpicfile:D
  }
\cs_new_eq:NN \@@_backend_getbb_png:n \@@_backend_getbb_jpg:n
\cs_new_protected:Npn \@@_backend_getbb_pdf:n #1
  {
    \tl_clear:N \l_graphics_decodearray_tl
    \bool_set_false:N \l_graphics_interpolate_bool
    \@@_backend_getbb_auxi:nN {#1} \tex_XeTeXpdffile:D
  }
\cs_new_protected:Npn \@@_backend_getbb_auxi:nN #1#2
  {
    \int_compare:nNnTF \l_graphics_page_int > 1
      { \@@_backend_getbb_auxii:VnN \l_graphics_page_int {#1} #2  }
      { \@@_backend_getbb_auxiii:nNnn {#1} #2 { :P 1 } { page 1 } }
  }
\cs_new_protected:Npn \@@_backend_getbb_auxii:nnN #1#2#3
  { \@@_backend_getbb_auxiii:nNnn {#2} #3 { :P #1 } { page #1 } }
\cs_generate_variant:Nn \@@_backend_getbb_auxii:nnN { V }
\cs_new_protected:Npn \@@_backend_getbb_auxiii:nNnn #1#2#3#4
  {
    \tl_if_empty:NTF \l_graphics_pagebox_tl
      { \@@_backend_getbb_auxiv:VnNnn \l_graphics_pagebox_tl }
      { \@@_backend_getbb_auxv:nNnn }
      {#1} #2 {#3} {#4}
  }
\cs_new_protected:Npn \@@_backend_getbb_auxiv:nnNnn #1#2#3#4#5
  {
    \use:x
      {
        \@@_backend_getbb_auxv:nNnn {#2} #3 { : #1 #4 }
          { #5 ~ \@@_backend_getbb_pagebox:w #1 }
      }
  }
\cs_generate_variant:Nn \@@_backend_getbb_auxiv:nnNnn { V }
\cs_new_protected:Npn \@@_backend_getbb_auxv:nNnn #1#2#3#4
  {
    \graphics_bb_restore:nF {#1#3}
      { \@@_backend_getbb_auxvi:nNnn {#1} #2 {#3} {#4} }
  }
\cs_new_protected:Npn \@@_backend_getbb_auxvi:nNnn #1#2#3#4
  {
    \hbox_set:Nn \l_@@_internal_box { #2 #1 ~ #4 }
    \dim_set:Nn \l_graphics_urx_dim { \box_wd:N \l_@@_internal_box }
    \dim_set:Nn \l_graphics_ury_dim { \box_ht:N \l_@@_internal_box }
    \graphics_bb_save:n {#1#3}
  }
\cs_new:Npn \@@_backend_getbb_pagebox:w #1 box {#1}
%    \end{macrocode}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@_backend_include_pdf:n}
% \begin{macro}{\@@_backend_include_bitmap_quote:w}
%   For PDF graphics, properly supporting the |pagebox| concept in \XeTeX{}
%   is best done using the |\tex_XeTeXpdffile:D| primitive. The syntax here
%   is the same as for the graphic measurement part, although we know at this
%   stage that there must be some valid setting for \cs{l_graphics_pagebox_tl}.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_pdf:n #1
  {
    \tex_XeTeXpdffile:D
      \@@_backend_include_pdf_quote:w #1 "#1" \s_@@_stop \c_space_tl
      \int_compare:nNnT \l_graphics_page_int > 0
        { page ~ \int_use:N \l_graphics_page_int \c_space_tl }
        \exp_after:wN \@@_backend_getbb_pagebox:w \l_graphics_pagebox_tl
  }
\cs_new:Npn \@@_backend_include_pdf_quote:w #1 " #2 " #3 \s_@@_stop
  { " #2 " }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
%</xetex>
%    \end{macrocode}
%
% \subsection{\texttt{dvisvgm} backend}
%
%    \begin{macrocode}
%<*dvisvgm>
%    \end{macrocode}
%
% \begin{macro}{\@@_backend_getbb_eps:n}
%   Simply use the generic function.
%    \begin{macrocode}
\cs_new_eq:NN \@@_backend_getbb_eps:n \graphics_read_bb:n
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@_backend_getbb_png:n, \@@_backend_getbb_jpg:n}
%   These can be included by extracting the bounding box data.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_getbb_jpg:n #1
  {
    \int_zero:N \l_graphics_page_int
    \tl_clear:N \l_graphics_pagebox_tl
    \graphics_extract_bb:n {#1}
  }
\cs_new_eq:NN \@@_backend_getbb_png:n \@@_backend_getbb_jpg:n
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@_backend_getbb_pdf:n}
%   Same as for \texttt{dvipdfmx}: use the generic function
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_getbb_pdf:n #1
  {
    \tl_clear:N \l_graphics_decodearray_tl
    \bool_set_false:N \l_graphics_interpolate_bool
    \graphics_extract_bb:n {#1}
  }
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@@_backend_include_eps:n, \@@_backend_include_pdf:n}
% \begin{macro}{\@@_backend_include:nn}
%   The special syntax is relatively clear here: remember we need PostScript
%   sizes here. (This is the same as the \texttt{dvips} code.)
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_eps:n #1
  { @@_backend_include:nn { PSfile } {#1} }
\cs_new_protected:Npn \@@_backend_include_pdf:n #1
  { @@_backend_include:nn { pdffile } {#1} }
\cs_new_protected:Npn \@@_backend_include:nn #1#2
  {
    \__kernel_backend_literal:x
      {
        #1 = #2 \c_space_tl
        llx = \dim_to_decimal_in_bp:n \l_graphics_llx_dim \c_space_tl
        lly = \dim_to_decimal_in_bp:n \l_graphics_lly_dim \c_space_tl
        urx = \dim_to_decimal_in_bp:n \l_graphics_urx_dim \c_space_tl
        ury = \dim_to_decimal_in_bp:n \l_graphics_ury_dim
      }
  }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
% \begin{macro}{\@@_backend_include_png:n, \@@_backend_include_jpg:n}
% \begin{macro}{\@@_backend_include_bitmap_quote:w}
%   The backend here has built-in support for basic graphic inclusion (see
%   \texttt{dvisvgm.def} for a more complex approach, needed if clipping,
%   \emph{etc.}, is covered at the graphic backend level). The only issue is
%   that |#1| must be quote-corrected. The \texttt{dvisvgm:img} operation
%   quotes the file name, but if it is already quoted (contains spaces)
%   then we have an issue: we simply strip off any quotes as a result.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_backend_include_png:n #1
  {
     \__kernel_backend_literal:x
       {
         dvisvgm:img~
         \dim_to_decimal:n { \l_graphics_ury_dim } ~
         \dim_to_decimal:n { \l_graphics_ury_dim } ~
         \@@_backend_include_bitmap_quote:w #1 " #1 " \s_@@_stop
       }
  }
\cs_new_eq:NN \@@_backend_include_jpg:n \@@_backend_include_png:n
\cs_new:Npn \@@_backend_include_bitmap_quote:w #1 " #2 " #3 \s_@@_stop
  { " #2 " }
%    \end{macrocode}
% \end{macro}
% \end{macro}
%
%    \begin{macrocode}
%</dvisvgm>
%    \end{macrocode}
%
%    \begin{macrocode}
%</package>
%    \end{macrocode}
%
% \end{implementation}
%
% \PrintIndex

{'repo_name': 'latex3/latex3', 'stars': '905', 'repo_language': 'TeX', 'file_name': 'xor001.luatex.tlg', 'mime_type': 'text/plain', 'hash': 3994992907024332584, 'source_dataset': 'data'}


//
// Prefix header for all source files of the 'GBCli' target in the 'GBCli' project
//

#ifdef __OBJC__
	#import <Foundation/Foundation.h>
#endif

{'repo_name': 'tomaz/GBCli', 'stars': '177', 'repo_language': 'Objective-C', 'file_name': 'SwiftyOptions.swift', 'mime_type': 'text/plain', 'hash': 7530681221700727922, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: 3439cfcaac78eef478385036ab21cf3d
timeCreated: 1509278715
licenseType: Free
MonoImporter:
  externalObjects: {}
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'NFMynster/ArenaGame', 'stars': '163', 'repo_language': 'C#', 'file_name': 'AudioManager.asset', 'mime_type': 'text/plain', 'hash': -5645595832674780028, 'source_dataset': 'data'}


// Copyright (c) 2019 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include "libcef/browser/net_service/response_filter_wrapper.h"

#include <queue>

#include "base/logging.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "mojo/public/cpp/system/string_data_source.h"

namespace net_service {

namespace {

// Match the default |capacity_num_bytes| value from mojo::Core::CreateDataPipe.
static const size_t kBufferSize = 64 * 1024;  // 64 Kbytes.
static const size_t kMinBufferSpace = 1024;   // 1 Kbytes.

class ResponseFilterWrapper {
 public:
  ResponseFilterWrapper(CefRefPtr<CefResponseFilter> filter,
                        mojo::ScopedDataPipeConsumerHandle source_handle,
                        base::OnceClosure error_callback);

  // Creates and returns the output handle, or |source_handle| on failure.
  bool CreateOutputHandle(mojo::ScopedDataPipeConsumerHandle* output_handle);

 private:
  void OnSourceReadable(MojoResult, const mojo::HandleSignalsState&);
  void Filter(const char* data, size_t size);
  void Write(std::unique_ptr<std::string> data);
  void OnWriteComplete(std::unique_ptr<std::string>, MojoResult result);
  void Drain(bool complete);
  void MaybeSuccess();
  void Cleanup(bool success);

  CefRefPtr<CefResponseFilter> filter_;
  mojo::ScopedDataPipeConsumerHandle source_handle_;
  base::OnceClosure error_callback_;

  std::unique_ptr<mojo::DataPipeProducer> forwarder_;
  mojo::SimpleWatcher source_watcher_;

  bool read_pending_ = false;
  bool write_pending_ = false;
  std::queue<std::unique_ptr<std::string>> pending_data_;
  cef_response_filter_status_t last_status_ = RESPONSE_FILTER_NEED_MORE_DATA;

  DISALLOW_COPY_AND_ASSIGN(ResponseFilterWrapper);
};

ResponseFilterWrapper::ResponseFilterWrapper(
    CefRefPtr<CefResponseFilter> filter,
    mojo::ScopedDataPipeConsumerHandle source_handle,
    base::OnceClosure error_callback)
    : filter_(filter),
      source_handle_(std::move(source_handle)),
      error_callback_(std::move(error_callback)),
      source_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL) {}

bool ResponseFilterWrapper::CreateOutputHandle(
    mojo::ScopedDataPipeConsumerHandle* output_handle) {
  if (!filter_->InitFilter()) {
    *output_handle = std::move(source_handle_);
    return false;
  }

  mojo::ScopedDataPipeProducerHandle forwarding_handle;
  if (CreateDataPipe(nullptr, &forwarding_handle, output_handle) !=
      MOJO_RESULT_OK) {
    *output_handle = std::move(source_handle_);
    return false;
  }

  forwarder_ =
      std::make_unique<mojo::DataPipeProducer>(std::move(forwarding_handle));

  source_watcher_.Watch(
      source_handle_.get(),
      MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
      MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
      base::BindRepeating(&ResponseFilterWrapper::OnSourceReadable,
                          base::Unretained(this)));
  source_watcher_.ArmOrNotify();
  read_pending_ = true;

  return true;
}

void ResponseFilterWrapper::OnSourceReadable(MojoResult,
                                             const mojo::HandleSignalsState&) {
  const void* buffer = nullptr;
  uint32_t read_bytes = 0;
  MojoResult result = source_handle_->BeginReadData(&buffer, &read_bytes,
                                                    MOJO_READ_DATA_FLAG_NONE);
  if (result == MOJO_RESULT_SHOULD_WAIT) {
    source_watcher_.ArmOrNotify();
    return;
  }

  if (result != MOJO_RESULT_OK) {
    // Whole body has been read, or something went wrong.
    Drain(result == MOJO_RESULT_FAILED_PRECONDITION);
    return;
  }

  Filter(static_cast<const char*>(buffer), read_bytes);
  if (last_status_ == RESPONSE_FILTER_ERROR) {
    // Something went wrong.
    Drain(false);
    return;
  }

  source_handle_->EndReadData(read_bytes);
  source_watcher_.ArmOrNotify();
}

void ResponseFilterWrapper::Filter(const char* data, size_t size) {
  size_t data_in_size = size;
  auto data_in_ptr = data_in_size > 0 ? data : nullptr;

  size_t data_out_offset = 0;
  std::unique_ptr<std::string> data_out;

  while (true) {
    size_t data_in_read = 0;

    if (!data_out) {
      // Start a new buffer. Should have no offset to begin with.
      DCHECK_EQ(0U, data_out_offset);
      data_out = std::make_unique<std::string>();
      data_out->resize(kBufferSize);
    }

    auto data_out_ptr = data_out->data() + data_out_offset;
    size_t data_out_size = kBufferSize - data_out_offset;
    size_t data_out_written = 0;

    last_status_ = filter_->Filter(
        const_cast<char*>(data_in_ptr), data_in_size, data_in_read,
        const_cast<char*>(data_out_ptr), data_out_size, data_out_written);
    if (last_status_ == RESPONSE_FILTER_ERROR)
      break;

    // Validate the out values.
    if (data_in_read > data_in_size) {
      LOG(ERROR) << "potential buffer overflow; data_in_read > data_in_size";
      last_status_ = RESPONSE_FILTER_ERROR;
      break;
    }
    if (data_out_written > data_out_size) {
      LOG(ERROR)
          << "potential buffer overflow; data_out_written > data_out_size";
      last_status_ = RESPONSE_FILTER_ERROR;
      break;
    }
    if (data_out_written == 0 && data_in_read != data_in_size) {
      LOG(ERROR) << "when no data is written all input must be consumed; "
                    "data_out_written == 0 && data_in_read != data_in_size";
      last_status_ = RESPONSE_FILTER_ERROR;
      break;
    }

    if (data_out_written > 0) {
      data_out_offset += data_out_written;
      if (data_out_offset > kBufferSize - kMinBufferSpace) {
        // The buffer is full or almost full. Write the data that we've
        // received so far and start a new buffer.
        data_out->resize(data_out_offset);
        Write(std::move(data_out));
        data_out_offset = 0;
      }
    }

    if (data_in_read < data_in_size) {
      // Keep going until the user reads all data.
      data_in_ptr += data_in_read;
      data_in_size -= data_in_read;
      continue;
    }

    // At this point the user has read all data...
    if (data_in_ptr) {
      // Clear the input buffer.
      data_in_read = data_in_size = 0;
      data_in_ptr = nullptr;
    }

    if (data_out_written == data_out_size &&
        last_status_ == RESPONSE_FILTER_NEED_MORE_DATA) {
      // Output buffer was filled, but data is still pending.
      continue;
    }

    if (data_out_offset > 0) {
      // Write the last of the data that we've received.
      data_out->resize(data_out_offset);
      Write(std::move(data_out));
    }

    break;
  }
}

void ResponseFilterWrapper::Write(std::unique_ptr<std::string> data) {
  if (write_pending_) {
    // Only one write at a time is supported.
    pending_data_.push(std::move(data));
    return;
  }

  write_pending_ = true;

  base::StringPiece string_piece(*data);
  forwarder_->Write(std::make_unique<mojo::StringDataSource>(
                        string_piece, mojo::StringDataSource::AsyncWritingMode::
                                          STRING_STAYS_VALID_UNTIL_COMPLETION),
                    base::BindOnce(&ResponseFilterWrapper::OnWriteComplete,
                                   base::Unretained(this), std::move(data)));
}

void ResponseFilterWrapper::OnWriteComplete(std::unique_ptr<std::string>,
                                            MojoResult result) {
  write_pending_ = false;

  if (result != MOJO_RESULT_OK) {
    // Something went wrong.
    Cleanup(false);
    return;
  }

  MaybeSuccess();
}

void ResponseFilterWrapper::Drain(bool complete) {
  read_pending_ = false;
  source_handle_.reset();
  source_watcher_.Cancel();

  if (!complete) {
    // Something went wrong.
    Cleanup(false);
    return;
  }

  if (last_status_ == RESPONSE_FILTER_NEED_MORE_DATA) {
    // Let the user write any remaining data.
    Filter(nullptr, 0);
    if (last_status_ != RESPONSE_FILTER_DONE) {
      // Something went wrong.
      Cleanup(false);
      return;
    }
  }

  MaybeSuccess();
}

void ResponseFilterWrapper::MaybeSuccess() {
  if (!write_pending_ && !pending_data_.empty()) {
    // Write the next data segment.
    auto next = std::move(pending_data_.front());
    pending_data_.pop();
    Write(std::move(next));
    return;
  }

  if (!read_pending_ && !write_pending_)
    Cleanup(true);
}

void ResponseFilterWrapper::Cleanup(bool success) {
  if (!success && error_callback_)
    std::move(error_callback_).Run();
  delete this;
}

}  // namespace

mojo::ScopedDataPipeConsumerHandle CreateResponseFilterHandler(
    CefRefPtr<CefResponseFilter> filter,
    mojo::ScopedDataPipeConsumerHandle source_handle,
    base::OnceClosure error_callback) {
  // |filter_wrapper| will delete itself when filtering is complete if
  // CreateOutputHandle returns true. Otherwise, it will return the
  // original |source_handle|.
  auto filter_wrapper = new ResponseFilterWrapper(
      filter, std::move(source_handle), std::move(error_callback));
  mojo::ScopedDataPipeConsumerHandle output_handle;
  if (!filter_wrapper->CreateOutputHandle(&output_handle))
    delete filter_wrapper;
  return output_handle;
}

}  // namespace net_service

{'repo_name': 'chromiumembedded/cef', 'stars': '693', 'repo_language': 'C++', 'file_name': 'cef_macros.cmake.in', 'mime_type': 'text/plain', 'hash': -7468079631109461991, 'source_dataset': 'data'}


/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2011 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Library to create tooltips for Blockly.
 * First, call Blockly.Tooltip.init() after onload.
 * Second, set the 'tooltip' property on any SVG element that needs a tooltip.
 * If the tooltip is a string, then that message will be displayed.
 * If the tooltip is an SVG element, then that object's tooltip will be used.
 * Third, call Blockly.Tooltip.bindMouseEvents(e) passing the SVG element.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Tooltip');

goog.require('goog.dom');

/**
 * Is a tooltip currently showing?
 */
Blockly.Tooltip.visible = false;

/**
 * Maximum width (in characters) of a tooltip.
 */
Blockly.Tooltip.LIMIT = 50;

/**
 * PID of suspended thread to clear tooltip on mouse out.
 * @private
 */
Blockly.Tooltip.mouseOutPid_ = 0;

/**
 * PID of suspended thread to show the tooltip.
 * @private
 */
Blockly.Tooltip.showPid_ = 0;

/**
 * Last observed X location of the mouse pointer (freezes when tooltip appears).
 * @private
 */
Blockly.Tooltip.lastX_ = 0;

/**
 * Last observed Y location of the mouse pointer (freezes when tooltip appears).
 * @private
 */
Blockly.Tooltip.lastY_ = 0;

/**
 * Current element being pointed at.
 * @private
 */
Blockly.Tooltip.element_ = null;

/**
 * Once a tooltip has opened for an element, that element is 'poisoned' and
 * cannot respawn a tooltip until the pointer moves over a different element.
 * @private
 */
Blockly.Tooltip.poisonedElement_ = null;

/**
 * Horizontal offset between mouse cursor and tooltip.
 */
Blockly.Tooltip.OFFSET_X = 0;

/**
 * Vertical offset between mouse cursor and tooltip.
 */
Blockly.Tooltip.OFFSET_Y = 10;

/**
 * Radius mouse can move before killing tooltip.
 */
Blockly.Tooltip.RADIUS_OK = 10;

/**
 * Delay before tooltip appears.
 */
Blockly.Tooltip.HOVER_MS = 1000;

/**
 * Horizontal padding between tooltip and screen edge.
 */
Blockly.Tooltip.MARGINS = 5;

/**
 * The HTML container.  Set once by Blockly.Tooltip.createDom.
 * @type {Element}
 */
Blockly.Tooltip.DIV = null;

/**
 * Create the tooltip div and inject it onto the page.
 */
Blockly.Tooltip.createDom = function() {
  if (Blockly.Tooltip.DIV) {
    return;  // Already created.
  }
  // Create an HTML container for popup overlays (e.g. editor widgets).
  Blockly.Tooltip.DIV = goog.dom.createDom('div', 'blocklyTooltipDiv');
  document.body.appendChild(Blockly.Tooltip.DIV);
};

/**
 * Binds the required mouse events onto an SVG element.
 * @param {!Element} element SVG element onto which tooltip is to be bound.
 */
Blockly.Tooltip.bindMouseEvents = function(element) {
  Blockly.bindEvent_(element, 'mouseover', null, Blockly.Tooltip.onMouseOver_);
  Blockly.bindEvent_(element, 'mouseout', null, Blockly.Tooltip.onMouseOut_);
  Blockly.bindEvent_(element, 'mousemove', null, Blockly.Tooltip.onMouseMove_);
};

/**
 * Hide the tooltip if the mouse is over a different object.
 * Initialize the tooltip to potentially appear for this object.
 * @param {!Event} e Mouse event.
 * @private
 */
Blockly.Tooltip.onMouseOver_ = function(e) {
  // If the tooltip is an object, treat it as a pointer to the next object in
  // the chain to look at.  Terminate when a string or function is found.
  var element = e.target;
  while (!goog.isString(element.tooltip) && !goog.isFunction(element.tooltip)) {
    element = element.tooltip;
  }
  if (Blockly.Tooltip.element_ != element) {
    Blockly.Tooltip.hide();
    Blockly.Tooltip.poisonedElement_ = null;
    Blockly.Tooltip.element_ = element;
  }
  // Forget about any immediately preceeding mouseOut event.
  clearTimeout(Blockly.Tooltip.mouseOutPid_);
};

/**
 * Hide the tooltip if the mouse leaves the object and enters the workspace.
 * @param {!Event} e Mouse event.
 * @private
 */
Blockly.Tooltip.onMouseOut_ = function(e) {
  // Moving from one element to another (overlapping or with no gap) generates
  // a mouseOut followed instantly by a mouseOver.  Fork off the mouseOut
  // event and kill it if a mouseOver is received immediately.
  // This way the task only fully executes if mousing into the void.
  Blockly.Tooltip.mouseOutPid_ = setTimeout(function() {
    Blockly.Tooltip.element_ = null;
    Blockly.Tooltip.poisonedElement_ = null;
    Blockly.Tooltip.hide();
  }, 1);
  clearTimeout(Blockly.Tooltip.showPid_);
};

/**
 * When hovering over an element, schedule a tooltip to be shown.  If a tooltip
 * is already visible, hide it if the mouse strays out of a certain radius.
 * @param {!Event} e Mouse event.
 * @private
 */
Blockly.Tooltip.onMouseMove_ = function(e) {
  if (!Blockly.Tooltip.element_ || !Blockly.Tooltip.element_.tooltip) {
    // No tooltip here to show.
    return;
  } else if (Blockly.dragMode_ != Blockly.DRAG_NONE) {
    // Don't display a tooltip during a drag.
    return;
  } else if (Blockly.WidgetDiv.isVisible()) {
    // Don't display a tooltip if a widget is open (tooltip would be under it).
    return;
  }
  if (Blockly.Tooltip.visible) {
    // Compute the distance between the mouse position when the tooltip was
    // shown and the current mouse position.  Pythagorean theorem.
    var dx = Blockly.Tooltip.lastX_ - e.pageX;
    var dy = Blockly.Tooltip.lastY_ - e.pageY;
    if (Math.sqrt(dx * dx + dy * dy) > Blockly.Tooltip.RADIUS_OK) {
      Blockly.Tooltip.hide();
    }
  } else if (Blockly.Tooltip.poisonedElement_ != Blockly.Tooltip.element_) {
    // The mouse moved, clear any previously scheduled tooltip.
    clearTimeout(Blockly.Tooltip.showPid_);
    // Maybe this time the mouse will stay put.  Schedule showing of tooltip.
    Blockly.Tooltip.lastX_ = e.pageX;
    Blockly.Tooltip.lastY_ = e.pageY;
    Blockly.Tooltip.showPid_ =
        setTimeout(Blockly.Tooltip.show_, Blockly.Tooltip.HOVER_MS);
  }
};

/**
 * Hide the tooltip.
 */
Blockly.Tooltip.hide = function() {
  if (Blockly.Tooltip.visible) {
    Blockly.Tooltip.visible = false;
    if (Blockly.Tooltip.DIV) {
      Blockly.Tooltip.DIV.style.display = 'none';
    }
  }
  clearTimeout(Blockly.Tooltip.showPid_);
};

/**
 * Create the tooltip and show it.
 * @private
 */
Blockly.Tooltip.show_ = function() {
  Blockly.Tooltip.poisonedElement_ = Blockly.Tooltip.element_;
  if (!Blockly.Tooltip.DIV) {
    return;
  }
  // Erase all existing text.
  goog.dom.removeChildren(/** @type {!Element} */ (Blockly.Tooltip.DIV));
  // Get the new text.
  var tip = Blockly.Tooltip.element_.tooltip;
  while (goog.isFunction(tip)) {
    tip = tip();
  }

  var tooltip_is_image = 0;
  if (tip.match(/^<img /)) {
    var div = document.createElement('div');
    var tmp = document.createElement('div');
    tmp.innerHTML = tip;
    var elem = tmp.getElementsByTagName('img')[0];
    // if elem contains a src attribute I'll use it
    if (elem['src']) {
      div.appendChild(elem);
      tooltip_is_image = 1;
      Blockly.Tooltip.DIV.appendChild(div);
    }
  }
  if (!tooltip_is_image) {
    tip = Blockly.utils.wrap(tip, Blockly.Tooltip.LIMIT);
    // Create new text, line by line.
    var lines = tip.split('\n');
    for (var i = 0; i < lines.length; i++) {
      var div = document.createElement('div');
      div.appendChild(document.createTextNode(lines[i]));
      Blockly.Tooltip.DIV.appendChild(div);
    }
  }
  var rtl = Blockly.Tooltip.element_.RTL;
  var windowSize = goog.dom.getViewportSize();
  // Display the tooltip.
  Blockly.Tooltip.DIV.style.direction = rtl ? 'rtl' : 'ltr';
  Blockly.Tooltip.DIV.style.display = 'block';
  Blockly.Tooltip.visible = true;
  // Move the tooltip to just below the cursor.
  var anchorX = Blockly.Tooltip.lastX_;
  if (rtl) {
    anchorX -= Blockly.Tooltip.OFFSET_X + Blockly.Tooltip.DIV.offsetWidth;
  } else {
    anchorX += Blockly.Tooltip.OFFSET_X;
  }
  var anchorY = Blockly.Tooltip.lastY_ + Blockly.Tooltip.OFFSET_Y;

  if (anchorY + Blockly.Tooltip.DIV.offsetHeight >
      windowSize.height + window.scrollY) {
    // Falling off the bottom of the screen; shift the tooltip up.
    anchorY -= Blockly.Tooltip.DIV.offsetHeight + 2 * Blockly.Tooltip.OFFSET_Y;
  }
  if (rtl) {
    // Prevent falling off left edge in RTL mode.
    anchorX = Math.max(Blockly.Tooltip.MARGINS - window.scrollX, anchorX);
  } else {
    if (anchorX + Blockly.Tooltip.DIV.offsetWidth >
        windowSize.width + window.scrollX - 2 * Blockly.Tooltip.MARGINS) {
      // Falling off the right edge of the screen;
      // clamp the tooltip on the edge.
      anchorX = windowSize.width - Blockly.Tooltip.DIV.offsetWidth -
          2 * Blockly.Tooltip.MARGINS;
    }
  }
  Blockly.Tooltip.DIV.style.top = anchorY + 'px';
  Blockly.Tooltip.DIV.style.left = anchorX + 'px';
};

{'repo_name': 'EinsteinsWorkshop/BlocksCAD', 'stars': '172', 'repo_language': 'JavaScript', 'file_name': 'bootstrap.js', 'mime_type': 'text/plain', 'hash': 1737686593350704175, 'source_dataset': 'data'}


import {
    StudentService
} from "../service/student_service";
import {
    Student
} from "../model/student";
import * as $ from "jquery";
import { initJsStore } from "../service/idb_service";

export class StudentGrid {

    getHtml() {
        return `

                            Name
                            Gender
                            Country
                            City

                            <input type="text"/>
                            <input type="text"/>
                            <input type="text"/>
                            <input type="text"/>
                            <button id="btnAdd">Add</button>
                            <button id="btnClear">Clear</button>

`
    }

    async init() {
        try {
           await initJsStore();
        }
        catch (ex) {
            alert(ex.message);
            return;
        }
        var studentService = new StudentService();
        var html = '';
        try {
            const students = await studentService.getStudents();
            students.forEach((student) => {
                html += this.getRowHtml(student);
            })
            $('table tbody').html(html);
            this.catchEvents();
        } catch (err) {
            console.error(err);
        }

    }

    getRowHtml(student) {
        const html = `

                        ${student.name}
                        ${student.gender}
                        ${student.country}
                        ${student.city}
                        <button class='btn-edit'>Edit</button>
                        <button class='btn-delete'>Delete</button>

`;
        return html;
    }

    clearAddRowTextBoxValue() {
        $('table thead tr td input').val('');
    }

    async addStudentIntoDb(student) {
        var studentService = new StudentService();
        try {
            const addedStudents = await studentService.addStudent(student);
            if (addedStudents.length > 0) {
                this.clearAddRowTextBoxValue();
                $('table tbody').append(this.getRowHtml(addedStudents[0]));
            }
        } catch (err) {
            alert(err.message);
        }
    }

    catchEvents() {
        $('#btnAdd').click(() => {
            const addRow = $('table thead tr')[1];
            const student = new Student(
                null,
                $(addRow.cells[0]).find('input').val(),
                $(addRow.cells[1]).find('input').val(),
                $(addRow.cells[2]).find('input').val(),
                $(addRow.cells[3]).find('input').val()
            );
            this.addStudentIntoDb(student);
        });

        $('#btnClear').click(() => {
            this.clearAddRowTextBoxValue();
        });

        $('body').on('click', 'table .btn-delete', async function () {
            var row = $(this).parents('tr');
            var studentId = Number(row.data('id'));
            var studentService = new StudentService();
            try {
                const noOfRowsDeleted = await studentService.removeStudent(studentId);
                if (noOfRowsDeleted > 0) {
                    row.remove();
                }
            } catch (err) {
                alert(err.message);
            }
        });

        $('body').on('click', 'table .btn-edit', function () {
            var row = $(this).parents('tr');
            row.find('td').each(function () {
                var $el = $(this);
                if ($el.find('button').length === 0) {
                    $el.html(`<input type="text" value="${$el.text()}"/>`);
                }
            });
            row.find('td:eq(4)').html('<button class="btn-update">Update</button>');
            row.find('td:eq(5)').html('<button class="btn-cancel-update">Cancel</button>');
        });

        $('body').on('click', 'table .btn-cancel-update', async function () {
            var row = $(this).parents('tr');
            var studentService = new StudentService();
            try {
                const students = await studentService.getStudentById(Number(row.data('id')));
                if (students.length > 0) {
                    const student = students[0];
                    row.find('td:eq(0)').html(student.name);
                    row.find('td:eq(1)').html(student.gender);
                    row.find('td:eq(2)').html(student.country);
                    row.find('td:eq(3)').html(student.city);
                }
                row.find('td:eq(4)').html('<button class="btn-edit">Edit</button>');
                row.find('td:eq(5)').html('<button class="btn-delete">Delete</button>');
            } catch (err) {
                alert(err.message);
            }
        });

        $('body').on('click', 'table .btn-update', async function () {
            var row = $(this).parents('tr');
            var student = {
                name: row.find('td:eq(0) input').val(),
                gender: row.find('td:eq(1) input').val(),
                country: row.find('td:eq(2) input').val(),
                city: row.find('td:eq(3) input').val()
            };
            var studentService = new StudentService();
            var studentId = Number(row.data('id'));
            try {
                const noOfRowsUpdated = await studentService.updateStudentById(studentId, student);
                if (noOfRowsUpdated > 0) {
                    row.find('td').each(function (index) {
                        var $el = $(this);
                        if ($el.find('button').length === 0) {
                            $el.html(row.find(`td:eq(${index}) input`).val());
                        }
                    });
                    row.find('td:eq(4)').html('<button class="btn-edit">Edit</button>');
                    row.find('td:eq(5)').html('<button class="btn-delete">Delete</button>');
                }
            } catch (err) {
                alert(err.message);
            }

        })
    }

}

{'repo_name': 'ujjwalguptaofficial/JsStore', 'stars': '352', 'repo_language': 'JavaScript', 'file_name': 'webpack.dev.config.js', 'mime_type': 'text/plain', 'hash': 5782464782567115945, 'source_dataset': 'data'}


// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;

namespace ColorSyntax.Parsing
{
    public interface ILanguageParser
    {
        void Parse(string sourceCode,
                   ILanguage language,
                   Action<string, IList<Scope>> parseHandler);
    }
}

{'repo_name': 'UWPCommunity/Quarrel', 'stars': '146', 'repo_language': 'C++', 'file_name': 'Flyouts.resw', 'mime_type': 'text/xml', 'hash': 505370743794145826, 'source_dataset': 'data'}


// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;

namespace Pulumi.Aws.WafV2.Inputs
{

    public sealed class WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementXssMatchStatementFieldToMatchMethodArgs : Pulumi.ResourceArgs
    {
        public WebAclRuleStatementRateBasedStatementScopeDownStatementOrStatementStatementXssMatchStatementFieldToMatchMethodArgs()
        {
        }
    }
}

{'repo_name': 'pulumi/pulumi-aws', 'stars': '117', 'repo_language': 'Go', 'file_name': 'job.go', 'mime_type': 'text/x-c', 'hash': -8725277440152750970, 'source_dataset': 'data'}


---
layout: "default"
title: "FloatingPointSign"
description: "Swift documentation for 'FloatingPointSign': The sign of a floating-point value."
keywords: "FloatingPointSign,enum,swift,documentation"
root: "/v3.1"
---

enum FloatingPointSign

The sign of a floating-point value.

Import
import Swift

Cases

case plus

The sign for a positive value.

Declaration

case minus

The sign for a negative value.

Declaration

{'repo_name': 'SwiftDocOrg/swiftdoc.org', 'stars': '217', 'repo_language': 'HTML', 'file_name': 'index.html', 'mime_type': 'text/plain', 'hash': 9028036984833636007, 'source_dataset': 'data'}