text:
import logging, os, sys

# ----------------------------------------------------------------------------------------------------
## initialize logger (default to stdout). if successful return handle to logger
## logs will be rotated after file exceeds maxbytes
## input: path to log output file (string), max size (in MB) allowed before rotating log output file (int)
## output: file handle to logger
#---------------------------------------------------

def logInit(level, outputLocation="stdout", modulename="root", maxmb=5):
    from logging import handlers
    root = logging.getLogger(modulename)
    if level == 'VERBOSE' or level == None:
        level = 'INFO'
    root.setLevel(getattr(logging, level))

    ch = None
    if outputLocation == "stdout":
        ch = logging.StreamHandler(sys.stdout)
    else:
        pglogdir = os.path.dirname(os.path.abspath(outputLocation))
        if not os.path.isdir(pglogdir):
            print 'cannot find '+pglogdir+' quitting'
            return None
        try:
            fp = open(os.path.abspath(outputLocation), 'a')
        except IOError as e:
            raise
            print 'Cannot write to '+outputLocation+' using stdout as default'
            return None
        ch = logging.handlers.RotatingFileHandler(os.path.abspath(outputLocation), maxBytes=(1048576*maxmb), backupCount=7)
    if not ch:
        return ch
    ch.setLevel(getattr(logging, level))
    formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
    ch.setFormatter(formatter)
    root.addHandler(ch)
    return root


text:
package hudson.plugins.graph;

import java.io.IOException;
import java.util.ArrayList;

import hudson.model.Job;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import java.util.List;
import java.util.SortedSet;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * UI model that displays graphs list. Almost of the public methods are called by jelly from GraphGroupView/*.jelly
 *
 * @author Nigel Daley
 */
public class GraphGroupView
{
    private List<Graph> graphs;

    private Job job;

    private String group;

    public GraphGroupView(Job job, String group, SortedSet<Graph> graphs)
    {
        this.job = job;
        this.group = group;
        this.graphs = new ArrayList<Graph>(graphs);
    }

    @SuppressWarnings("unused")
    public Job getJob()
    {
        return job;
    }

    public String getGroup()
    {
        return group;
    }

    @SuppressWarnings("unused")
    public List<Graph> getGraphs()
    {
        return graphs;
    }

    private JSONArray getGraphsJson(StaplerRequest req) throws IOException
    {
        JSONArray graphsJson = new JSONArray();

        for (Graph graph : graphs)
        {
            graphsJson.add(graph.toJson(req.findAncestorObject(Job.class)));
        }

        return graphsJson;
    }

    @SuppressWarnings("unused")
    public void doGetGroup(StaplerRequest req, StaplerResponse res) throws IOException
    {
        JSONObject groupJson = new JSONObject();

        groupJson.put("name", group);

        groupJson.put("graphs", getGraphsJson(req));

        res.setContentType("application/json");

        res.getWriter().write(groupJson.toString());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package parquet.thrift.projection.amend;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.*;
import parquet.thrift.struct.ThriftField;
import parquet.thrift.struct.ThriftType;
import parquet.thrift.struct.ThriftType.StructType;

import java.util.*;

/**
 * fill in default value for required fields in TProtocols after projection is specified.
 *
 * @author Tianshuo Deng
 */
public class ProtocolEventsAmender {
  List<TProtocol> rootEvents;
  List<TProtocol> fixedEvents = new ArrayList<TProtocol>();

  public ProtocolEventsAmender(List<TProtocol> rootEvents) {
    this.rootEvents = rootEvents;
  }

  /**
   * Given a thrift definition, protocols events, it checks all the required fields,
   * and create default value if a required field is missing
   *
   * @param recordThriftType the Thrift Struct definition for events
   * @return
   * @throws TException
   */
  public List<TProtocol> amendMissingRequiredFields(StructType recordThriftType) throws TException {
    Iterator<TProtocol> protocolIter = rootEvents.iterator();
    checkStruct(protocolIter, recordThriftType);
    return fixedEvents;
  }

  private TProtocol acceptProtocol(TProtocol p) {
    this.fixedEvents.add(p);
    return p;
  }

  private void checkStruct(Iterator<TProtocol> eventIter, ThriftType.StructType thriftStructType) throws TException {
    TStruct tStruct = acceptProtocol(eventIter.next()).readStructBegin();

    List<ThriftField> childrenFields = thriftStructType.getChildren();

    Set<Short> includedFieldsIds = new HashSet<Short>();

    while (true) {
      TProtocol next = eventIter.next();
      TField field = next.readFieldBegin();

      if (isStopField(field))
        break;
      acceptProtocol(next);
      includedFieldsIds.add(field.id);
      ThriftField fieldDefinition = thriftStructType.getChildById(field.id);
      checkField(field.type, eventIter, fieldDefinition);
      acceptProtocol(eventIter.next()).readFieldEnd();
    }

    for (ThriftField requiredField : childrenFields) {
      if (!isRequired(requiredField)) {
        continue;
      }
      if (!includedFieldsIds.contains(requiredField.getFieldId())) {
        fixedEvents.addAll(new DefaultProtocolEventsGenerator().createProtocolEventsForField(requiredField));
      }
    }

    acceptProtocol(DefaultProtocolEventsGenerator.READ_FIELD_STOP);
    acceptProtocol(eventIter.next()).readStructEnd();
  }

  private void checkField(byte type, Iterator<TProtocol> eventIter, ThriftField fieldDefinition) throws TException {
    switch (type) {
      case TType.STRUCT:
        checkStruct(eventIter, (ThriftType.StructType) fieldDefinition.getType());
        return;
      case TType.LIST:
        checkList(eventIter, fieldDefinition);
        return;
      case TType.MAP:
        checkMap(eventIter, fieldDefinition);
        return;
      case TType.SET:
        checkSet(eventIter, fieldDefinition);
        return;
    }
    checkPrimitiveField(type, eventIter);
  }

  /**
   * check each element of the Set, make sure all the element contain required fields
   *
   * @param eventIter
   * @param setFieldDefinition
   * @throws TException
   */
  private void checkSet(Iterator<TProtocol> eventIter, ThriftField setFieldDefinition) throws TException {
    TSet thriftSet = acceptProtocol(eventIter.next()).readSetBegin();
    ThriftField elementFieldDefinition = ((ThriftType.SetType) setFieldDefinition.getType()).getValues();
    int setSize = thriftSet.size;
    for (int i = 0; i < setSize; i++) {
      checkField(thriftSet.elemType, eventIter, elementFieldDefinition);
    }
    acceptProtocol(eventIter.next()).readSetEnd();
  }

  private void checkMap(Iterator<TProtocol> eventIter, ThriftField mapFieldForWriting) throws TException {
    TMap thriftMap = acceptProtocol(eventIter.next()).readMapBegin();
    ThriftField keyFieldForWriting = ((ThriftType.MapType) mapFieldForWriting.getType()).getKey();
    ThriftField valueFieldForWriting = ((ThriftType.MapType) mapFieldForWriting.getType()).getValue();

    int mapSize = thriftMap.size;
    for (int i = 0; i < mapSize; i++) {
      //readkey
      checkField(thriftMap.keyType, eventIter, keyFieldForWriting);
      //readValue
      checkField(thriftMap.valueType, eventIter, valueFieldForWriting);
    }
    acceptProtocol(eventIter.next()).readMapEnd();
  }

  private void checkList(Iterator<TProtocol> eventIter, ThriftField listFieldUsedForWriting) throws TException {
    ThriftField valueFieldForWriting = ((ThriftType.ListType) listFieldUsedForWriting.getType()).getValues();
    TList thriftList = acceptProtocol(eventIter.next()).readListBegin();
    int listSize = thriftList.size;
    for (int i = 0; i < listSize; i++) {
      checkField(thriftList.elemType, eventIter, valueFieldForWriting);
    }
    acceptProtocol(eventIter.next()).readListEnd();
  }

  /**
   * Once reached primitive field, just the copy the event.
   *
   * @param type
   * @param eventIter
   * @throws TException
   */
  private void checkPrimitiveField(byte type, Iterator<TProtocol> eventIter) throws TException {
    acceptProtocol(eventIter.next());
  }

  private boolean isStopField(TField field) {
    return field.type == TType.STOP;
  }

  private boolean isRequired(ThriftField requiredField) {
    return requiredField.getRequirement() == ThriftField.Requirement.REQUIRED;
  }

}


text: continue<caret>


text:
{{}}

{{ lang.NumFmt 0 .Site.Data.certcount.count }}


text:
namespace MyServer.ViewComponents.ImageGallery.Components.AllAlbums.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    using AutoMapper;

    using MyServer.Common.ImageGallery;
    using MyServer.Data.Models;
    using MyServer.Services.Mappings;
    using MyServer.ViewComponents.ImageGallery._Common.Models;

    public class AllImagesViewModel : IMapFrom<Image>, IHaveCustomMappings
    {
        public Guid? AlbumId { get; set; }

        [MaxLength(50)]
        public string Aperture { get; set; }

        [MaxLength(50)]
        public string CameraMaker { get; set; }

        [MaxLength(50)]
        public string CameraModel { get; set; }

        public DateTime? DateTaken { get; set; }

        [MaxLength(50)]
        public string ExposureBiasStep { get; set; }

        [MaxLength(200)]
        public string FileName { get; set; }

        [MaxLength(50)]
        public string FocusLen { get; set; }

        public List<double> GpsCoordinates { get; set; }

        public string GpsName { get; set; }

        public int Height { get; set; }

        public Guid Id { get; set; }

        public GpsDataViewModel ImageGpsData { get; set; }

        public string Info { get; set; }

        [MaxLength(50)]
        public string Iso { get; set; }

        [MaxLength(100)]
        public string Lenses { get; set; }

        public int LowHeight { get; set; }

        public string LowImageSource { get; set; }

        public int LowWidth { get; set; }

        public string MiddleImageSource { get; set; }

        public int MidHeight { get; set; }

        public int MidWidth { get; set; }

        public string OriginalDownloadPath { get; set; }

        [MaxLength(100)]
        public string OriginalFileName { get; set; }

        [MaxLength(50)]
        public string ShutterSpeed { get; set; }

        [MaxLength(200)]
        public string Title { get; set; }

        public int Width { get; set; }

        public void CreateMappings(IMapperConfigurationExpression configuration)
        {
            configuration.CreateMap<Image, AllImagesViewModel>()
                .ForMember(m => m.Info, opt => opt.MapFrom(src => MappingFunctions.MapInfo(src)))
                .ForMember(m => m.GpsCoordinates, opt => opt.MapFrom(src => MappingFunctions.MapGpsCoordinates(src)))
                .ForMember(m => m.GpsName, opt => opt.MapFrom(src => MappingFunctions.MapGpsName(src)))
                .ForMember(
                    m => m.OriginalDownloadPath,
                    opt => opt.MapFrom(
                        c => Constants.MainContentFolder + "/" + c.AlbumId + "/" + Constants.ImageFolderOriginal + "/"
                             + c.FileName))
                .ForMember(
                    m => m.MiddleImageSource,
                    opt => opt.MapFrom(
                        c => Constants.MainContentFolder + "/" + c.AlbumId + "/" + Constants.ImageFolderMiddle + "/"
                             + c.FileName)).ForMember(
                    m => m.LowImageSource,
                    opt => opt.MapFrom(
                        c => Constants.MainContentFolder + "/" + c.AlbumId + "/" + Constants.ImageFolderLow + "/"
                             + c.FileName));
        }
    }
}


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

using Quartz;
using Quartz.Impl;

/// <summary>
/// Summary description for QuartzScheduler
/// </summary>
public class QuartzSchedulerForEmail
{
    public static void Start()
    {
        IJobDetail emailJob = JobBuilder.Create<QuartzTriggerForEmail>()
              .WithIdentity("job2")
              .Build();

        ITrigger trigger = TriggerBuilder.Create()
            .WithDailyTimeIntervalSchedule
              (s =>
                 s.WithIntervalInSeconds(30)
                .OnEveryDay()
              )
             .ForJob(emailJob)
             .WithIdentity("trigger2")
             .StartNow()
             .WithCronSchedule("0 0 12 * * ?")
             .Build();

        ISchedulerFactory sf = new StdSchedulerFactory();
        IScheduler sc = sf.GetScheduler();
        sc.ScheduleJob(emailJob, trigger);
        sc.Start();
    }
}


text:
from collections import OrderedDict
from functools import partial

from django.db import models
from django.conf import settings
from django.template import Context
from django.template.loader import get_template
from django.templatetags.static import static
from django.utils.translation import ugettext_lazy as _

from cms.models.pluginmodel import CMSPlugin

from filer.fields.image import FilerImageField

from aldryn_social_addthis import defaults

SOCIAL_NETWORKS = (
    ('facebook', _('Facebook')),
    ('instagram', _('Instagram')),
    ('google', _('Google+')),
    ('twitter', _('Twitter')),
    ('youtube', _('YouTube')),
    ('xing', _('XING')),
    ('linkedin', _('LinkedIn')),
    ('rss', _('RSS')),
)

SOCIAL_NETWORKS_BY_NAME = OrderedDict(SOCIAL_NETWORKS)

AVAILABLE_NETWORKS = getattr(settings, 'ALDRYN_SOCIAL_ADDTHIS_NETWORKS', SOCIAL_NETWORKS_BY_NAME.keys())

CMSPluginField = partial(
    models.OneToOneField,
    to=CMSPlugin,
    related_name='%(app_label)s_%(class)s',
    parent_link=True,
)

class Like(CMSPlugin):

