text:
namespace {

class CefAuthCallbackImpl : public CefAuthCallback {
 public:
  CefAuthCallbackImpl(const net::NetworkDelegate::AuthCallback& callback,
                      net::AuthCredentials* credentials)
      : callback_(callback),
        credentials_(credentials) {
  }
  ~CefAuthCallbackImpl() {
    if (!callback_.is_null()) {
      // The auth callback is still pending. Cancel it now.
      if (CEF_CURRENTLY_ON_IOT()) {
        CancelNow(callback_);
      } else {
        CEF_POST_TASK(CEF_IOT,
            base::Bind(&CefAuthCallbackImpl::CancelNow, callback_));
      }
    }
  }

  virtual void Continue(const CefString& username,
                        const CefString& password) OVERRIDE {
    if (CEF_CURRENTLY_ON_IOT()) {
      if (!callback_.is_null()) {
        credentials_->Set(username, password);
        callback_.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
        callback_.Reset();
      }
    } else {
      CEF_POST_TASK(CEF_IOT,
          base::Bind(&CefAuthCallbackImpl::Continue, this, username, password));
    }
  }

  virtual void Cancel() OVERRIDE {
    if (CEF_CURRENTLY_ON_IOT()) {
      if (!callback_.is_null()) {
        CancelNow(callback_);
        callback_.Reset();
      }
    } else {
      CEF_POST_TASK(CEF_IOT, base::Bind(&CefAuthCallbackImpl::Cancel, this));
    }
  }

  void Disconnect() {
    callback_.Reset();
  }

 private:
  static void CancelNow(const net::NetworkDelegate::AuthCallback& callback) {
    CEF_REQUIRE_IOT();
    callback.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION);
  }

  net::NetworkDelegate::AuthCallback callback_;
  net::AuthCredentials* credentials_;

  IMPLEMENT_REFCOUNTING(CefAuthCallbackImpl);
};

}  // namespace

CefNetworkDelegate::CefNetworkDelegate() {
}

CefNetworkDelegate::~CefNetworkDelegate() {
}

int CefNetworkDelegate::OnBeforeURLRequest(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    GURL* new_url) {
  CefRefPtr<CefBrowserHostImpl> browser =
      CefBrowserHostImpl::GetBrowserForRequest(request);
  if (browser.get()) {
    CefRefPtr<CefClient> client = browser->GetClient();
    if (client.get()) {
      CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
      if (handler.get()) {
        CefRefPtr<CefFrame> frame = browser->GetFrameForRequest(request);

        GURL old_url = request->url();

        // Populate the request data.
        CefRefPtr<CefRequestImpl> requestPtr(new CefRequestImpl());
        requestPtr->Set(request);

        // Give the client an opportunity to cancel the request.
        if (handler->OnBeforeResourceLoad(browser.get(), frame,
            requestPtr.get())) {
          return net::ERR_ABORTED;
        }

        GURL url = GURL(std::string(requestPtr->GetURL()));
        if (old_url != url)
          new_url ->Swap(&url);

        requestPtr->Get(request);
      }
    }
  }

  return net::OK;
}

int CefNetworkDelegate::OnBeforeSendHeaders(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    net::HttpRequestHeaders* headers) {
  return net::OK;
}

void CefNetworkDelegate::OnSendHeaders(
    net::URLRequest* request,
    const net::HttpRequestHeaders& headers) {
}

int CefNetworkDelegate::OnHeadersReceived(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    const net::HttpResponseHeaders* original_response_headers,
    scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
  return net::OK;
}

void CefNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
                                          const GURL& new_location) {
}

void CefNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
}

void CefNetworkDelegate::OnRawBytesRead(const net::URLRequest& request,
                                        int bytes_read) {
}

void CefNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) {
}

void CefNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
}

void CefNetworkDelegate::OnPACScriptError(int line_number,
                                          const string16& error) {
}

net::NetworkDelegate::AuthRequiredResponse CefNetworkDelegate::OnAuthRequired(
    net::URLRequest* request,
    const net::AuthChallengeInfo& auth_info,
    const AuthCallback& callback,
    net::AuthCredentials* credentials) {
  CefRefPtr<CefBrowserHostImpl> browser =
      CefBrowserHostImpl::GetBrowserForRequest(request);
  if (browser.get()) {
    CefRefPtr<CefClient> client = browser->GetClient();
    if (client.get()) {
      CefRefPtr<CefRequestHandler> handler = client->GetRequestHandler();
      if (handler.get()) {
        CefRefPtr<CefFrame> frame = browser->GetFrameForRequest(request);

        CefRefPtr<CefAuthCallbackImpl> callbackPtr(
            new CefAuthCallbackImpl(callback, credentials));
        if (handler->GetAuthCredentials(browser.get(),
                                        frame,
                                        auth_info.is_proxy,
                                        auth_info.challenger.host(),
                                        auth_info.challenger.port(),
                                        auth_info.realm,
                                        auth_info.scheme,
                                        callbackPtr.get())) {
          return AUTH_REQUIRED_RESPONSE_IO_PENDING;
        } else {
          callbackPtr->Disconnect();
        }
      }
    }
  }

  return AUTH_REQUIRED_RESPONSE_NO_ACTION;
}

bool CefNetworkDelegate::OnCanGetCookies(const net::URLRequest& request,
                                         const net::CookieList& cookie_list) {
  return true;
}

bool CefNetworkDelegate::OnCanSetCookie(const net::URLRequest& request,
                                        const std::string& cookie_line,
                                        net::CookieOptions* options) {
  return true;
}

bool CefNetworkDelegate::OnCanAccessFile(const net::URLRequest& request,
                                         const FilePath& path) const {
  return true;
}

bool CefNetworkDelegate::OnCanThrottleRequest(
    const net::URLRequest& request) const {
  return false;
}

int CefNetworkDelegate::OnBeforeSocketStreamConnect(
    net::SocketStream* socket,
    const net::CompletionCallback& callback) {
  return net::OK;
}

void CefNetworkDelegate::OnRequestWaitStateChange(const net::URLRequest& request,
                                                  RequestWaitState state) {
}


text:
struct AutocompleteLog;
struct AutocompleteMatch;
class AutocompleteResult;
class HistoryService;
class PredictorsHandler;
class Profile;

namespace history {
class URLDatabase;
}

namespace predictors {

// This class is responsible for determining the correct predictive network
// action to take given for a given AutocompleteMatch and entered text. it uses
// a AutocompleteActionPredictorTable accessed asynchronously on the DB thread
// to permanently store the data used to make predictions, and keeps local
// caches of that data to be able to make predictions synchronously on the UI
// thread where it lives. It can be accessed as a weak pointer so that it can
// safely use PostTaskAndReply without fear of crashes if it is destroyed before
// the reply triggers. This is necessary during initialization.
class AutocompleteActionPredictor
    : public ProfileKeyedService,
      public content::NotificationObserver,
      public base::SupportsWeakPtr<AutocompleteActionPredictor> {
 public:
  enum Action {
    ACTION_PRERENDER = 0,
    ACTION_PRECONNECT,
    ACTION_NONE,
    LAST_PREDICT_ACTION = ACTION_NONE
  };

  explicit AutocompleteActionPredictor(Profile* profile);
  virtual ~AutocompleteActionPredictor();

  static void set_hit_weight(double weight) { hit_weight_ = weight; }
  static double get_hit_weight() { return hit_weight_; }

  // Registers an AutocompleteResult for a given |user_text|. This will be used
  // when the user navigates from the Omnibox to determine early opportunities
  // to predict their actions.
  void RegisterTransitionalMatches(const string16& user_text,
                                   const AutocompleteResult& result);

  // Clears any transitional matches that have been registered. Called when, for
  // example, the AutocompleteEditModel is reverted.
  void ClearTransitionalMatches();

  // Return the recommended action given |user_text|, the text the user has
  // entered in the Omnibox, and |match|, the suggestion from Autocomplete.
  // This method uses information from the ShortcutsBackend including how much
  // of the matching entry the user typed, and how long it's been since the user
  // visited the matching URL, to calculate a score between 0 and 1. This score
  // is then mapped to an Action.
  Action RecommendAction(const string16& user_text,
                         const AutocompleteMatch& match) const;

  // Return true if the suggestion type warrants a TCP/IP preconnection.
  // i.e., it is now quite likely that the user will select the related domain.
  static bool IsPreconnectable(const AutocompleteMatch& match);

 private:
  friend class AutocompleteActionPredictorTest;
  friend class ::PredictorsHandler;

  struct TransitionalMatch {
    TransitionalMatch();
    ~TransitionalMatch();

    string16 user_text;
    std::vector<GURL> urls;

    bool operator==(const string16& other_user_text) const {
      return user_text == other_user_text;
    }
  };

  struct DBCacheKey {
    string16 user_text;
    GURL url;

    bool operator<(const DBCacheKey& rhs) const {
      return (user_text != rhs.user_text) ?
          (user_text < rhs.user_text) :  (url < rhs.url);
    }

    bool operator==(const DBCacheKey& rhs) const {
      return (user_text == rhs.user_text) && (url == rhs.url);
    }
  };

  struct DBCacheValue {
    int number_of_hits;
    int number_of_misses;
  };

  typedef std::map<DBCacheKey, DBCacheValue> DBCacheMap;
  typedef std::map<DBCacheKey, AutocompleteActionPredictorTable::Row::Id>
      DBIdCacheMap;

  static const int kMaximumDaysToKeepEntry;

  // Multiplying factor applied to the |number_of_hits| for a database entry
  // when calculating the confidence. It is currently set by a field trial so is
  // static. Once the field trial ends, this will be a constant value.
  static double hit_weight_;

  // NotificationObserver
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // Called when NOTIFICATION_OMNIBOX_OPENED_URL is observed.
  void OnOmniboxOpenedUrl(const AutocompleteLog& log);

  // Deletes any old or invalid entries from the local caches. |url_db| and
  // |id_list| must not be NULL. Every row id deleted will be added to id_list.
  void DeleteOldIdsFromCaches(
      history::URLDatabase* url_db,
      std::vector<AutocompleteActionPredictorTable::Row::Id>* id_list);

  // Called to delete any old or invalid entries from the database. Called after
  // the local caches are created once the history service is available.
  void DeleteOldEntries(history::URLDatabase* url_db);

  // Called to populate the local caches. This also calls DeleteOldEntries
  // if the history service is available, or registers for the notification of
  // it becoming available.
  void CreateCaches(
      std::vector<AutocompleteActionPredictorTable::Row>* row_buffer);

  // Attempts to call DeleteOldEntries if the in-memory database has been loaded
  // by |service|. Returns success as a boolean.
  bool TryDeleteOldEntries(HistoryService* service);

  // Uses local caches to calculate an exact percentage prediction that the user
  // will take a particular match given what they have typed. |is_in_db| is set
  // to differentiate trivial zero results resulting from a match not being
  // found from actual zero results where the calculation returns 0.0.
  double CalculateConfidence(const string16& user_text,
                             const AutocompleteMatch& match,
                             bool* is_in_db) const;

  // Calculates the confidence for an entry in the DBCacheMap.
  double CalculateConfidenceForDbEntry(DBCacheMap::const_iterator iter) const;

  // Adds and updates rows in the database and caches.
  void AddAndUpdateRows(
    const AutocompleteActionPredictorTable::Rows& rows_to_add,
    const AutocompleteActionPredictorTable::Rows& rows_to_update);

  // Removes all rows from the database and caches.
  void DeleteAllRows();

  // Removes rows from the database and caches that contain a URL in |rows|.
  void DeleteRowsWithURLs(const history::URLRows& rows);

  Profile* profile_;
  scoped_refptr<AutocompleteActionPredictorTable> table_;
  content::NotificationRegistrar notification_registrar_;

  // This is cleared after every Omnibox navigation.
  std::vector<TransitionalMatch> transitional_matches_;

  // This allows us to predict the effect of confidence threshold changes on
  // accuracy.
  mutable std::vector<std::pair<GURL, double> > tracked_urls_;

  DBCacheMap db_cache_;
  DBIdCacheMap db_id_cache_;

  bool initialized_;

  DISALLOW_COPY_AND_ASSIGN(AutocompleteActionPredictor);
};

}  // namespace predictors