    facebook = models.BooleanField(_('facebook'), default=False)
    google = models.BooleanField(_('google'), default=False)
    twitter = models.BooleanField(_('twitter'), default=False)
    pinterest = models.BooleanField(_('pinterest'), default=False)
    email = models.BooleanField(_('email'), default=False)

    buttons = [
        ('facebook', 'aldryn_social_addthis/likes/facebook.html'),
        ('google', 'aldryn_social_addthis/likes/google.html'),
        ('twitter', 'aldryn_social_addthis/likes/twitter.html'),
        ('pinterest', 'aldryn_social_addthis/likes/pinterest.html'),
        ('email', 'aldryn_social_addthis/likes/email.html')
    ]

    title = models.CharField(
        verbose_name=_('title'),
        max_length=255,
        default=defaults.LIKE['title'],
        blank=True,
        null=True,
        help_text=_('Uses the title of the browser window if empty.')
    )
    description = models.CharField(
        verbose_name=_('description'),
        max_length=255,
        default=defaults.LIKE['description'],
        blank=True,
        null=True
    )
    image = FilerImageField(
        verbose_name=_('image'),
        blank=True,
        null=True,
        help_text=_('This setting can only be set once per page. If set twice, it will be overridden.')
    )
    cmsplugin_ptr = CMSPluginField()

    def get_buttons(self):
        context = Context({'title': self.title,
                           'description': self.description})
        for button, template_path in self.buttons:
            if getattr(self, button):
                template = get_template(template_path)
                yield template.render(context)

class Mail(CMSPlugin):

    subject = models.CharField(_('subject'), max_length=100)
    body = models.TextField(_('body'), default='', blank=True)
    append_url = models.BooleanField(
        verbose_name=_('append url'),
        default=True,
        help_text=_('Append the current web address at the end of the mail.')
    )
    cmsplugin_ptr = CMSPluginField()

class Links(CMSPlugin):

    facebook = models.URLField(_('Facebook'), null=True, blank=True)
    instagram = models.URLField(_('Instagram'), null=True, blank=True)
    google = models.URLField(_('Google+'), null=True, blank=True)
    twitter = models.URLField(_('Twitter'), null=True, blank=True)
    youtube = models.URLField(_('YouTube'), null=True, blank=True)
    xing = models.URLField(_('XING'), null=True, blank=True)
    linkedin = models.URLField(_('LinkedIn'), null=True, blank=True)
    rss = models.URLField(_('RSS'), null=True, blank=True)
    cmsplugin_ptr = CMSPluginField()

    def get_link(self, network):
        icon_path = self.get_plugin_class().ICON_URL % {'network': network}
        return {'name': network, 'url': getattr(self, network), 'icon_url': static(icon_path)}

    def get_links(self):
        return [self.get_link(network) for network in AVAILABLE_NETWORKS if getattr(self, network)]


text:
package org.apereo.cas.web.flow;

import org.apereo.cas.config.CasAuthenticationEventExecutionPlanTestConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationServiceSelectionStrategyConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasDefaultServiceTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasPersonDirectoryTestConfiguration;
import org.apereo.cas.config.CasRegisteredServicesTestConfiguration;
import org.apereo.cas.config.PasswordlessAuthenticationConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.logout.config.CasCoreLogoutConfiguration;
import org.apereo.cas.web.config.CasCookieConfiguration;
import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration;
import org.apereo.cas.web.flow.config.CasWebflowContextConfiguration;

import org.junit.ClassRule;
import org.junit.Rule;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;

/**
 * This is {@link BasePasswordlessAuthenticationActionTests}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@SpringBootTest(classes = {
    PasswordlessAuthenticationConfiguration.class,
    CasCoreAuthenticationPolicyConfiguration.class,
    CasCoreAuthenticationConfiguration.class,
    CasCoreAuthenticationHandlersConfiguration.class,
    CasCoreAuthenticationMetadataConfiguration.class,
    CasCoreAuthenticationPrincipalConfiguration.class,
    RefreshAutoConfiguration.class,
    CasCoreWebflowConfiguration.class,
    CasWebflowContextConfiguration.class,
    CasCoreConfiguration.class,
    CasCookieConfiguration.class,
    CasCoreTicketsConfiguration.class,
    CasCoreLogoutConfiguration.class,
    CasCoreServicesConfiguration.class,
    CasCoreTicketIdGeneratorsConfiguration.class,
    CasCoreTicketCatalogConfiguration.class,
    CasCoreAuthenticationServiceSelectionStrategyConfiguration.class,
    CasCoreHttpConfiguration.class,
    CasCoreWebConfiguration.class,
    CasPersonDirectoryTestConfiguration.class,
    CasCoreUtilConfiguration.class,
    CasRegisteredServicesTestConfiguration.class,
    CasWebApplicationServiceFactoryConfiguration.class,
    CasAuthenticationEventExecutionPlanTestConfiguration.class,
    CasDefaultServiceTicketIdGeneratorsConfiguration.class,
    CasCoreAuthenticationPrincipalConfiguration.class
})
public abstract class BasePasswordlessAuthenticationActionTests {
    @ClassRule
    public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();

    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();
}


text:
#include "third_party/blink/renderer/modules/websockets/websocket_channel_impl.h"

#include <memory>

#include "base/callback.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "third_party/blink/public/common/browser_interface_broker_proxy.h"
#include "third_party/blink/public/mojom/websockets/websocket_connector.mojom-blink.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_url.h"
#include "third_party/blink/public/platform/websocket_handshake_throttle.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/fileapi/file_error.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader.h"
#include "third_party/blink/renderer/core/fileapi/file_reader_loader_client.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/base_fetch_context.h"
#include "third_party/blink/renderer/core/loader/mixed_content_checker.h"
#include "third_party/blink/renderer/core/loader/subresource_filter.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/modules/websockets/inspector_websocket_events.h"
#include "third_party/blink/renderer/modules/websockets/websocket_channel_client.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/loader/fetch/unique_identifier.h"
#include "third_party/blink/renderer/platform/network/network_log.h"
#include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/shared_buffer.h"
#include "third_party/blink/renderer/platform/wtf/std_lib_extras.h"
#include "third_party/blink/renderer/platform/wtf/text/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/text/string_impl.h"

namespace blink {

namespace {

enum WebSocketOpCode {
  kOpCodeText = 0x1,
  kOpCodeBinary = 0x2,
};

}  // namespace

class WebSocketChannelImpl::BlobLoader final
    : public GarbageCollected<WebSocketChannelImpl::BlobLoader>,
      public FileReaderLoaderClient {
 public:
  BlobLoader(scoped_refptr<BlobDataHandle>,
             WebSocketChannelImpl*,
             scoped_refptr<base::SingleThreadTaskRunner>);
  ~BlobLoader() override = default;

  void Cancel();

  // FileReaderLoaderClient functions.
  void DidStartLoading() override {}
  void DidReceiveData() override {}
  void DidFinishLoading() override;
  void DidFail(FileErrorCode) override;

  void Trace(Visitor* visitor) { visitor->Trace(channel_); }

 private:
  Member<WebSocketChannelImpl> channel_;
  std::unique_ptr<FileReaderLoader> loader_;
};

class WebSocketChannelImpl::Message final
    : public GarbageCollected<WebSocketChannelImpl::Message> {
 public:
  Message(const std::string&, base::OnceClosure completion_callback);
  explicit Message(scoped_refptr<BlobDataHandle>);
  Message(DOMArrayBuffer*, base::OnceClosure completion_callback);
  // Close message
  Message(uint16_t code, const String& reason);

  void Trace(Visitor* visitor) { visitor->Trace(array_buffer); }

  MessageType type;

  std::string text;
  scoped_refptr<BlobDataHandle> blob_data_handle;
  Member<DOMArrayBuffer> array_buffer;
  uint16_t code;
  String reason;
  base::OnceClosure completion_callback;
};

WebSocketChannelImpl::BlobLoader::BlobLoader(
    scoped_refptr<BlobDataHandle> blob_data_handle,
    WebSocketChannelImpl* channel,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : channel_(channel),
      loader_(std::make_unique<FileReaderLoader>(
          FileReaderLoader::kReadAsArrayBuffer,
          this,
          std::move(task_runner))) {
  loader_->Start(std::move(blob_data_handle));
}

void WebSocketChannelImpl::BlobLoader::Cancel() {
  loader_->Cancel();
  loader_ = nullptr;
}

void WebSocketChannelImpl::BlobLoader::DidFinishLoading() {
  channel_->DidFinishLoadingBlob(loader_->ArrayBufferResult());
  loader_ = nullptr;
}

void WebSocketChannelImpl::BlobLoader::DidFail(FileErrorCode error_code) {
  channel_->DidFailLoadingBlob(error_code);
  loader_ = nullptr;
}

struct WebSocketChannelImpl::ConnectInfo {
  ConnectInfo(const String& selected_protocol, const String& extensions)
      : selected_protocol(selected_protocol), extensions(extensions) {}

  const String selected_protocol;
  const String extensions;
};

// static
WebSocketChannelImpl* WebSocketChannelImpl::CreateForTesting(
    ExecutionContext* execution_context,
    WebSocketChannelClient* client,
    std::unique_ptr<SourceLocation> location,
    std::unique_ptr<WebSocketHandshakeThrottle> handshake_throttle) {
  auto* channel = MakeGarbageCollected<WebSocketChannelImpl>(
      execution_context, client, std::move(location));
  channel->handshake_throttle_ = std::move(handshake_throttle);
  return channel;
}

// static
WebSocketChannelImpl* WebSocketChannelImpl::Create(
    ExecutionContext* execution_context,
    WebSocketChannelClient* client,
    std::unique_ptr<SourceLocation> location) {
  auto* channel = MakeGarbageCollected<WebSocketChannelImpl>(
      execution_context, client, std::move(location));
  channel->handshake_throttle_ =
      channel->GetBaseFetchContext()->CreateWebSocketHandshakeThrottle();
  return channel;
}

WebSocketChannelImpl::WebSocketChannelImpl(
    ExecutionContext* execution_context,
    WebSocketChannelClient* client,
    std::unique_ptr<SourceLocation> location)
    : client_(client),
      identifier_(CreateUniqueIdentifier()),
      message_chunks_(execution_context->GetTaskRunner(TaskType::kNetworking)),
      execution_context_(execution_context),
      location_at_construction_(std::move(location)),
      websocket_(execution_context),
      handshake_client_receiver_(this, execution_context),
      client_receiver_(this, execution_context),
      readable_watcher_(
          FROM_HERE,
          mojo::SimpleWatcher::ArmingPolicy::MANUAL,
          execution_context->GetTaskRunner(TaskType::kNetworking)),
      file_reading_task_runner_(
          execution_context->GetTaskRunner(TaskType::kFileReading)) {
  if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_))
    scope->EnsureFetcher();
}

WebSocketChannelImpl::~WebSocketChannelImpl() = default;

bool WebSocketChannelImpl::Connect(const KURL& url, const String& protocol) {
  NETWORK_DVLOG(1) << this << " Connect()";

  if (GetBaseFetchContext()->ShouldBlockWebSocketByMixedContentCheck(url)) {
    has_initiated_opening_handshake_ = false;
    return false;
  }

  if (auto* scheduler = execution_context_->GetScheduler()) {
    feature_handle_for_scheduler_ = scheduler->RegisterFeature(
        SchedulingPolicy::Feature::kWebSocket,
        {SchedulingPolicy::DisableAggressiveThrottling(),
         SchedulingPolicy::RecordMetricsForBackForwardCache()});
  }

  if (MixedContentChecker::IsMixedContent(
          execution_context_->GetSecurityOrigin(), url)) {
    String message =
        "Connecting to a non-secure WebSocket server from a secure origin is "
        "deprecated.";
    execution_context_->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
        mojom::ConsoleMessageSource::kJavaScript,
        mojom::ConsoleMessageLevel::kWarning, message));
  }

  url_ = url;
  Vector<String> protocols;
  // Avoid placing an empty token in the Vector when the protocol string is
  // empty.
  if (!protocol.IsEmpty()) {
    // Since protocol is already verified and escaped, we can simply split
    // it.
    protocol.Split(", ", true, protocols);
  }

  // If the connection needs to be filtered, asynchronously fail. Synchronous
  // failure blocks the worker thread which should be avoided. Note that
  // returning "true" just indicates that this was not a mixed content error.
  if (ShouldDisallowConnection(url)) {
    execution_context_->GetTaskRunner(TaskType::kNetworking)
        ->PostTask(FROM_HERE,
                   WTF::Bind(&WebSocketChannelImpl::TearDownFailedConnection,
                             WrapPersistent(this)));
    return true;
  }

  mojo::Remote<mojom::blink::WebSocketConnector> connector;
  execution_context_->GetBrowserInterfaceBroker().GetInterface(
      connector.BindNewPipeAndPassReceiver(
          execution_context_->GetTaskRunner(TaskType::kWebSocket)));

  connector->Connect(
      url, protocols, GetBaseFetchContext()->GetSiteForCookies(),
      execution_context_->UserAgent(),
      handshake_client_receiver_.BindNewPipeAndPassRemote(
          execution_context_->GetTaskRunner(TaskType::kWebSocket)));
  handshake_client_receiver_.set_disconnect_with_reason_handler(
      WTF::Bind(&WebSocketChannelImpl::OnConnectionError,
                WrapWeakPersistent(this), FROM_HERE));
  has_initiated_opening_handshake_ = true;

  if (handshake_throttle_) {
    // The use of WrapWeakPersistent is safe and motivated by the fact that if
    // the WebSocket is no longer referenced, there's no point in keeping it
    // alive just to receive the throttling result.
    handshake_throttle_->ThrottleHandshake(
        url, WTF::Bind(&WebSocketChannelImpl::OnCompletion,
                       WrapWeakPersistent(this)));
  } else {
    // Treat no throttle as success.
    throttle_passed_ = true;
  }

  TRACE_EVENT_INSTANT1("devtools.timeline", "WebSocketCreate",
                       TRACE_EVENT_SCOPE_THREAD, "data",
                       InspectorWebSocketCreateEvent::Data(
                           execution_context_, identifier_, url, protocol));
  probe::DidCreateWebSocket(execution_context_, identifier_, url, protocol);
  return true;
}

WebSocketChannel::SendResult WebSocketChannelImpl::Send(
    const std::string& message,
    base::OnceClosure completion_callback) {
  NETWORK_DVLOG(1) << this << " Send(" << message << ") (std::string argument)";
  probe::DidSendWebSocketMessage(execution_context_, identifier_,
                                 WebSocketOpCode::kOpCodeText, true,
                                 message.c_str(), message.length());
  if (messages_.empty() &&
      MaybeSendSynchronously(network::mojom::blink::WebSocketMessageType::TEXT,
                             message)) {
    return SendResult::SENT_SYNCHRONOUSLY;
  }

  messages_.push_back(
      MakeGarbageCollected<Message>(message, std::move(completion_callback)));

  ProcessSendQueue();

  // If we managed to flush this message synchronously after all, it would mean
  // that the callback was fired re-entrantly, which would be bad.
  DCHECK(!messages_.empty());

  return SendResult::CALLBACK_WILL_BE_CALLED;
}

void WebSocketChannelImpl::Send(
    scoped_refptr<BlobDataHandle> blob_data_handle) {
  NETWORK_DVLOG(1) << this << " Send(" << blob_data_handle->Uuid() << ", "
                   << blob_data_handle->GetType() << ", "
                   << blob_data_handle->size() << ") "
                   << "(BlobDataHandle argument)";
  // FIXME: We can't access the data here.
  // Since Binary data are not displayed in Inspector, this does not
  // affect actual behavior.
  probe::DidSendWebSocketMessage(execution_context_, identifier_,
                                 WebSocketOpCode::kOpCodeBinary, true, "", 0);
  messages_.push_back(
      MakeGarbageCollected<Message>(std::move(blob_data_handle)));
  ProcessSendQueue();
}

WebSocketChannel::SendResult WebSocketChannelImpl::Send(
    const DOMArrayBuffer& buffer,
    size_t byte_offset,
    size_t byte_length,
    base::OnceClosure completion_callback) {
  NETWORK_DVLOG(1) << this << " Send(" << buffer.Data() << ", " << byte_offset
                   << ", " << byte_length << ") "
                   << "(DOMArrayBuffer argument)";
  probe::DidSendWebSocketMessage(
      execution_context_, identifier_, WebSocketOpCode::kOpCodeBinary, true,
      static_cast<const char*>(buffer.Data()) + byte_offset, byte_length);
  if (messages_.empty() &&
      MaybeSendSynchronously(
          network::mojom::blink::WebSocketMessageType::BINARY,
          base::make_span(static_cast<const char*>(buffer.Data()) + byte_offset,
                          byte_length))) {
    return SendResult::SENT_SYNCHRONOUSLY;
  }

  // buffer.Slice copies its contents.
  messages_.push_back(MakeGarbageCollected<Message>(
      buffer.Slice(byte_offset, byte_offset + byte_length),
      std::move(completion_callback)));

  ProcessSendQueue();

  // If we managed to flush this message synchronously after all, it would mean
  // that the callback was fired re-entrantly, which would be bad.
  DCHECK(!messages_.empty());

  return SendResult::CALLBACK_WILL_BE_CALLED;
}

void WebSocketChannelImpl::Close(int code, const String& reason) {
  DCHECK_EQ(GetState(), State::kOpen);
  NETWORK_DVLOG(1) << this << " Close(" << code << ", " << reason << ")";
  uint16_t code_to_send = static_cast<uint16_t>(
      code == kCloseEventCodeNotSpecified ? kCloseEventCodeNoStatusRcvd : code);
  messages_.push_back(MakeGarbageCollected<Message>(code_to_send, reason));
  ProcessSendQueue();
}

void WebSocketChannelImpl::Fail(const String& reason,
                                mojom::ConsoleMessageLevel level,
                                std::unique_ptr<SourceLocation> location) {
  NETWORK_DVLOG(1) << this << " Fail(" << reason << ")";
  probe::DidReceiveWebSocketMessageError(execution_context_, identifier_,
                                         reason);
  const String message =
      "WebSocket connection to '" + url_.ElidedString() + "' failed: " + reason;

  std::unique_ptr<SourceLocation> captured_location = SourceLocation::Capture();
  if (!captured_location->IsUnknown()) {
    // If we are in JavaScript context, use the current location instead
    // of passed one - it's more precise.
    location = std::move(captured_location);
  } else if (location->IsUnknown()) {
    // No information is specified by the caller. Use the line number at the
    // connection.
    location = location_at_construction_->Clone();
  }

  execution_context_->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>(
      mojom::ConsoleMessageSource::kJavaScript, level, message,
      std::move(location)));
  // |reason| is only for logging and should not be provided for scripts,
  // hence close reason must be empty in tearDownFailedConnection.
  TearDownFailedConnection();
}

void WebSocketChannelImpl::Disconnect() {
  NETWORK_DVLOG(1) << this << " disconnect()";
  if (identifier_) {
    TRACE_EVENT_INSTANT1(
        "devtools.timeline", "WebSocketDestroy", TRACE_EVENT_SCOPE_THREAD,
        "data", InspectorWebSocketEvent::Data(execution_context_, identifier_));
    probe::DidCloseWebSocket(execution_context_, identifier_);
  }

  AbortAsyncOperations();
  Dispose();
}

void WebSocketChannelImpl::CancelHandshake() {
  NETWORK_DVLOG(1) << this << " CancelHandshake()";
  if (GetState() != State::kConnecting)
    return;

  // This may still disconnect even if the handshake is complete if we haven't
  // got the message yet.
  // TODO(ricea): Plumb it through to the network stack to fix the race
  // condition.
  Disconnect();
}

void WebSocketChannelImpl::ApplyBackpressure() {
  NETWORK_DVLOG(1) << this << " ApplyBackpressure";
  backpressure_ = true;
}

void WebSocketChannelImpl::RemoveBackpressure() {
  NETWORK_DVLOG(1) << this << " RemoveBackpressure";
  if (backpressure_) {
    backpressure_ = false;
    ConsumePendingDataFrames();
  }
}

void WebSocketChannelImpl::OnOpeningHandshakeStarted(
    network::mojom::blink::WebSocketHandshakeRequestPtr request) {
  DCHECK_EQ(GetState(), State::kConnecting);
  NETWORK_DVLOG(1) << this << " OnOpeningHandshakeStarted("
                   << request->url.GetString() << ")";

  TRACE_EVENT_INSTANT1(
      "devtools.timeline", "WebSocketSendHandshakeRequest",
      TRACE_EVENT_SCOPE_THREAD, "data",
      InspectorWebSocketEvent::Data(execution_context_, identifier_));
  probe::WillSendWebSocketHandshakeRequest(execution_context_, identifier_,
                                           request.get());
  handshake_request_ = std::move(request);
}

void WebSocketChannelImpl::OnConnectionEstablished(
    mojo::PendingRemote<network::mojom::blink::WebSocket> websocket,
    mojo::PendingReceiver<network::mojom::blink::WebSocketClient>
        client_receiver,
    network::mojom::blink::WebSocketHandshakeResponsePtr response,
    mojo::ScopedDataPipeConsumerHandle readable,
    mojo::ScopedDataPipeProducerHandle writable) {
  DCHECK_EQ(GetState(), State::kConnecting);
  const String& protocol = response->selected_protocol;
  const String& extensions = response->extensions;
  NETWORK_DVLOG(1) << this << " OnConnectionEstablished(" << protocol << ", "
                   << extensions << ")";
  TRACE_EVENT_INSTANT1(
      "devtools.timeline", "WebSocketReceiveHandshakeResponse",
      TRACE_EVENT_SCOPE_THREAD, "data",
      InspectorWebSocketEvent::Data(execution_context_, identifier_));
  probe::DidReceiveWebSocketHandshakeResponse(execution_context_, identifier_,
                                              handshake_request_.get(),
                                              response.get());
  handshake_request_ = nullptr;

  // From now on, we will detect mojo errors via |client_receiver_|.
  handshake_client_receiver_.reset();
  client_receiver_.Bind(
      std::move(client_receiver),
      execution_context_->GetTaskRunner(TaskType::kNetworking));
  client_receiver_.set_disconnect_with_reason_handler(
      WTF::Bind(&WebSocketChannelImpl::OnConnectionError,
                WrapWeakPersistent(this), FROM_HERE));

  DCHECK(!websocket_.is_bound());
  websocket_.Bind(std::move(websocket),
                  execution_context_->GetTaskRunner(TaskType::kNetworking));
  readable_ = std::move(readable);
  // TODO(suzukikeita): Implement upload via |writable_| instead of SendFrame.
  writable_ = std::move(writable);
  const MojoResult mojo_result = readable_watcher_.Watch(
      readable_.get(), MOJO_HANDLE_SIGNAL_READABLE,
      MOJO_WATCH_CONDITION_SATISFIED,
      WTF::BindRepeating(&WebSocketChannelImpl::OnReadable,
                         WrapWeakPersistent(this)));
  DCHECK_EQ(mojo_result, MOJO_RESULT_OK);

  if (!throttle_passed_) {
    connect_info_ = std::make_unique<ConnectInfo>(protocol, extensions);
    return;
  }

  DCHECK_EQ(GetState(), State::kOpen);
  websocket_->StartReceiving();
  handshake_throttle_.reset();
  client_->DidConnect(protocol, extensions);
}

void WebSocketChannelImpl::OnDataFrame(
    bool fin,
    network::mojom::blink::WebSocketMessageType type,
    uint64_t data_length) {
  DCHECK_EQ(GetState(), State::kOpen);
  NETWORK_DVLOG(1) << this << " OnDataFrame(" << fin << ", " << type << ", "
                   << "(data_length = " << data_length << "))";
  pending_data_frames_.push_back(
      DataFrame(fin, type, static_cast<uint32_t>(data_length)));
  ConsumePendingDataFrames();
}

void WebSocketChannelImpl::AddSendFlowControlQuota(int64_t quota) {
  // TODO(yhirano): This should be DCHECK_EQ(GetState(), State::kOpen).
  DCHECK(GetState() == State::kOpen || GetState() == State::kConnecting);
  NETWORK_DVLOG(1) << this << " AddSendFlowControlQuota(" << quota << ")";

  sending_quota_ += quota;
  ProcessSendQueue();
}

void WebSocketChannelImpl::OnDropChannel(bool was_clean,
                                         uint16_t code,
                                         const String& reason) {
  // TODO(yhirano): This should be DCHECK_EQ(GetState(), State::kOpen).
  DCHECK(GetState() == State::kOpen || GetState() == State::kConnecting);
  NETWORK_DVLOG(1) << this << " OnDropChannel(" << was_clean << ", " << code
                   << ", " << reason << ")";

  if (identifier_) {
    TRACE_EVENT_INSTANT1(
        "devtools.timeline", "WebSocketDestroy", TRACE_EVENT_SCOPE_THREAD,
        "data", InspectorWebSocketEvent::Data(execution_context_, identifier_));
    probe::DidCloseWebSocket(execution_context_, identifier_);
    identifier_ = 0;
  }

  HandleDidClose(was_clean, code, reason);
}

void WebSocketChannelImpl::OnClosingHandshake() {
  DCHECK_EQ(GetState(), State::kOpen);
  NETWORK_DVLOG(1) << this << " OnClosingHandshake()";

  client_->DidStartClosingHandshake();
}

void WebSocketChannelImpl::Trace(Visitor* visitor) {
  visitor->Trace(blob_loader_);
  visitor->Trace(messages_);
  visitor->Trace(client_);
  visitor->Trace(execution_context_);
  visitor->Trace(websocket_);
  visitor->Trace(handshake_client_receiver_);
  visitor->Trace(client_receiver_);
  WebSocketChannel::Trace(visitor);
}

WebSocketChannelImpl::Message::Message(const std::string& text,
                                       base::OnceClosure completion_callback)
    : type(kMessageTypeText),
      text(text),
      completion_callback(std::move(completion_callback)) {}

WebSocketChannelImpl::Message::Message(
    scoped_refptr<BlobDataHandle> blob_data_handle)
    : type(kMessageTypeBlob), blob_data_handle(std::move(blob_data_handle)) {}

WebSocketChannelImpl::Message::Message(DOMArrayBuffer* array_buffer,
                                       base::OnceClosure completion_callback)
    : type(kMessageTypeArrayBuffer),
      array_buffer(array_buffer),
      completion_callback(std::move(completion_callback)) {}

WebSocketChannelImpl::Message::Message(uint16_t code, const String& reason)
    : type(kMessageTypeClose), code(code), reason(reason) {}

WebSocketChannelImpl::State WebSocketChannelImpl::GetState() const {
  if (!has_initiated_opening_handshake_) {
    return State::kConnecting;
  }
  if (client_receiver_.is_bound() && throttle_passed_) {
    return State::kOpen;
  }
  if (handshake_client_receiver_.is_bound() || client_receiver_.is_bound()) {
    return State::kConnecting;
  }
  return State::kDisconnected;
}

void WebSocketChannelImpl::SendInternal(
    network::mojom::blink::WebSocketMessageType message_type,
    const char* data,
    size_t total_size,
    uint64_t* consumed_buffered_amount) {
  network::mojom::blink::WebSocketMessageType frame_type =
      sent_size_of_top_message_
          ? network::mojom::blink::WebSocketMessageType::CONTINUATION
          : message_type;
  DCHECK_GE(total_size, sent_size_of_top_message_);
  // The cast is safe since the result of min() never exceeds the range of
  // size_t.
  size_t size = static_cast<size_t>(std::min<uint64_t>(
      sending_quota_, total_size - sent_size_of_top_message_));
  bool final = (sent_size_of_top_message_ + size == total_size);

  SendAndAdjustQuota(final, frame_type,
                     base::make_span(data + sent_size_of_top_message_, size),
                     consumed_buffered_amount);

  sent_size_of_top_message_ += size;

  if (final) {
    base::OnceClosure completion_callback =
        std::move(messages_.front()->completion_callback);
    if (!completion_callback.is_null())
      std::move(completion_callback).Run();
    messages_.pop_front();
    sent_size_of_top_message_ = 0;
  }
}

void WebSocketChannelImpl::SendAndAdjustQuota(
    bool fin,
    network::mojom::blink::WebSocketMessageType type,
    base::span<const char> data,
    uint64_t* consumed_buffered_amount) {
  base::span<const uint8_t> data_to_pass(
      reinterpret_cast<const uint8_t*>(data.data()), data.size());
  websocket_->SendFrame(fin, type, data_to_pass);

  sending_quota_ -= data.size();
  *consumed_buffered_amount += data.size();
}

bool WebSocketChannelImpl::MaybeSendSynchronously(
    network::mojom::blink::WebSocketMessageType frame_type,
    base::span<const char> data) {
  DCHECK(messages_.empty());
  if (data.size() > sending_quota_)
    return false;

  uint64_t consumed_buffered_amount = 0;
  SendAndAdjustQuota(true, frame_type, data, &consumed_buffered_amount);
  if (client_ && consumed_buffered_amount > 0)
    client_->DidConsumeBufferedAmount(consumed_buffered_amount);

  return true;
}

void WebSocketChannelImpl::ProcessSendQueue() {
  // TODO(yhirano): This should be DCHECK_EQ(GetState(), State::kOpen).
  DCHECK(GetState() == State::kOpen || GetState() == State::kConnecting);
  uint64_t consumed_buffered_amount = 0;
  while (!messages_.IsEmpty() && !blob_loader_) {
    Message* message = messages_.front().Get();
    CHECK(message);
    if (sending_quota_ == 0 && message->type != kMessageTypeClose)
      break;
    switch (message->type) {
      case kMessageTypeText:
        SendInternal(network::mojom::blink::WebSocketMessageType::TEXT,
                     message->text.data(), message->text.length(),
                     &consumed_buffered_amount);
        break;
      case kMessageTypeBlob:
        CHECK(!blob_loader_);
        CHECK(message);
        CHECK(message->blob_data_handle);
        blob_loader_ = MakeGarbageCollected<BlobLoader>(
            message->blob_data_handle, this, file_reading_task_runner_);
        break;
      case kMessageTypeArrayBuffer:
        CHECK(message->array_buffer);
        SendInternal(network::mojom::blink::WebSocketMessageType::BINARY,
                     static_cast<const char*>(message->array_buffer->Data()),
                     message->array_buffer->ByteLengthAsSizeT(),
                     &consumed_buffered_amount);
        break;
      case kMessageTypeClose: {
        // No message should be sent from now on.
        DCHECK_EQ(messages_.size(), 1u);
        DCHECK_EQ(sent_size_of_top_message_, 0u);
        handshake_throttle_.reset();
        websocket_->StartClosingHandshake(
            message->code,
            message->reason.IsNull() ? g_empty_string : message->reason);
        messages_.pop_front();
        break;
      }
    }
  }
  if (client_ && consumed_buffered_amount > 0)
    client_->DidConsumeBufferedAmount(consumed_buffered_amount);
}

void WebSocketChannelImpl::AbortAsyncOperations() {
  if (blob_loader_) {
    blob_loader_->Cancel();
    blob_loader_.Clear();
  }
}

void WebSocketChannelImpl::HandleDidClose(bool was_clean,
                                          uint16_t code,
                                          const String& reason) {
  DCHECK_NE(GetState(), State::kDisconnected);
  WebSocketChannelClient::ClosingHandshakeCompletionStatus status =
      was_clean ? WebSocketChannelClient::kClosingHandshakeComplete
                : WebSocketChannelClient::kClosingHandshakeIncomplete;
  client_->DidClose(status, code, reason);
  AbortAsyncOperations();
  Dispose();
}

void WebSocketChannelImpl::OnCompletion(
    const base::Optional<WebString>& console_message) {
  DCHECK(!throttle_passed_);
  DCHECK(handshake_throttle_);
  handshake_throttle_ = nullptr;

  if (GetState() == State::kDisconnected) {
    return;
  }
  DCHECK_EQ(GetState(), State::kConnecting);
  if (console_message) {
    FailAsError(*console_message);
    return;
  }

  throttle_passed_ = true;
  if (connect_info_) {
    websocket_->StartReceiving();
    client_->DidConnect(std::move(connect_info_->selected_protocol),
                        std::move(connect_info_->extensions));
    connect_info_.reset();
    DCHECK_EQ(GetState(), State::kOpen);
  }
}

void WebSocketChannelImpl::DidFinishLoadingBlob(DOMArrayBuffer* buffer) {
  DCHECK_EQ(GetState(), State::kOpen);

  blob_loader_.Clear();
  // The loaded blob is always placed on |messages_[0]|.
  DCHECK_GT(messages_.size(), 0u);
  DCHECK_EQ(messages_.front()->type, kMessageTypeBlob);
  // We replace it with the loaded blob.
  messages_.front() =
      MakeGarbageCollected<Message>(buffer, base::OnceClosure());
  ProcessSendQueue();
}

void WebSocketChannelImpl::DidFailLoadingBlob(FileErrorCode error_code) {
  DCHECK_EQ(GetState(), State::kOpen);

  blob_loader_.Clear();
  if (error_code == FileErrorCode::kAbortErr) {
    // The error is caused by cancel().
    return;
  }
  // FIXME: Generate human-friendly reason message.
  FailAsError("Failed to load Blob: error code = " +
              String::Number(static_cast<unsigned>(error_code)));
}

void WebSocketChannelImpl::TearDownFailedConnection() {
  if (GetState() == State::kDisconnected) {
    return;
  }
  client_->DidError();
  if (GetState() == State::kDisconnected) {
    return;
  }
  HandleDidClose(false, kCloseEventCodeAbnormalClosure, String());
}

bool WebSocketChannelImpl::ShouldDisallowConnection(const KURL& url) {
  SubresourceFilter* subresource_filter =
      GetBaseFetchContext()->GetSubresourceFilter();
  if (!subresource_filter)
    return false;
  return !subresource_filter->AllowWebSocketConnection(url);
}

BaseFetchContext* WebSocketChannelImpl::GetBaseFetchContext() const {
  ResourceFetcher* resource_fetcher = execution_context_->Fetcher();
  return static_cast<BaseFetchContext*>(&resource_fetcher->Context());
}

void WebSocketChannelImpl::OnReadable(MojoResult result,
                                      const mojo::HandleSignalsState& state) {
  DCHECK_EQ(GetState(), State::kOpen);
  NETWORK_DVLOG(2) << this << " OnReadable mojo_result=" << result;
  if (result != MOJO_RESULT_OK) {
    // We don't detect mojo errors on data pipe. Mojo connection errors will
    // be detected via |client_receiver_|.
    return;
  }
  ConsumePendingDataFrames();
}

void WebSocketChannelImpl::ConsumePendingDataFrames() {
  DCHECK_EQ(GetState(), State::kOpen);
  while (!pending_data_frames_.empty() && !backpressure_ &&
         GetState() == State::kOpen) {
    DataFrame& data_frame = pending_data_frames_.front();
    NETWORK_DVLOG(2) << " ConsumePendingDataFrame frame=(" << data_frame.fin
                     << ", " << data_frame.type
                     << ", (data_length = " << data_frame.data_length << "))";
    if (data_frame.data_length == 0) {
      ConsumeDataFrame(data_frame.fin, data_frame.type, nullptr, 0);
      pending_data_frames_.pop_front();
      continue;
    }

    const void* buffer;
    uint32_t readable_size;
    const MojoResult begin_result = readable_->BeginReadData(
        &buffer, &readable_size, MOJO_READ_DATA_FLAG_NONE);
    if (begin_result == MOJO_RESULT_SHOULD_WAIT) {
      readable_watcher_.ArmOrNotify();
      return;
    }
    if (begin_result == MOJO_RESULT_FAILED_PRECONDITION) {
      // |client_receiver_| will catch the connection error.
      return;
    }
    DCHECK_EQ(begin_result, MOJO_RESULT_OK);

    if (readable_size >= data_frame.data_length) {
      ConsumeDataFrame(data_frame.fin, data_frame.type,
                       static_cast<const char*>(buffer),
                       data_frame.data_length);
      const MojoResult end_result =
          readable_->EndReadData(data_frame.data_length);
      DCHECK_EQ(end_result, MOJO_RESULT_OK);
      pending_data_frames_.pop_front();
      continue;
    }

    DCHECK_LT(readable_size, data_frame.data_length);
    ConsumeDataFrame(false, data_frame.type, static_cast<const char*>(buffer),
                     readable_size);
    const MojoResult end_result = readable_->EndReadData(readable_size);
    DCHECK_EQ(end_result, MOJO_RESULT_OK);
    data_frame.type = network::mojom::blink::WebSocketMessageType::CONTINUATION;
    data_frame.data_length -= readable_size;
  }
}

void WebSocketChannelImpl::ConsumeDataFrame(
    bool fin,
    network::mojom::blink::WebSocketMessageType type,
    const char* data,
    size_t size) {
  DCHECK_EQ(GetState(), State::kOpen);
  DCHECK(!backpressure_);
  // Non-final frames cannot be empty.
  DCHECK(fin || size > 0);

  switch (type) {
    case network::mojom::blink::WebSocketMessageType::CONTINUATION:
      break;
    case network::mojom::blink::WebSocketMessageType::TEXT:
      DCHECK_EQ(message_chunks_.GetSize(), 0u);
      receiving_message_type_is_text_ = true;
      break;
    case network::mojom::blink::WebSocketMessageType::BINARY:
      DCHECK_EQ(message_chunks_.GetSize(), 0u);
      receiving_message_type_is_text_ = false;
      break;
  }

  const size_t message_size_so_far = message_chunks_.GetSize();
  if (message_size_so_far > std::numeric_limits<wtf_size_t>::max()) {
    message_chunks_.Clear();
    FailAsError("Message size is too large.");
    return;
  }

  // TODO(yoichio): Do this after EndReadData by reading |message_chunks_|
  // instead.
  if (receiving_message_type_is_text_ && received_text_is_all_ascii_) {
    for (size_t i = 0; i < size; i++) {
      if (!IsASCII(data[i])) {
        received_text_is_all_ascii_ = false;
        break;
      }
    }
  }

  if (!fin) {
    message_chunks_.Append(base::make_span(data, size));
    return;
  }

  Vector<base::span<const char>> chunks = message_chunks_.GetView();
  if (size > 0) {
    chunks.push_back(base::make_span(data, size));
  }
  auto opcode = receiving_message_type_is_text_
                    ? WebSocketOpCode::kOpCodeText
                    : WebSocketOpCode::kOpCodeBinary;
  probe::DidReceiveWebSocketMessage(execution_context_, identifier_, opcode,
                                    false, chunks);

  if (receiving_message_type_is_text_) {
    String message = GetTextMessage(
        chunks, static_cast<wtf_size_t>(message_size_so_far + size));
    if (message.IsNull()) {
      FailAsError("Could not decode a text frame as UTF-8.");
    } else {
      client_->DidReceiveTextMessage(message);
    }
  } else {
    client_->DidReceiveBinaryMessage(chunks);
  }
  message_chunks_.Clear();
  received_text_is_all_ascii_ = true;
}

String WebSocketChannelImpl::GetTextMessage(
    const Vector<base::span<const char>>& chunks,
    wtf_size_t size) {
  DCHECK(receiving_message_type_is_text_);

  if (size == 0) {
    return g_empty_string;
  }

  // We can skip UTF8 encoding if received text contains only ASCII.
  // We do this in order to avoid constructing a temporary buffer.
  if (received_text_is_all_ascii_) {
    LChar* buffer;
    scoped_refptr<StringImpl> string_impl =
        StringImpl::CreateUninitialized(size, buffer);
    size_t index = 0;
    for (const auto& chunk : chunks) {
      DCHECK_LE(index + chunk.size(), size);
      memcpy(buffer + index, chunk.data(), chunk.size());
      index += chunk.size();
    }
    DCHECK_EQ(index, size);
    return String(std::move(string_impl));
  }

  Vector<char> flatten;
  base::span<const char> span;
  if (chunks.size() > 1) {
    flatten.ReserveCapacity(size);
    for (const auto& chunk : chunks) {
      flatten.Append(chunk.data(), static_cast<wtf_size_t>(chunk.size()));
    }
    span = base::make_span(flatten.data(), flatten.size());
  } else if (chunks.size() == 1) {
    span = chunks[0];
  }
  DCHECK_EQ(span.size(), size);
  return String::FromUTF8(span.data(), span.size());
}

void WebSocketChannelImpl::OnConnectionError(const base::Location& set_from,
                                             uint32_t custom_reason,
                                             const std::string& description) {
  DCHECK_NE(GetState(), State::kDisconnected);
  NETWORK_DVLOG(1) << " OnConnectionError("
                   << " reason: " << custom_reason
                   << ", description:" << description
                   << "), set_from:" << set_from.ToString();
  String message = "Unknown reason";
  if (custom_reason == network::mojom::blink::WebSocket::kInternalFailure) {
    message = String::FromUTF8(description.c_str(), description.size());
  }

  // This function is called when the implementation in the network service is
  // required to fail the WebSocket connection. Hence we fail this channel by
  // calling FailAsError function.
  FailAsError(message);
}

void WebSocketChannelImpl::Dispose() {
  message_chunks_.Reset();
  has_initiated_opening_handshake_ = true;
  feature_handle_for_scheduler_.reset();
  handshake_throttle_.reset();
  websocket_.reset();
  readable_watcher_.Cancel();
  handshake_client_receiver_.reset();
  client_receiver_.reset();
  identifier_ = 0;
}

std::ostream& operator<<(std::ostream& ostream,
                         const WebSocketChannelImpl* channel) {
  return ostream << "WebSocketChannelImpl "
                 << static_cast<const void*>(channel);
}

}  // namespace blink


text:
<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-03-13
 * Time: 22:11
 */

namespace sunsun\feederV2\action;

use sunsun\server\interfaces\BaseActionV2;

class FeederV2DeviceCtrlAction extends BaseActionV2
{
}


text:
<?php
/**
 * Generated by Protobuf protoc plugin.
 *
 * File descriptor : POGOProtos/Networking/Responses/DownloadSettingsResponse.proto
 */

namespace POGOProtos\Networking\Responses;

/**
 * Protobuf message : POGOProtos.Networking.Responses.DownloadSettingsResponse
 */
class DownloadSettingsResponse extends \Protobuf\AbstractMessage
{