#endif  // CHROME_BROWSER_PREDICTORS_AUTOCOMPLETE_ACTION_PREDICTOR_H_

redpajama_set_name: RedPajamaGithub


text:
Resumis is _Esperanto_ for "summarized". It's also an API and headless CMS for your
personal web presence, a CV generator, and JSON Resume provider.

### Requirements
* Ruby 2.6
* PostgreSQL 9.3+ with development dependencies
* Node.js 10+
* `wkhtmltopdf`. 0.12.5 recommended. Anything lower has known issues. Will use a binary specified by `WKHTMLTOPDF_PATH` or defaults to `/usr/local/bin/wkhtmltopdf`.
* `imagemagick`
* Redis for Sidekiq.
* SMTP server (Production is configured to use SendGrid with credentials set by environmental variables `SENDGRID_USERNAME`, `SENDGRID_PASSWORD`, and `SENDGRID_DOMAIN`). It's only used by Devise for things like password resets, or confirmation emails. This is not a hard dependency and certainly not needed for development.

and others. See [Gemfile](Gemfile).

### Installation & Setup

* Clone the repo

  ```
  $ git clone git@github.com:maxfierke/resumis.git && cd resumis
  ```

* Install dependencies with Bundler

  ```
  $ bundle install
  ```
* See [Configuration](#Configuration) below and set any needed environment variables. In development, put them in `.env`.

* Create the database, run the migrations

  ```
  $ rake db:create db:migrate
  ```

* Run the app using [foreman](https://github.com/ddollar/foreman) or [forego](https://github.com/ddollar/forego)

  ```
  $ foreman start
  ```

* Create a user for yourself

  ```
  $ rake resumis:useradd -- -e {EMAIL} -p {PASSWORD} -f {FIRST_NAME} -l {LAST_NAME} -d {DOMAIN_NAME} --admin
  ```

* Go to [localhost:5000](http:/localhost:5000) to log into the management interface.

#### Configuration

Resumis-specific configuration can be done either through the `config/initializers/resumis.rb` initializer file, or through a some environmental variables.

* `SECRET_KEY_BASE` - Generate a value via `rake secret`.
* `RESUMIS_DEVISE_SECRET` - Generate a value via `rake secret`.
* `RESUMIS_MAIL_SENDER` - `From:` address for emails sent by Resumis (password resets, confirmations, etc.)
* `RESUMIS_CANONICAL_HOST` - Canonical hostname.

#### Deploying in Production (preferred)

* [Deploying with Docker](https://github.com/maxfierke/resumis/wiki/Running-Resumis-in-production-with-Docker)

## LICENSE

Apache License 2.0. See LICENSE


text:
import mock
import pytest
from django.core import mail

from keybar.models.user import User
from keybar.tests.factories.user import UserFactory

@pytest.mark.django_db
class TestUserModel:

    def setup(self):
        self.user = UserFactory.create()

    def test_send_email(self):
        self.user.send_mail('subject', 'message')

        assert len(mail.outbox) == 1
        message = mail.outbox[0]

        assert message.subject == 'subject'
        assert message.to == [self.user.email]
        assert message.body == 'message'

    @mock.patch('keybar.models.user.send_mail_async.delay')
    def test_send_mail_called_async(self, send_mail_async):
        self.user.send_mail('subject', 'message')
        send_mail_async.assert_called_once_with('subject', 'message',
            mock.ANY, [self.user.email])

    @mock.patch('keybar.tasks.mail.django_send_mail')
    @mock.patch('keybar.models.user.send_mail_async.retry')
    def test_send_mail_retried_on_error(self, retry, django_send_mail):
        django_send_mail.side_effect = Exception()
        self.user.send_mail('subject', 'message')
        retry.assert_called_once_with(retry_countdown=60, exc=mock.ANY)

    def test_short_name(self):
        assert self.user.get_short_name() == self.user.email

    def test_check_password(self):
        user = User()
        user.set_password('test')
        assert user.check_password('test')

    def test_check_password_unicode(self):
        user = User()
        user.set_password('winter is coming ☃❄')
        assert user.check_password('winter is coming ☃❄')


text:
/**
 * The actual js entry point from the HTML page; just triggers game setup and start on load
 */
$(function() {
    UI.init();
});


text:
Django Not-Or-Hot
###################

Reusable app to build "Hot or Not" / "KittenWar" type websites

Installation
============

We'll package this and release it to PyPi eventually, but for now, use::

   pip install -e git+https://github.com/sbnoemi/notorhot.git@master#egg=django-notorhot

Configuration
=============

In settings.py, update INSTALLED_APPS to include::

   INSTALLED_APPS = (
      ...
      'model_utils',
      'sorl.thumbnail',
      'notorhot',
      ...
   )

Include django-notorhot's URLs in urls.py::

   urlpatterns = patterns('',
      ...
      url(r'^not-or-hot/',  include('notorhot.urls')),
      ...
   )

Populate Categories and Candidates via the admin panel; override templates as needed.

Dependencies
============

django-notorhot requires:

* `Django <https://www.djangoproject.com/>`_
* `Sorl Thumbnail <https://github.com/mariocesar/sorl-thumbnail>`_
* `Django Model Utils <https://bitbucket.org/carljm/django-model-utils/src>`_
* `PIL <https://pypi.python.org/pypi/PIL>`_ (deprecated) or `Pillow <https://pypi.python.org/pypi/Pillow/>`_ (recommended)
* `django-autoslug <https://pypi.python.org/pypi/django-autoslug>`_

Additionally, `South <https://pypi.python.org/pypi/South/>`_ is recommended but not required.

Documentation
=============

Documentation can be built using `Sphinx <http://sphinx-doc.org/>`_.  Please note that there is a bug in Sphinx Autodoc in v1.1 that prevents members of some classes (notably, ``notorhot.contrib.write_in.AbstractFieldTracker``) from being displayed in the documentation.  This bug appears to be fixed in Sphinx v1.2, but as of this writing, Sphinx v1.2 is still in beta.


text:
import cn from 'classnames';
import { bind } from 'decko';
import * as React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

import DatasetEntityDescriptionManager from 'features/descriptionManager/view/DatasetEntityDescriptionManager/DatasetEntityDescriptionManager';
import DatasetEntityTagsManager from 'features/tagsManager/view/DatasetEntityTagsManager/DatasetEntityTagsManager';
import WithCurrentUserActionsAccesses from 'shared/view/domain/WithCurrentUserActionsAccesses/WithCurrentUserActionsAccesses';
import { Dataset, DatasetType } from 'shared/models/Dataset';
import routes from 'shared/routes';

import DatasetBulkDeletion from './DatasetBulkDeletion/DatasetBulkDeletion';
import styles from './DatasetWidget.module.css';
import WithCopyTextIcon from 'shared/view/elements/WithCopyTextIcon/WithCopyTextIcon';

interface ILocalProps {
  dataset: Dataset;
}

type AllProps = ILocalProps;

class DatasetWidget extends React.PureComponent<AllProps> {
  public render() {
    const { dataset } = this.props;

    return (
      <WithCurrentUserActionsAccesses
        entityType="dataset"
        entityId={dataset.id}
        actions={['delete']}
      >
        {({ actionsAccesses }) => (
          <DatasetBulkDeletion
            id={dataset.id}
            isEnabled={actionsAccesses.delete}
          >
            {togglerForDeletion => (

                <Link
                  className={styles.dataset_link}
                  to={routes.datasetSummary.getRedirectPathWithCurrentWorkspace(
                    {
                      datasetId: dataset.id,
                    }
                  )}
                >

                        <WithCopyTextIcon
                          text={dataset.name}
                          onClick={this.preventRedirect}
                        >
                          {dataset.name}
                        </WithCopyTextIcon>

                          <DatasetEntityDescriptionManager
                            datasetId={dataset.id}
                            entityId={dataset.id}
                            entityType="dataset"
                            description={dataset.description}
                          />

                      <DatasetEntityTagsManager
                        id={dataset.id}
                        datasetId={dataset.id}
                        entityType="dataset"
                        tags={dataset.tags}
                        isDraggableTags={true}
                        onClick={this.onTagsManagerClick}
                      />

                      Type:{' '}
                      {(() => {
                        const valueType: Record<DatasetType, string> = {
                          path: 'Path',
                          query: 'Query',
                          raw: 'Raw',
                        };
                        return valueType[dataset.type];
                      })()}

                        Created: {dataset.dateCreated.toLocaleDateString()}

                        Updated: {dataset.dateUpdated.toLocaleDateString()}

                      {togglerForDeletion && (

                          {togglerForDeletion}

                      )}

                </Link>

            )}
          </DatasetBulkDeletion>
        )}
      </WithCurrentUserActionsAccesses>
    );
  }

  @bind
  private onTagsManagerClick(e: React.MouseEvent, byEmptiness: boolean) {
    if (!byEmptiness) {
      this.preventRedirect(e);
    }
  }

  @bind
  private preventRedirect(e: React.MouseEvent) {
    e.preventDefault();
  }
}

export default connect()(DatasetWidget);


text:
package org.apache.pulsar.broker.authentication;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.naming.AuthenticationException;
import lombok.Cleanup;
import org.apache.commons.codec.digest.Crypt;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.broker.authentication.metrics.AuthenticationMetrics;
import org.apache.pulsar.client.api.url.URL;

public class AuthenticationProviderBasic implements AuthenticationProvider {
    private static final String HTTP_HEADER_NAME = "Authorization";
    private static final String CONF_SYSTEM_PROPERTY_KEY = "pulsar.auth.basic.conf";
    private static final String CONF_PULSAR_PROPERTY_KEY = "basicAuthConf";
    private Map<String, String> users;

    @Override
    public void close() throws IOException {
        // noop
    }

    public static byte[] readData(String data)
            throws IOException, URISyntaxException, InstantiationException, IllegalAccessException {
        if (data.startsWith("data:") || data.startsWith("file:")) {
            return IOUtils.toByteArray(URL.createURL(data));
        } else if (Files.exists(Paths.get(data))) {
            return Files.readAllBytes(Paths.get(data));
        } else if (org.apache.commons.codec.binary.Base64.isBase64(data)) {
            return Base64.getDecoder().decode(data);
        } else {
            String msg = "Not supported config";
            throw new IllegalArgumentException(msg);
        }
    }

    @Override
    public void initialize(ServiceConfiguration config) throws IOException {
        String data = config.getProperties().getProperty(CONF_PULSAR_PROPERTY_KEY);
        if (StringUtils.isEmpty(data)) {
            data = System.getProperty(CONF_SYSTEM_PROPERTY_KEY);
        }
        if (StringUtils.isEmpty(data)) {
            throw new IOException("No basic authentication config provided");
        }

        @Cleanup BufferedReader reader = null;
        try {
            byte[] bytes = readData(data);
            reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }

        users = new HashMap<>();
        for (String line : reader.lines().toArray(s -> new String[s])) {
            List<String> splitLine = Arrays.asList(line.split(":"));
            if (splitLine.size() != 2) {
                throw new IOException("The format of the password auth conf file is invalid");
            }
            users.put(splitLine.get(0), splitLine.get(1));
        }
    }

    @Override
    public String getAuthMethodName() {
        return "basic";
    }

    @Override
    public String authenticate(AuthenticationDataSource authData) throws AuthenticationException {
        AuthParams authParams = new AuthParams(authData);
        String userId = authParams.getUserId();
        String password = authParams.getPassword();
        String msg = "Unknown user or invalid password";

        try {
            if (users.get(userId) == null) {
                throw new AuthenticationException(msg);
            }

            String encryptedPassword = users.get(userId);

            // For md5 algorithm
            if ((users.get(userId).startsWith("$apr1"))) {
                List<String> splitEncryptedPassword = Arrays.asList(encryptedPassword.split("\\$"));
                if (splitEncryptedPassword.size() != 4 || !encryptedPassword
                        .equals(Md5Crypt.apr1Crypt(password.getBytes(), splitEncryptedPassword.get(2)))) {
                    throw new AuthenticationException(msg);
                }
                // For crypt algorithm
            } else if (!encryptedPassword.equals(Crypt.crypt(password.getBytes(), encryptedPassword.substring(0, 2)))) {
                throw new AuthenticationException(msg);
            }
        } catch (AuthenticationException exception) {
            AuthenticationMetrics.authenticateFailure(getClass().getSimpleName(), getAuthMethodName(),
                    exception.getMessage());
            throw exception;
        }
        AuthenticationMetrics.authenticateSuccess(getClass().getSimpleName(), getAuthMethodName());
        return userId;
    }

    private class AuthParams {
        private String userId;
        private String password;

        public AuthParams(AuthenticationDataSource authData) throws AuthenticationException {
            String authParams;
            if (authData.hasDataFromCommand()) {
                authParams = authData.getCommandData();
            } else if (authData.hasDataFromHttp()) {
                String rawAuthToken = authData.getHttpHeader(HTTP_HEADER_NAME);
                // parsing and validation
                if (StringUtils.isBlank(rawAuthToken) || !rawAuthToken.toUpperCase().startsWith("BASIC ")) {
                    throw new AuthenticationException("Authentication token has to be started with \"Basic \"");
                }
                String[] splitRawAuthToken = rawAuthToken.split(" ");
                if (splitRawAuthToken.length != 2) {
                    throw new AuthenticationException("Base64 encoded token is not found");
                }

                try {
                    authParams = new String(Base64.getDecoder().decode(splitRawAuthToken[1]));
                } catch (Exception e) {
                    throw new AuthenticationException("Base64 decoding is failure: " + e.getMessage());
                }
            } else {
                throw new AuthenticationException("Authentication data source does not have data");
            }

            String[] parsedAuthParams = authParams.split(":");
            if (parsedAuthParams.length != 2) {
                throw new AuthenticationException("Base64 decoded params are invalid");
            }

            userId = parsedAuthParams[0];
            password = parsedAuthParams[1];
        }

        public String getUserId() {
            return userId;
        }

        public String getPassword() {
            return password;
        }
    }
}


text:
var cdb = require('cartodb.js');
var Backbone = require('backbone');

/**
 *  Collection with all fields model
 *  included.
 *
 */

module.exports = Backbone.Collection.extend({

  isValid: function() {
    return !this.getInvalid();
  },

  getInvalid: function() {
    return this.find(function(mdl) {
      return !mdl.isValid()
    });
  }

})


text:
"""The tests for the Modbus light component."""
from pymodbus.exceptions import ModbusException
import pytest

from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.modbus.const import (
    CALL_TYPE_COIL,
    CALL_TYPE_DISCRETE,
    CALL_TYPE_REGISTER_HOLDING,
    CALL_TYPE_REGISTER_INPUT,
    CONF_INPUT_TYPE,
    CONF_STATE_OFF,
    CONF_STATE_ON,
    CONF_VERIFY,
    CONF_WRITE_TYPE,
    MODBUS_DOMAIN,
)
from homeassistant.const import (
    CONF_ADDRESS,
    CONF_COMMAND_OFF,
    CONF_COMMAND_ON,
    CONF_HOST,
    CONF_LIGHTS,
    CONF_NAME,
    CONF_PORT,
    CONF_SLAVE,
    CONF_TYPE,
    STATE_OFF,
    STATE_ON,
    STATE_UNAVAILABLE,
)
from homeassistant.core import State
from homeassistant.setup import async_setup_component

from .conftest import ReadResult, base_config_test, base_test, prepare_service_update

from tests.common import mock_restore_cache

@pytest.mark.parametrize(
    "do_config",
    [
        {
            CONF_ADDRESS: 1234,
        },
        {
            CONF_ADDRESS: 1234,
            CONF_WRITE_TYPE: CALL_TYPE_COIL,
        },
        {
            CONF_ADDRESS: 1234,
            CONF_SLAVE: 1,
            CONF_COMMAND_OFF: 0x00,
            CONF_COMMAND_ON: 0x01,
            CONF_VERIFY: {
                CONF_INPUT_TYPE: CALL_TYPE_REGISTER_HOLDING,
                CONF_ADDRESS: 1235,
                CONF_STATE_OFF: 0,
                CONF_STATE_ON: 1,
            },
        },
        {
            CONF_ADDRESS: 1234,
            CONF_SLAVE: 1,
            CONF_COMMAND_OFF: 0x00,
            CONF_COMMAND_ON: 0x01,
            CONF_VERIFY: {
                CONF_INPUT_TYPE: CALL_TYPE_REGISTER_INPUT,
                CONF_ADDRESS: 1235,
                CONF_STATE_OFF: 0,
                CONF_STATE_ON: 1,
            },
        },
        {
            CONF_ADDRESS: 1234,
            CONF_SLAVE: 1,
            CONF_COMMAND_OFF: 0x00,
            CONF_COMMAND_ON: 0x01,
            CONF_VERIFY: {
                CONF_INPUT_TYPE: CALL_TYPE_DISCRETE,
                CONF_ADDRESS: 1235,
                CONF_STATE_OFF: 0,
                CONF_STATE_ON: 1,
            },
        },
        {
            CONF_ADDRESS: 1234,
            CONF_SLAVE: 1,
            CONF_COMMAND_OFF: 0x00,
            CONF_COMMAND_ON: 0x01,
            CONF_VERIFY: None,
        },
    ],
)
async def test_config_light(hass, do_config):
    """Run test for light."""
    device_name = "test_light"

    device_config = {
        CONF_NAME: device_name,
        **do_config,
    }

    await base_config_test(
        hass,
        device_config,
        device_name,
        LIGHT_DOMAIN,
        CONF_LIGHTS,
        None,
        method_discovery=True,
    )

@pytest.mark.parametrize("call_type", [CALL_TYPE_COIL, CALL_TYPE_REGISTER_HOLDING])
@pytest.mark.parametrize(
    "regs,verify,expected",
    [
        (
            [0x00],
            {CONF_VERIFY: {}},
            STATE_OFF,
        ),
        (
            [0x01],
            {CONF_VERIFY: {}},
            STATE_ON,
        ),
        (
            [0xFE],
            {CONF_VERIFY: {}},
            STATE_OFF,
        ),
        (
            None,
            {CONF_VERIFY: {}},
            STATE_UNAVAILABLE,
        ),
        (
            None,
            {},
            STATE_OFF,
        ),
    ],
)
async def test_all_light(hass, call_type, regs, verify, expected):
    """Run test for given config."""
    light_name = "modbus_test_light"
    state = await base_test(
        hass,
        {
            CONF_NAME: light_name,
            CONF_ADDRESS: 1234,
            CONF_SLAVE: 1,
            CONF_WRITE_TYPE: call_type,
            **verify,
        },
        light_name,
        LIGHT_DOMAIN,
        CONF_LIGHTS,
        None,
        regs,
        expected,
        method_discovery=True,
        scan_interval=5,
    )
    assert state == expected

async def test_restore_state_light(hass):
    """Run test for sensor restore state."""

    light_name = "test_light"
    entity_id = f"{LIGHT_DOMAIN}.{light_name}"
    test_value = STATE_ON
    config_light = {CONF_NAME: light_name, CONF_ADDRESS: 17}
    mock_restore_cache(
        hass,
        (State(f"{entity_id}", test_value),),
    )
    await base_config_test(
        hass,
        config_light,
        light_name,
        LIGHT_DOMAIN,
        CONF_LIGHTS,
        None,
        method_discovery=True,
    )
    assert hass.states.get(entity_id).state == test_value

async def test_light_service_turn(hass, caplog, mock_pymodbus):
    """Run test for service turn_on/turn_off."""

    entity_id1 = f"{LIGHT_DOMAIN}.light1"
    entity_id2 = f"{LIGHT_DOMAIN}.light2"
    config = {
        MODBUS_DOMAIN: {
            CONF_TYPE: "tcp",
            CONF_HOST: "modbusTestHost",
            CONF_PORT: 5501,
            CONF_LIGHTS: [
                {
                    CONF_NAME: "light1",
                    CONF_ADDRESS: 17,
                    CONF_WRITE_TYPE: CALL_TYPE_REGISTER_HOLDING,
                },
                {
                    CONF_NAME: "light2",
                    CONF_ADDRESS: 17,
                    CONF_WRITE_TYPE: CALL_TYPE_REGISTER_HOLDING,
                    CONF_VERIFY: {},
                },
            ],
        },
    }
    assert await async_setup_component(hass, MODBUS_DOMAIN, config) is True
    await hass.async_block_till_done()
    assert MODBUS_DOMAIN in hass.config.components

    assert hass.states.get(entity_id1).state == STATE_OFF
    await hass.services.async_call(
        "light", "turn_on", service_data={"entity_id": entity_id1}
    )
    await hass.async_block_till_done()
    assert hass.states.get(entity_id1).state == STATE_ON
    await hass.services.async_call(
        "light", "turn_off", service_data={"entity_id": entity_id1}
    )
    await hass.async_block_till_done()
    assert hass.states.get(entity_id1).state == STATE_OFF

    mock_pymodbus.read_holding_registers.return_value = ReadResult([0x01])
    assert hass.states.get(entity_id2).state == STATE_OFF
    await hass.services.async_call(
        "light", "turn_on", service_data={"entity_id": entity_id2}
    )
    await hass.async_block_till_done()
    assert hass.states.get(entity_id2).state == STATE_ON
    mock_pymodbus.read_holding_registers.return_value = ReadResult([0x00])
    await hass.services.async_call(
        "light", "turn_off", service_data={"entity_id": entity_id2}
    )
    await hass.async_block_till_done()
    assert hass.states.get(entity_id2).state == STATE_OFF

    mock_pymodbus.write_register.side_effect = ModbusException("fail write_")
    await hass.services.async_call(
        "light", "turn_on", service_data={"entity_id": entity_id2}
    )
    await hass.async_block_till_done()
    assert hass.states.get(entity_id2).state == STATE_UNAVAILABLE
    mock_pymodbus.write_coil.side_effect = ModbusException("fail write_")
    await hass.services.async_call(
        "light", "turn_off", service_data={"entity_id": entity_id1}
    )
    await hass.async_block_till_done()
    assert hass.states.get(entity_id1).state == STATE_UNAVAILABLE

async def test_service_light_update(hass, mock_pymodbus):
    """Run test for service homeassistant.update_entity."""

    entity_id = "light.test"
    config = {
        CONF_LIGHTS: [
            {
                CONF_NAME: "test",
                CONF_ADDRESS: 1234,
                CONF_WRITE_TYPE: CALL_TYPE_COIL,
                CONF_VERIFY: {},
            }
        ]
    }
    mock_pymodbus.read_discrete_inputs.return_value = ReadResult([0x01])
    await prepare_service_update(
        hass,
        config,
    )
    await hass.services.async_call(
        "homeassistant", "update_entity", {"entity_id": entity_id}, blocking=True
    )
    assert hass.states.get(entity_id).state == STATE_ON
    mock_pymodbus.read_coils.return_value = ReadResult([0x00])
    await hass.services.async_call(
        "homeassistant", "update_entity", {"entity_id": entity_id}, blocking=True
    )
    assert hass.states.get(entity_id).state == STATE_OFF


text:
package org.cronhub.dispatchexecutor.crontab;

public class CronFileBinder {
}


text:
@font-face {
  font-family: "Hack";
  src: url("../fonts/Hack-Regular.ttf"); }

@font-face {
  font-family: "Webly Sleek";
  src: url("../fonts/weblysleekuil.ttf"); }

* {
  outline: none;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
  margin: 0px;
  padding: 0px;
  overflow: hidden;
  transition-duration: 400ms;
  font-family: "Webly Sleek"; }

::selection {
  background: #00AAAA; }

html, body, #container {
  height: 100%;
  width: 100%; }

body {
  background-color: #171717; }

.btn {
  cursor: pointer; }

@keyframes loading {
  from {
    background-position: 0 0; }
  to {
    background-position: 200px 100px; } }

#header {
  transition-duration: 0s;
  height: 90px;
  width: 100%;
  background-color: #151515;
  box-shadow: 0px 0px 10px;
  -webkit-app-region: drag; }
  #header.loading {
    background-size: 100px 100px;
    background-image: linear-gradient(45deg, rgba(0, 0, 0, 0.1) 25%, transparent 25%, transparent 50%, rgba(0, 0, 0, 0.1) 50%, rgba(0, 0, 0, 0.1) 75%, transparent 75%, transparent);
    animation: loading 0.5s linear infinite; }
  #header #player {
    position: absolute;
    top: 10px;
    left: 10px;
    display: inline-flex;
    z-index: 2;
    overflow: initial; }
    #header #player .player-btn {
      width: 10px;
      position: relative;
      opacity: 0.6; }
      #header #player .player-btn:hover {
        transform: scale(1.1);
        opacity: 1; }
      #header #player .player-btn img {
        width: 100%;
        position: absolute;
        top: 50%;
        transform: translateY(-50%); }
    #header #player #prev-btn {
      height: 40px;
      top: 20px;
      margin-right: 5px; }
    #header #player #next-btn {
      height: 60px;
      width: 20px;
      margin-left: 5px;
      top: 10px; }
      #header #player #next-btn:hover {
        margin-left: 8px; }
    #header #player #cover-wrap {
      background: #151515;
      box-shadow: 0px 0px 10px;
      border-radius: 3px;
      width: 80px; }
      #header #player #cover-wrap #cover {
        width: 80px;
        height: 80px; }
        #header #player #cover-wrap #cover #cover-image {
          position: absolute;
          height: inherit;
          border-top-left-radius: 3px;
          border-top-right-radius: 3px;
          z-index: 2;
          width: 80px;
          height: 80px; }
        #header #player #cover-wrap #cover #play-btn {
          position: absolute;
          height: inherit;
          width: 80px;
          background: black;
          z-index: 3;
          border-top-left-radius: 3px;
          border-top-right-radius: 3px; }
          #header #player #cover-wrap #cover #play-btn #pause-img {
            width: 40px;
            height: 40px;
            margin-left: 20px;
            margin-top: 20px; }
            #header #player #cover-wrap #cover #play-btn #pause-img.zoomed {
              margin-top: -10px;
              margin-left: -10px;
              width: 100px;
              height: 100px;
              opacity: 0; }
      #header #player #cover-wrap #seek-section {
        position: relative;
        width: 100%;
        height: 10px; }
        #header #player #cover-wrap #seek-section #vis {
          position: absolute;
          width: 100%;
          height: inherit;
          border-bottom-left-radius: 3px;
          border-bottom-right-radius: 3px; }
        #header #player #cover-wrap #seek-section #seek-bar {
          cursor: pointer;
          position: absolute;
          height: inherit;
          width: 100%;
          border-bottom-left-radius: 3px;
          border-bottom-right-radius: 3px; }
      #header #player #cover-wrap .ui-slider-range {
        background: #00AAAA;
        opacity: 0.4;
        height: 100%;
        border-bottom-left-radius: 3px;
        border-bottom-right-radius: 3px; }
      #header #player #cover-wrap .ui-slider .ui-slider-handle {
        width: 2px;
        height: 10px;
        background: #00AAAA;
        position: absolute;
        top: 0px; }
  #header #info-text {
    position: absolute;
    top: 25px;
    left: 150px;
    color: #eee;
    white-space: nowrap;
    overflow: hidden; }
    #header #info-text #track-name {
      font-size: 20px; }
    #header #info-text #artist-name {
      color: #949494;
      font-weight: bold;
      font-size: 13px; }