    /**
     * @var \Protobuf\UnknownFieldSet
     */
    protected $unknownFieldSet = null;

    /**
     * @var \Protobuf\Extension\ExtensionFieldMap
     */
    protected $extensions = null;

    /**
     * error optional string = 1
     *
     * @var string
     */
    protected $error = null;

    /**
     * hash optional string = 2
     *
     * @var string
     */
    protected $hash = null;

    /**
     * settings optional message = 3
     *
     * @var \POGOProtos\Settings\GlobalSettings
     */
    protected $settings = null;

    /**
     * Check if 'error' has a value
     *
     * @return bool
     */
    public function hasError()
    {
        return $this->error !== null;
    }

    /**
     * Get 'error' value
     *
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * Set 'error' value
     *
     * @param string $value
     */
    public function setError($value = null)
    {
        $this->error = $value;
    }

    /**
     * Check if 'hash' has a value
     *
     * @return bool
     */
    public function hasHash()
    {
        return $this->hash !== null;
    }

    /**
     * Get 'hash' value
     *
     * @return string
     */
    public function getHash()
    {
        return $this->hash;
    }

    /**
     * Set 'hash' value
     *
     * @param string $value
     */
    public function setHash($value = null)
    {
        $this->hash = $value;
    }

    /**
     * Check if 'settings' has a value
     *
     * @return bool
     */
    public function hasSettings()
    {
        return $this->settings !== null;
    }