#metadata-wrap {
  display: none;
  position: fixed;
  top: 0px;
  bottom: 35px;
  left: 0px;
  right: 0px;
  z-index: 100;
  background-color: rgba(23, 23, 23, 0.8);
  transition-duration: 0s; }
  #metadata-wrap #metadata {
    position: absolute;
    top: 40%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    width: 500px; }
    #metadata-wrap #metadata #confirm-metadata {
      height: 50px;
      padding-top: 5px;
      text-align: center;
      font-size: 15px;
      color: #949494; }
      #metadata-wrap #metadata #confirm-metadata .key-btn {
        border-style: solid;
        border-width: 1px;
        border-radius: 5px;
        font-family: "Hack";
        font-size: 14px;
        padding: 3px;
        padding-left: 7px;
        padding-right: 7px; }
    #metadata-wrap #metadata .metadata-label {
      text-align: right;
      color: #00AAAA;
      font-size: 16px; }
    #metadata-wrap #metadata input {
      font-size: 40px;
      width: 100%;
      color: #eee;
      background: transparent;
      border-width: 0px;
      border-bottom-width: 1px;
      border-style: solid;
      border-color: #00AAAA; }

#scatter {
  position: absolute;
  top: 90px;
  bottom: 35px;
  left: 0px;
  right: 0px; }
  #scatter #hover-info {
    position: absolute;
    margin-left: 10px;
    margin-top: 10px;
    font-size: 11px;
    color: #949494;
    pointer-events: none;
    transition-duration: 100ms; }
    #scatter #hover-info #hover-artist {
      font-size: 12px; }
  #scatter #scatter-overlay {
    position: absolute;
    top: 0px;
    left: 0px;
    pointer-events: none;
    z-index: 1; }
    #scatter #scatter-overlay circle {
      transition-duration: 0s;
      fill: none;
      stroke: #00AAAA; }
    #scatter #scatter-overlay circle.similar {
      fill: #00AAAA;
      opacity: 0.2;
      stroke: none; }
    #scatter #scatter-overlay circle.hover {
      stroke-width: 4; }
    #scatter #scatter-overlay circle.current {
      stroke-width: 1; }
      #scatter #scatter-overlay circle.current#inner {
        stroke-width: 2; }