    /**
     * Get 'settings' value
     *
     * @return \POGOProtos\Settings\GlobalSettings
     */
    public function getSettings()
    {
        return $this->settings;
    }

    /**
     * Set 'settings' value
     *
     * @param \POGOProtos\Settings\GlobalSettings $value
     */
    public function setSettings(\POGOProtos\Settings\GlobalSettings $value = null)
    {
        $this->settings = $value;
    }

    /**
     * {@inheritdoc}
     */
    public function extensions()
    {
        if ( $this->extensions !== null) {
            return $this->extensions;
        }

        return $this->extensions = new \Protobuf\Extension\ExtensionFieldMap(__CLASS__);
    }

    /**
     * {@inheritdoc}
     */
    public function unknownFieldSet()
    {
        return $this->unknownFieldSet;
    }

    /**
     * {@inheritdoc}
     */
    public static function fromStream($stream, \Protobuf\Configuration $configuration = null)
    {
        return new self($stream, $configuration);
    }

    /**
     * {@inheritdoc}
     */
    public static function fromArray(array $values)
    {
        $message = new self();
        $values  = array_merge([
            'error' => null,
            'hash' => null,
            'settings' => null
        ], $values);

        $message->setError($values['error']);
        $message->setHash($values['hash']);
        $message->setSettings($values['settings']);

        return $message;
    }

    /**
     * {@inheritdoc}
     */
    public static function descriptor()
    {
        return \google\protobuf\DescriptorProto::fromArray([
            'name'      => 'DownloadSettingsResponse',
            'field'     => [
                \google\protobuf\FieldDescriptorProto::fromArray([
                    'number' => 1,
                    'name' => 'error',
                    'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_STRING(),
                    'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL()
                ]),
                \google\protobuf\FieldDescriptorProto::fromArray([
                    'number' => 2,
                    'name' => 'hash',
                    'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_STRING(),
                    'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL()
                ]),
                \google\protobuf\FieldDescriptorProto::fromArray([
                    'number' => 3,
                    'name' => 'settings',
                    'type' => \google\protobuf\FieldDescriptorProto\Type::TYPE_MESSAGE(),
                    'label' => \google\protobuf\FieldDescriptorProto\Label::LABEL_OPTIONAL(),
                    'type_name' => '.POGOProtos.Settings.GlobalSettings'
                ]),
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function toStream(\Protobuf\Configuration $configuration = null)
    {
        $config  = $configuration ?: \Protobuf\Configuration::getInstance();
        $context = $config->createWriteContext();
        $stream  = $context->getStream();

        $this->writeTo($context);
        $stream->seek(0);

        return $stream;
    }

    /**
     * {@inheritdoc}
     */
    public function writeTo(\Protobuf\WriteContext $context)
    {
        $stream      = $context->getStream();
        $writer      = $context->getWriter();
        $sizeContext = $context->getComputeSizeContext();

        if ($this->error !== null) {
            $writer->writeVarint($stream, 10);
            $writer->writeString($stream, $this->error);
        }

        if ($this->hash !== null) {
            $writer->writeVarint($stream, 18);
            $writer->writeString($stream, $this->hash);
        }

        if ($this->settings !== null) {
            $writer->writeVarint($stream, 26);
            $writer->writeVarint($stream, $this->settings->serializedSize($sizeContext));
            $this->settings->writeTo($context);
        }

        if ($this->extensions !== null) {
            $this->extensions->writeTo($context);
        }

        return $stream;
    }

    /**
     * {@inheritdoc}
     */
    public function readFrom(\Protobuf\ReadContext $context)
    {
        $reader = $context->getReader();
        $length = $context->getLength();
        $stream = $context->getStream();

        $limit = ($length !== null)
            ? ($stream->tell() + $length)
            : null;

        while ($limit === null || $stream->tell() < $limit) {

            if ($stream->eof()) {
                break;
            }

            $key  = $reader->readVarint($stream);
            $wire = \Protobuf\WireFormat::getTagWireType($key);
            $tag  = \Protobuf\WireFormat::getTagFieldNumber($key);

            if ($stream->eof()) {
                break;
            }

            if ($tag === 1) {
                \Protobuf\WireFormat::assertWireType($wire, 9);

                $this->error = $reader->readString($stream);

                continue;
            }

            if ($tag === 2) {
                \Protobuf\WireFormat::assertWireType($wire, 9);

                $this->hash = $reader->readString($stream);

                continue;
            }

            if ($tag === 3) {
                \Protobuf\WireFormat::assertWireType($wire, 11);

                $innerSize    = $reader->readVarint($stream);
                $innerMessage = new \POGOProtos\Settings\GlobalSettings();

                $this->settings = $innerMessage;

                $context->setLength($innerSize);
                $innerMessage->readFrom($context);
                $context->setLength($length);

                continue;
            }

            $extensions = $context->getExtensionRegistry();
            $extension  = $extensions ? $extensions->findByNumber(__CLASS__, $tag) : null;

            if ($extension !== null) {
                $this->extensions()->add($extension, $extension->readFrom($context, $wire));

                continue;
            }

            if ($this->unknownFieldSet === null) {
                $this->unknownFieldSet = new \Protobuf\UnknownFieldSet();
            }

            $data    = $reader->readUnknown($stream, $wire);
            $unknown = new \Protobuf\Unknown($tag, $wire, $data);

            $this->unknownFieldSet->add($unknown);

        }
    }

    /**
     * {@inheritdoc}
     */
    public function serializedSize(\Protobuf\ComputeSizeContext $context)
    {
        $calculator = $context->getSizeCalculator();
        $size       = 0;

        if ($this->error !== null) {
            $size += 1;
            $size += $calculator->computeStringSize($this->error);
        }

        if ($this->hash !== null) {
            $size += 1;
            $size += $calculator->computeStringSize($this->hash);
        }

        if ($this->settings !== null) {
            $innerSize = $this->settings->serializedSize($context);

            $size += 1;
            $size += $innerSize;
            $size += $calculator->computeVarintSize($innerSize);
        }

        if ($this->extensions !== null) {
            $size += $this->extensions->serializedSize($context);
        }

        return $size;
    }

    /**
     * {@inheritdoc}
     */
    public function clear()
    {
        $this->error = null;
        $this->hash = null;
        $this->settings = null;
    }

    /**
     * {@inheritdoc}
     */
    public function merge(\Protobuf\Message $message)
    {
        if ( ! $message instanceof \POGOProtos\Networking\Responses\DownloadSettingsResponse) {
            throw new \InvalidArgumentException(sprintf('Argument 1 passed to %s must be a %s, %s given', __METHOD__, __CLASS__, get_class($message)));
        }

        $this->error = ($message->error !== null) ? $message->error : $this->error;
        $this->hash = ($message->hash !== null) ? $message->hash : $this->hash;
        $this->settings = ($message->settings !== null) ? $message->settings : $this->settings;
    }

}


text:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^$', 'microblogging.views.personal', name='tweets_you_follow'),
    url(r'^all/$', 'microblogging.views.public', name='all_tweets'),
    url(r'^(\d+)/$', 'microblogging.views.single', name='single_tweet'),

    url(r'^followers/(\w+)/$', 'microblogging.views.followers', name='tweet_followers'),
    url(r'^following/(\w+)/$', 'microblogging.views.following', name='tweet_following'),
)


text:
// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert-plus');
var util = require('util');

var asn1 = require('asn1');

var Control = require('../controls').Control;
var Protocol = require('../protocol');

///--- Globals

var Ber = asn1.Ber;
var BerReader = asn1.BerReader;
var BerWriter = asn1.BerWriter;
var getControl = require('../controls').getControl;

///--- API

/**
 * LDAPMessage structure.
 *
 * @param {Object} options stuff.
 */
function LDAPMessage(options) {
  assert.object(options);

  this.messageID = options.messageID || 0;
  this.protocolOp = options.protocolOp || undefined;
  this.controls = options.controls ? options.controls.slice(0) : [];

  this.log = options.log;
}
Object.defineProperties(LDAPMessage.prototype, {
  id: {
    get: function getId() { return this.messageID; },
    configurable: false
  },
  dn: {
    get: function getDN() { return this._dn || ''; },
    configurable: false
  },
  type: {
    get: function getType() { return 'LDAPMessage'; },
    configurable: false
  },
  json: {
    get: function () {
      var out = this._json({
        messageID: this.messageID,
        protocolOp: this.type
      });
      out.controls = this.controls;
      return out;
    },
    configurable: false
  }
});

LDAPMessage.prototype.toString = function () {
  return JSON.stringify(this.json);
};

LDAPMessage.prototype.parse = function (ber) {
  assert.ok(ber);

  if (this.log.trace())
    this.log.trace('parse: data=%s', util.inspect(ber.buffer));

  // Delegate off to the specific type to parse
  this._parse(ber, ber.length);

  // Look for controls
  if (ber.peek() === 0xa0) {
    ber.readSequence();
    var end = ber.offset + ber.length;
    while (ber.offset < end) {
      var c = getControl(ber);
      if (c)
        this.controls.push(c);
    }
  }

  if (this.log.trace())
    this.log.trace('Parsing done: %j', this.json);
  return true;
};

LDAPMessage.prototype.toBer = function () {
  var writer = new BerWriter();
  writer.startSequence();
  writer.writeInt(this.messageID);

  writer.startSequence(this.protocolOp);
  if (this._toBer)
    writer = this._toBer(writer);
  writer.endSequence();

  if (this.controls && this.controls.length) {
    writer.startSequence(0xa0);
    this.controls.forEach(function (c) {
      c.toBer(writer);
    });
    writer.endSequence();
  }

  writer.endSequence();
  return writer.buffer;
};

///--- Exports

module.exports = LDAPMessage;


text:
package com.dilipkumarg.qb;

import org.junit.Before;
import org.junit.Test;

import com.dilipkumarg.qb.models.SqlQuery;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * @author Dilip Kumar.
 * @since 2/7/14
 */
public class DeleteQueryBuilderTest {
    private QPerson person;
    private DeleteQueryBuilder builder;

    public DeleteQueryBuilderTest() {
        person = new QPerson();
    }

    @Before
    public void setUp() {
        builder = new DeleteQueryBuilder(person);
    }

    @Test
    public void testBasicDelete() {
        SqlQuery query = builder.build();
        assertNotNull(query);
        assertEquals("DELETE FROM PERSON", query.getQuery());
        assertEquals(0, query.getArgs().length);
    }

    @Test
    public void testDeleteWithWhere() {
        builder.where(person.name.eq("TEST"));
        SqlQuery query = builder.build();
        assertNotNull(query);
        assertEquals("DELETE FROM PERSON WHERE NAME = ?", query.getQuery());
        assertEquals(1, query.getArgs().length);
        assertEquals("TEST", query.getArgs()[0]);
    }

    @Test
    public void testDeleteWithColumnWhere() {
        builder.where(person.name.eq(person.lastName));
        SqlQuery query = builder.build();
        assertEquals("DELETE FROM PERSON WHERE NAME = LAST_NAME", query.getQuery());
        assertEquals(0, query.getArgs().length);
    }

    @Test
    public void testDeleteWithMultipleWhere() {
        builder.where(person.name.eq("TEST"));
        builder.where(person.age.le(20));
        SqlQuery query = builder.build();
        assertNotNull(query);
        assertEquals("DELETE FROM PERSON WHERE NAME = ? AND AGE <= ?", query.getQuery());
        assertEquals(2, query.getArgs().length);
        assertEquals("TEST", query.getArgs()[0]);
        assertEquals(20, query.getArgs()[1]);
    }

    @Test
    public void testAll() {
        SqlQuery query = builder.where(person.name.eq("TEST"))
                .where(person.age.le(20))
                .build();
        assertNotNull(query);
        assertEquals("DELETE FROM PERSON WHERE NAME = ? AND AGE <= ?", query.getQuery());
        assertEquals(2, query.getArgs().length);
        assertEquals("TEST", query.getArgs()[0]);
        assertEquals(20, query.getArgs()[1]);
    }
}


text:
<?php
$conecta = mysql_connect("localhost", "root", "root");

mysql_select_db("cadastro", $conecta);
//pega a variavel via post
$email = $_POST['email'];

$sql = mysql_query("SELECT * FROM inscricaologin WHERE email='$email'");
$result = mysql_query($sql, $conecta);

//conta quantos tem
$num_rows = mysql_num_rows($result);
//se tiver  + de 1 cadastrado
if($num_rows=='1'){
	//faz um while para vc coloar os dados nas variavels
	while($row_email = mysql_fetch_array($result){
		$rowemail = $row_email['email'];
		$rowsenha = $row_email['senha'];
		}

//enviar um email para variavel email juntamente com a variável senha;
$mensage ="Você solicitou a recuperação de senha, confira seu dados.";
$mensage .="E-mail= " . $rowemail;
$mensage .="Senha:" . $rowsenha;
mail($rowemail, "recuperação de senha", $mensage);

echo"<script>alert(Sua senha foi enviada para o e-mail indicado.),window.open('login.html','_self')</script>";

}else{

	echo"<script>alert('E-mail não cadastrado em nosso sistema'),window.open('login.html','_self')</script>";

}
?>


text:
package io.trane.ndbc.value;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CharacterValueTest {

  @Test
  public void getCharacter() {
    final Character value = 'j';
    final CharacterValue wrapper = new CharacterValue(value);
    assertEquals(value, wrapper.getCharacter());
  }

  @Test
  public void getString() {
    final Character value = 'j';
    final CharacterValue wrapper = new CharacterValue(value);
    assertEquals(value.toString(), wrapper.getString());
  }

  @Test
  public void getBooleanTrue1() {
    final Character value = '1';
    final CharacterValue wrapper = new CharacterValue(value);
    assertEquals(true, wrapper.getBoolean());
  }

  @Test
  public void getBooleanTrueT() {
    final Character value = 'T';
    final CharacterValue wrapper = new CharacterValue(value);
    assertEquals(true, wrapper.getBoolean());
  }

  @Test
  public void getBooleanFalse0() {
    final Character value = '0';
    final CharacterValue wrapper = new CharacterValue(value);
    assertEquals(false, wrapper.getBoolean());
  }

  @Test
  public void getBooleanFalseF() {
    final Character value = 'F';
    final CharacterValue wrapper = new CharacterValue(value);
    assertEquals(false, wrapper.getBoolean());
  }
}


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Http;
    using System.Threading;
    using System.Linq.Expressions;

    /// <summary>
    /// The type WorkbookPivotTableRequest.
    /// </summary>
    public partial class WorkbookPivotTableRequest : BaseRequest, IWorkbookPivotTableRequest
    {
        /// <summary>
        /// Constructs a new WorkbookPivotTableRequest.
        /// </summary>
        /// <param name="requestUrl">The URL for the built request.</param>
        /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
        /// <param name="options">Query and header option name value pairs for the request.</param>
        public WorkbookPivotTableRequest(
            string requestUrl,
            IBaseClient client,
            IEnumerable<Option> options)
            : base(requestUrl, client, options)
        {
        }

        /// <summary>
        /// Creates the specified WorkbookPivotTable using POST.
        /// </summary>
        /// <param name="workbookPivotTableToCreate">The WorkbookPivotTable to create.</param>
        /// <returns>The created WorkbookPivotTable.</returns>
        public System.Threading.Tasks.Task<WorkbookPivotTable> CreateAsync(WorkbookPivotTable workbookPivotTableToCreate)
        {
            return this.CreateAsync(workbookPivotTableToCreate, CancellationToken.None);
        }

        /// <summary>
        /// Creates the specified WorkbookPivotTable using POST.
        /// </summary>
        /// <param name="workbookPivotTableToCreate">The WorkbookPivotTable to create.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The created WorkbookPivotTable.</returns>
        public async System.Threading.Tasks.Task<WorkbookPivotTable> CreateAsync(WorkbookPivotTable workbookPivotTableToCreate, CancellationToken cancellationToken)
        {
            this.ContentType = "application/json";
            this.Method = "POST";
            var newEntity = await this.SendAsync<WorkbookPivotTable>(workbookPivotTableToCreate, cancellationToken).ConfigureAwait(false);
            this.InitializeCollectionProperties(newEntity);
            return newEntity;
        }

        /// <summary>
        /// Deletes the specified WorkbookPivotTable.
        /// </summary>
        /// <returns>The task to await.</returns>
        public System.Threading.Tasks.Task DeleteAsync()
        {
            return this.DeleteAsync(CancellationToken.None);
        }

        /// <summary>
        /// Deletes the specified WorkbookPivotTable.
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The task to await.</returns>
        public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
        {
            this.Method = "DELETE";
            await this.SendAsync<WorkbookPivotTable>(null, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets the specified WorkbookPivotTable.
        /// </summary>
        /// <returns>The WorkbookPivotTable.</returns>
        public System.Threading.Tasks.Task<WorkbookPivotTable> GetAsync()
        {
            return this.GetAsync(CancellationToken.None);
        }

        /// <summary>
        /// Gets the specified WorkbookPivotTable.
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The WorkbookPivotTable.</returns>
        public async System.Threading.Tasks.Task<WorkbookPivotTable> GetAsync(CancellationToken cancellationToken)
        {
            this.Method = "GET";
            var retrievedEntity = await this.SendAsync<WorkbookPivotTable>(null, cancellationToken).ConfigureAwait(false);
            this.InitializeCollectionProperties(retrievedEntity);
            return retrievedEntity;
        }

        /// <summary>
        /// Updates the specified WorkbookPivotTable using PATCH.
        /// </summary>
        /// <param name="workbookPivotTableToUpdate">The WorkbookPivotTable to update.</param>
        /// <returns>The updated WorkbookPivotTable.</returns>
        public System.Threading.Tasks.Task<WorkbookPivotTable> UpdateAsync(WorkbookPivotTable workbookPivotTableToUpdate)
        {
            return this.UpdateAsync(workbookPivotTableToUpdate, CancellationToken.None);
        }

        /// <summary>
        /// Updates the specified WorkbookPivotTable using PATCH.
        /// </summary>
        /// <param name="workbookPivotTableToUpdate">The WorkbookPivotTable to update.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
        /// <returns>The updated WorkbookPivotTable.</returns>
        public async System.Threading.Tasks.Task<WorkbookPivotTable> UpdateAsync(WorkbookPivotTable workbookPivotTableToUpdate, CancellationToken cancellationToken)
        {
            this.ContentType = "application/json";
            this.Method = "PATCH";
            var updatedEntity = await this.SendAsync<WorkbookPivotTable>(workbookPivotTableToUpdate, cancellationToken).ConfigureAwait(false);
            this.InitializeCollectionProperties(updatedEntity);
            return updatedEntity;
        }

        /// <summary>
        /// Adds the specified expand value to the request.
        /// </summary>
        /// <param name="value">The expand value.</param>
        /// <returns>The request object to send.</returns>
        public IWorkbookPivotTableRequest Expand(string value)
        {
            this.QueryOptions.Add(new QueryOption("$expand", value));
            return this;
        }

        /// <summary>
        /// Adds the specified expand value to the request.
        /// </summary>
        /// <param name="expandExpression">The expression from which to calculate the expand value.</param>
        /// <returns>The request object to send.</returns>
        public IWorkbookPivotTableRequest Expand(Expression<Func<WorkbookPivotTable, object>> expandExpression)
        {
		    if (expandExpression == null)
            {
                throw new ArgumentNullException(nameof(expandExpression));
            }
            string error;
            string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
            if (value == null)
            {
                throw new ArgumentException(error, nameof(expandExpression));
            }
            else
            {
                this.QueryOptions.Add(new QueryOption("$expand", value));
            }
            return this;
        }

        /// <summary>
        /// Adds the specified select value to the request.
        /// </summary>
        /// <param name="value">The select value.</param>
        /// <returns>The request object to send.</returns>
        public IWorkbookPivotTableRequest Select(string value)
        {
            this.QueryOptions.Add(new QueryOption("$select", value));
            return this;
        }

        /// <summary>
        /// Adds the specified select value to the request.
        /// </summary>
        /// <param name="selectExpression">The expression from which to calculate the select value.</param>
        /// <returns>The request object to send.</returns>
        public IWorkbookPivotTableRequest Select(Expression<Func<WorkbookPivotTable, object>> selectExpression)
        {
            if (selectExpression == null)
            {
                throw new ArgumentNullException(nameof(selectExpression));
            }
            string error;
            string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
            if (value == null)
            {
                throw new ArgumentException(error, nameof(selectExpression));
            }
            else
            {
                this.QueryOptions.Add(new QueryOption("$select", value));
            }
            return this;
        }

        /// <summary>
        /// Initializes any collection properties after deserialization, like next requests for paging.
        /// </summary>
        /// <param name="workbookPivotTableToInitialize">The <see cref="WorkbookPivotTable"/> with the collection properties to initialize.</param>
        private void InitializeCollectionProperties(WorkbookPivotTable workbookPivotTableToInitialize)
        {

        }
    }
}


text:
package com.alibaba.ydt.portal.domain.common;

import com.alibaba.ydt.portal.util.FeatureUtils;
import org.codehaus.jackson.annotate.JsonIgnore;

import javax.persistence.Basic;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.util.*;

/**
 * Base feature support
 */
@MappedSuperclass
public class BaseFeatureSupport extends BaseModel implements Serializable {

    public static final String ADDABLE_FEATURE_KEY = "addable";
    public static final String REMOVABLE_FEATURE_KEY = "removable";
    public static final String EDITABLE_FEATURE_KEY = "editable";
    public static final String GLOBAL_FEATURE_KEY = "global";

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -3896451590403307619L;

    /**
     * Used for ORM
     */
    @Basic
    private String features;

    /**
     * Query feature by name
     *
     * @param name key
     * @return feature value
     */
    public FeatureDO getFeature(String name) {
        Map<String, FeatureDO> featureMap = FeatureUtils.fromString(features);
        return featureMap != null ? featureMap.get(name) : null;
    }

    /**
     * Query feature by name
     *
     * @param name key
     * @return string represented feature value
     */
    public String getFeatureValue(String name) {
        Map<String, FeatureDO> featureMap = FeatureUtils.fromString(features);
        return featureMap != null ? (featureMap.containsKey(name) ? featureMap.get(name).getValue() : null) : null;
    }

    /**
     * Set a feature
     *
     * @param name  feature name
     * @param value feature value
     */
    public void setFeature(String name, Object value) {
        FeatureDO f = new FeatureDO();
        f.setKey(name);
        f.setValue(value.toString());
        setFeature(f);
    }

    /**
     * Set features in a batch
     *
     * @param featureMap features to set
     */
    public void setFeatureMap(List<FeatureDO> featureMap) {
        if (null != featureMap) {
            for (FeatureDO f : featureMap) {
                setFeature(f);
            }
        }
    }

    /**
     * Set a feature
     *
     * @param feature feature to set
     */
    public void setFeature(FeatureDO feature) {
        if (null != feature) {
            Map<String, FeatureDO> map = FeatureUtils.fromString(features);
            map.put(feature.getKey(), feature);
            features = FeatureUtils.toString(map);
        }
    }

    /**
     * Get all feature's key
     *
     * @return keys keys
     */
    public Set<String> getFeatureKeys() {
        return (null != FeatureUtils.fromString(features) ? FeatureUtils.fromString(features).keySet() : new HashSet<String>());
    }

    /**
     * Get features as map
     *
     * @return featureMap Map
     */
    protected Map<String, FeatureDO> getFeatureMap() {
        return FeatureUtils.fromString(features);
    }

    /**
     * Get features as list
     *
     * @return featureMap List
     */
    public List<FeatureDO> getFeatureList() {
        if (FeatureUtils.fromString(features) != null) {
            return new ArrayList<FeatureDO>(FeatureUtils.fromString(features).values());
        }
        return Collections.emptyList();
    }

    /**
     * Remove a feature by key
     *
     * @param key key
     */
    public void removeFeature(String key) {
        if (key == null) {
            return;
        }
        if (FeatureUtils.fromString(features) == null) {
            return;
        }
        Map<String, FeatureDO> map = FeatureUtils.fromString(features);
        map.remove(key);
        features = FeatureUtils.toString(map);
    }

    /**
     * Remove a feature
     *
     * @param feature FeatureDO
     */
    public void removeFeature(FeatureDO feature) {
        if (feature == null) {
            return;
        }
        if (FeatureUtils.fromString(features) == null) {
            return;
        }
        Map<String, FeatureDO> map = FeatureUtils.fromString(features);
        map.remove(feature.getKey());
        features = FeatureUtils.toString(map);
    }

    /**
     * Clear all features
     */
    public void clearAllFeature() {
        features = "";
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~ Following methods used for ORM ~~~~~~~~~~~~~~~~~~~~~~~~

    /**
     * Set string represent feature
     *
     * @param features string represent feature
     */
    public void setFeatures(String features) {
        this.features = features;
    }

    /**
     * @return get features as a string
     */
    @JsonIgnore
    public String getFeatures() {
        return features;
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>

    <link rel="stylesheet" href="css/tooltip.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/testAdmin.css">
    <title>Object Lookup</title>

Selection

        Pool:
        <select id="pool" ng-model="pool" >
            <option ng-repeat="pool in pools" value="{{ pool.name }}" >{{ pool.name }}</option>
        </select>
        Object id:
        <input type="text" ng-model="objectId" name="objectId" placeholder="object id">

Date : {{date | date:'HH:mm:ss'}}

Pool	{{pool}}

Object	{{objectId}}

PG	{{data.pgid}}

acting	{{data.acting}}

up	{{data.up}}

Acting OSD :

            {{osd}}

                    osd.{{osd}}

                    {{osdState(getOsd(osd).stat.in,getOsd(osd).stat.up)}}

                    weight : {{getOsd(osd).weight}}

                    public addr : {{getOsd(osd).public_addr}}

                    cluster addr : {{getOsd(osd).cluster_addr}}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>vmax units in calc statement test - no javascript.</title>
    <meta name="description" content="Example of viewport units used with CSS calc" />
    <meta name="author" content="Zoltan Hawryluk" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <link href="stylesheets/vmax-calc.css" type="text/css" rel="stylesheet" />

        This circle is always centered vertically and horizontally to the viewport,
        thanks to the calc() CSS property in conjuction with viewport-units.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.dspace.modules</groupId>
	<artifactId>bagit</artifactId>
	<packaging>war</packaging>
	<name>DSpace BagIt :: Web Application</name>
	<version>0.0.1</version>

	<description> DSpace BagIt Webapp </description>

	<parent>
		<groupId>org.dspace.modules</groupId>
		<artifactId>bagit-modules</artifactId>
		<version>0.0.1</version>
	</parent>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<archiveClasses>false</archiveClasses>
					<webResources>
						<resource>
							<filtering>true</filtering>
							<directory>${basedir}/src/main/webapp</directory>
							<includes>
								<include>WEB-INF/web.xml</include>
							</includes>
						</resource>
					</webResources>
				</configuration>
				<executions>
					<execution>
						<phase>prepare-package</phase>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<!--
         when activated a dspace.config configuration
         file location passed on the commandline
         (-Ddspace.config=...) can be passed through
         to be used as a filter source by projects for
         tasks such as updating the ${dspace.dir} in
         web.xml etc.
      -->
		<profile>
			<activation>
				<property>
					<name>dspace.config</name>
				</property>
			</activation>
			<build>
				<filters>
					<filter>${dspace.config}</filter>
				</filters>
			</build>
		</profile>
	</profiles>

	<dependencies>
		<dependency>
			<groupId>org.dspace.modules</groupId>
			<artifactId>bagit-api</artifactId>
			<version>0.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.dspace</groupId>
			<artifactId>dspace-api</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.4</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>postgresql</groupId>
			<artifactId>postgresql</artifactId>
			<version>8.1-407.jdbc3</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.5</version>
		</dependency>
	</dependencies>

</project>