#footer {
  position: absolute;
  bottom: 0px;
  width: 100%;
  height: 35px;
  background-color: #151515;
  box-shadow: 0px 0px 10px; }
  #footer .fa-stack .fa-stack-2x {
    color: transparent; }
  #footer .fa-stack .fa-stack-1x {
    color: #00AAAA; }
    #footer .fa-stack .fa-stack-1x.disabled {
      color: rgba(148, 148, 148, 0.5); }
  #footer #command-line {
    float: left;
    width: 50%;
    height: inherit; }
    #footer #command-line input {
      border: none;
      background-color: transparent;
      font-family: "Hack";
      color: #eee;
      width: inherit;
      font-size: 11px; }
  #footer #status-line {
    text-align: right;
    float: right;
    height: inherit;
    display: inline-flex; }
    #footer #status-line #mode {
      font-family: "Hack";
      color: #949494;
      font-size: 15px;
      padding: 4px;
      letter-spacing: 5px;
      font-variant: small-caps; }
  #footer #foot-line {
    position: absolute;
    bottom: 0px;
    height: 3px;
    background-color: #00AAAA;
    width: 100%; }
    #footer #foot-line.error {
      background-color: #f00; }
    #footer #foot-line.ok {
      background-color: #3DD342; }


text:
from canvasapi.canvas_object import CanvasObject

class ContentExport(CanvasObject):
    def __str__(self):
        return "{} {} ({})".format(self.export_type, self.user_id, self.id)


text:
package com.orientechnologies.orient.core.metadata.schema;

import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.schema.clusterselection.OClusterSelectionFactory;
import com.orientechnologies.orient.core.type.ODocumentWrapper;

import java.util.Collection;
import java.util.List;
import java.util.Set;

public interface OSchema {

  public int countClasses();

  public OClass createClass(final Class<?> iClass);

  public OClass createClass(final Class<?> iClass, final int iDefaultClusterId);

  public OClass createClass(final String iClassName);

  public OClass createClass(final String iClassName, final OClass iSuperClass);

  public OClass createClass(final String iClassName, final int iDefaultClusterId);

  public OClass createClass(final String iClassName, final OClass iSuperClass, final int iDefaultClusterId);

  public OClass createClass(final String iClassName, final OClass iSuperClass, final int[] iClusterIds);

  public OClass createAbstractClass(final Class<?> iClass);

  public OClass createAbstractClass(final String iClassName);

  public OClass createAbstractClass(final String iClassName, final OClass iSuperClass);

  public void dropClass(final String iClassName);

  public <RET extends ODocumentWrapper> RET reload();

  public boolean existsClass(final String iClassName);

  public OClass getClass(final Class<?> iClass);

  /**
   * Returns the OClass instance by class name.
   *
   * If the class is not configured and the database has an entity manager with the requested class as registered, then creates a
   * schema class for it at the fly.
   *
   * If the database nor the entity manager have not registered class with specified name, returns null.
   *
   * @param iClassName
   *          Name of the class to retrieve
   * @return class instance or null if class with given name is not configured.
   */
  public OClass getClass(final String iClassName);

  public OClass getOrCreateClass(final String iClassName);

  public OClass getOrCreateClass(final String iClassName, final OClass iSuperClass);

  public Collection<OClass> getClasses();

  public void create();

  @Deprecated
  public int getVersion();

  public ORID getIdentity();

  /**
   * Do nothing. Starting from 1.0rc2 the schema is auto saved!
   *
   * @COMPATIBILITY 1.0rc1
   */
  @Deprecated
  public <RET extends ODocumentWrapper> RET save();

  /**
   * Returns all the classes that rely on a cluster
   *
   * @param iClusterName
   *          Cluster name
   */
  public Set<OClass> getClassesRelyOnCluster(String iClusterName);

  public OClass getClassByClusterId(int clusterId);

  public OGlobalProperty getGlobalPropertyById(int id);

  public List<OGlobalProperty> getGlobalProperties();

  public OGlobalProperty createGlobalProperty(String name, OType type, Integer id);

  public OClusterSelectionFactory getClusterSelectionFactory();

  public OImmutableSchema makeSnapshot();

  /**
   * IMPORTANT! Only for internal usage.
   */
  boolean isFullCheckpointOnChange();

  /**
   * IMPORTANT! Only for internal usage.
   */
  void setFullCheckpointOnChange(boolean fullCheckpointOnChange);
}


text:
var assert = require('assert');
var flyd = require('../../../lib');
var stream = flyd.stream;

var previous = require('../index.js');

describe('previous', function() {
  it('is always one value behind the source stream', function() {
    var s = stream(1);
    var p = previous(s);
    s(2)(3)(4);
    assert.equal(p(), 3);
  });

  it('starts streaming after the second value is pushed into the source stream', function() {
    var s = stream();
    var p = previous(s);
    var calls = 0;
    flyd.on(function() { calls += 1; }, p);
    s(1);
    assert.equal(calls, 0);
    s(2);
    assert.equal(calls, 1);
  });
});


text:
package play.db;

import com.typesafe.config.Config;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.sql.DataSource;
import play.Environment;
import play.api.db.DatabaseConfig;

/** Default delegating implementation of the connection pool API. */
@Singleton
public class DefaultConnectionPool implements ConnectionPool {

  private final play.api.db.ConnectionPool cp;

  @Inject
  public DefaultConnectionPool(play.api.db.ConnectionPool connectionPool) {
    this.cp = connectionPool;
  }

  public DataSource create(String name, Config config, Environment environment) {
    return cp.create(
        name,
        DatabaseConfig.fromConfig(new play.api.Configuration(config), environment.asScala()),
        config);
  }

  public void close(DataSource dataSource) {
    cp.close(dataSource);
  }

  @Override
  public play.api.db.ConnectionPool asScala() {
    return cp;
  }
}


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

// HTTP router used for receiving messages from users and sending responses.
const express = require('express');
const router = express.Router();
const moment = require('moment');

const {google} = require('googleapis');
const businessmessages = require('businessmessages');
const {v4: uuidv4} = require('uuid');

// Set the private key to the service account file
const privatekey = require('../resources/credentials.json');

// Initialize the Business Messages API
const bmApi =
  new businessmessages.businessmessages_v1.Businessmessages({});

// Set the scope that we need for the Business Messages API
const scopes = [
  'https://www.googleapis.com/auth/businessmessages',
];

// Reference to the backend datastore util
const datastoreUtil = require('../libs/datastore_util');

// Name of the brand
const BUSINESS_NAME = 'Acme Retail';

// Name of the CRM
const CRM_NAME = 'The Simple CRM (Acme Retail)';

// The possible states for who manages the conversation on behalf of the business
const BOT_THREAD_STATE = 'Bot';
const QUEUED_THREAD_STATE = 'Queued';
const LIVE_AGENT_THREAD_STATE = 'Live Agent';

/**
 * Main entry point to the CRM chat app.
 * Displays list of queued and active threads with users.
 */
router.get('/', function(req, res, next) {
  res.render('index', {title: CRM_NAME});
});

/**
 * Retrieves list of all active and queued threads, ordered by most recently updated.
 */
router.get('/retrieveThreads', function(req, res, next) {
  datastoreUtil.listMessageThreads((threads) => {
    // Convert lastUpdated date and time field into a nicely formatted value
    for (let i = 0; i < threads.length; i++) {
      threads[i].lastUpdated = moment(threads[i].lastUpdated).fromNow();
    }

    res.json({
      'threads': threads,
    });
  });
});

/**
 * Updates the thread state and sends a representative join signal to the user.
 */
router.post('/joinConversation', async function(req, res, next) {
  let conversationId = req.body.conversationId;

  await changeThreadState(conversationId, LIVE_AGENT_THREAD_STATE, 'REPRESENTATIVE_JOINED');

  res.json({
    'result': 'ok',
  });
});

/**
 * Updates the thread state and sends a representative left signal to the user.
 */
router.post('/leaveConversation', async function(req, res, next) {
  console.log("Leaving conversation...");

  let conversationId = req.body.conversationId;

  await changeThreadState(conversationId, BOT_THREAD_STATE, 'REPRESENTATIVE_LEFT');

  storeAndSendResponse('You are now speaking with the Echo Bot',
    conversationId, BOT_THREAD_STATE, 'BOT');

  res.json({
    'result': 'ok',
  });
});

/**
 * Displays the messages for a thread.
 */
router.get('/messages', function(req, res, next) {
  let conversationId = req.query.conversationId;

  datastoreUtil.getMessageThread(conversationId, (thread) => {
    res.render('messages', {title: CRM_NAME, thread: thread});
  });
});

/**
 * Retrieves list of all messages for a thread.
 */
router.get('/retrieveMessages', function(req, res, next) {
  let conversationId = req.query.conversationId;

  datastoreUtil.listMessages(conversationId, (messages) => {
    // Convert createdDate date and time field into a nicely formatted value
    for (let i = 0; i < messages.length; i++) {
      messages[i].createdDate = moment(messages[i].createdDate).fromNow();
    }
    res.json({
      'messages': messages,
    });
  });
});

/**
 * Sends a message from the CRM to the targetted user.
 */
router.post('/sendMessage', function(req, res, next) {
  let message = req.body.message;
  let conversationId = req.body.conversationId;

  storeAndSendResponse(message, conversationId, LIVE_AGENT_THREAD_STATE, 'HUMAN');

  res.json({
    'response': 'ok',
  });
});

/**
 * The webhook callback method.
 */
router.post('/callback', function(req, res, next) {
  let requestBody = req.body;

  // Extract the message payload parameters
  let conversationId = requestBody.conversationId;
  let messageId = requestBody.requestId;
  let agentName = requestBody.agent;
  let brandId = agentName.substr(agentName.indexOf('brands/') + 7,
    agentName.indexOf('/agents') - 7);
  let displayName = requestBody.context.userInfo.displayName;

  // Log message parameters
  console.log('conversationId: ' + conversationId);
  console.log('displayName: ' + displayName);
  console.log('brandId: ' + brandId);

  datastoreUtil.getMessageThread(conversationId, async function(thread) {
    let currentThreadState = BOT_THREAD_STATE;
    if (thread !== null) {
      currentThreadState = thread.state;
    }

    // Initialize object details that will be used to create thread and message records
    let threadAndMessage = {
      messageId: messageId,
      userType: 'User',
      displayName: displayName,
      brandId: brandId,
      conversationId: conversationId,
      state: currentThreadState,
    };

    // Check that the message and text values exist
    if ((requestBody.message !== undefined
      && requestBody.message.text !== undefined)) {
      let message = requestBody.message.text;

      console.log('message: ' + message);

      threadAndMessage.message = message;

      await storeMessage(threadAndMessage);

      // Only echo response if the bot has control of the conversation
      if (currentThreadState === BOT_THREAD_STATE) {
        storeAndSendResponse(message, conversationId, currentThreadState, 'BOT');
      }
    } else if (requestBody.suggestionResponse !== undefined) {
      let message = requestBody.suggestionResponse.text;

      console.log('message: ' + message);

      threadAndMessage.message = message;

      await storeMessage(threadAndMessage);

      // Only echo response if the bot has control of the conversation
      if (currentThreadState === BOT_THREAD_STATE) {
        storeAndSendResponse(message, conversationId, currentThreadState, 'BOT');
      }
    } else if (requestBody.userStatus !== undefined) {
      if (requestBody.userStatus.requestedLiveAgent !== undefined) {
        console.log('User requested transfer to live agent');

        queueThreadForLiveAgent(conversationId);
      }
    }
  });

  res.sendStatus(200);
});

/**
 * Updates the thread's state for a live agent and sends corresponding event
 * to the user through the Business Messages API.
 *
 * @param {string} conversationId The unique id for this user and agent.
 * @param {string} threadState The new state to assign to the thread.
 * @param {string} eventType The type of event to send as a representative
 */
async function changeThreadState(conversationId, threadState, eventType) {
  return new Promise((resolve, reject) => {
    datastoreUtil.getMessageThread(conversationId, async function(thread) {
      thread.state = threadState;

      datastoreUtil.saveThread(thread);

      let authClient = await initCredentials();

      // Create the payload for sending an event
      let apiEventParams = {
        auth: authClient,
        parent: 'conversations/' + conversationId,
        resource: {
          eventType: eventType,
          representative: getRepresentative('HUMAN'),
        },
        eventId: uuidv4(),
      };

      // Send the event
      bmApi.conversations.events.create(apiEventParams, {auth: authClient}, () => {
        resolve();
      });
    });
  });
}

/**
 * Updates the thread's state to be queued for a live agent to join.
 *
 * @param {string} conversationId The unique id for this user and agent.
 */
function queueThreadForLiveAgent(conversationId) {
  datastoreUtil.getMessageThread(conversationId, (thread) => {
    thread.state = QUEUED_THREAD_STATE;

    datastoreUtil.saveThread(thread);
  });
}

/**
 * Updates the thread, adds a new message and sends a response to the user.
 *
 * @param {string} message The message content that was received.
 * @param {string} conversationId The unique id for this user and agent.
 * @param {string} threadState Represents who is managing the conversation for the CRM.
 * @param {string} representativeType The representative sending the message, BOT or HUMAN.
 */
async function storeAndSendResponse(message, conversationId, threadState, representativeType) {
  let messageId = uuidv4();

  // Store the message
  await storeMessage({
    messageId: messageId,
    message: message,
    userType: 'CRM',
    displayName: BUSINESS_NAME,
    conversationId: conversationId,
    state: threadState,
  });

  // Send message to the user
  sendResponse({
    messageId: messageId,
    representative: getRepresentative(representativeType),
    text: message,
    containsRichText: true,
    fallback: message,
    suggestions: [
      {
        liveAgentRequest: {},
      },
    ],
  }, conversationId);
}

/**
 * Updates the thread and saves a new message for the conversation as received
 * from a user talking to the business or from a business messaging the user.
 *
 * @param {object} threadAndMessage Object containining thread and message details.
 * @param {string} params.message The message content that was received.
 * @param {string} params.messageId The unique identifier for the message.
 * @param {string} params.userType User or CRM, depending on inbound or outbound message.
 * @param {string} params.displayName The name of the user.
 * @param {string} params.brandId The unique identifier for the business.
 * @param {string} params.conversationId The unique id for this user and agent.
 * @param {string} params.state Represents who is managing the conversation for the CRM.
 */
async function storeMessage(threadAndMessage) {
  return new Promise((resolve, reject) => {
    // Update the thread
    datastoreUtil.saveThread({
      lastMessageText: threadAndMessage.message,
      lastUpdated: new Date(),
      conversationId: threadAndMessage.conversationId,
      displayName: threadAndMessage.displayName,
      brandId: threadAndMessage.brandId,
      state: threadAndMessage.state,
    }, () => {
      // Store the message
      datastoreUtil.saveMessage({
        messageId: threadAndMessage.messageId,
        messageText: threadAndMessage.message,
        conversationId: threadAndMessage.conversationId,
        userType: threadAndMessage.userType,
        displayName: threadAndMessage.displayName,
        createdDate: new Date(),
      });

      resolve();
    });
  });
}

/**
 * Posts a message to the Business Messages API, first sending a typing
 * indicator event and sending a stop typing event after the message
 * has been sent.
 *
 * @param {object} messageObject The message object payload to send to the user.
 * @param {string} conversationId The unique id for this user and agent.
 */
async function sendResponse(messageObject, conversationId) {
  let authClient = await initCredentials();

  // Create the payload for sending a typing started event
  let apiEventParams = {
    auth: authClient,
    parent: 'conversations/' + conversationId,
    resource: {
      eventType: 'TYPING_STARTED',
      representative: messageObject.representative,
    },
    eventId: uuidv4(),
  };

  // Send the typing started event
  bmApi.conversations.events.create(apiEventParams,
    {auth: authClient}, (err, response) => {
    let apiParams = {
      auth: authClient,
      parent: 'conversations/' + conversationId,
      resource: messageObject,
    };

    // Call the message create function using the
    // Business Messages client library
    bmApi.conversations.messages.create(apiParams,
      {auth: authClient}, (err, response) => {
      // Update the event parameters
      apiEventParams.resource.eventType = 'TYPING_STOPPED';
      apiEventParams.eventId = uuidv4();

      // Send the typing stopped event
      bmApi.conversations.events.create(apiEventParams,
        {auth: authClient}, (err, response) => {
      });
    });
  });
}

/**
 * Returns a representative for the business.
 * @param {string} representativeType The representative sending the message,
 * BOT or HUMAN.
 * @return The representative type object.
 */
function getRepresentative(representativeType) {
  return {
    representativeType: representativeType,
    displayName: BUSINESS_NAME,
  };
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 * @return A Promise with an authentication object.
 */
async function initCredentials() {
  // configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

module.exports = router;


text:
package com.wegas.core.websocket.pusher;

import java.io.IOException;
import org.apache.http.client.ClientProtocolException;

public class PusherRequest {

	/**
	 * Name of the event
	 */
	private String eventName;

	/**
	 * Channel identifier
	 */
	private String channelName;

	/**
	 * Create an instance and assign a channelName that is used for each request
	 * @param channelName
	 */
	public PusherRequest(String channelName) {
		super();
		this.channelName = channelName;
	}

	/**
	 * Create an instance and assign both channelName and eventName that are used for each request
	 * @param eventName
	 * @param channelName
	 */
	public PusherRequest(String channelName, String eventName) {
		super();
		this.channelName = channelName;
		this.eventName = eventName;
	}

	/**
	 * Triggers a new push with default channelName, eventName properties
	 * @param jsonData
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String triggerPush(String jsonData) throws ClientProtocolException, IOException{
		return Pusher.triggerPush(channelName, eventName, jsonData);
	}

	/**
	 * Triggers a new push with default channelName property
	 * @param jsonData
	 * @param eventName
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String triggerPush(String jsonData, String eventName) throws ClientProtocolException, IOException{
		return Pusher.triggerPush(channelName, eventName, jsonData);
	}

	/**
	 * Triggers a new push with default channelName property
	 * @param jsonData
	 * @param eventName
	 * @param socketId
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public String triggerPush(String jsonData, String eventName, String socketId) throws ClientProtocolException, IOException{
		return Pusher.triggerPush(channelName, eventName, jsonData, socketId);
	}

    /**
     *
     * @param eventName
     */
    public void setEventName(String eventName) {
		this.eventName = eventName;
	}

    /**
     *
     * @return
     */
    public String getEventName() {
		return eventName;
	}

    /**
     *
     * @param channelName
     */
    public void setChannelName(String channelName) {
		this.channelName = channelName;
	}

    /**
     *
     * @return
     */
    public String getChannelName() {
		return channelName;
	}

}


text:
var showEffect;

//description area effect
showEffect="true";

$(document).ready(function(){
	var slider_area;
	var slider_buttons;

	// Which slider
	if ($('#slider_area').length>0){

		// Home Page Slider
		slider_area="#slider_area";
		slider_buttons=".slider_thumbs";

		$(slider_area).cycle({
			fx:     'fade',
			timeout:  4000,
			easing: 'backout',
                        pager:  '.slider_thumbs',
			cleartype:  1,
			pause:           true,     // true to enable "pause on hover"
			pauseOnPagerHover: true,   // true to pause when hovering over pager link
			before:  onBefore,
			after:   onAfter ,
			pagerAnchorBuilder: function(idx) {
				 return '.slider_thumbs li:eq(' + idx + ') a';
			}
		});

	}

	if ($('.news_bar').length>0){

		// news bar
		news_bar=".news_bar";

		$(news_bar).cycle({
			fx:     'scrollDown',
			timeout:  6000,
			cleartype:  1
		});

	}

	if ($('.product_image_slider').length>0){

		// product image slider
		product_image_slider=".p_box .thumbs";

		$('.product_image_slider').cycle({
			fx:     'scrollUp',
			timeout:  6000,
			pager:  product_image_slider,
			cleartype:  1,
			pause:           true,     // true to enable "pause on hover"
			pauseOnPagerHover: true,   // true to pause when hovering over pager link
			before:  onBefore,
			after:   onAfter ,
			pagerAnchorBuilder: function(idx) {
				 return product_image_slider +' li:eq(' + idx + ') a';
			}
		});

	}

	function onBefore() {
		if (showEffect!="false"){
			jQuery('.desc').stop().animate({left:-700},0);
		}else{

		}
	}

	function onAfter() {
		if (showEffect!="false"){
			jQuery('.desc').stop().animate({left:0},600);
		}else{

		}
	}

});

//pretty photo
$(document).ready(function(){
        $("a[rel^='prettyPhoto']").prettyPhoto();
});

//cufon fonts
$(document).ready(function(){

         Cufon.replace('h1,h2,h3,h4,h5,h6, #navigation > li > a, .cufon', {

                  hover: true,
		  textShadow: '1px 1px #fff'
         });

         Cufon.replace('.desc .title', {

                  hover: true
         });
});

//drop down menu
$(document).ready(function() {
	$("#navigation li").each(function()
	{

            $(this).hover(function()
            {

                       $(this).find('ul:first').stop().css({
                             paddingTop:"8px",
                             height:"auto",
                             overflow:"hidden",
                             display:"none"
                             }).slideDown(200, function()
                       {
                       $(this).css({
                             height:"auto",
                             overflow:"visible"
                       });
            });

            },

            function()
            {
                 $(this).find('ul:first').stop().slideUp(200, function()
                 {
                         $(this).css({
                          display:"none",
                          overflow:"hidden"
                          });
                 });
            });
	});

        $("#navigation ul ").css({
            display: "none"}
         );
});

$(document).ready(function() {
$(".j_ttip[title]").tooltip({

   // tweak the position
	position: "top center",
         offset: [0, 0],

   // use the "slide" effect
   effect: 'slide'

// add dynamic plugin with optional configuration for bottom edge
}).dynamic({ bottom: { direction: 'down', bounce: true } });

});

//search field function
$(document).ready(function() {
	var search_text=jQuery(".search_bar .search_text").val();

	jQuery(".search_bar .search_text").focus(function() {
		jQuery(".search_bar .search_text").val('');
	});

	jQuery(".search_bar .search_text").focus(function() {
		jQuery(".search_bar .search_text").val('');
	});

         jQuery(".search_bar form .searchsubmit").css( {opacity:"0"} )
         jQuery(".search_bar")

          .mouseover(function(){
                 jQuery(".search_bar form .searchsubmit").stop().animate(
                         {opacity:"1"},
                         {duration:500})
                 })
          .mouseout(function(){
                 jQuery(".search_bar form .searchsubmit").stop().animate(
                         {opacity:"0"},
                         {duration:500})
                 })

});

//RT Portfolio Effect
$(document).ready(function() {

        $(window).load(function() {
                  var portfolio_item=jQuery("a.imgeffect");

                  portfolio_item.each(function(){

                           var img_width = $(this).find('img').width();
                           var img_height = $(this).find('img').innerHeight();
                           var imageClass = $(this).attr("class");
                           $(this).prepend('');

                           var p = $(this).find('img');
                           var position = p.position();
                           var PosTop= parseInt(p.css("margin-top"))+position.top;
                           var PosLeft= parseInt(p.css("margin-left"))+position.left;
			   if (!PosLeft) {PosLeft= position.left};

                           $(this).find('.imagemask').css({top: PosTop});
			   $(this).find('.imagemask').css({left: PosLeft});

                           $('.imagemask', this).css({width:img_width,height:img_height,backgroundPosition:'center center'});

                           if($.browser.msie){ $('.imagemask', this).css({display:'none'});}

                  });

         });

         var image_e= $("a.imgeffect");

		if($.browser.msie){//ignore the shadow effect if browser IE

				image_e.mouseover(function(){

				$(this).find('.imagemask').stop().css({
						  display:"block"
						  });

				}).mouseout(function(){
					$(this).find('.imagemask').stop().css({
						 display:"none"
						} );
				});

		}else{//real browsers :)
			 image_e.mouseover(function(){

			 $(this).find('.imagemask').stop().animate({
					   display:"block",
					   opacity:1
					   }, 500);

			 }).mouseout(function(){
				 $(this).find('.imagemask').stop().animate({
					   display:"none",
					   opacity:0
					 }, 400 );
			 });
		}

});

//validate contact form
$(document).ready(function(){

      // show a simple loading indicator
      var loader = jQuery('')
              .appendTo(".loading")
              .hide();
      jQuery().ajaxStart(function() {
              loader.show();
      }).ajaxStop(function() {
              loader.hide();
      }).ajaxError(function(a, b, e) {
              throw e;
      });

      jQuery.validator.messages.required = "";
      var v = jQuery("#validate_form").validate({
              submitHandler: function(form) {
                      jQuery(form).ajaxSubmit({
                              target: "#result"
                      });
              }
      });

      jQuery("#reset").click(function() {
              v.resetForm();
      });
 });


text:
<?php

namespace FOS\HttpCache\Exception;

/**
 * Common interface for all exceptions thrown by this library.
 */
interface HttpCacheExceptionInterface
{}


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

import java.util.concurrent.TimeUnit;

import org.jctools.queues.MessagePassingQueue;
import org.jctools.queues.MessagePassingQueueByTypeFactory;
import org.openjdk.jmh.annotations.AuxCounters;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

@State(Scope.Group)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 10, time = 1)
@Measurement(iterations = 10, time = 1)
public class MpqThroughputBackoffNone {
    private static final long DELAY_PRODUCER = Long.getLong("delay.p", 0L);
    private static final long DELAY_CONSUMER = Long.getLong("delay.c", 0L);
    static final Object TEST_ELEMENT = 1;
    Integer element = 1;
    Integer escape;
    MessagePassingQueue<Integer> q;

    @Param(value = { "SpscArrayQueue", "MpscArrayQueue", "SpmcArrayQueue", "MpmcArrayQueue" })
    String qType;

    @Param(value = { "132000" })
    int qCapacity;

    @Setup()
    public void createQandPrimeCompilation() {
        q = MessagePassingQueueByTypeFactory.createQueue(qType, 128);

        // stretch the queue to the limit, working through resizing and full
        for (int i = 0; i < 128 + 100; i++) {
            q.offer(element);
        }
        for (int i = 0; i < 128 + 100; i++) {
            q.poll();
        }
        // stretch the queue to the limit, working through resizing and full
        for (int i = 0; i < 128 + 100; i++) {
            q.relaxedOffer(element);
        }
        for (int i = 0; i < 128 + 100; i++) {
            q.relaxedPoll();
        }
        // make sure the important common case is exercised
        for (int i = 0; i < 20000; i++) {
            q.offer(element);
            q.poll();
            q.relaxedOffer(element);
            q.relaxedPoll();
        }
        q = MessagePassingQueueByTypeFactory.createQueue(qType, qCapacity);
    }

    @AuxCounters
    @State(Scope.Thread)
    public static class PollCounters {
        public long pollsFailed;
        public long pollsMade;
    }

    @AuxCounters
    @State(Scope.Thread)
    public static class OfferCounters {
        public long offersFailed;
        public long offersMade;
    }

    @Benchmark
    @Group("nor")
    public void offerNoR(OfferCounters counters) {
        if (!q.offer(element)) {
            counters.offersFailed++;
            backoff();
        } else {
            counters.offersMade++;
        }
        if (DELAY_PRODUCER != 0) {
            Blackhole.consumeCPU(DELAY_PRODUCER);
        }
    }

    @Benchmark
    @Group("nor")
    public void pollNoR(PollCounters counters) {
        Integer e = q.poll();
        if (e == null) {
            counters.pollsFailed++;
            backoff();
        } else if (e == TEST_ELEMENT) {
            counters.pollsMade++;
        } else {
            escape = e;
        }
        if (DELAY_CONSUMER != 0) {
            Blackhole.consumeCPU(DELAY_CONSUMER);
        }
    }

    @Benchmark
    @Group("bothr")
    public void offerBothR(OfferCounters counters) {
        if (!q.relaxedOffer(element)) {
            counters.offersFailed++;
            backoff();
        } else {
            counters.offersMade++;
        }
        if (DELAY_PRODUCER != 0) {
            Blackhole.consumeCPU(DELAY_PRODUCER);
        }
    }

    @Benchmark
    @Group("bothr")
    public void pollBothR(PollCounters counters) {
        Integer e = q.relaxedPoll();
        if (e == null) {
            counters.pollsFailed++;
            backoff();
        } else if (e == TEST_ELEMENT) {
            counters.pollsMade++;
        } else {
            escape = e;
        }
        if (DELAY_CONSUMER != 0) {
            Blackhole.consumeCPU(DELAY_CONSUMER);
        }
    }

    @Benchmark
    @Group("pr")
    public void offerPR(OfferCounters counters) {
        if (!q.relaxedOffer(element)) {
            counters.offersFailed++;
            backoff();
        } else {
            counters.offersMade++;
        }
        if (DELAY_PRODUCER != 0) {
            Blackhole.consumeCPU(DELAY_PRODUCER);
        }
    }

    @Benchmark
    @Group("pr")
    public void pollPR(PollCounters counters) {
        Integer e = q.poll();
        if (e == null) {
            counters.pollsFailed++;
            backoff();
        } else if (e == TEST_ELEMENT) {
            counters.pollsMade++;
        } else {
            escape = e;
        }
        if (DELAY_CONSUMER != 0) {
            Blackhole.consumeCPU(DELAY_CONSUMER);
        }
    }

    @Benchmark
    @Group("cr")
    public void offerCR(OfferCounters counters) {
        if (!q.offer(element)) {
            counters.offersFailed++;
            backoff();
        } else {
            counters.offersMade++;
        }
        if (DELAY_PRODUCER != 0) {
            Blackhole.consumeCPU(DELAY_PRODUCER);
        }
    }

    @Benchmark
    @Group("cr")
    public void pollCR(PollCounters counters) {
        Integer e = q.relaxedPoll();
        if (e == null) {
            counters.pollsFailed++;
            backoff();
        } else if (e == TEST_ELEMENT) {
            counters.pollsMade++;
        } else {
            escape = e;
        }
        if (DELAY_CONSUMER != 0) {
            Blackhole.consumeCPU(DELAY_CONSUMER);
        }
    }

    @TearDown(Level.Iteration)
    public void emptyQ() {
        synchronized (q)
        {
            while (q.poll() != null)
                ;
        }
    }

    protected void backoff() {
    }
}


text:
package com.cllstudy.coolweather.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by ChenLianglei on 2017/9/8 21:31.
 */

public class Forecast {
    public String date;
    @SerializedName("tmp")
   public Temperature temperature;
    @SerializedName("cond")
    public More more;
    public class Temperature {
        public String max;
        public String min;
    }

    public class More {
        @SerializedName("txt")
        public String info;
    }
}


text:
@constructor can.EJS
@parent canjs
@group can.EJS.tags Tags

@description EJS provides __live__ ERB-style client-side templates.

@signature `new can.EJS(options)`

Creates an EmbeddedJS template. Use EJS with [can.view] or [can.view.ejs].

@body

## Basic Example

The following renders a Teacher's name and students into an element.  First,
create a teacher template in a script tag like:

Notice the magic tags?  Those are things that look like `<% %>` and
`<%= %>`.  Code between `<% %>` is run and the return value of code
between `<%= %>` is inserted into the page.

Next, create a teacher and use can.view to render the template:

    var teacher = {
      name : "Mr. Smith",
      grade : "a",
      students : [
        {name : "Suzy"},
        {name : "Payal"},
        {name : "Curtis"},
        {name : "Alexis"}
      ]
    };

    document.getElementById('teacher')
      .appendChild( can.view("teacherEJS", teacher) )

This results in HTML like:

        Mr. Smith

Suzy

Payal

Curtis

Alexis

This is nice, but what if we change properties of the teacher?

## Basic Live Binding Example

EJS sets up live templating binding when a [can.Observe]'s properties are read
via [can.Observe::attr attr] within a magic tag.  To make this template
respond to changes in the teacher data, first rewrite the template
to use the attr method to read properties and `list( observeList, cb(item, i) )`
to iterate through a list like:

__Note:__ The end of this page discusses why using `list` is
helpful, but it does nothing fancy.

Next, turn your teacher into a `new can.Observe(object)` and pass
that to `can.view`:

    var teacher = new can.Observe({
      name : "Mr. Smith",
      grade : "a",
      students : [
        {name : "Suzy"},
        {name : "Payal"},
        {name : "Curtis"},
        {name : "Alexis"}
      ]
    });

    document.getElementById('teacher')
      .appendChild( can.view("teacherEJS", teacher) );

Finally, update some properties of teacher and slap your
head with disbelief ...

    teacher.attr('name',"Prof. Snape")
    teacher.attr('grade','f+')
    teacher.attr('students').push({
      name : "Harry Potter"
    })

... but don't slap it too hard, you'll need it for building awesome apps.

## Demo

The following demo shows an EJS template being rendered with observable data.
It demonstrates live binding to attributes. The template and all data properties
are editable, so experiment!

@iframe can/view/ejs/demo.html 1020

## Magic Tags

EJS uses 5 types of tags:

__`<%= CODE %>`__ - Runs JS Code and writes the _escaped_ result into the result of the template.

The following results in the user seeing "my favorite element is <blink>BLINK<blink>" and not
<blink>BLINK</blink>.

my favorite element is <%= '<blink>BLINK</blink>' %>.

__`<%== CODE %>`__  - Runs JS Code and writes the _unescaped_ result into the result of the template.

The following results in "my favorite element is B.". Using `<%==` is useful
for sub-templates.

my favorite element is <%== 'B' %>.

__`<%% CODE %>`__ - Writes <% CODE %> to the result of the template.  This is very useful for generators.

         <%%= 'hello world' %>

__`<%# CODE %>`__  - Used for comments.  This does nothing.

         <%# 'hello world' %>

## Live Binding

EJS allows live binding by wrapping magic tag content within a function. When `attr()` is called
to update an observable object, these functions are executed to return the new value.

    // Suppose an observable "foo":

    var foo = can.Observe({
      count: '0'
    });

    // Suppose also, the above observable is passed to our view:

    <%= foo.attr('bar') %>

    // EJS locates the magic tag and turns the above into:

    function() { return foo.attr('bar'); }

    // As "foo" is updated using attr(), this function is called again to
    // render the view with the new value.

This means that each function tag has a closure will reference variables in it's
parent functions. This can cause problems if you don't understand closures in
JavaScript. For example, the following binding does not work:

    <% for(var i =0; i < items.attr('length'); i++){ %>

<%= items[i].attr('name') %>

    <% } %>

This is because it gets turned into:

    <% for(var i =0; i < items.attr('length'); i++){ %>
      LIVEBIND( function() { return items[i].attr('name') )
    <% } %>

When the wrapping function is called again, `i` will
not be the index of the item, but instead be items.length.

The [can.EJS.Helpers::view view](observeList,function(item,index,list){}) method in EJS should be used to iterate through observe lists:

    <% list(items, function(item){ %>

<%= item.attr('name') %>

    <% }) %>

## Advanced Live Binding

Once you get the hang of how EJS works, it makes live-binding of complex
calculations possible.  The following extends a [can.Model.List] to suppot a `completed` method that
returns the total number of completed items in the list.  It can be used in a template like:

<%= todos.complete() %> Complete Todos

And implemented like:

    Todo.List = can.Model.List({
      completed: function() {
        var count = 0;

        this.attr('length');
        this.each(function(i, todo) {
          if(this.attr('completed')) {
            count++;
          }
        });

        return count;
      }
    });

`completed` listens on changes to the list (via `this.attr('length')`) and
each item's `'completed'` property.  EJS keeps track of which observe/attribute pairs are called
by `.complete()`.  If they change, EJS will automatically unbind.

Adding a "completed" helper function to the todo model list to return the number of completed todos:

__Note:__ The object passed into the view becomes "this" within the view template.

    var todos = Todo.findAll({}); //returns a can.Model.List
    can.view('//todo/views/init.ejs', todos)

## Element Callbacks

If a function is returned by the `<%= %>` or `<%== %>` magic tags within an element's tag like:

    <div <%= function( element ) { element.style.display = 'none' } %> >
      Hello

The function is called back with the HTMLElement as the first argument. This is useful to initialize functionality on an element within the view. This is so common that EJS supports ES5 arrow functions that get passed the NodeList wrapped element. Using jQuery, this lets you write the above callback as:

    <div <%= (el) -> el.hide() %> >
      Hello

This technique is commonly used to add data, especially model instances, to an element like:

    <% todos.each( function( todo ) { %>
      <li <%= (el) -> el.data( 'todo', todo ) %>>
        <%= todo.attr( 'name' ) %>

    <% } ) %>

jQuery's `el.data( NAME, data )` adds data to an element. If your library does not support this, can provides it as `can.data( NodeList, NAME, data )`. Rewrite the above example as:

    <% list(todos, function( todo ) { %>
      <li <%= (el) -> can.data( el, 'todo', todo ) %>>
        <%= todo.attr( 'name' ) %>

    <% } ) %>


text:
namespace ui {

// static
KeyboardLayoutEngineManager* KeyboardLayoutEngineManager::instance_ = nullptr;

KeyboardLayoutEngineManager::KeyboardLayoutEngineManager(
    KeyboardLayoutEngine* engine)
    : keyboard_layout_engine_(engine) {
  CHECK(!instance_) << "Only one keyboard layout manager can be created.";
  instance_ = this;
}

KeyboardLayoutEngineManager::~KeyboardLayoutEngineManager() {
  CHECK_EQ(this, instance_);
  instance_ = NULL;
}

void KeyboardLayoutEngineManager::SetKeyboardLayoutEngine(
    std::unique_ptr<KeyboardLayoutEngine> engine) {
  if (instance_)
    instance_->keyboard_layout_engine_.reset(engine.release());
  else
    new KeyboardLayoutEngineManager(engine.release());
}

KeyboardLayoutEngine* KeyboardLayoutEngineManager::GetKeyboardLayoutEngine() {
  // TODO(kpschoedel): crbug.com/430194 This lazy initialization is a
  // workaround for not yet initializing KeyboardLayoutEngineManager
  // expliclity in all tests that need it.
  if (!instance_)
    new KeyboardLayoutEngineManager(new StubKeyboardLayoutEngine());
  return instance_->keyboard_layout_engine_.get();
}

}  // namespace ui


text:
<!DOCTYPE html>

<title>Photofy Demo</title>
<link rel="stylesheet" type="text/css" href="layout.css" />


text:
package org.sisioh.aws4s.sns.model

import com.amazonaws.services.sns.model.ConfirmSubscriptionRequest
import org.sisioh.aws4s.PimpedType

object ConfirmSubscriptionRequestFactory {

  def create(): ConfirmSubscriptionRequest =
    new ConfirmSubscriptionRequest()

  def create(topicArn: String, token: String): ConfirmSubscriptionRequest =
    new ConfirmSubscriptionRequest(topicArn, token)

  def create(topicArn: String, token: String, authenticateOnUnsubscribe: String): ConfirmSubscriptionRequest =
    new ConfirmSubscriptionRequest(topicArn, token, authenticateOnUnsubscribe)

}

class RichConfirmSubscriptionRequest(val underlying: ConfirmSubscriptionRequest)
    extends AnyVal
    with PimpedType[ConfirmSubscriptionRequest] {

  def topicArnOpt: Option[String] =
    Option(underlying.getTopicArn)

  def topicArnOpt_=(value: Option[String]): Unit =
    underlying.setTopicArn(value.orNull)

  def withTopicArnOpt(value: Option[String]): ConfirmSubscriptionRequest =
    underlying.withTopicArn(value.orNull)

  def tokenOpt: Option[String] =
    Option(underlying.getToken)

  def tokenOpt_=(value: Option[String]): Unit =
    underlying.setToken(value.orNull)

  def withTokenOpt(value: Option[String]): ConfirmSubscriptionRequest =
    underlying.withToken(value.orNull)

  def authenticateOnUnsubscribeOpt: Option[String] =
    Option(underlying.getAuthenticateOnUnsubscribe)

  def authenticateOnUnsubscribeOpt_=(value: Option[String]) =
    underlying.setAuthenticateOnUnsubscribe(value.orNull)

  def withAuthenticateOnUnsubscribeOpt(authenticateOnUnsubscribe: Option[String]): ConfirmSubscriptionRequest =
    underlying.withAuthenticateOnUnsubscribe(authenticateOnUnsubscribe.orNull)

}


text:
#region license

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

#endregion

using System;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;

namespace SolrNet.Impl.ResponseParsers {
    /// <summary>
    /// Parses documents from a query response
    /// </summary>
    /// <typeparam name="T">Document type</typeparam>
    public class ResultsResponseParser<T> : ISolrAbstractResponseParser<T> {
        private readonly ISolrDocumentResponseParser<T> docParser;

        public ResultsResponseParser(ISolrDocumentResponseParser<T> docParser) {
            this.docParser = docParser;
        }

        private static XElement GetMainResultNode(XDocument xml) {
            return xml.Element("response").Elements("result")
                .FirstOrDefault(e => {
                    var nameAttr = e.Attribute("name");
                    if (nameAttr == null)
                        return true;
                    return string.IsNullOrEmpty(nameAttr.Value) || nameAttr.Value == "response";
                });
        }

        private static XElement GetGroupResultNode(XDocument xml) {
            var groupElement = xml.Element("response").Elements("lst")
                .FirstOrDefault(e => e.Attribute("name").Value == "grouped");
            if (groupElement == null)
                return null;
            return groupElement.Descendants().FirstOrDefault(e => e.Name == "result");
        }

        private static StartOrCursor.Cursor GetNextCursorMark(XDocument xml)
        {
            var nextCursorMarkElement = xml.Element("response").Elements("str")
                .FirstOrDefault(e => e.Attribute("name").Value == "nextCursorMark");
            if (nextCursorMarkElement == null)
                return null;
            return new StartOrCursor.Cursor(nextCursorMarkElement.Value);
        }

        /// <inheritdoc/>
        public void Parse(XDocument xml, AbstractSolrQueryResults<T> results) {
            var resultNode = GetMainResultNode(xml) ?? GetGroupResultNode(xml);
            if (resultNode == null)
                return;

            results.NumFound = Convert.ToInt64(resultNode.Attribute("numFound").Value);
            results.Start = Convert.ToInt64(resultNode.Attribute("start").Value);
            var maxScore = resultNode.Attribute("maxScore");
            if (maxScore != null)
                results.MaxScore = double.Parse(maxScore.Value, CultureInfo.InvariantCulture.NumberFormat);

            results.AddRange(docParser.ParseResults(resultNode));
            results.NextCursorMark = GetNextCursorMark(xml);
        }
    }
}


text:
package org.wickedsource.coderadar.core.rest.dates.series;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.wickedsource.coderadar.core.rest.dates.Day;
import org.wickedsource.coderadar.core.rest.dates.serialize.DayDeserializer;
import org.wickedsource.coderadar.core.rest.dates.serialize.DaySerializer;

import java.util.Calendar;
import java.util.Date;

@JsonTypeName("day")
public class DayPoint extends Point<Day, Long> {

    @JsonIgnore
    private Day day;

    @JsonIgnore
    private Long value;

    public DayPoint() {
    }

    public DayPoint(Day day, Long value) {
        this.day = day;
        this.value = value;
    }

    public static DayPoint from(Date date, Long value) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        Day day = new Day(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
        return new DayPoint(day, value);
    }

    @Override
    @JsonSerialize(using = DaySerializer.class)
    @JsonDeserialize(using = DayDeserializer.class)
    public Day getX() {
        return day;
    }

    @Override
    public Long getY() {
        return value;
    }

    public void setX(Day day) {
        this.day = day;
    }

    public void setY(Long value) {
        this.value = value;
    }
}


text:
package io.seldon.api.state;

import java.util.Map;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class ZkCuratorHandler implements ConnectionStateListener {

    private static Logger logger = Logger.getLogger(ZkCuratorHandler.class.getName());
    private static ZkCuratorHandler peer;
    final private static String ENV_VAR_SELDON_ZKSERVERS = "SELDON_ZKSERVERS";

    public ZkCuratorHandler() {
        String servers = null;
        servers = System.getenv(ENV_VAR_SELDON_ZKSERVERS);
        logger.info(String.format("using %s[%s]", ENV_VAR_SELDON_ZKSERVERS, servers));
        if (servers == null) {
            logger.warn("*WARNING* SELDON_ZKSERVERS environment variable not set!");
            servers = "localhost";
        }
        this.zkServers = servers;
        startClient();
        peer = this;
    }

    public static void shutdown() {
        if (peer != null)
            peer.stopClient();
    }

    public static ZkCuratorHandler getPeer() {
        return peer;
    }

    CuratorFramework curator;
    String zkServers;

    private void stopClient() {
        curator.close();
    }

    private void startClient() {
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
        logger.info("Trying to connect to servers at " + zkServers);
        curator = builder.connectString(zkServers).retryPolicy(new ExponentialBackoffRetry(1000, 100)).build();
        curator.getConnectionStateListenable().addListener(this);
        curator.start();
    }

    public CuratorFramework getCurator() {
        return curator;
    }

    @Override
    public void stateChanged(CuratorFramework client, ConnectionState state) {
        switch (state) {
        case RECONNECTED: {
            logger.warn("Reconnection to zookeeper " + zkServers);
        }
            break;
        case LOST: {
            logger.error("Connection lost to zookeeper " + zkServers);
        }
            break;
        case CONNECTED: {
            logger.info("Connection to zookeeper " + zkServers);
        }
            break;
        case SUSPENDED: {
            logger.error("Connection suspended to zookeeper " + zkServers);
        }
            break;
        }

    }

    public static void dump_env() {
        Map<String, String> env = System.getenv();
        logger.info("*** ENV ***");
        StringBuilder lines = new StringBuilder();
        for (String envName : env.keySet()) {
            lines.append(String.format("%s=%s%n", envName, env.get(envName)));
        }
        logger.info(lines.toString());
    }
}


text:
require 'logger'
require 'stringio'
require 'monitor'
require 'timeout'
require 'optionable'
require 'bones/rpc/errors'
require 'bones/rpc/loggable'
require 'bones/rpc/uri'
require 'bones/rpc/adapter'
require 'bones/rpc/backend'
require 'bones/rpc/parser'
require 'bones/rpc/protocol'
require 'bones/rpc/session'
require 'bones/rpc/version'

module Bones
  module RPC
    extend Loggable

    FutureValue = Struct.new(:value)
  end
end


text:
using System;

// ReSharper disable CheckNamespace
namespace FluentIL.Emitters
// ReSharper restore CheckNamespace
{
    partial class DynamicMethodBody
    {
        public DynamicMethodBody Throw<TException>(params Type[] types)
            where TException : Exception
        {
            return Newobj<TException>(types)
                .Throw();
        }
    }
}


text:
extern "Java"
{
  namespace javax
  {
    namespace swing
    {
      namespace plaf
      {
          class DesktopIconUI;
      }
    }
  }
}

class javax::swing::plaf::DesktopIconUI : public ::javax::swing::plaf::ComponentUI
{

public:
  DesktopIconUI();
  static ::java::lang::Class class$;
};

#endif // __javax_swing_plaf_DesktopIconUI__


text:
package io.iohk.ethereum.healthcheck

final case class HealthcheckResult private (description: String, status: String, error: Option[String]) {
  assert(
    status == HealthcheckStatus.OK && error.isEmpty || status == HealthcheckStatus.ERROR && error.isDefined
  )

  def isOK: Boolean = status == HealthcheckStatus.OK
}

object HealthcheckResult {
  def apply(description: String, error: Option[String]): HealthcheckResult =
    new HealthcheckResult(
      description = description,
      status = error.fold(HealthcheckStatus.OK)(_ => HealthcheckStatus.ERROR),
      error = error
    )
}


text: Wrapper library for Roslyn compiler where user can select allowed types for compilation